text:
<?php
namespace prototypr {
    /**
     * Extension class
     * @package prototypr
     */
    class Extension {
        /**
         * array of extensions keyed by class
         * self::$extensions[class]
         * @var array
         */
        private static $extensions = [];

        /**
         * Checks is prototype is extending another
         * @param mixed $class
         * @param mixed $target
         * @return boolean
         */
        public static function extending($class,$target) {
            if(is_object($class)) {
                $class = get_class($class);
            }

            if(is_object($target)) {
                $target = get_class($target);
            }

            $target = strtolower($target);
            $class = strtolower($class);

            if(array_key_exists($class,self::$extensions) &&
               in_array($target,self::$extensions[$class])) {
                return true;
            }

            return false;
        }

        /**
         * Copies methods from one prototype to another
         * @param mixed $class
         * @param mixed $target
         */
        public static function addExtension($class,$target) {
            if(is_object($class)) {
                $class = get_class($class);
            }

            if(is_object($target)) {
                $target = get_class($target);
            }

            $target = strtolower($target);
            $class = strtolower($class);

            if(!array_key_exists($class,self::$extensions)) {
                self::$extensions[$class] = [];
            }

            self::$extensions[$class][] = (string)$target;

            Registry::addExtension($class, $target);
        }

        /**
         * Retrieve all extensions of a class
         * @param string $class
         * @return array
         */
        public static function getExtensions($class) {
            if(is_object($class)) {
                $class = get_class($class);
            }

            $class = strtolower($class);

            return self::$extensions[$class];
        }

        /**
         * Ensures oop-like extensions
         * @param string $class
         */
        public static function autoExtend($class) {
            if(array_key_exists($class,self::$extensions)) {
                foreach(self::$extensions[$class] as $extension) {
                    if($extension !== $class) {
                        Manager::extend($class,$extension);
                    }
                }
            }

            self::manageScope($class);
        }

        /**
         * Deliberately forgets scope
         * @param string $class
         */
        public static function manageScope($class) {
            if(Manager::scoped()) {
                $return = Manager::scope();
                $returnClass = strtolower(get_class($return));

                if($returnClass === $class) {
                    Manager::clearScope();
                }
            }
        }
    }
}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/ship/components/droid_interface/shared_ddi_hk_mk1.iff"
	result.attribute_template_id = 8
	result.stfName("space/space_item","ddi_hk_mk1_n")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result

redpajama_set_name: RedPajamaGithub


text:
package org.gradle.launcher.configuration;

import org.gradle.api.internal.StartParameterInternal;
import org.gradle.initialization.BuildLayoutParameters;

import java.io.File;

/**
 * Immutable build layout, calculated from the command-line options and environment.
 */
public interface BuildLayoutResult {
    void applyTo(BuildLayoutParameters buildLayout);

    void applyTo(StartParameterInternal startParameter);

    File getGradleUserHomeDir();
}


text:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	xmlns:g="urn:import:com.google.gwt.user.client.ui"
	xmlns:c="urn:import:com.google.gwt.user.cellview.client"
	xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
	xmlns:t="urn:import:org.sagebionetworks.web.client.widget.table.v2"
	xmlns:a="urn:import:org.sagebionetworks.web.client.widget.table.v2"
	xmlns:bg="urn:import:org.gwtbootstrap3.client.ui.gwt"
	xmlns:bh="urn:import:org.gwtbootstrap3.client.ui.html">

	<b:Modal ui:field="modal" title="Delete Team?" closable="true"
		dataBackdrop="STATIC" dataKeyboard="true">
		<b:ModalBody>
			<bh:Text>Are you sure you want to delete this Team?</bh:Text>
			<g:SimplePanel ui:field="synAlertPanel" />
		</b:ModalBody>
		<b:ModalFooter>
			<b:Button ui:field="cancelButton" type="LINK"
				dataDismiss="MODAL">Cancel</b:Button>
			<b:Button ui:field="primaryButton" type="DANGER"
				dataLoadingText="Deleting...">Delete</b:Button>
		</b:ModalFooter>
	</b:Modal>
</ui:UiBinder>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6.1 virtualenv at ~/Projects/internship2017/internship-env (1)" project-jdk-type="Python SDK" />
</project>


text:
// Copyright (c) 2015, Dean ChaoJun Pan.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

#ifndef GO_ROCKSDB_INCLUDE_MERGE_OPERATOR_H_
#define GO_ROCKSDB_INCLUDE_MERGE_OPERATOR_H_

#include "types.h"
#include "env.h"
#include "slice.h"
#include "cstring.h"

#ifdef __cplusplus
extern "C" {
#endif

DEFINE_C_WRAP_STRUCT(PMergeOperator)
DEFINE_C_WRAP_CONSTRUCTOR_DEC(PMergeOperator)
DEFINE_C_WRAP_DESTRUCTOR_DEC(PMergeOperator)

// Return a MergeOperator from a go MergeOperator interface
PMergeOperator_t NewMergeOperator(void* go_cmp);

#ifdef __cplusplus
}  /* end extern "C" */
#endif

#endif  // GO_ROCKSDB_INCLUDE_MERGE_OPERATOR_H_


text:
package com.danielasfregola.randomdatagenerator.utils

import org.scalacheck.derive._

private[randomdatagenerator] trait ShapelessLike
    extends SingletonInstances
    with HListInstances
    with CoproductInstances
    with DerivedInstances
    with FieldTypeInstances


text:
<?php namespace OfficeTwit\Exceptions;

use Exception;

class BadSettingNameException extends Exception {

    public function __construct($message, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}


text:
#ifndef TENSORFLOW_LITE_DELEGATES_NNAPI_NNAPI_DELEGATE_MOCK_TEST_H_
#define TENSORFLOW_LITE_DELEGATES_NNAPI_NNAPI_DELEGATE_MOCK_TEST_H_

// Cannot mock the delegate when using the disabled version
// (see the condition in the BUILD file).
#ifndef NNAPI_DELEGATE_DISABLED

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <memory>

#include <gtest/gtest.h>
#include "absl/memory/memory.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h"
#include "tensorflow/lite/nnapi/NeuralNetworksTypes.h"
#include "tensorflow/lite/nnapi/nnapi_handler.h"
#include "tensorflow/lite/nnapi/nnapi_implementation.h"

namespace tflite {
namespace delegate {
namespace nnapi {

class NnApiMock : public ::tflite::nnapi::NnApiHandler {
 public:
  explicit NnApiMock(NnApi* nnapi, int android_sdk_version = 29)
      : ::tflite::nnapi::NnApiHandler(nnapi) {
    nnapi_->nnapi_exists = true;
    nnapi_->android_sdk_version = android_sdk_version;

    nnapi_->ANeuralNetworksCompilation_free =
        [](ANeuralNetworksCompilation* compilation) {};
    nnapi_->ANeuralNetworksMemory_free = [](ANeuralNetworksMemory* memory) {};
    nnapi_->ANeuralNetworksModel_free = [](ANeuralNetworksModel* model) {};
    nnapi_->ANeuralNetworksExecution_free =
        [](ANeuralNetworksExecution* execution) {};
    nnapi_->ASharedMemory_create = [](const char* name, size_t size) -> int {
      return open("/dev/zero", O_RDWR);
    };

    ModelCreateReturns<ANEURALNETWORKS_NO_ERROR>();
    AddOperandReturns<ANEURALNETWORKS_NO_ERROR>();
    SetOperandValueReturns<ANEURALNETWORKS_NO_ERROR>();
    AddOperationReturns<ANEURALNETWORKS_NO_ERROR>();
    IdentifyInputAndOutputsReturns<ANEURALNETWORKS_NO_ERROR>();
    RelaxComputationFloatReturns<ANEURALNETWORKS_NO_ERROR>();
    ModelFinishReturns<ANEURALNETWORKS_NO_ERROR>();
    MemoryCreateFromFdReturns<ANEURALNETWORKS_NO_ERROR>();
    CompilationCreateReturns<ANEURALNETWORKS_NO_ERROR>();
    CompilationCreateForDevicesReturns<ANEURALNETWORKS_NO_ERROR>();
    CompilationFinishReturns<ANEURALNETWORKS_NO_ERROR>();
    ExecutionCreateReturns<ANEURALNETWORKS_NO_ERROR>();
    ExecutionSetInputFromMemoryReturns<ANEURALNETWORKS_NO_ERROR>();
    ExecutionSetOutputFromMemoryReturns<ANEURALNETWORKS_NO_ERROR>();
    ExecutionComputeReturns<ANEURALNETWORKS_NO_ERROR>();
    SetNnapiSupportedDevice("test-device", android_sdk_version);
  }

  ~NnApiMock() { Reset(); }
};

class NnApiDelegateMockTest : public ::testing::Test {
 protected:
  void SetUp() override {
    nnapi_ = const_cast<NnApi*>(NnApiImplementation());
    nnapi_mock_ = absl::make_unique<NnApiMock>(nnapi_);
  }

  NnApi* nnapi_;
  std::unique_ptr<NnApiMock> nnapi_mock_;
};

}  // namespace nnapi
}  // namespace delegate
}  // namespace tflite

#endif  // #ifndef NNAPI_DELEGATE_DISABLED

#endif  // TENSORFLOW_LITE_DELEGATES_NNAPI_NNAPI_DELEGATE_MOCK_TEST_H_


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SocialApi.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SocialApi.Controllers.Tests
{
  [TestClass()]
  public class RatesControllerTests
  {
    [TestMethod()]
    public void GetRatesTest()
    {

    }

    [TestMethod()]
    public void GetRateTest()
    {

    }

    [TestMethod()]
    public void PutRateTest()
    {

    }

    [TestMethod()]
    public void PostRateTest()
    {

    }

    [TestMethod()]
    public void DeleteRateTest()
    {

    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Rochester Acad. Sci. 6: 96 (1921)

#### Original name
Melanopsamma subrhombispora Fairm.

### Remarks
null


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

package com.google.collide.codemirror2;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * Native CodeMirror {@link Stream} wrapper.
 */
public class CmStream extends JavaScriptObject implements Stream {

  protected CmStream() {
  }

  @Override
  public final native boolean isEnd() /*-{
    return this.eol();
  }-*/;
}


text:
package java.util.logging;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import org.apache.harmony.logging.internal.nls.Messages;

/**
 * A {@code StreamHandler} object writes log messages to an output stream, that
 * is, objects of the class {@link java.io.OutputStream}.
 *

 * A {@code StreamHandler} object reads the following properties from the log
 * manager to initialize itself. A default value will be used if a property is
 * not found or has an invalid value.
 *

 *
java.util.logging.StreamHandler.encoding specifies the encoding this
 * handler will use to encode log messages. Default is the encoding used by the
 * current platform.
 *
java.util.logging.StreamHandler.filter specifies the name of the filter
 * class to be associated with this handler. No Filter is used by
 * default.
 *
java.util.logging.StreamHandler.formatter specifies the name of the
 * formatter class to be associated with this handler. Default is
 * {@code java.util.logging.SimpleFormatter}.
 *
java.util.logging.StreamHandler.level specifies the logging level.
 * Defaults is {@code Level.INFO}.
 *

 *

 * This class is not thread-safe.
 */
public class StreamHandler extends Handler {

    // the output stream this handler writes to
    private OutputStream os;

    // the writer that writes to the output stream
    private Writer writer;

    // the flag indicating whether the writer has been initialized
    private boolean writerNotInitialized;

    /**
     * Constructs a {@code StreamHandler} object. The new stream handler
     * does not have an associated output stream.
     */
    public StreamHandler() {
        initProperties("INFO", null, "java.util.logging.SimpleFormatter", //$NON-NLS-1$//$NON-NLS-2$
                null);
        this.os = null;
        this.writer = null;
        this.writerNotInitialized = true;
    }

    /**
     * Constructs a {@code StreamHandler} object with the supplied output
     * stream. Default properties are read.
     *
     * @param os
     *            the output stream this handler writes to.
     */
    StreamHandler(OutputStream os) {
        this();
        this.os = os;
    }

    /**
     * Constructs a {@code StreamHandler} object. The specified default values
     * will be used if the corresponding properties are not found in the log
     * manager's properties.
     */
    StreamHandler(String defaultLevel, String defaultFilter,
            String defaultFormatter, String defaultEncoding) {
        initProperties(defaultLevel, defaultFilter, defaultFormatter,
                defaultEncoding);
        this.os = null;
        this.writer = null;
        this.writerNotInitialized = true;
    }

    /**
     * Constructs a {@code StreamHandler} object with the supplied output stream
     * and formatter.
     *
     * @param os
     *            the output stream this handler writes to.
     * @param formatter
     *            the formatter this handler uses to format the output.
     * @throws NullPointerException
     *             if {@code os} or {@code formatter} is {@code null}.
     */
    public StreamHandler(OutputStream os, Formatter formatter) {
        this();
        if (os == null) {
            // logging.2=The OutputStream parameter is null
            throw new NullPointerException(Messages.getString("logging.2")); //$NON-NLS-1$
        }
        if (formatter == null) {
            // logging.3=The Formatter parameter is null.
            throw new NullPointerException(Messages.getString("logging.3")); //$NON-NLS-1$
        }
        this.os = os;
        internalSetFormatter(formatter);
    }

    // initialize the writer
    private void initializeWritter() {
        this.writerNotInitialized = false;
        if (null == getEncoding()) {
            this.writer = new OutputStreamWriter(this.os);
        } else {
            try {
                this.writer = new OutputStreamWriter(this.os, getEncoding());
            } catch (UnsupportedEncodingException e) {
                /*
                 * Should not happen because it's checked in
                 * super.initProperties().
                 */
            }
        }
        write(getFormatter().getHead(this));
    }

    // Write a string to the output stream.
    private void write(String s) {
        try {
            this.writer.write(s);
        } catch (Exception e) {
            // logging.14=Exception occurred when writing to the output stream.
            getErrorManager().error(Messages.getString("logging.14"), e, //$NON-NLS-1$
                    ErrorManager.WRITE_FAILURE);
        }
    }

    /**
     * Sets the output stream this handler writes to. Note it does nothing else.
     *
     * @param newOs
     *            the new output stream
     */
    void internalSetOutputStream(OutputStream newOs) {
        this.os = newOs;
    }

    /**
     * Sets the output stream this handler writes to. If there's an existing
     * output stream, the tail string of the associated formatter will be
     * written to it. Then it will be flushed, closed and replaced with
     * {@code os}.
     *
     * @param os
     *            the new output stream.
     * @throws SecurityException
     *             if a security manager determines that the caller does not
     *             have the required permission.
     * @throws NullPointerException
     *             if {@code os} is {@code null}.
     */
    protected void setOutputStream(OutputStream os) {
        if (null == os) {
            throw new NullPointerException();
        }
        LogManager.getLogManager().checkAccess();
        close(true);
        this.writer = null;
        this.os = os;
        this.writerNotInitialized = true;
    }

    /**
     * Sets the character encoding used by this handler. A {@code null} value
     * indicates that the default encoding should be used.
     *
     * @param encoding
     *            the character encoding to set.
     * @throws SecurityException
     *             if a security manager determines that the caller does not
     *             have the required permission.
     * @throws UnsupportedEncodingException
     *             if the specified encoding is not supported by the runtime.
     */
    @Override
    public void setEncoding(String encoding) throws SecurityException,
            UnsupportedEncodingException {
        // flush first before set new encoding
        this.flush();
        super.setEncoding(encoding);
        // renew writer only if the writer exists
        if (null != this.writer) {
            if (null == getEncoding()) {
                this.writer = new OutputStreamWriter(this.os);
            } else {
                try {
                    this.writer = new OutputStreamWriter(this.os, getEncoding());
                } catch (UnsupportedEncodingException e) {
                    /*
                     * Should not happen because it's checked in
                     * super.initProperties().
                     */
                    throw new AssertionError(e);
                }
            }
        }
    }

    /**
     * Closes this handler, but the underlying output stream is only closed if
     * {@code closeStream} is {@code true}. Security is not checked.
     *
     * @param closeStream
     *            whether to close the underlying output stream.
     */
    void close(boolean closeStream) {
        if (null != this.os) {
            if (this.writerNotInitialized) {
                initializeWritter();
            }
            write(getFormatter().getTail(this));
            try {
                this.writer.flush();
                if (closeStream) {
                    this.writer.close();
                    this.writer = null;
                    this.os = null;
                }
            } catch (Exception e) {
                // logging.15=Exception occurred when closing the output stream.
                getErrorManager().error(Messages.getString("logging.15"), e, //$NON-NLS-1$
                        ErrorManager.CLOSE_FAILURE);
            }
        }
    }

    /**
     * Closes this handler. The tail string of the formatter associated with
     * this handler is written out. A flush operation and a subsequent close
     * operation is then performed upon the output stream. Client applications
     * should not use a handler after closing it.
     *
     * @throws SecurityException
     *             if a security manager determines that the caller does not
     *             have the required permission.
     */
    @Override
    public void close() {
        LogManager.getLogManager().checkAccess();
        close(true);
    }

    /**
     * Flushes any buffered output.
     */
    @Override
    public void flush() {
        if (null != this.os) {
            try {
                if (null != this.writer) {
                    this.writer.flush();
                } else {
                    this.os.flush();
                }
            } catch (Exception e) {
                // logging.16=Exception occurred while flushing the output
                // stream.
                getErrorManager().error(Messages.getString("logging.16"), //$NON-NLS-1$
                        e, ErrorManager.FLUSH_FAILURE);
            }
        }
    }

    /**
     * Accepts a logging request. The log record is formatted and written to the
     * output stream if the following three conditions are met:
     *

     *
the supplied log record has at least the required logging level;
     *
the supplied log record passes the filter associated with this
     * handler, if any;
     *
the output stream associated with this handler is not {@code null}.
     *

     * If it is the first time a log record is written out, the head string of
     * the formatter associated with this handler is written out first.
     *
     * @param record
     *            the log record to be logged.
     */
    @Override
    public synchronized void publish(LogRecord record) {
        try {
            if (this.isLoggable(record)) {
                if (this.writerNotInitialized) {
                    initializeWritter();
                }
                String msg = null;
                try {
                    msg = getFormatter().format(record);
                } catch (Exception e) {
                    // logging.17=Exception occurred while formatting the log
                    // record.
                    getErrorManager().error(Messages.getString("logging.17"), //$NON-NLS-1$
                            e, ErrorManager.FORMAT_FAILURE);
                }
                write(msg);
            }
        } catch (Exception e) {
            // logging.18=Exception occurred while logging the record.
            getErrorManager().error(Messages.getString("logging.18"), e, //$NON-NLS-1$
                    ErrorManager.GENERIC_FAILURE);
        }
    }

    /**
     * Determines whether the supplied log record needs to be logged. The
     * logging levels are checked as well as the filter. The output stream of
     * this handler is also checked. If it is {@code null}, this method returns
     * {@code false}.
     *

     * Notice : Case of no output stream will return {@code false}.
     *
     * @param record
     *            the log record to be checked.
     * @return {@code true} if {@code record} needs to be logged, {@code false}
     *         otherwise.
     */
    @Override
    public boolean isLoggable(LogRecord record) {
        if (null == record) {
            return false;
        }
        if (null != this.os && super.isLoggable(record)) {
            return true;
        }
        return false;
    }
}


text:
@echo off
%SystemDrive%\Python27\python.exe build.py %*


text:
"""
mbed SDK
Copyright (c) 2014 ARM Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from exporters import Exporter
from os.path import splitext, basename

class CoIDE(Exporter):
    NAME = 'CoIDE'
    TOOLCHAIN = 'GCC_ARM'

    TARGETS = [
        'KL25Z',
        'KL05Z',
    ]

    # seems like CoIDE currently supports only one type
    FILE_TYPES = {
        'c_sources':'1',
        'cpp_sources':'1',
        's_sources':'1'
    }

    def generate(self):
        self.resources.win_to_unix()
        source_files = []
        for r_type, n in CoIDE.FILE_TYPES.iteritems():
            for file in getattr(self.resources, r_type):
                source_files.append({
                    'name': basename(file), 'type': n, 'path': file
                })

        libraries = []
        for lib in self.resources.libraries:
            l, _ = splitext(basename(lib))
            libraries.append(l[3:])

        ctx = {
            'name': self.program_name,
            'source_files': source_files,
            'include_paths': self.resources.inc_dirs,
            'scatter_file': self.resources.linker_script,
            'library_paths': self.resources.lib_dirs,
            'object_files': self.resources.objects,
            'libraries': libraries,
            'symbols': self.toolchain.get_symbols()
        }
        target = self.target.lower()

        # Project file
        self.gen_file('coide_%s.coproj.tmpl' % target, ctx, '%s.coproj' % self.program_name)


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    Exception.h
 *
 *  @author Nanbor Wang <nanbor@cs.wustl.edu>
 */
//=============================================================================

#ifndef _ACEXML_EXCEPTION_H_
#define _ACEXML_EXCEPTION_H_

#include /**/ "ace/pre.h"
#include "ACEXML/common/ACEXML_Export.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
#pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "ACEXML/common/XML_Types.h"

/**
 * @class ACEXML_Exception
 *
 * @brief ACEXML_Exception
 *
 * ACEXML_Exception is the base class for all ACEXML related exceptions.
 * Since ACEXML currently does not support native exceptions, all
 * exceptions should be thrown thru ACEXML_Env.
 *
 * @sa ACEXML_Env
 */
class ACEXML_Export ACEXML_Exception
{
public:

  /// Destructor.
  virtual ~ACEXML_Exception (void);

  /// Throw the exception.
  virtual void _raise (void) = 0;

  /// Static narrow operation.
  static ACEXML_Exception* _downcast (ACEXML_Exception* ex);

  /// Return the exception type.  (for safe downcast.)
  virtual const ACEXML_Char *id (void) const ;

  /// Dynamically create a copy of this exception.
  virtual ACEXML_Exception *duplicate (void) const = 0;

  /// Check whether this is an exception of type specified by <name>.
  virtual int is_a (const ACEXML_Char *name);

  /// Print out exception using ACE_DEBUG.
  virtual void print (void) const = 0;

protected:
  /// Default constructor.
  ACEXML_Exception (void);

  /// All exceptions have names.  This name is used to identify the
  /// type of an exception.
  static const ACEXML_Char *exception_name_;

  /// A null string that we return when there is no exception.
  static const ACEXML_Char *null_;
};

#if defined (__ACEXML_INLINE__)
# include "ACEXML/common/Exception.inl"
#endif /* __ACEXML_INLINE__ */

#include /**/ "ace/post.h"

#endif /* _ACEXML_EXCEPTION_H_ */


text:
#ifndef SdFatUtil_h
#define SdFatUtil_h
/**
 * \file
 * Useful utility functions.
 */
#include <Arduino.h>
#ifdef __AVR__
#include <avr/pgmspace.h>
/** Store and print a string in flash memory.*/
#define PgmPrint(x) SerialPrint_P(PSTR(x))
/** Store and print a string in flash memory followed by a CR/LF.*/
#define PgmPrintln(x) SerialPrintln_P(PSTR(x))
/** Defined so doxygen works for function definitions. */
#endif
#define NOINLINE __attribute__((noinline,unused))
#define UNUSEDOK __attribute__((unused))
//------------------------------------------------------------------------------
/** Return the number of bytes currently free in RAM. */
static UNUSEDOK int FreeRam(void) {
  extern int  __bss_end;
  extern int* __brkval;
  int free_memory;
  if (reinterpret_cast<int>(__brkval) == 0) {
    // if no heap use from end of bss section
    free_memory = reinterpret_cast<int>(&free_memory)
                  - reinterpret_cast<int>(&__bss_end);
  } else {
    // use from top of stack to heap
    free_memory = reinterpret_cast<int>(&free_memory)
                  - reinterpret_cast<int>(__brkval);
  }
  return free_memory;
}
#ifdef __AVR__
//------------------------------------------------------------------------------
/**
 * %Print a string in flash memory to the serial port.
 *
 * \param[in] str Pointer to string stored in flash memory.
 */
static NOINLINE void SerialPrint_P(PGM_P str) {
  for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.write(c);
}
//------------------------------------------------------------------------------
/**
 * %Print a string in flash memory followed by a CR/LF.
 *
 * \param[in] str Pointer to string stored in flash memory.
 */
static NOINLINE void SerialPrintln_P(PGM_P str) {
  SerialPrint_P(str);
  Serial.println();
}
#endif  // __AVR__
#endif  // #define SdFatUtil_h


text:
module Deterministic
  class ProtocolBuilder

    def initialize(typevar, block)
      @typevar, @block = typevar, block
      @protocol = Class.new
    end

    def build
      instance_exec(&@block)
      @protocol
    end

    def method_missing(m, *args)
      [m, args]
    end

    Signature = Struct.new(:name, :params, :return_type, :block)

    def fn(signature, &block)
      m = signature.to_a.flatten
      name        = m[0]
      return_type = m[-1]
      params      = Hash[(m[1..-2][0] || {}).map { |k, v| [k[0], v] }]

      @protocol.instance_eval {
          define_singleton_method(name) {
            Signature.new(name, params, return_type, block)
          }
      }

      @protocol.instance_eval {
        if block
          define_method(name) { |*args|
            block.call(args)
          }
        end
      }
    end
  end

  class InstanceBuilder
    def initialize(protocol, type, block)
      @protocol, @type, @block = protocol, type, block
      @instance = Class.new(@protocol::Protocol)
    end

    def build
      @instance.class_exec(&@block)
      protocol  = @protocol::Protocol
      methods   = protocol.methods(false)
      inst_type = @type

      @instance.instance_exec {
        methods.each { |name|
          if method_defined?(name)
            meth        = instance_method(name)
            signature   = protocol.send(name)
            params      = signature.params
            expect_type = inst_type[signature.return_type]

            define_method(name) { |*args|
              args.each_with_index { |arg, i|
                name     = params.keys[i]
                arg_type = params.fetch(name)
                expect_arg_type = inst_type.fetch(arg_type)

                raise TypeError, "Expected arg #{name} to be a #{expect_arg_type}, got #<#{arg.class}: #{arg.inspect}>" unless arg.is_a? expect_arg_type
              }

              result = meth.bind(self).call(*args)
              raise TypeError, "Expected #{name}(#{args.join(', ')}) to return a #{expect_type}, got #<#{result.class}: #{result.inspect}>" unless result.is_a? expect_type
              result
            }
          end
        }
      }

      missing = methods.detect { |m| !@instance.instance_methods(false).include?(m) }

      raise NotImplementedError, "`#{missing}` has no default implementation for #{@protocol} #{@type.to_s}" unless missing.nil?

      @instance
    end
  end

module_function
  def protocol(typevar, &block)
    protocol = ProtocolBuilder.new(typevar, block).build
    p_module = block.binding.eval('self')
    p_module.const_set(:Protocol, protocol)
  end

  def instance(protocol, type, &block)
    InstanceBuilder.new(protocol, type, block).build
  end

  module Protocol
    def const_missing(c)
      c
    end
  end
end


text:
<?php

namespace Google\AdsApi\AdManager\v202211;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class createCustomFieldsResponse
{

    /**
     * @var \Google\AdsApi\AdManager\v202211\CustomField[] $rval
     */
    protected $rval = null;

    /**
     * @param \Google\AdsApi\AdManager\v202211\CustomField[] $rval
     */
    public function __construct(array $rval = null)
    {
      $this->rval = $rval;
    }

    /**
     * @return \Google\AdsApi\AdManager\v202211\CustomField[]
     */
    public function getRval()
    {
      return $this->rval;
    }

    /**
     * @param \Google\AdsApi\AdManager\v202211\CustomField[]|null $rval
     * @return \Google\AdsApi\AdManager\v202211\createCustomFieldsResponse
     */
    public function setRval(array $rval = null)
    {
      $this->rval = $rval;
      return $this;
    }

}


text:
/*********************************************************************************
* (Algebra: 2 * 2 linear equations) Design a class named LinearEquation for a    *
* 2 * 2 system of linear equations:                                              *
*                                                                                *
*  ax + by = e, cx + dy = f; x = (ed - bf) / (ad - bc) y = (af - ec) / (ad - bc) *
*                                                                                *
* The class contains:                                                            *
* ■ Private data fields a, b, c, d, e, and f.                                    *
* ■ A constructor with the arguments for a, b, c, d, e, and f.                   *
* ■ Six getter methods for a, b, c, d, e, and f.                                 *
* ■ A method named isSolvable() that returns true if ad - bc is not 0.           *
* ■ Methods getX() and getY() that return the solution for the equation.         *
*                                                                                *
* Draw the UML diagram for the class and then implement the class. Write a test  *
* program that prompts the user to enter a, b, c, d, e, and f and displays the   *
* result. If ad - bc is 0, report that "The equation has no solution." See       *
* Programming Exercise 3.3 for sample runs.                                      *
*********************************************************************************/
import java.util.Scanner;

public class Exercise_09_11 {
	/** Main method */
	public static void main(String[] args) {
		// Create a Scanner object
		Scanner input = new Scanner(System.in);

		// Prompt the user to enter a, b, c, d, e, and f
		System.out.print("Enter a, b, c, d, e, f: ");
		double a = input.nextDouble();
		double b = input.nextDouble();
		double c = input.nextDouble();
		double d = input.nextDouble();
		double e = input.nextDouble();
		double f = input.nextDouble();

		// Create a LinearEquation object
		LinearEquation linearEquation = new LinearEquation(a, b, c, d, e, f);

		// Display results
		if (linearEquation.isSolvable()) {
			System.out.println("x is " + linearEquation.getX() +
				" and y is " + linearEquation.getY());
		}
		else
			System.out.println("The equation has no solution.");
	}
}


text:
author: linpx
date: '2005-04-18 09:15:24'
layout: post
slug: springs-coming
status: publish
comments: true
title: spring's coming
wordpress_id: '347'
---

i have never been relly interested in a spring time until i came to this place
where barely nothing could be enjoyed but flowers and good seneries of spring
time.

it got to be beautiful.


text:
<?php

namespace Exylon\Fuse\Sanitizer;

use Exylon\Fuse\Support\Arr;
use Illuminate\Container\Container;
use Illuminate\Support\Str;

class Sanitizer
{

    /**
     * @var array
     */
    protected $globalRules = [];

    /**
     * @var array
     */
    protected $registeredSanitizers = [];

    /**
     * Sets the default/global sanitizer rules
     *
     * @param array $sanitizers
     */
    public function setGlobalRules(array $sanitizers)
    {
        $this->globalRules = Arr::dot($sanitizers);
    }

    /**
     * Run sanitation on an associative array data
     *
     * @param       $data
     * @param array $rules
     * @param bool  $ignoreGlobalRules
     *
     * @return array
     */
    public function sanitize($data, $rules = [], $ignoreGlobalRules = false)
    {
        $rules = Arr::dot($rules);
        $data = Arr::dot($data);
        $ignoreGlobalRules = $ignoreGlobalRules || empty($this->globalRules);

        foreach ($data as $field => $value) {

            // Global Wildcard
            if (!$ignoreGlobalRules && array_key_exists('*', $this->globalRules)) {
                $data[$field] = $this->sanitizeValue($data[$field], $this->globalRules['*']);
            }

            // Global Rules
            if (!$ignoreGlobalRules && array_key_exists($field, $this->globalRules)) {
                $data[$field] = $this->sanitizeValue($data[$field], $this->globalRules[$field]);
            }

            // Field Wildcard
            if (array_key_exists('*', $rules)) {
                $data[$field] = $this->sanitizeValue($data[$field], $rules['*']);
            }

            // Field Rules
            if (array_key_exists($field, $rules)) {
                $data[$field] = $this->sanitizeValue($data[$field], $rules[$field]);
            }
        }

        return array_dot_reverse($data);
    }

    /**
     * Run sanitation on a value
     *
     * @param mixed $value
     * @param mixed $rules
     *
     * @return mixed
     */
    public function sanitizeValue($value, $rules)
    {
        if (is_string($rules)) {
            $rules = explode('|', $rules);
        }
        $rules = \Illuminate\Support\Arr::wrap($rules);
        foreach ($rules as $rule) {
            if (is_string($rule) && Str::contains($rule, ':')) {

                list($function, $parameters, $dataType) = array_pad(explode(':', $rule), 3, null);

                $value = $this->apply(
                    $value,
                    $function,
                    Str::contains($parameters, ',') ? explode(',', $parameters) : $parameters,
                    $dataType
                );
            } else {
                $value = $this->apply($value, $rule);
            }
        }

        return $value;
    }

    protected function apply($value, $rule, $parameters = null, $dataType = null)
    {
        $parameters = \Illuminate\Support\Arr::wrap($parameters ?: []);
        $dataType = $dataType ?: 'string';

        static $allowedDataTypes = [
            'string',
            'array',
            'int',
            'float',
            'double',
            'long',
            'numeric',
            'integer'
        ];
        // Let's skip sanitation rule if it's not applicable to the data type
        if (is_string($rule) && in_array($dataType, $allowedDataTypes) && !call_user_func('is_' . $dataType, $value)) {
            return $value;
        }

        if (!empty($this->registeredSanitizers) && array_key_exists($rule, $this->registeredSanitizers)) {
            $rule = $this->registeredSanitizers[$rule];
        }

        return Container::getInstance()->call(is_object($rule) && !is_callable($rule) ? [$rule, 'sanitize'] : $rule,
            array_merge([$value], $parameters));
    }

    public function register(string $name, $callback)
    {
        $this->registeredSanitizers[$name] = $callback;
    }

}


text:
#include "EncoderImage.h"

#ifdef printMessages
#warning "            Inside EncoderImage.cpp"
#endif

edk::codecs::EncoderImage::EncoderImage()
//: edk::codecs::CodecImage()
{
    //printf("\nEncoderImage Construtor");fflush(stdout);
}

edk::codecs::EncoderImage::~EncoderImage()
{
    //printf("\nEncoderImage Destrutor");fflush(stdout);
    this->deleteEncoded();
}

//process the encoder
bool edk::codecs::EncoderImage::encode(edk::uint8* frame,edk::size2ui32 size,edk::uint8 channels,edk::uint32 quality){
    //test the frame and the size
    if(frame && size.width && size.height && quality && channels){
        return true;
    }
    return false;
}
bool edk::codecs::EncoderImage::encode(edk::uint8* frame,edk::uint32 width,edk::uint32 height,edk::uint8 channels,edk::uint32 quality){
    return this->encode(frame,edk::size2ui32(width,height),channels,quality);
}
bool edk::codecs::EncoderImage::encode(const unsigned char* frame,edk::size2ui32 size,edk::uint8 channels,edk::uint32 quality){
    return this->encode((edk::uint8*) frame,size,channels,quality);
}
bool edk::codecs::EncoderImage::encode(const unsigned char* frame,edk::uint32 width,edk::uint32 height,edk::uint8 channels,edk::uint32 quality){
    return this->encode((edk::uint8*) frame,width,height,channels,quality);
}

//process the encoder and save to a file
bool edk::codecs::EncoderImage::encodeToFile(edk::uint8* frame,edk::size2ui32 size,edk::uint8 channels,edk::uint32 quality,const edk::char8* fileName){
    return this->encodeToFile(frame,size,channels,quality,(edk::char8*) fileName);
}
bool edk::codecs::EncoderImage::encodeToFile(edk::uint8* frame,edk::size2ui32 size,edk::uint8 channels,edk::uint32 quality,edk::char8* fileName){
    //test the frame and the size
    if(frame && size.width && size.height && fileName && quality){
        bool ret = false;
        //create the file
        if(this->file.createAndOpenBinFile(fileName)){
            //process the encoder
            if(this->encode(frame,size,channels,quality)){
                if(edk::codecs::CodecImage::getEncoded() && edk::codecs::CodecImage::getEncodedSize()){
                    //write the encoded in the file
                    this->file.writeBin(this->getEncoded(),this->getEncodedSize());
                    //delete the encoded
                    this->deleteEncoded();
                    //return true
                    ret=true;
                }
            }

            //close the file
            this->file.closeFile();
        }
        return ret;
    }
    return false;
}
bool edk::codecs::EncoderImage::encodeToFile(edk::uint8* frame,edk::uint32 width,edk::uint32 height,edk::uint8 channels,edk::uint32 quality,const edk::char8* fileName){
    return this->encodeToFile(frame,width,height,channels,quality,(edk::char8*) fileName);
}
bool edk::codecs::EncoderImage::encodeToFile(edk::uint8* frame,edk::uint32 width,edk::uint32 height,edk::uint8 channels,edk::uint32 quality,edk::char8* fileName){
    return this->encodeToFile(frame,edk::size2ui32(width,height),channels,quality,fileName);
}

bool edk::codecs::EncoderImage::encodeToFile(const unsigned char* frame,edk::size2ui32 size,edk::uint8 channels,edk::uint32 quality,const edk::char8* fileName){
    return this->encodeToFile((edk::uint8*) frame,size,channels,quality,fileName);
}
bool edk::codecs::EncoderImage::encodeToFile(const unsigned char* frame,edk::size2ui32 size,edk::uint8 channels,edk::uint32 quality,edk::char8* fileName){
    return this->encodeToFile((edk::uint8*) frame,size,channels,quality,fileName);
}
bool edk::codecs::EncoderImage::encodeToFile(const unsigned char* frame,edk::uint32 width,edk::uint32 height,edk::uint8 channels,edk::uint32 quality,const edk::char8* fileName){
    return this->encodeToFile((edk::uint8*) frame,width,height,channels,quality,fileName);
}
bool edk::codecs::EncoderImage::encodeToFile(const unsigned char* frame,edk::uint32 width,edk::uint32 height,edk::uint8 channels,edk::uint32 quality,edk::char8* fileName){
    return this->encodeToFile((edk::uint8*) frame,width,height,channels,quality,fileName);
}

//return the frame encoded
edk::uint8* edk::codecs::EncoderImage::getEncoded(){
    return edk::codecs::CodecImage::getEncoded();
}
edk::uint32 edk::codecs::EncoderImage::getEncodedSize(){
    return edk::codecs::CodecImage::getEncodedSize();
}
//delete the encoded
void edk::codecs::EncoderImage::deleteEncoded(){
    edk::codecs::CodecImage::deleteEncoded();
}


text:
copyright:
  years: 2016

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen:.screen}
{:codeblock:.codeblock}

# Configurando o domínio customizado do servidor {{site.data.keyword.mobilefoundation_short}}
{: #configcustomdomain}

*Última atualização: 15 de junho de 2016*
{: .last-updated}

O {{site.data.keyword.mobilefoundation_short}} provisiona um {{site.data.keyword.mfserver_short_notm}} no {{site.data.keyword.containerlong}} como um grupo de contêiner. O grupo de contêiner será mapeado para uma URL que tem os nomes de domínio baseados na **Região** do {{site.data.keyword.Bluemix_notm}}. Também é possível configurar seu próprio domínio customizado.
{:shortdesc}

Um grupo de contêiner é criado com uma URL ou uma rota que tem os nomes de domínio padrão baseados na `Region` do {{site.data.keyword.Bluemix_notm}}.

*Tabela 1. Nomes de domínio de aplicativo baseados na
'Region' no {{site.data.keyword.Bluemix_notm}}*

  |Domínio |  Região  |
  |:----- | :----- |
  |`mybluemix.net` | Dallas, EUA  |
  |`eu-gb.mybluemix.net` | Londres, Reino Unido  |
  |`au-syd.mybluemix.net`  | Sydney, Austrália |

Para ser capaz de usar seu próprio domínio, você precisará configurar o domínio customizado executando as etapas a seguir:

1.	Crie uma instância {{site.data.keyword.mfserver_short_notm}} criando a instância de serviço {{site.data.keyword.mobilefoundation_short}} escolhendo um dos planos suportados.

+ Inclua o domínio customizado que você gostaria de usar na `Organization` do {{site.data.keyword.Bluemix_notm}}. Acesse **Gerenciar organizações > DOMÍNIOS > INCLUIR DOMÍNIO** para incluir seu próprio domínio.

+ Configure uma rota para o grupo de contêiner usar seu domínio customizado.

+ Acesse o provedor DNS de seu domínio e inclua uma entrada CNAME, que roteará o tráfego de seu domínio para a rota padrão do {{site.data.keyword.Bluemix_notm}}, em que o grupo de contêiner está em execução.

+ Se quiser configurar `https` para seu domínio customizado, faça upload do certificado SSL para seu domínio no {{site.data.keyword.Bluemix_notm}}. Para fazer isso, acesse **Gerenciar organizações > DOMÍNIOS**, selecione o domínio customizado para o qual você deseja configurar o certificado SSL, clique em **Fazer upload de certificado** para fazer upload do certificado SSL para seu domínio. Consulte [Certificados SSL e Domínios customizados do Bluemix](https://developer.ibm.com/bluemix/2014/09/28/ssl-certificates-bluemix-custom-domains/), para obter mais informações.


text:
package org.assertj.core.api;

import static org.assertj.core.error.OptionalShouldBeEmpty.shouldBeEmpty;
import static org.assertj.core.error.OptionalShouldBePresent.shouldBePresent;
import static org.assertj.core.error.OptionalShouldContain.shouldContain;

import java.util.OptionalInt;

import org.assertj.core.internal.Failures;
import org.assertj.core.internal.Integers;
import org.assertj.core.util.VisibleForTesting;

/**
 * Assertions for {@link java.util.OptionalInt}.
 *
 * @author Jean-Christophe Gay
 * @author Alexander Bischof
 * @author Grzegorz Piwowarek
 */
public abstract class AbstractOptionalIntAssert<SELF extends AbstractOptionalIntAssert<SELF>> extends
    AbstractAssert<SELF, OptionalInt> {

  @VisibleForTesting
  Integers integers = Integers.instance();

  protected AbstractOptionalIntAssert(OptionalInt actual, Class<?> selfType) {
    super(actual, selfType);
  }

  /**
   * Verifies that there is a value present in the actual {@link java.util.OptionalInt}.
   *

   * Assertion will pass :
   *
 assertThat(OptionalInt.of(10)).isPresent();

   *

   * Assertion will fail :
   *
 assertThat(OptionalInt.empty()).isPresent();

   *
   * @return this assertion object.
   * @throws AssertionError if actual value is empty.
   * @throws AssertionError if actual is null.
   */
  public SELF isPresent() {
    isNotNull();
    if (!actual.isPresent()) throwAssertionError(shouldBePresent(actual));
    return myself;
  }

  /**
   * Verifies that the actual {@link java.util.OptionalInt} is empty (alias of {@link #isEmpty()}).
   *

   * Assertion will pass :
   *
 assertThat(OptionalInt.empty()).isNotPresent();

   *
   * Assertion will fail :
   *
 assertThat(OptionalInt.of(10)).isNotPresent();

   *
   * @return this assertion object.
   */
  public SELF isNotPresent() {
    return isEmpty();
  }

  /**
   * Verifies that the actual {@link java.util.OptionalInt} is empty.
   *

   * Assertion will pass :
   *
 assertThat(OptionalInt.empty()).isEmpty();

   *

   * Assertion will fail :
   *
 assertThat(OptionalInt.of(10)).isEmpty();

   *
   * @return this assertion object.
   * @throws AssertionError if actual value is present.
   * @throws AssertionError if actual is null.
   */
  public SELF isEmpty() {
    isNotNull();
    if (actual.isPresent()) throwAssertionError(shouldBeEmpty(actual));
    return myself;
  }

  /**
   * Verifies that there is a value present in the actual {@link java.util.OptionalInt}, it's an alias of {@link #isPresent()}.
   *

   * Assertion will pass :
   *
 assertThat(OptionalInt.of(10)).isNotEmpty();

   *

   * Assertion will fail :
   *
 assertThat(OptionalInt.empty()).isNotEmpty();

   *
   * @return this assertion object.
   * @throws AssertionError if actual value is empty.
   * @throws AssertionError if actual is null.
   */
  public SELF isNotEmpty() {
    return isPresent();
  }

  /**
   * Verifies that the actual {@link java.util.OptionalInt} has the value in argument.
   *

   * Assertion will pass :
   *
 assertThat(OptionalInt.of(8)).hasValue(8);
   * assertThat(OptionalInt.of(8)).hasValue(Integer.valueOf(8));

   *

   * Assertion will fail :
   *
 assertThat(OptionalInt.empty()).hasValue(8);
   * assertThat(OptionalInt.of(7)).hasValue(8);

   *
   * @param expectedValue the expected value inside the {@link java.util.OptionalInt}.
   * @return this assertion object.
   * @throws AssertionError if actual value is empty.
   * @throws AssertionError if actual is null.
   * @throws AssertionError if actual has not the value as expected.
   */
  public SELF hasValue(int expectedValue) {
    isNotNull();
    if (!actual.isPresent()) throwAssertionError(shouldContain(expectedValue));
    if (expectedValue != actual.getAsInt())
      throw Failures.instance().failure(info, shouldContain(actual, expectedValue), actual.getAsInt(), expectedValue);
    return myself;
  }
}


text:
'use strict';

const reg = process.env.WEBPACK_DEV_SERVER === "true" ?
    require('serviceworker-webpack-plugin/lib/runtime').register()
    : register()

module.exports = reg;

function register() {
    if (!('serviceWorker' in navigator)) {
        return Promise.reject("ServiceWorker not supported")
    }
    return navigator.serviceWorker.register('service-worker.js')
}

reg.then(function (reg) {
    reg.update()
      // .then(res => console.warn("sw-update result: ", res))
      .catch(console.error)

    // updatefound is fired if service-worker.js changes.
    reg.onupdatefound = function () {
        // The updatefound event implies that reg.installing is set; see
        // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
        const installingWorker = reg.installing

        installingWorker.onstatechange = function () {
            switch (installingWorker.state) {
                case 'installed':
                    if (navigator.serviceWorker.controller) {
                        // At this point, the old content will have been purged and the fresh content will
                        // have been added to the cache.
                        // It's the perfect time to display a "New content is available; please refresh."
                        // message in the page's interface.
                        console.log('New or updated content is available.');
                    } else {
                        // At this point, everything has been precached.
                        // It's the perfect time to display a "Content is cached for offline use." message.
                        console.log('Content is now available offline!');
                    }
                    break;

                case 'redundant':
                    console.error('The installing service worker became redundant.');
                    break;
            }
        };
    };
    return reg
})

// const swScriptPath = IS_DEVELOPMENT_ENV ? "/notification-sw.js" : '/service-worker.js'
// // const swScriptPath = "/notification-sw.js"
// export default navigator.serviceWorker.register(swScriptPath)


text:
package com.auth0.jwt;

import com.auth0.jwt.exception.JWTNotBeforeException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import java.security.SignatureException;

import static org.junit.Assert.assertEquals;

public class JWTVerifierTest {

    private static final Base64 decoder = new Base64(true);;
    public static final java.lang.String SECRET_KEY = "such secret";

    @Test(expected = IllegalArgumentException.class)
    public void constructorShouldFailOnEmptySecret() {
        new JWTVerifier("");
    }

    @Test(expected = IllegalStateException.class)
    public void shouldFailOn1Segments() throws Exception {
        new JWTVerifier("such secret").verify("crypto");
    }

    @Test(expected = IllegalStateException.class)
    public void shouldFailOn2Segments() throws Exception {
        new JWTVerifier("such secret").verify("much.crypto");
    }

    @Test(expected = IllegalStateException.class)
    public void shouldFailOn4Segments() throws Exception {
        new JWTVerifier("such secret").verify("much.crypto.so.token");
    }

    @Test(expected = IllegalStateException.class)
    public void shouldFailOnEmptyStringToken() throws Exception {
        new JWTVerifier("such secret").verify("");
    }

    @Test(expected = IllegalStateException.class)
    public void shouldFailOnNullToken() throws Exception {
        new JWTVerifier("such secret").verify(null);
    }

    @Test(expected = IllegalStateException.class)
    public void shouldFailIfAlgorithmIsNotSetOnToken() throws Exception {
        new JWTVerifier("such secret").getAlgorithm(JsonNodeFactory.instance.objectNode());
    }

    @Test(expected = IllegalStateException.class)
    public void shouldFailIfAlgorithmIsNotSupported() throws Exception {
        new JWTVerifier("such secret").getAlgorithm(createSingletonJSONNode("alg", "doge-crypt"));
    }

    @Test
    public void shouldWorkIfAlgorithmIsSupported() throws Exception {
       new JWTVerifier("such secret").getAlgorithm(createSingletonJSONNode("alg", "HS256"));
    }

    @Test(expected = SignatureException.class)
    public void shouldFailOnInvalidSignature() throws Exception {
        final String jws = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9" +
                "." +
                "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt" +
                "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ" +
                "." +
                "suchsignature_plzvalidate_zomgtokens";
        String secret = "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow";
        new JWTVerifier(secret, "audience").verifySignature(jws.split("\\."), "HmacSHA256");
    }

    @Test
    public void shouldVerifySignature() throws Exception {
        final String jws = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9" +
                "." +
                "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt" +
                "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ" +
                "." +
                "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        byte[] secret = decoder.decodeBase64("AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow");
        new JWTVerifier(secret, "audience")
                .verifySignature(jws.split("\\."), "HmacSHA256");
    }

    @Test(expected = JWTExpiredException.class)
    public void shouldFailWhenExpired1SecondAgo() throws Exception {
        new JWTVerifier("such secret").verifyExpiration(
                createSingletonJSONNode("exp", Long.toString(System.currentTimeMillis() / 1000L - 1L)));
    }

    @Test
    public void shouldVerifyExpiration() throws Exception {
        new JWTVerifier("such secret").verifyExpiration(
                createSingletonJSONNode("exp", Long.toString(System.currentTimeMillis() / 1000L + 50L)));
    }

    @Test(expected = JWTNotBeforeException.class)
    public void shouldFailWhen1SecondBeforeNotBefore() throws Exception {
        new JWTVerifier(SECRET_KEY).verifyNotBefore(
                createSingletonJSONNode(Claim.NOTBEFORE.getValue(), Long.toString(System.currentTimeMillis() / 1000L + 1L)));
    }

    @Test
    public void shouldVerifyNotBefore() throws Exception {
        new JWTVerifier(SECRET_KEY).verifyNotBefore(
                createSingletonJSONNode(Claim.NOTBEFORE.getValue(), Long.toString(System.currentTimeMillis() / 1000L - 50L)));
    }

    @Test
    public void shouldVerifyIssuer() throws Exception {
        new JWTVerifier("such secret", "amaze audience", "very issuer")
                .verifyIssuer(createSingletonJSONNode("iss", "very issuer"));
    }

    @Test(expected = JWTIssuerException.class)
    public void shouldFailIssuer() throws Exception {
        new JWTVerifier("such secret", "amaze audience", "very issuer")
                .verifyIssuer(createSingletonJSONNode("iss", "wow"));
    }

    @Test
    public void shouldVerifyIssuerWhenNotFoundInClaimsSet() throws Exception {
        new JWTVerifier("such secret", "amaze audience", "very issuer")
                .verifyIssuer(JsonNodeFactory.instance.objectNode());
    }

    @Test
    public void shouldVerifyAudience() throws Exception {
        new JWTVerifier("such secret", "amaze audience")
                .verifyAudience(createSingletonJSONNode("aud", "amaze audience"));
    }

    @Test(expected = JWTAudienceException.class)
    public void shouldFailAudience() throws Exception {
        new JWTVerifier("such secret", "amaze audience")
                .verifyAudience(createSingletonJSONNode("aud", "wow"));
    }

    @Test
    public void shouldVerifyAudienceWhenNotFoundInClaimsSet() throws Exception {
        new JWTVerifier("such secret", "amaze audience")
                .verifyAudience(JsonNodeFactory.instance.objectNode());
    }

    @Test
    public void shouldVerifyNullAudience() throws Exception {
        new JWTVerifier("such secret")
                .verifyAudience(createSingletonJSONNode("aud", "wow"));
    }

    @Test
    public void shouldVerifyArrayAudience() throws Exception {
        new JWTVerifier("such secret", "amaze audience")
                .verifyAudience(createSingletonJSONNode("aud",
                        new ObjectMapper().readValue("[ \"foo\", \"amaze audience\" ]", ArrayNode.class)));
    }

    @Test(expected = JWTAudienceException.class)
    public void shouldFailArrayAudience() throws Exception {
        new JWTVerifier("such secret", "amaze audience")
                .verifyAudience(createSingletonJSONNode("aud",
                        new ObjectMapper().readValue("[ \"foo\" ]", ArrayNode.class)));
    }

    @Test
    public void decodeAndParse() throws Exception {
        final Base64 encoder = new Base64(true);
        final String encodedJSON = new String(encoder.encode("{\"some\": \"json\", \"number\": 123}".getBytes()));
        final JWTVerifier jwtVerifier = new JWTVerifier("secret", "audience");

        final JsonNode decodedJSON = jwtVerifier.decodeAndParse(encodedJSON);

        assertEquals("json", decodedJSON.get("some").asText());
        assertEquals(null, decodedJSON.get("unexisting_property"));
        assertEquals("123", decodedJSON.get("number").asText());
    }

    public static JsonNode createSingletonJSONNode(String key, String value) {
        final ObjectNode jsonNodes = JsonNodeFactory.instance.objectNode();
        jsonNodes.put(key, value);
        return jsonNodes;
    }

    public static JsonNode createSingletonJSONNode(String key, JsonNode value) {
        final ObjectNode jsonNodes = JsonNodeFactory.instance.objectNode();
        jsonNodes.put(key, value);
        return jsonNodes;
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>This shows some plugins | My Python Project</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,600,600i%7CSource+Code+Pro:400,400i,600" />
  <link rel="stylesheet" href="m-dark+documentation.compiled.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      My Python Project

          This shows some plugins

This project is on GitHub and

The
tables

render
nicer now.

Yup!

See, glDrawElements() is the grandpa of vkCmdDraw(). But
not everything is as it "seems" to be
— however the typography makes that bearable. Python bindings for
Corrade::Containers and Magnum are nice too:

>>> from magnum import *
>>> a = Vector3(1.0, 2.0, 3.0)
>>> a.dot()
14.0

Images!

Image in a subdir

~~~ Custom plugins! ~~~


text:
var express = require('express');

//Recuperation de la variable de config
var config = require('./config/config');

var app = express();
var swig=require('swig');
var path = require('path');
var bodyParser = require('body-parser');
var multer = require('multer');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var ldap = require('./modules/ldap');

var coherenceView = require('./modules/Client/View/coherenceView');

// Monkey patch pour controler les format et params des requetes
require('./response');

app.use(bodyParser.json({limit: '50mb'})); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' })); // for parsing application/x-www-form-urlencoded
app.use(multer().single('multiInputFileName')); // for parsing multipart/form-data

// Permet d'acceder depuis la page aux ressources du repertoire public
app.use(express.static(__dirname + '/public'));

// Allow parsing cookies from request headers
app.use(cookieParser());
// Session management
app.sessionStore=new session.MemoryStore({ reapInterval: 60000 * 10 });
app.use(session({
	// Private crypting key
	"secret": config.session.secret,
	// Internal session data storage engine, this is the default engine embedded with connect.
	"store": this.sessionStore,
	resave: true,
    saveUninitialized: true,
    cookie:{maxAge:3600000} // 1000 = 1 secondes => 3600000 = 1heure
}));

// view engine setup
// utilisation du moteur de swig pour les .html
app.engine('html', swig.renderFile);
// utiliser le moteur de template pour les .html
app.set('view engine', 'html');
// dossier des vues
app.set('views', path.join(__dirname, 'views'));

var server = require('http').Server(app);

var io = require('socket.io')(server);
server.listen(config.port);

/*********************************************************************/
/*************************** LAUNCHER ********************************/
/*********************************************************************/

// Lancement de la récuperation périodique des sources
require('./modules/SourcesLauncher/launcher');
// Lancement de la récuperation périodique des cohérences
require('./modules/ConsistenciesLauncher/launcher');

/*********************************************************************/
/**************************** ROUTER *********************************/
/*********************************************************************/

var defaultOnglet='coherence';

var renderOnglet=function(req,res,onglet){
	// On verifie si le user c'est déjà connecté
	if (req.session.username || config.debug) {
		res.render("onglet/"+onglet,{server:config.web.url,username:req.session.username,siteName:config.siteName}, function(err, html) {
			if(!err)
				res.send(html);
			else
				res.render("onglet/"+defaultOnglet,{server:config.web.url,username:req.session.username,siteName:config.siteName});
		});
	} else {
		res.redirect("login");
	}
}

app.get('/', function (req, res, next) {
	res.redirect("/onglet/"+defaultOnglet);
});

app.param("onglet",function(req, res, next, onglet){
	renderOnglet(req, res, onglet);
});

app.get('/onglet/:onglet', function (req, res, next) {});
app.get('/onglet', function (req, res, next) {
	res.redirect("/onglet/"+defaultOnglet);
});

// Affichage de la page de login
app.get("/login", function (req, res) {
	// Show form, default value = current username
	res.render("login", { "login": req.session.username, "error": null, "version" : config.version });
});

// Verification du login et pass
app.post("/login", function (req, res) {
	var options = { "login": req.body.login, "error": null };
	if (!req.body.login) {
		options.error = "Login OPS manquant!";
		res.render("login", options);
	} else if (!req.body.pass) {
		options.error = "Mot de passe manquant!";
		res.render("login", options);
	} else if (req.body.login == req.session.username) {
		// User has not changed username, accept it as-is
	    res.redirect("/");
	} else {
		ldap.connect(req.body.login,req.body.pass,function(goodConnect){
			if(goodConnect){
				req.session.username = req.body.login;
		    	res.redirect("/");
			}else{
				options.error = "Mauvais login/mot de passe!";
				res.render("login", options);
		    }
		});
	}
});

io.sockets.on('connection', function(client) {
	console.log('connecter');

	client.on("loadOngletListener",function(onglet){
		switch(onglet){
			case "coherence" : coherenceView.initialize(client,io.sockets); break;
		}
	});
});


text:
const double MainWindow::solMassOfEarth = 3.00316726157558694887e-6;

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow),
        translator(new QTranslator()),
        timer(new QTimer()),
        progressBar(new QProgressBar()),
        statusLabel(new QLabel())
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::Window | Qt::MSWindowsFixedSizeDialogHint);
    ui->doubleSpinBox_maxInclination->setSuffix("°");
    ui->doubleSpinBox_totalMass->setSuffix(" M⊙");
    connect(ui->radioButton_earthMass, &QRadioButton::toggled,
            [=](bool checked) {
                if (checked) {
                    ui->doubleSpinBox_totalMass->setValue(
                            ui->doubleSpinBox_totalMass->value() / solMassOfEarth);
                    ui->doubleSpinBox_totalMass->setSuffix(" M⊕");
                }
                else {
                    ui->doubleSpinBox_totalMass->setValue(
                            ui->doubleSpinBox_totalMass->value() * solMassOfEarth);
                    ui->doubleSpinBox_totalMass->setSuffix(" M⊙");
                }
            });
    ui->pushButton_resetEpoch->setIcon(QIcon(QPixmap(":/images/reset.png")));
    ui->pushButton_resetEpoch->setIconSize(QSize(15, 15));

    mapSettingsPreset.insert("Vulcanoids", Settings::Preset::Vulcanoids);
    mapSettingsPreset.insert("Oort Cloud", Settings::Preset::OortCloud);
    mapSettingsPreset.insert("Toliman A Comets", Settings::Preset::TolimanAComets);
    mapSettingsPreset.insert("eBelt-EM", Settings::Preset::eBelt_EM);
    for (auto k : mapSettingsPreset.keys()) {
        ui->menu_loadPreset->addAction(new QAction(k, this));
    }

    connect(ui->menu_loadPreset, SIGNAL(triggered(QAction * )), this, SLOT(menuClicked(QAction * )));

    connect(ui->action_Credits, &QAction::triggered, [=]() {
        QMessageBox::about(this, tr("Credits"), QString("
JackDole - %1
"
                                                                "
FaceDeer, quarior14, JackDole - %2</p").arg(
                tr("original Batch version"), tr("Python version and enhancements")));
    });

    auto fr = QLocale(QLocale::French).nativeLanguageName();
    fr = fr.left(1).toUpper() + fr.mid(1);
    ui->action_french->setText(fr);
    connect(ui->action_french, &QAction::triggered, [=]() {
        if (translator->load("lang_fr", ":/i18n")) {
            qApp->installTranslator(translator);
        }
    });
    auto de = QLocale(QLocale::German).nativeLanguageName();
    de = de.left(1).toUpper() + de.mid(1);
    ui->action_german->setText(de);
    connect(ui->action_german, &QAction::triggered, [=]() {
        if (translator->load("lang_de", ":/i18n")) {
            qApp->installTranslator(translator);
        }
    });
    ui->action_english->setText("English");
    connect(ui->action_english, &QAction::triggered, [=]() {
        if (translator->load("lang_en", ":/i18n")) {
            qApp->installTranslator(translator);
        }
    });

    mapReferencePlane.insert("Ecliptic", Orbit::ReferencePlane::Ecliptic);
    mapReferencePlane.insert("Equator", Orbit::ReferencePlane::Equator);
    mapReferencePlane.insert("Extrasolar", Orbit::ReferencePlane::Extrasolar);
    ui->comboBox_referencePlane->addItems(QStringList(mapReferencePlane.keys()));

    mapObjectType.insert(tr("Asteroid"), BaseAsteroid::ObjectType::Asteroid);
    mapObjectType.insert(tr("Comet"), BaseAsteroid::ObjectType::Comet);
    ui->comboBox_objectType->addItems(QStringList(mapObjectType.keys()));

    Settings settings(Settings::Preset::Vulcanoids);
    loadPreset(settings);

    auto color = QApplication::palette().color(QPalette::Mid);
    this->statusBar()->setStyleSheet(
            "QStatusBar {border-top: 1px solid " + color.name() + ";}"
                    "QStatusBar QProgressBar { margin-right: 2px;}"
                    "QStatusBar QLabel { margin-left: 1px;} "
    );
    this->statusBar()->addPermanentWidget(statusLabel, 1);
    this->statusBar()->addPermanentWidget(progressBar, 2);
    progressBar->setVisible(false);
    progressBar->setMaximumHeight(15);
    progressBar->setTextVisible(false);
    progressBar->setValue(0);
    progressBar->setMinimum(0);
    progressBar->setMaximum(100);
    statusLabel->setText(tr("Ready"));

    connect(ui->pushButton_generate, SIGNAL(clicked()), this, SLOT(generate()));
    connect(ui->pushButton_resetEpoch, SIGNAL(clicked()), this, SLOT(resetEpoch()));
    timer->setInterval(10);
    timer->setTimerType(Qt::CoarseTimer);
    connect(timer, SIGNAL(timeout()), this, SLOT(check()));

    auto locale = QLocale::system().name().left(2);
    if (translator->load("lang_" + locale, ":/i18n")) {
        qApp->installTranslator(translator);
    }else if (translator->load("lang_en", ":/i18n")) {
        qApp->installTranslator(translator);
    }
}

void MainWindow::loadPreset(const Settings& settings)
{
    ui->comboBox_objectType->setCurrentIndex(mapObjectType.keys().indexOf(mapObjectType.key(settings.objectType)));
    ui->lineEdit_beltName->setText(QString::fromStdString(settings.asterName));
    ui->lineEdit_beltCenter->setText(QString::fromStdString(settings.beltCenter));
    ui->checkBox_barycenter->setChecked(settings.barycenter);
    ui->radioButton_solarMass->setChecked(true);
    ui->doubleSpinBox_totalMass->setValue(settings.totalMass);
    ui->spinBox_number->setValue(settings.number);
    ui->doubleSpinBox_innerRadius->setValue(settings.innerRadius);
    ui->doubleSpinBox_outerRadius->setValue(settings.outerRadius);
    ui->doubleSpinBox_minRadius->setValue(settings.minRadiusOfAster);
    ui->doubleSpinBox_maxRadius->setValue(settings.maxRadiusOfAster);
    ui->doubleSpinBox_minEccentricity->setValue(settings.minEccentricity);
    ui->doubleSpinBox_maxEccentricity->setValue(settings.maxEccentricity);
    ui->doubleSpinBox_maxInclination->setValue(settings.maxInclination);
    ui->comboBox_referencePlane->setCurrentIndex(
            mapReferencePlane.keys().indexOf(mapReferencePlane.key(settings.referencePlane)));
    ui->doubleSpinBox_epoch->setValue(settings.epoch);
}

void MainWindow::resetEpoch()
{
    ui->doubleSpinBox_epoch->setValue(2457395.5);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete translator;
    delete progressBar;
    delete statusLabel;
    delete timer;
}

void MainWindow::generate()
{
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::AnyFile);
    dialog.setNameFilter(tr("SC file (*.sc)"));
    dialog.setDefaultSuffix("sc");
    dialog.setAcceptMode(QFileDialog::AcceptMode::AcceptSave);
    QString filename;
    if (dialog.exec())
        filename = dialog.selectedFiles().first();
    if (filename != Q_NULLPTR) {
        ui->pushButton_generate->setDisabled(true);
        ui->pushButton_generate->setEnabled(false);
        Settings settings;
        settings.objectType = mapObjectType.value(ui->comboBox_objectType->currentText());
        settings.asterName = ui->lineEdit_beltName->text().toStdString();
        settings.beltCenter = ui->lineEdit_beltCenter->text().toStdString();
        settings.barycenter = ui->checkBox_barycenter->isChecked();
        settings.totalMass = ui->doubleSpinBox_totalMass->value();
        if (ui->radioButton_earthMass->isChecked())
            settings.totalMass *= MainWindow::solMassOfEarth;
        settings.number = static_cast<unsigned int>(ui->spinBox_number->value());
        settings.innerRadius = ui->doubleSpinBox_innerRadius->value();
        settings.outerRadius = ui->doubleSpinBox_outerRadius->value();
        settings.maxRadiusOfAster = ui->doubleSpinBox_maxRadius->value();
        settings.minRadiusOfAster = ui->doubleSpinBox_minRadius->value();
        settings.maxEccentricity = ui->doubleSpinBox_maxEccentricity->value();
        settings.minEccentricity = ui->doubleSpinBox_minEccentricity->value();
        settings.maxInclination = ui->doubleSpinBox_maxInclination->value();
        settings.referencePlane = mapReferencePlane.value(ui->comboBox_referencePlane->currentText());
        settings.epoch = ui->doubleSpinBox_epoch->value();
        done = false;
        generated = false;
        timer->start();
        statusLabel->setText(tr("Generating"));
        progressBar->setValue(0);
        progressBar->setVisible(true);
        progress = 0;
        worker = std::thread([&](Settings s, const std::string& file) {
            Generator generator(s);
            generator.generate(progress);
            generated = true;
            generator.save(file, progress);
            done = true;
        }, settings, filename.toStdString());
    }
}

void MainWindow::check()
{
    progressBar->setValue(progress);
    if (done) {
        if (worker.joinable())
            worker.join();
        timer->stop();
        statusLabel->setText(tr("Ready"));
        progressBar->setVisible(false);
        ui->pushButton_generate->setEnabled(true);
        ui->pushButton_generate->setDisabled(false);
    } else if (generated) {
        generated = false;
        statusLabel->setText(tr("Saving"));
    }
}

void MainWindow::menuClicked(QAction *action)
{
    loadPreset(Settings(mapSettingsPreset.value(action->text())));
}

void MainWindow::changeEvent(QEvent *event)
{
    if (event->type() == QEvent::LanguageChange) {
        ui->retranslateUi(this);
    }
    QWidget::changeEvent(event);
}


text:
import re

import logging
logger = logging.getLogger(__name__)

import util

TAVERN = 0
AIR = -1
WALL = -2

PLAYER1 = 1
PLAYER2 = 2
PLAYER3 = 3
PLAYER4 = 4

class HeroTile(object):
    def __init__(self, id):
        self.id = id

class MineTile(object):
    def __init__(self, heroId = None):
        self.heroId = heroId

class Game(object):
    """A model of the entire game state.  This is instantiated once per game.
    """
    def __init__(self, state):
        self.state = state
        self.board = Board(state['game']['board'])
        self.heroes = [Hero(state['game']['heroes'][i]) for i in range(len(state['game']['heroes']))]
        self.me = Hero(state['hero'])
        self.my_intpos = self.me.pos['x'], self.me.pos['y']
        self.mines_locs = {}
        self.heroes_locs = {}
        self.taverns_locs = set([])
        self.me = Hero(state['hero'])
        self.my_intpos = self.me.pos['x'], self.me.pos['y']
        for row in range(len(self.board.tiles)):
            for col in range(len(self.board.tiles[row])):
                obj = self.board.tiles[row][col]
                if isinstance(obj, MineTile):
                    self.mines_locs[(row, col)] = obj.heroId
                elif isinstance(obj, HeroTile):
                    self.heroes_locs[(row, col)] = obj.id
                elif (obj == TAVERN):
                    self.taverns_locs.add((row, col))

class Board(object):
    def __parseTile(self, str):
        if (str == '  '):
            return AIR
        if (str == '##'):
            return WALL
        if (str == '[]'):
            return TAVERN
        match = re.match('\$([-0-9])', str)
        if (match):
            return MineTile(match.group(1))
        match = re.match('\@([0-9])', str)
        if (match):
            return HeroTile(match.group(1))

    def __parseTiles(self, tiles):
        vector = [tiles[i:i+2] for i in range(0, len(tiles), 2)]
        matrix = [vector[i:i+self.size] for i in range(0, len(vector), self.size)]

        return [[self.__parseTile(x) for x in xs] for xs in matrix]

    def __init__(self, board):
        self.size = board['size']
        self.tiles = self.__parseTiles(board['tiles'])

    def is_passable(self, loc):
        'true if can walk through'
        x, y = loc
        if (x > self.size-1 or x < 0 or
            y > self.size-1 or y < 0): return False
        pos = self.tiles[x][y]
        return (pos != WALL) or (pos != TAVERN) or not isinstance(pos, MineTile)

    def is_wall(self, loc):
        'true if loc is wall'
        x, y = loc
        pos = self.tiles[x][y]
        return pos == WALL

    def is_tavern(self, loc):
        'true if loc is tavern'
        x, y = loc
        pos = self.tiles[x][y]
        return pos == TAVERN

    def is_mine(self, loc):
        'true if loc is mine'
        x, y = loc
        pos = self.tiles[x][y]
        return isinstance(pos, MineTile)

    def can_step_to(self, loc):
        """" true if can move in this direction

        This differs from is_passable because it returns True for taverns and mines,
        because stepping to these is legal, even though the hero doesn't move.
        """
        x, y = loc
        return self.is_passable(loc) or self.is_tavern(loc) or self.is_mine(loc)

    def is_wall(self, loc):
        'true if loc is wall'
        x, y = loc
        pos = self.tiles[x][y]
        return pos == WALL

    def is_tavern(self, loc):
        'true if loc is tavern'
        x, y = loc
        pos = self.tiles[x][y]
        return pos == TAVERN

    def is_mine(self, loc):
        'true if loc is mine'
        x, y = loc
        pos = self.tiles[x][y]
        return isinstance(pos, MineTile)

class Hero(object):
    def __init__(self, hero):
        if hero['crashed'] == 'true':
            logger.fatal("Hero crashed.")
        self.heroId = hero['id']
        self.name = hero['name']
        self.pos = hero['pos']
        self.life = hero['life']
        self.gold = hero['gold']