text:
<?php

class Zip {

	// for creating or adding files
	protected $lib;				// which library to use
	protected $org_files;       // an array of the files or strings to be zipped
	protected $new_file_path;	// the path to which the zip will be created
	protected $new_file_name;	// file name

	// for extracting files
	protected $extr_file;		// the file to be extracted
	protected $extr_dirc;		// the target directory which will hold the extarcted files

	public function __construct(){
		$this->lib = 0;
		$this->extr_file = 0;
		$this->new_file_path = 0;
		$this->org_files = array();
	}

	/**=========================================================================
	 *
	 * ZIP -> ZIP START
	 * -------------------------------------------------------------------------
	 * # Description:   When creating (or adding files to) a zip file
	 *					this method will initilize the process
	 *					by taking the zip file path and deceding
	 *					which library to use.
	 *					--------------------------------------------------------
	 *					Note: This method doesn't interact in anyway with the
	 *					zip library.  It just saves variables and decides which
	 *					library to use.
	 * -------------------------------------------------------------------------
	 * # params:        $file_path	<string>	.zip file name.
	 * -------------------------------------------------------------------------
	 * # return:		VOID
	 * -------------------------------------------------------------------------
	**/

	public function zip_start($file_path) {

		// save the new file path
		$this->new_file_path = $file_path;

		// Some php installtions doesn't have the ZipArchive
		// So in this case we'll use another lib called PclZip
		if(class_exists("ZipArchive")) $this->lib = 1;
		else $this->lib = 2;

	}

	/**=========================================================================
	 *
	 * ZIP -> ZIP ADD
	 * -------------------------------------------------------------------------
	 * # Description:   When creating (or adding files to) a zip file
	 *					this method will add a file(s) path to the files array.
	 *					--------------------------------------------------------
	 *					Note: This method doesn't interact in anyway with the
	 *					zip library.  It just adds file to the array variable.
	 *					--------------------------------------------------------
	 *					Note: in case of a directory this method will pass the
	 *					directory path to a private method that will do the
	 *					heavy lifting.
	 * -------------------------------------------------------------------------
	 * # params:        $in		<string>	file path
	 *							<string>	directory path
	 *							<string>	file paths and directories delimited
	 *										by ",".
	 *							<array>		array of file and directory paths
	 * -------------------------------------------------------------------------
	 * # return:		0:	you have to call zip_start before this.
	 *					1:	success.
	 * -------------------------------------------------------------------------
	**/

	public function zip_add($in){

		// just to make sure.. if the user haven't called the earlier metho
		if($this->lib === 0 || $this->new_file_path === 0) return 0;

		// passing a string => check if it's files delimited by ","
		if(is_string($in)) if(strpos($in,",") !== false) $in = explode(",",$in);

		// then check if it exists => either push single file
		// or push whole directory.
		// pushing whole directory done through a private method of this class.
		if(is_string($in)){
			if(file_exists($in)) {
				if(!is_dir($in)) array_push($this->org_files,$in);
				else $this->push_whole_dir($in);
			}
		}

		// passing an array => recursively call this same method for every value
		else foreach($in as $value){
			$this->zip_add($value);
		}

		return 1;

	}

	/**=========================================================================
	 *
	 * ZIP -> ZIP END
	 * -------------------------------------------------------------------------
	 * # Description:   When creating (or adding files to) a zip file
	 *					this method is what actually going to create the zip
	 *					file, using the variables registered by previously
	 *					called methods
	 * -------------------------------------------------------------------------
	 * # params:        NONE
	 * -------------------------------------------------------------------------
	 * # return:		-4: After doing the zippig operations, the file size
	 *						is 0 bytes!
	 *					-3:	After doing the zipping operations, the file doesn't
	 *						seem to exist.
	 *					-2:	After adding the files, the files that has been
	 *						added isn't equal to the files that were supposed
	 *						to be added.
	 *					-1:	Couldn't open zip file, permission denied or zlib
	 *						wasn't found.
	 *					00:	Zip_start and zip_add haven't been called yet!
	 *					+1:	success
	 * -------------------------------------------------------------------------
	**/

	public function zip_end() {

		// just to make sure.. if the user haven't called the earlier method
		if($this->lib === 0 || $this->new_file_path === 0) return 0;

		// using zipArchive class
		if($this->lib === 1) {
			$lib = new ZipArchive();
			if(!$lib->open($this->new_file_path,ZIPARCHIVE::CREATE)) return -1;

			$count_before = $lib->numFiles;

			// add each file
			foreach ($this->org_files as $org_file_path) {
				// get file name from the path
				$name = substr($org_file_path,strrpos($org_file_path,"/")+1);
				// add the file to the archive
				$lib->addFile($org_file_path,$name);
			}

			$count_after = $lib->numFiles;

			// check number of files now in the archive
			if(($count_after - $count_before) < count($this->org_files)) return -2;
			// close the archive
			$lib->close();
		}

		// using PclZip
		if($this->lib === 2) {
			// require the lib
			require_once "inc/pclzip.lib.php";
			if(!$lib = new PclZip($this->new_file_path)) return -1;
			$count_before = count($lib->listContent());
			// add them
			$lib->add($this->org_files,PCLZIP_OPT_REMOVE_ALL_PATH);
			// check number of files now in the archive
			$count_after = count($lib->listContent());
			if(($count_after - $count_before) < count($this->org_files)) return -2;
		}

		var_dump(file_exists($this->new_file_path));

		if(!file_exists($this->new_file_path)) return -3;
		if(filesize($this->new_file_path) === 0) return -4;

		// empty the array
		$this->org_files = array();

		return 1;
	}

	/**=========================================================================
	 *
	 * ZIP -> ZIP FILES
	 * -------------------------------------------------------------------------
	 * # Description:   Just a wrapper around the three functions above for
	 *					one-line style coding
	 * -------------------------------------------------------------------------
	 * # params:        $files	<string>	file path
	 *							<string>	directory path
	 *							<string>	file paths and directories delimited
	 *										by ",".
	 *							<array>		array of file and directory paths
	 *					--------------------------------------------------------
	 *					$to		<string>	zip file name.
	 * -------------------------------------------------------------------------
	 * # return:		SAME AS zip_end()
	 * -------------------------------------------------------------------------
	**/

	public function zip_files($files,$to) {

		$this->zip_start($to);
		$this->zip_add($files);
		return $this->zip_end();

	}

	/**=========================================================================
	 *
	 * ZIP -> UNZIP FILE
	 * -------------------------------------------------------------------------
	 * # Description:   Unzipping files is either initilized by this method or
	 *					done completely with this method, depending on the
	 *					second parameter.
	 * -------------------------------------------------------------------------
	 * # params:        $file_path		<string>	zip file path
	 *					--------------------------------------------------------
	 *					$target_dir		<string>	target directory to which
	 *												the contents of the zip
	 *												file will be extract to
	 * -------------------------------------------------------------------------
	 * # return:		00: file doesn't exist
	 *					-1: file type isn't zip
	 *					+1: success
	 * -------------------------------------------------------------------------
	**/

	public function unzip_file($file_path,$target_dir=NULL) {

		// if it doesn't exist
		if(!file_exists($file_path)) return 0;

		// check mimetype
		$_FILEINFO = finfo_open(FILEINFO_MIME_TYPE);
		$file_mime_type = finfo_file($_FILEINFO, $file_path);
		if(!array_search($file_mime_type,array(
			'application/x-zip',
			'application/zip',
			'application/x-zip-compressed',
			'application/s-compressed',
			'multipart/x-zip')
		)) return -1;

		$this->extr_file = $file_path;

		if(class_exists("ZipArchive")) $this->lib = 1;
		else $this->lib = 2;

		if($target_dir !== NULL) return $this->unzip_to($target_dir);
		else return true;

	}

	/**=========================================================================
	 *
	 * ZIP -> UNZIP TO
	 * -------------------------------------------------------------------------
	 * # Description:   In multi-line style coding this method will be used
	 *					for unzipping
	 * -------------------------------------------------------------------------
	 * # params:        $target_dir		<string>	target directory to which
	 *												the contents of the zip
	 *												file will be extract to
	 * -------------------------------------------------------------------------
	 * # return:		-2:	unzip_file hasn't been called
	 *					-3: target directory exists as a file not a directory
	 *					-4: directory not found, and unable to create it
	 *					-5:	unable to open the zip file
	 *					-6: unable to extract files
	 * -------------------------------------------------------------------------
	**/

	public function unzip_to($target_dir) {

		// validations -- start //
		if($this->lib === 0 && $this->extr_file === 0) return -2;
		// it exists, but it's not a directory
		if(file_exists($target_dir) && (!is_dir($target_dir))) return -3;
		// it doesn't exist
		if(!file_exists($target_dir)) if(!mkdir($target_dir)) return -4;
		// validations -- end //

		$this->extr_dirc = $target_dir;

		// extract using ZipArchive
		if($this->lib === 1) {
			$lib = new ZipArchive;
			if(!$lib->open($this->extr_file)) return -5;
			if(!$lib->extractTo($this->extr_dirc)) return -6;
			$lib->close();
		}

		// extarct using PclZip
		if($this->lib === 2) {
			require_once "inc/pclzip.lib.php";
			$lib = new PclZip($this->extr_file);
			if(!$lib->extract(PCLZIP_OPT_PATH,$this->extr_dirc)) return -6;
		}

		return 1;

	}

	/**=========================================================================
	 *
	 * ZIP -> dir_to_assoc_arr
	 * -------------------------------------------------------------------------
	 * # Description:   When dealing with directories being added to the zip.
	 *					This method is useful in converting a whole directory
	 *					and subdirectories into an associative array with the
	 *					file names.
	 *
	 * -------------------------------------------------------------------------
	 * # params:        $dir		<string>	target directory.
	 * -------------------------------------------------------------------------
	 * # return:		Associate array
	 * -------------------------------------------------------------------------
	**/

	private function dir_to_assoc_arr(DirectoryIterator $dir) {
		$data = array();
		foreach ($dir as $node) {
			if ( $node->isDir() && !$node->isDot() ) {
				$data[$node->getFilename()] = $this->dir_to_assoc_arr(new DirectoryIterator($node->getPathname()));
			} else if( $node->isFile() ) {
				$data[] = $node->getFilename();
			}
		}
		return $data;
	}

	/**=========================================================================
	 *
	 * ZIP -> push_whole_dir
	 * -------------------------------------------------------------------------
	 * # Description:   When dealing with directories being added to the zip.
	 *					This method will call the one above (dir_to_assoc_arr)
	 *					to convert the directory to an associative array, then
	 *					convert this associative array to a plain array on
	 *					which each value is a path of the file.
	 *					--------------------------------------------------------
	 *					KNOWN LIMITS: since the array will be plain, the files
	 *					of the directory will be added to the zip plainly,
	 *					meaning the zip file will not have any directory
	 *					even if the original directory from which the files are
	 *					taken have sub directories.
	 * -------------------------------------------------------------------------
	 * # params:        $dir	<string>	target directory.
	 * -------------------------------------------------------------------------
	 * # return:		VOID
	 * -------------------------------------------------------------------------
	**/

	private function push_whole_dir($dir){
		$dir_array = $this->dir_to_assoc_arr(new DirectoryIterator($dir));
		foreach($dir_array as $key => $value) {
			if(!is_array($value)) array_push($this->org_files,$this->path($dir,$value));
			else {
				$this->push_whole_dir($this->path($dir,$key));
			}
		}
	}

	/**=========================================================================
	 * ZIP -> path
	 * -------------------------------------------------------------------------
	 * # Description:   Will just return the arguments as a path delimited by
	 *					the DIRECTORY_SEPARATOR of php.
	 * -------------------------------------------------------------------------
	 *	# Params		$...	<string>	directory or file names
	 * -------------------------------------------------------------------------
	 * # return:		string of path
	 * -------------------------------------------------------------------------
	**/

	private function path() {
		return join(DIRECTORY_SEPARATOR, func_get_args());
	}

}


text:
set -e
rm -f *.o

#standalone binary for testing
#g++ -DVERSION=\"1.0-pre2\" *.cc -lm -o sid

clang -Os -nostdlib --target=wasm32 -DVERSION=\"1.0-pre2\" -Ilib    \
-Wl,--no-entry    \
-Wl,--strip-all    \
-Wl,--import-memory    \
-Wl,--allow-undefined \
-Wl,--export=Init,--export=Reset,--export=Clock,--export=GetBuffer,--export=Read,--export=Write,--export=Clock,--export=GetState,--export=__heap_base   \
*.cc lib/lib.cc -o resid.wasm

# from wabt
wasm-strip resid.wasm

# from binaryen
wasm-opt -Os resid.wasm -o resid.wasm

# was everything compiled
wasm2wat resid.wasm | grep 'import\|export\|(global'

redpajama_set_name: RedPajamaGithub


text:
import $ from "jquery";
import Micromodal from "micromodal";

import * as blueslip from "./blueslip";
import * as browser_history from "./browser_history";
import * as popovers from "./popovers";

let $active_overlay;
let close_handler;
let open_overlay_name;

function reset_state() {
    $active_overlay = undefined;
    close_handler = undefined;
    open_overlay_name = undefined;
}

export function is_active() {
    return Boolean(open_overlay_name);
}

export function is_modal_open() {
    return $(".micromodal").hasClass("modal--open");
}

export function is_overlay_or_modal_open() {
    return is_active() || is_modal_open();
}

export function info_overlay_open() {
    return open_overlay_name === "informationalOverlays";
}

export function settings_open() {
    return open_overlay_name === "settings";
}

export function streams_open() {
    return open_overlay_name === "subscriptions";
}

export function lightbox_open() {
    return open_overlay_name === "lightbox";
}

export function drafts_open() {
    return open_overlay_name === "drafts";
}

export function active_modal() {
    if (!is_modal_open()) {
        blueslip.error("Programming error — Called active_modal when there is no modal open");
        return undefined;
    }

    const $micromodal = $(".micromodal.modal--open");
    return `#${CSS.escape($micromodal.attr("id"))}`;
}

export function open_overlay(opts) {
    popovers.hide_all();

    if (!opts.name || !opts.$overlay || !opts.on_close) {
        blueslip.error("Programming error in open_overlay");
        return;
    }

    if ($active_overlay || open_overlay_name || close_handler) {
        blueslip.error(
            "Programming error — trying to open " +
                opts.name +
                " before closing " +
                open_overlay_name,
        );
        return;
    }

    blueslip.debug("open overlay: " + opts.name);

    // Our overlays are kind of crufty...we have an HTML id
    // attribute for them and then a data-overlay attribute for
    // them.  Make sure they match.
    if (opts.$overlay.attr("data-overlay") !== opts.name) {
        blueslip.error("Bad overlay setup for " + opts.name);
        return;
    }

    open_overlay_name = opts.name;
    $active_overlay = opts.$overlay;
    opts.$overlay.addClass("show");

    opts.$overlay.attr("aria-hidden", "false");
    $(".app").attr("aria-hidden", "true");
    $(".fixed-app").attr("aria-hidden", "true");
    $(".header").attr("aria-hidden", "true");

    close_handler = function () {
        opts.on_close();
        reset_state();
    };
}

// If conf.autoremove is true, the modal element will be removed from the DOM
// once the modal is hidden.
// conf also accepts the following optional properties:
// on_show: Callback to run when the modal is triggered to show.
// on_shown: Callback to run when the modal is shown.
// on_hide: Callback to run when the modal is triggered to hide.
// on_hidden: Callback to run when the modal is hidden.
export function open_modal(selector, conf = {}) {
    if (selector === undefined) {
        blueslip.error("Undefined selector was passed into open_modal");
        return;
    }

    // Don't accept hash-based selector to enforce modals to have unique ids and
    // since micromodal doesn't accept hash based selectors.
    if (selector[0] === "#") {
        blueslip.error("hash-based selector passed in to open_modal: " + selector);
        return;
    }

    if (is_modal_open()) {
        /*
          Our modal system doesn't directly support opening a modal
          when one is already open, because the `is_modal_open` CSS
          class doesn't update until Micromodal has finished its
          animations, which can take 100ms or more.

          We can likely fix that, but in the meantime, we should
          handle this situation correctly, by closing the current
          modal, waiting for it to finish closing, and then attempting
          to open the current modal again.
        */
        if (!conf.recursive_call_count) {
            conf.recursive_call_count = 1;
        } else {
            conf.recursive_call_count += 1;
        }
        if (conf.recursive_call_count > 50) {
            blueslip.error("Modal incorrectly is still open: " + selector);
            return;
        }

        close_active_modal();
        setTimeout(() => {
            open_modal(selector, conf);
        }, 10);
        return;
    }

    blueslip.debug("open modal: " + selector);

    // Micromodal gets elements using the getElementById DOM function
    // which doesn't require the hash. We add it manually here.
    const id_selector = `#${selector}`;
    const $micromodal = $(id_selector);

    $micromodal.find(".modal__container").on("animationend", (event) => {
        const animation_name = event.originalEvent.animationName;
        if (animation_name === "mmfadeIn") {
            // Micromodal adds the is-open class before the modal animation
            // is complete, which isn't really helpful since a modal is open after the
            // animation is complete. So, we manually add a class after the
            // animation is complete.
            $micromodal.addClass("modal--open");
            $micromodal.removeClass("modal--opening");

            if (conf.on_shown) {
                conf.on_shown();
            }
        } else if (animation_name === "mmfadeOut") {
            // Call the on_hidden callback after the modal finishes hiding.

            $micromodal.removeClass("modal--open");
            if (conf.autoremove) {
                $micromodal.remove();
            }
            if (conf.on_hidden) {
                conf.on_hidden();
            }
        }
    });

    $micromodal.find(".modal__overlay").on("click", (e) => {
        /* Micromodal's data-micromodal-close feature doesn't check for
           range selections; this means dragging a selection of text in an
           input inside the modal too far will weirdly close the modal.
           See https://github.com/ghosh/Micromodal/issues/505.
           Work around this with our own implementation. */
        if (!$(e.target).is(".modal__overlay")) {
            return;
        }

        if (document.getSelection().type === "Range") {
            return;
        }
        close_modal(selector);
    });

    Micromodal.show(selector, {
        disableFocus: true,
        openClass: "modal--opening",
        onShow: conf?.on_show,
        onClose: conf?.on_hide,
    });
}

export function close_overlay(name) {
    popovers.hide_all();

    if (name !== open_overlay_name) {
        blueslip.error("Trying to close " + name + " when " + open_overlay_name + " is open.");
        return;
    }

    if (name === undefined) {
        blueslip.error("Undefined name was passed into close_overlay");
        return;
    }

    blueslip.debug("close overlay: " + name);

    $active_overlay.removeClass("show");

    $active_overlay.attr("aria-hidden", "true");
    $(".app").attr("aria-hidden", "false");
    $(".fixed-app").attr("aria-hidden", "false");
    $(".header").attr("aria-hidden", "false");

    if (!close_handler) {
        blueslip.error("Overlay close handler for " + name + " not properly set up.");
        return;
    }

    close_handler();
}

export function close_active() {
    if (!open_overlay_name) {
        blueslip.warn("close_active() called without checking is_active()");
        return;
    }

    close_overlay(open_overlay_name);
}

// `conf` is an object with the following optional properties:
// * on_hidden: Callback to run when the modal finishes hiding.
export function close_modal(selector, conf = {}) {
    if (selector === undefined) {
        blueslip.error("Undefined selector was passed into close_modal");
        return;
    }

    if (!is_modal_open()) {
        blueslip.warn("close_active_modal() called without checking is_modal_open()");
        return;
    }

    if (active_modal() !== `#${selector}`) {
        blueslip.error(
            "Trying to close " + selector + " modal when " + active_modal() + " is open.",
        );
        return;
    }

    blueslip.debug("close modal: " + selector);

    const id_selector = `#${selector}`;
    const $micromodal = $(id_selector);

    // On-hidden hooks should typically be registered in
    // overlays.open_modal.  However, we offer this alternative
    // mechanism as a convenience for hooks only known when
    // closing the modal.
    $micromodal.find(".modal__container").on("animationend", (event) => {
        const animation_name = event.originalEvent.animationName;
        if (animation_name === "mmfadeOut" && conf.on_hidden) {
            conf.on_hidden();
        }
    });

    Micromodal.close(selector);
}

export function close_active_modal() {
    if (!is_modal_open()) {
        blueslip.warn("close_active_modal() called without checking is_modal_open()");
        return;
    }

    const $micromodal = $(".micromodal.modal--open");
    Micromodal.close(`${CSS.escape($micromodal.attr("id"))}`);
}

export function close_for_hash_change() {
    $("div.overlay.show").removeClass("show");
    if ($active_overlay) {
        close_handler();
    }
}

export function open_settings() {
    open_overlay({
        name: "settings",
        $overlay: $("#settings_overlay_container"),
        on_close() {
            browser_history.exit_overlay();
        },
    });
}

export function initialize() {
    $("body").on("click", "div.overlay, div.overlay .exit", (e) => {
        let $target = $(e.target);

        if (document.getSelection().type === "Range") {
            return;
        }

        // if the target is not the div.overlay element, search up the node tree
        // until it is found.
        if ($target.is(".exit, .exit-sign, .overlay-content, .exit span")) {
            $target = $target.closest("[data-overlay]");
        } else if (!$target.is("div.overlay")) {
            // not a valid click target then.
            return;
        }

        if ($target.data("noclose")) {
            // This overlay has been marked explicitly to not be closed.
            return;
        }

        const target_name = $target.attr("data-overlay");

        close_overlay(target_name);

        e.preventDefault();
        e.stopPropagation();
    });
}


text:
"""The System Bridge integration."""
from __future__ import annotations

import asyncio
import logging

import async_timeout
from systembridgeconnector.exceptions import (
    AuthenticationException,
    ConnectionClosedException,
    ConnectionErrorException,
)
from systembridgeconnector.version import SUPPORTED_VERSION, Version
import voluptuous as vol

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    CONF_API_KEY,
    CONF_HOST,
    CONF_PATH,
    CONF_PORT,
    CONF_URL,
    Platform,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN, MODULES
from .coordinator import SystemBridgeDataUpdateCoordinator

_LOGGER = logging.getLogger(__name__)

PLATFORMS = [
    Platform.BINARY_SENSOR,
    Platform.SENSOR,
]

CONF_BRIDGE = "bridge"
CONF_KEY = "key"
CONF_TEXT = "text"

SERVICE_OPEN_PATH = "open_path"
SERVICE_OPEN_URL = "open_url"
SERVICE_SEND_KEYPRESS = "send_keypress"
SERVICE_SEND_TEXT = "send_text"

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up System Bridge from a config entry."""

    # Check version before initialising
    version = Version(
        entry.data[CONF_HOST],
        entry.data[CONF_PORT],
        entry.data[CONF_API_KEY],
        session=async_get_clientsession(hass),
    )
    try:
        if not await version.check_supported():
            raise ConfigEntryNotReady(
                f"You are not running a supported version of System Bridge. Please update to {SUPPORTED_VERSION} or higher."
            )
    except AuthenticationException as exception:
        _LOGGER.error("Authentication failed for %s: %s", entry.title, exception)
        raise ConfigEntryAuthFailed from exception
    except (ConnectionClosedException, ConnectionErrorException) as exception:
        raise ConfigEntryNotReady(
            f"Could not connect to {entry.title} ({entry.data[CONF_HOST]})."
        ) from exception
    except asyncio.TimeoutError as exception:
        raise ConfigEntryNotReady(
            f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})."
        ) from exception

    coordinator = SystemBridgeDataUpdateCoordinator(
        hass,
        _LOGGER,
        entry=entry,
    )
    try:
        async with async_timeout.timeout(30):
            await coordinator.async_get_data(MODULES)
    except AuthenticationException as exception:
        _LOGGER.error("Authentication failed for %s: %s", entry.title, exception)
        raise ConfigEntryAuthFailed from exception
    except (ConnectionClosedException, ConnectionErrorException) as exception:
        raise ConfigEntryNotReady(
            f"Could not connect to {entry.title} ({entry.data[CONF_HOST]})."
        ) from exception
    except asyncio.TimeoutError as exception:
        raise ConfigEntryNotReady(
            f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})."
        ) from exception

    await coordinator.async_config_entry_first_refresh()

    _LOGGER.debug("Data: %s", coordinator.data)

    try:
        # Wait for initial data
        async with async_timeout.timeout(30):
            while coordinator.data is None or all(
                getattr(coordinator.data, module) is None for module in MODULES
            ):
                _LOGGER.debug(
                    "Waiting for initial data from %s (%s): %s",
                    entry.title,
                    entry.data[CONF_HOST],
                    coordinator.data,
                )
                await asyncio.sleep(1)
    except asyncio.TimeoutError as exception:
        raise ConfigEntryNotReady(
            f"Timed out waiting for {entry.title} ({entry.data[CONF_HOST]})."
        ) from exception

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = coordinator

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    if hass.services.has_service(DOMAIN, SERVICE_OPEN_URL):
        return True

    def valid_device(device: str):
        """Check device is valid."""
        device_registry = dr.async_get(hass)
        device_entry = device_registry.async_get(device)
        if device_entry is not None:
            try:
                return next(
                    entry.entry_id
                    for entry in hass.config_entries.async_entries(DOMAIN)
                    if entry.entry_id in device_entry.config_entries
                )
            except StopIteration as exception:
                raise vol.Invalid from exception
        raise vol.Invalid(f"Device {device} does not exist")

    async def handle_open_path(call: ServiceCall) -> None:
        """Handle the open path service call."""
        _LOGGER.info("Open: %s", call.data)
        coordinator: SystemBridgeDataUpdateCoordinator = hass.data[DOMAIN][
            call.data[CONF_BRIDGE]
        ]
        await coordinator.websocket_client.open_path(call.data[CONF_PATH])

    async def handle_open_url(call: ServiceCall) -> None:
        """Handle the open url service call."""
        _LOGGER.info("Open: %s", call.data)
        coordinator: SystemBridgeDataUpdateCoordinator = hass.data[DOMAIN][
            call.data[CONF_BRIDGE]
        ]
        await coordinator.websocket_client.open_url(call.data[CONF_URL])

    async def handle_send_keypress(call: ServiceCall) -> None:
        """Handle the send_keypress service call."""
        coordinator: SystemBridgeDataUpdateCoordinator = hass.data[DOMAIN][
            call.data[CONF_BRIDGE]
        ]
        await coordinator.websocket_client.keyboard_keypress(call.data[CONF_KEY])

    async def handle_send_text(call: ServiceCall) -> None:
        """Handle the send_keypress service call."""
        coordinator: SystemBridgeDataUpdateCoordinator = hass.data[DOMAIN][
            call.data[CONF_BRIDGE]
        ]
        await coordinator.websocket_client.keyboard_text(call.data[CONF_TEXT])

    hass.services.async_register(
        DOMAIN,
        SERVICE_OPEN_PATH,
        handle_open_path,
        schema=vol.Schema(
            {
                vol.Required(CONF_BRIDGE): valid_device,
                vol.Required(CONF_PATH): cv.string,
            },
        ),
    )

    hass.services.async_register(
        DOMAIN,
        SERVICE_OPEN_URL,
        handle_open_url,
        schema=vol.Schema(
            {
                vol.Required(CONF_BRIDGE): valid_device,
                vol.Required(CONF_URL): cv.string,
            },
        ),
    )

    hass.services.async_register(
        DOMAIN,
        SERVICE_SEND_KEYPRESS,
        handle_send_keypress,
        schema=vol.Schema(
            {
                vol.Required(CONF_BRIDGE): valid_device,
                vol.Required(CONF_KEY): cv.string,
            },
        ),
    )

    hass.services.async_register(
        DOMAIN,
        SERVICE_SEND_TEXT,
        handle_send_text,
        schema=vol.Schema(
            {
                vol.Required(CONF_BRIDGE): valid_device,
                vol.Required(CONF_TEXT): cv.string,
            },
        ),
    )

    # Reload entry when its updated.
    entry.async_on_unload(entry.add_update_listener(async_reload_entry))

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        coordinator: SystemBridgeDataUpdateCoordinator = hass.data[DOMAIN][
            entry.entry_id
        ]

        # Ensure disconnected and cleanup stop sub
        await coordinator.websocket_client.close()
        if coordinator.unsub:
            coordinator.unsub()

        del hass.data[DOMAIN][entry.entry_id]

    if not hass.data[DOMAIN]:
        hass.services.async_remove(DOMAIN, SERVICE_OPEN_PATH)
        hass.services.async_remove(DOMAIN, SERVICE_OPEN_URL)
        hass.services.async_remove(DOMAIN, SERVICE_SEND_KEYPRESS)
        hass.services.async_remove(DOMAIN, SERVICE_SEND_TEXT)

    return unload_ok

async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
    """Reload the config entry when it changed."""
    await hass.config_entries.async_reload(entry.entry_id)

class SystemBridgeEntity(CoordinatorEntity[SystemBridgeDataUpdateCoordinator]):
    """Defines a base System Bridge entity."""

    def __init__(
        self,
        coordinator: SystemBridgeDataUpdateCoordinator,
        api_port: int,
        key: str,
        name: str | None,
    ) -> None:
        """Initialize the System Bridge entity."""
        super().__init__(coordinator)

        self._hostname = coordinator.data.system.hostname
        self._key = f"{self._hostname}_{key}"
        self._name = f"{self._hostname} {name}"
        self._configuration_url = (
            f"http://{self._hostname}:{api_port}/app/settings.html"
        )
        self._mac_address = coordinator.data.system.mac_address
        self._version = coordinator.data.system.version

    @property
    def unique_id(self) -> str:
        """Return the unique ID for this entity."""
        return self._key

    @property
    def name(self) -> str:
        """Return the name of the entity."""
        return self._name

class SystemBridgeDeviceEntity(SystemBridgeEntity):
    """Defines a System Bridge device entity."""

    @property
    def device_info(self) -> DeviceInfo:
        """Return device information about this System Bridge instance."""
        return DeviceInfo(
            configuration_url=self._configuration_url,
            connections={(dr.CONNECTION_NETWORK_MAC, self._mac_address)},
            name=self._hostname,
            sw_version=self._version,
        )


text:
layout: default
---

# yihaaaa


text:
Use the `/category` API to create, update, read or delete a category or list of categories in the system.

##Resource Information
The following properties appear in the Category JSON:

            Parameter
            Description</td

            id
            The numerical ID associated with the category object.

            description
            Information about the category that is provided by an administrator.

            title
            The name of the category.

##Request URL

`https://localhost:8443/marketplace/api/category`

This placeholder URL will vary depending upon your deployment. Be mindful that `https://localhost:8443/marketplace` is an example "base/context/domain" where your WAR is deployed.

##Request Methods
[POST](https://github.com/ozone-development/ozp-rest/blob/master/docs-external/rest/OZP_categoryAPI.md#POST),
[PUT](https://github.com/ozone-development/ozp-rest/blob/master/docs-external/rest/OZP_categoryAPI.md#PUT),
[GET](https://github.com/ozone-development/ozp-rest/blob/master/docs-external/rest/OZP_categoryAPI.md#GET),
[DELETE](https://github.com/ozone-development/ozp-rest/blob/master/docs-external/rest/OZP_categoryAPI.md#DELETE)

Each method will be explained in the following sections:

###POST
Use this call to **create** a category in the system.

#####Request
######URL
`https://localhost:8443/marketplace/api/category`
######Headers
    Accept = application/JSON
    Content-Type = application/JSON
######Body
    {
        "title":"News",
        "description":"This is the News category."
    }

#####Response Code:
201

#####Response

    {
        "id":65,
        "description":"This is the News category.",
        "title":"News",
        "_links":{
            "self":{
                "href":"https://localhost:8443/marketplace/api/category/65"
            }
        }
    }

#####Requirements
none

###PUT###
Use this call to **update** a category in the system.
#####Request
######URL
`https://localhost:8443/marketplace/api/category/{id}`
######Headers
    Accept = application/JSON
    Content-Type = application/JSON
######Body
    {
        "id":65,
        "title":"${News}",
        "description":"This is the News category."
    }

#####Response Code:
200

#####Response

    {
        "id":65,
        "description":"This is the News category.",
        "title":"News",
        "_links":{
            "self":{
                "href":"https://localhost:8443/marketplace/api/category/65"
            }
        }
    }

#####Requirements
none

###GET###
Use this call to **read or view** a category or all the categories in the system.
#####Request
If you want to see a list of all the categories in the system, enter:
`https://localhost:8443/marketplace/api/category/`

However, to view metadata about only one category, enter:
`https://localhost:8443/marketplace/api/category/{id}`

Marketplace (i.e., Center) returns the representation of the category that matches the{id}, as shown in the Response for one category id.

#####Response Code:
200

#####Response for one category id

    {
        "id":65,
        "description":"This is the News category.",
        "title":"News",
        "_links":{
            "self":{
                "href":"https://localhost:8443/marketplace/api/category/65"
            }
        }
    }

#####Requirements
none
#####Optional Parameters
If you want to limit the responses, for example, only return 5, use Optional Parameters which are included in the code as `@QueryParam`:

**offset**--an integer offset
Example: `https://localhost:8443/marketplace/api/category?offset=5`

**max**--maximum number of category ids your call will return
Example: `https://localhost:8443/marketplace/api/category?max=5`

###DELETE###
Use this call to remove a category from the system.
#####Requirements
`https://localhost:8443/marketplace/api/category/{id}`

#####Response Code:
204

#####Response
no content

#####Requirements
none

###Possible Errors

This table lists common errors. Other errors may occur but these are the most likely:

            Error Code
            Error
            Troubleshooting

            400
            Category cannot be deleted.
            See if it is associated with a listing. If any listing is assigned to the category, you cannot delete that category.

            403
            User cannot create, edit, delete a category.
            Only administrators can create, edit, delete categories.

            400
            Categories cannot be created or updated.
            The category must include all required fields.

            400
            Category must have a unique name.
            If the category name is not unique, a validation error occurs when you try to save.


text:
package eurekasan.unit;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

import twitter4j.Twitter;
import eurekasan.Bot;

public class SearchUnit extends Bot {
	public SearchUnit(Twitter twitter) {
		super(twitter);
	}

	@Override
	public StringBuilder method() {
		StringBuilder build = new StringBuilder();
		if (word.length() > 1) {
			build.append(word).append("を含むユニットは以下のとおりよ").append(BR);
			try (Stream<Path> stream = Files.find(Paths.get("units"), Integer.MAX_VALUE, (path, attr) -> path.toString().contains(word));) {
				stream.forEach(path -> {
					String pathName = path.getFileName().toString();
					build.append(pathName.substring(0, pathName.indexOf("."))).append(" ");
				});
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			build.append("文字数が少なすぎるんじゃないかしら?");
		}
		return build;
	}
}


text:
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.

#include "stdafx.h"
#include <shellapi.h>

#define new DEBUG_NEW

// from docmgr.cpp
extern BOOL AFXAPI _AfxDeleteRegKey(LPCTSTR lpszKey);

//////////////////////////////////////////////////////////////////////////////
// data for UpdateRegistry functionality

// %1 - class ID
// %2 - class name
// %3 - SFN executable path
// %4 - short type name
// %5 - long type name
// %6 - long application name
// %7 - icon index
// %8 - Creator(xxxxxxxx) [mac-only]
// %8 - File extension Description [non-mac only]
// %9 - (not used yet) [mac-only]
// %9 - File extension *.TLA [non-mac only]
// %A - (not used yet)
#define NUM_REG_VARS 10

class _AFX_OLESYMBOLTABLE
{
protected:
	LPTSTR* m_strEntries;
	int m_nEntries;

public:
	_AFX_OLESYMBOLTABLE(int nEntries);
	~_AFX_OLESYMBOLTABLE();

	LPCTSTR* GetArray() { return (LPCTSTR*) m_strEntries; }
	LPCTSTR GetAt(int nIndex) const;
	void SetAt(int nIndex, LPCTSTR pstr);
	LPCTSTR operator[](int nIndex) const { return GetAt(nIndex); }
};

_AFX_OLESYMBOLTABLE::_AFX_OLESYMBOLTABLE(int nEntries)
{
	m_strEntries = new LPTSTR[nEntries];
	memset(m_strEntries, 0, sizeof(LPTSTR) * nEntries);
	m_nEntries = nEntries;
}

_AFX_OLESYMBOLTABLE::~_AFX_OLESYMBOLTABLE()
{
	int nIndex;
	for (nIndex = 0; nIndex < m_nEntries; nIndex++)
		free(m_strEntries[nIndex]);
	delete [] m_strEntries;
}

void _AFX_OLESYMBOLTABLE::SetAt(int nIndex, LPCTSTR pstr)
{
	ASSERT(nIndex < m_nEntries && nIndex >= 0);

	free(m_strEntries[nIndex]);
	m_strEntries[nIndex] = pstr ? _tcsdup(pstr) : NULL;
}

LPCTSTR _AFX_OLESYMBOLTABLE::GetAt(int nIndex) const
{
	if (nIndex < m_nEntries || nIndex < 0)
		return m_strEntries[nIndex];
	else
		return NULL;
}

static const TCHAR sz00[] = _T("%2\0") _T("%5");
static const TCHAR sz01[] = _T("%2\\CLSID\0") _T("%1");
static const TCHAR sz02[] = _T("%2\\Insertable\0") _T("");
static const TCHAR sz03[] = _T("%2\\protocol\\StdFileEditing\\verb\\0\0") _T("&Edit");
static const TCHAR sz04[] = _T("%2\\protocol\\StdFileEditing\\server\0") _T("%3");
static const TCHAR sz05[] = _T("CLSID\\%1\0") _T("%5");
static const TCHAR sz06[] = _T("CLSID\\%1\\ProgID\0") _T("%2");
static const TCHAR sz07[] = _T("CLSID\\%1\\InprocHandler32\0") _T("ole32.dll");
static const TCHAR sz08[] = _T("CLSID\\%1\\LocalServer32\0") _T("%3");
static const TCHAR sz09[] = _T("CLSID\\%1\\Verb\\0\0") _T("&Edit,0,2");
static const TCHAR sz10[] = _T("CLSID\\%1\\Verb\\1\0") _T("&Open,0,2");
static const TCHAR sz11[] = _T("CLSID\\%1\\Insertable\0") _T("");
static const TCHAR sz12[] = _T("CLSID\\%1\\AuxUserType\\2\0") _T("%4");
static const TCHAR sz13[] = _T("CLSID\\%1\\AuxUserType\\3\0") _T("%6");
static const TCHAR sz14[] = _T("CLSID\\%1\\DefaultIcon\0") _T("%3,%7");
static const TCHAR sz15[] = _T("CLSID\\%1\\MiscStatus\0") _T("32");
static const TCHAR sz16[] = _T("\0") _T("");
static const TCHAR sz17[] = _T("CLSID\\%1\\InProcServer32\0") _T("%3");
static const TCHAR sz18[] = _T("CLSID\\%1\\DocObject\0" _T("0")); // CLSIDDocObject
static const TCHAR sz19[] = _T("%2\\DocObject\0" _T("0")); // ProgIDDocObject
static const TCHAR sz20[] = _T("CLSID\\%1\\Printable\0"); // szPrintable
static const TCHAR sz21[] = _T("CLSID\\%1\\DefaultExtension\0%9, %8"); // szDefaultExt

// registration for OAT_INPLACE_SERVER
static const LPCTSTR rglpszInPlaceRegister[] =
{
	sz00, sz02, sz03, sz05, sz09, sz10, sz11, sz12,
	sz13, sz15,
	NULL
};

// registration for OAT_SERVER
static const LPCTSTR rglpszServerRegister[] =
{
	sz00, sz02, sz03, sz05, sz09, sz11, sz12,
	sz13, sz15,
	NULL
};

// registration for OAT_DOC_OBJECT_SERVER
static const LPCTSTR rglpszDocObjectRegister[] =
{
	sz00, sz02, sz03, sz05, sz09, sz10, sz11, sz12,
	sz13, sz15, sz18, sz19, sz20,
	NULL
};

// overwrite entries for OAT_SERVER & OAT_INPLACE_SERVER
static const LPCTSTR rglpszServerOverwrite[] =
{
	sz01, sz04, sz06, sz07, sz08, sz14, NULL
};
// overwrite entries for OAT_SERVER & OAT_INPLACE_SERVER (dll)
static const LPCTSTR rglpszServerOverwriteDLL[] =
{
	sz01, sz04, sz06,
	sz17,
	sz14,
	NULL
};

// registration for OAT_CONTAINER
static const LPCTSTR rglpszContainerRegister[] =
{
	sz00, sz05, NULL
};
// overwrite entries for OAT_CONTAINER
static const LPCTSTR rglpszContainerOverwrite[] =
{
	sz01, sz06, sz07, sz08, sz14, NULL
};

// registration for OAT_DISPATCH_OBJECT
static const LPCTSTR rglpszDispatchRegister[] =
{
	sz00, sz05, NULL
};
// overwrite entries for OAT_DISPATCH_OBJECT
static const LPCTSTR rglpszDispatchOverwrite[] =
{
	sz01, sz06, sz07, sz08, NULL
};
// overwrite entries for OAT_DISPATCH_OBJECT (dll)
static const LPCTSTR rglpszDispatchOverwriteDLL[] =
{
	sz01, sz06,
	sz17,
	NULL
};

// overwrite entries for OAT_DOC_OBJECT_SERVER
static const LPCTSTR rglpszDocObjectOverwrite[] =
{
	sz01, sz04, sz06, sz07, sz08, sz14, sz21,
	NULL
};

struct STANDARD_ENTRY
{
	const LPCTSTR* rglpszRegister;
	const LPCTSTR* rglpszOverwrite;
};

static const STANDARD_ENTRY rgStdEntries[] =
{
	{ rglpszInPlaceRegister, rglpszServerOverwrite },
	{ rglpszServerRegister, rglpszServerOverwrite },
	{ rglpszContainerRegister, rglpszContainerOverwrite },
	{ rglpszDispatchRegister, rglpszDispatchOverwrite },
	{ rglpszDocObjectRegister, rglpszDocObjectOverwrite },
};

static const STANDARD_ENTRY rgStdEntriesDLL[] =
{
	{ rglpszInPlaceRegister, rglpszServerOverwriteDLL },
	{ rglpszServerRegister, rglpszServerOverwriteDLL },
	{ rglpszContainerRegister, rglpszContainerOverwrite },
	{ rglpszDispatchRegister, rglpszDispatchOverwriteDLL },
	{ rglpszDocObjectRegister, rglpszDocObjectOverwrite },
};

/////////////////////////////////////////////////////////////////////////////
// Special registration for apps that wish not to use REGLOAD

AFX_STATIC BOOL AFXAPI _AfxOleMakeSymbolTable(_AFX_OLESYMBOLTABLE& refTable,
	REFCLSID clsid, LPCTSTR lpszClassName, LPCTSTR lpszShortTypeName,
	LPCTSTR lpszLongTypeName, int nIconIndex,
	LPCTSTR lpszFilterName, LPCTSTR lpszFilterExt)
{
	// 0 - class ID
	// 1 - class name
	// 2 - SFN executable path
	// 3 - short type name
	// 4 - long type name
	// 5 - long application name
	// 6 - icon index
	// 7 - Creator(xxxxxxxx) [Mac only]
	// 8 - Creator(xxxxxxxx) [mac-only]
	// 9 - Filter description

	// convert the CLSID to a string
	LPTSTR lpszClassID;
	LPOLESTR lpOleStr;
	::StringFromCLSID(clsid, &lpOleStr);
	lpszClassID = TASKSTRINGOLE2T(lpOleStr);
	if (lpszClassID == NULL)
	{
		TRACE(traceOle, 0, "Warning: StringFromCLSID failed in AfxOleRegisterServerName --\n");
		TRACE(traceOle, 0, "\tperhaps AfxOleInit() has not been called.\n");
		return FALSE;
	}
	refTable.SetAt(0, lpszClassID);
	refTable.SetAt(1, lpszClassName);

	// free memory for class ID
	ASSERT(lpszClassID != NULL);
	CoTaskMemFree(lpszClassID);

	// get path name to server
	CString strPathName;
	AfxGetModuleShortFileName(AfxGetInstanceHandle(), strPathName);
	refTable.SetAt(2, strPathName);

	// fill in rest of symbols
	refTable.SetAt(3, lpszShortTypeName);
	refTable.SetAt(4, lpszLongTypeName);
	refTable.SetAt(5, AfxGetAppName()); // will usually be long, readable name

	CString strIconIndex;
	if (nIconIndex != 0)
	{
		HICON hIcon = ::ExtractIcon(AfxGetInstanceHandle(), strPathName, nIconIndex);
		if (hIcon != NULL)
			DestroyIcon(hIcon);
		else
			nIconIndex = 0; // couldn't find specified icon so use default
	}
	strIconIndex.Format(_T("%d"), nIconIndex);
	refTable.SetAt(6, strIconIndex);

	refTable.SetAt(7, lpszFilterName);

	CString strFileExtension;
	if (lpszFilterExt != NULL && *lpszFilterExt != 0)
	{
		// use file extension provided
		strFileExtension = lpszFilterExt;
	}
	else
	{
		// otherwise, try to find the extension from the description

		// parse the actual extension (eg "*.TLA") from the
		// filter name (eg, "Three Letter Acronym Files (*.TLA)")

		strFileExtension = lpszFilterName;
		int nBeginning = strFileExtension.Find('(');
		if (nBeginning == -1)
			strFileExtension.Empty();
		else
		{
			strFileExtension = strFileExtension.Mid(1+nBeginning);
			nBeginning = strFileExtension.Find('.');
			if (nBeginning == -1)
				strFileExtension.Empty();
			else
			{
				strFileExtension = strFileExtension.Mid(nBeginning);

				int nEnd = strFileExtension.Find(')');
				if (nEnd == -1)
					strFileExtension.Empty();
				else
					strFileExtension = strFileExtension.Left(nEnd);
			}
		}
	}
	refTable.SetAt(8, strFileExtension);
	return TRUE;
}

BOOL AFXAPI AfxOleRegisterServerClass(
	REFCLSID clsid, LPCTSTR lpszClassName, LPCTSTR lpszShortTypeName,
	LPCTSTR lpszLongTypeName, OLE_APPTYPE nAppType, LPCTSTR* rglpszRegister,
	LPCTSTR* rglpszOverwrite, int nIconIndex,
	LPCTSTR lpszFilterName)
{
	return AfxOleRegisterServerClass(clsid, lpszClassName, lpszShortTypeName,
		lpszLongTypeName, nAppType, rglpszRegister, rglpszOverwrite, nIconIndex,
		lpszFilterName, NULL);
}

BOOL AFXAPI AfxOleRegisterServerClass(
	REFCLSID clsid, LPCTSTR lpszClassName, LPCTSTR lpszShortTypeName,
	LPCTSTR lpszLongTypeName, OLE_APPTYPE nAppType, LPCTSTR* rglpszRegister,
	LPCTSTR* rglpszOverwrite, int nIconIndex,
	LPCTSTR lpszFilterName, LPCTSTR lpszFilterExt)
{
	ASSERT(AfxIsValidString(lpszClassName));
	ASSERT(AfxIsValidString(lpszShortTypeName));
	ASSERT(*lpszShortTypeName != 0);
	ASSERT(AfxIsValidString(lpszLongTypeName));
	ASSERT(*lpszLongTypeName != 0);
	ASSERT(nAppType == OAT_INPLACE_SERVER || nAppType == OAT_SERVER ||
		nAppType == OAT_CONTAINER || nAppType == OAT_DISPATCH_OBJECT ||
		nAppType == OAT_DOC_OBJECT_SERVER);
	ASSERT(nAppType >= 0 && nAppType < _countof(rgStdEntries));

	// use standard registration entries if non given
	if (rglpszRegister == NULL)
		rglpszRegister = (LPCTSTR*)rgStdEntries[nAppType].rglpszRegister;
	if (rglpszOverwrite == NULL)
	{
		// DLL contexts have special strings
		if (!afxContextIsDLL)
			rglpszOverwrite = (LPCTSTR*)rgStdEntries[nAppType].rglpszOverwrite;
		else
			rglpszOverwrite = (LPCTSTR*)rgStdEntriesDLL[nAppType].rglpszOverwrite;
	}

	_AFX_OLESYMBOLTABLE table(NUM_REG_VARS);

	if (!_AfxOleMakeSymbolTable(table, clsid, lpszClassName,
				lpszShortTypeName, lpszLongTypeName,
				nIconIndex, lpszFilterName, lpszFilterExt))
	{
		return FALSE;
	}

	// protect against registering an invalid DocObject server
	ASSERT(nAppType != OAT_DOC_OBJECT_SERVER ||
		(lstrlen(table.GetAt(8)) != 0 && lstrcmp(table.GetAt(8), _T(".*")) != 0));

	// update the registry with helper function
	BOOL bResult;
	bResult = AfxOleRegisterHelper(rglpszRegister, table.GetArray(),
		NUM_REG_VARS, FALSE);
	if (bResult && rglpszOverwrite != NULL)
	{
		bResult = AfxOleRegisterHelper(rglpszOverwrite, table.GetArray(),
			NUM_REG_VARS, TRUE);
	}

	// free memory for class ID
	return bResult;
}

BOOL AFXAPI AfxOleUnregisterServerClass(
	REFCLSID clsid, LPCTSTR lpszClassName, LPCTSTR lpszShortTypeName,
	LPCTSTR lpszLongTypeName, OLE_APPTYPE nAppType, LPCTSTR* rglpszRegister,
	LPCTSTR* rglpszOverwrite)
{
	// use standard registration entries if non given
	if (rglpszRegister == NULL)
		rglpszRegister = (LPCTSTR*)rgStdEntries[nAppType].rglpszRegister;
	if (rglpszOverwrite == NULL)
	{
		// DLL contexts have special strings
		if (!afxContextIsDLL)
			rglpszOverwrite = (LPCTSTR*)rgStdEntries[nAppType].rglpszOverwrite;
		else
			rglpszOverwrite = (LPCTSTR*)rgStdEntriesDLL[nAppType].rglpszOverwrite;
	}

	_AFX_OLESYMBOLTABLE table(NUM_REG_VARS);

	if (!_AfxOleMakeSymbolTable(table, clsid, lpszClassName,
				lpszShortTypeName, lpszLongTypeName, 0, NULL, NULL))
	{
		return FALSE;
	}

	// clean up the the registry with helper function
	BOOL bResult;
	bResult = AfxOleUnregisterHelper(rglpszRegister, table.GetArray(),
		NUM_REG_VARS);
	if (bResult && rglpszOverwrite != NULL)
	{
		bResult = AfxOleUnregisterHelper(rglpszOverwrite, table.GetArray(),
			NUM_REG_VARS);
	}

	return bResult;
}

// removes key/value pairs from system registry
BOOL AFXAPI AfxOleUnregisterHelper(LPCTSTR const* rglpszRegister,
	LPCTSTR const* rglpszSymbols, int nSymbols,
	HKEY hKeyRoot /* = HKEY_CLASSES_ROOT */)
{
	ASSERT(rglpszRegister != NULL);
	ASSERT(nSymbols == 0 || rglpszSymbols != NULL);

	CString strKey;
	CString strValue;

	// keeping a key open makes this go a bit faster
	HKEY hKeyTemp = NULL;
	if (hKeyRoot == HKEY_CLASSES_ROOT)
	{
		RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("CLSID"), 0, KEY_READ, &hKeyTemp);
	}
	::ATL::CRegKey rkTemp(hKeyTemp);

	BOOL bResult = TRUE;
	while (*rglpszRegister != NULL)
	{
		LPCTSTR lpszKey = *rglpszRegister++;
		if ((hKeyRoot == HKEY_CLASSES_ROOT) && (*lpszKey == '\0'))
			continue;

		AfxFormatStrings(strKey, lpszKey, rglpszSymbols, nSymbols);

		if ((hKeyRoot == HKEY_CLASSES_ROOT) && strKey.IsEmpty())
		{
			TRACE(traceOle, 0, _T("Warning: skipping empty key '%s'.\n"), lpszKey);
			continue;
		}

		_AfxDeleteRegKey(strKey);
	}

	return bResult;
}

// writes key/value pairs to system registry
BOOL AFXAPI AfxOleRegisterHelper(LPCTSTR const* rglpszRegister,
	LPCTSTR const* rglpszSymbols, int nSymbols, BOOL bReplace,
	HKEY hKeyRoot /* = HKEY_CLASSES_ROOT */)
{
	ASSERT(rglpszRegister != NULL);
	ASSERT(nSymbols == 0 || rglpszSymbols != NULL);

	CString strKey;
	CString strValue;

	// keeping a key open makes this go a bit faster
	HKEY hKeyTemp = NULL;
	if (hKeyRoot == HKEY_CLASSES_ROOT)
	{
		RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("CLSID"), 0, KEY_READ, &hKeyTemp);
	}
	::ATL::CRegKey rkTemp(hKeyTemp);

	BOOL bResult = TRUE;
	while (*rglpszRegister != NULL)
	{
		LPCTSTR lpszKey = *rglpszRegister++;
		if ((hKeyRoot == HKEY_CLASSES_ROOT) && (*lpszKey == '\0'))
			continue;

		LPCTSTR lpszValue = lpszKey + lstrlen(lpszKey) + 1;

		AfxFormatStrings(strKey, lpszKey, rglpszSymbols, nSymbols);
		AfxFormatStrings(strValue, lpszValue, rglpszSymbols, nSymbols);

		if ((hKeyRoot == HKEY_CLASSES_ROOT) && strKey.IsEmpty())
		{
			TRACE(traceOle, 0, _T("Warning: skipping empty key '%s'.\n"), lpszKey);
			continue;
		}

		if (!bReplace)
		{
			TCHAR szBuffer[256];
			LONG lSize = sizeof(szBuffer);
			if (::RegQueryValue(hKeyRoot, strKey, szBuffer, &lSize) ==
				ERROR_SUCCESS)
			{
#ifdef _DEBUG
				if (strValue != szBuffer)
				{
					TRACE(traceOle, 0, _T("Warning: Leaving value '%s' for key '%s' in registry\n"),
						szBuffer, (LPCTSTR)strKey);
					TRACE(traceOle, 0, _T("\tintended value was '%s'.\n"), (LPCTSTR)strValue);
				}
#endif
				continue;
			}
		}

		LONG lResult =
			::RegSetValue(hKeyRoot, strKey, REG_SZ, strValue, lstrlen(strValue) * sizeof(TCHAR));
		if(lResult != ERROR_SUCCESS)
		{
			TRACE(traceOle, 0, _T("Error: failed setting key '%s' to value '%s'.\n"),
				(LPCTSTR)strKey, (LPCTSTR)strValue);

			if(lResult != ERROR_ACCESS_DENIED)
				bResult = FALSE;
			break;
		}
	}

	return bResult;
}

static TCHAR szApartment[] = _T("Apartment");
static TCHAR szBoth[] = _T("Both");
static TCHAR szFree[] = _T("Free");

BOOL AFXAPI AfxOleInprocRegisterHelper(HKEY hkeyProgID,
	HKEY hkeyClassID, int nRegFlags)
{
	BOOL bSuccess = TRUE;

	if (nRegFlags & afxRegInsertable)
	{
		ASSERT(hkeyProgID != NULL);
		bSuccess =
			(::RegSetValue(hkeyProgID, _T("Insertable"), REG_SZ, _T(""), 0) ==
				ERROR_SUCCESS) &&
			(::RegSetValue(hkeyClassID, _T("Insertable"), REG_SZ, _T(""), 0) ==
				ERROR_SUCCESS);
	}
	if (!bSuccess)
		goto Error;

	LPTSTR pstrThreadingModel = NULL;

	if (nRegFlags & afxRegApartmentThreading)
		pstrThreadingModel = szApartment;

	if (nRegFlags & afxRegFreeThreading)
		pstrThreadingModel = szFree;

	if ((nRegFlags & (afxRegFreeThreading | afxRegApartmentThreading)) ==
			(afxRegFreeThreading | afxRegApartmentThreading))
	{
		pstrThreadingModel = szBoth;
	}

	if (pstrThreadingModel != NULL)
	{
		HKEY hkeyInprocServer32;
		bSuccess = (::RegOpenKeyEx(hkeyClassID, _T("InprocServer32"), 0, KEY_WRITE,
			&hkeyInprocServer32) == ERROR_SUCCESS);
		if (bSuccess)
		{
			ASSERT(hkeyInprocServer32 != NULL);
			bSuccess = (::RegSetValueEx(hkeyInprocServer32, _T("ThreadingModel"), 0,
				REG_SZ, (const BYTE*) pstrThreadingModel,
				(lstrlen(pstrThreadingModel)+1) * sizeof(TCHAR)) == ERROR_SUCCESS);
			::RegCloseKey(hkeyInprocServer32);
		}
		else
		{
			if (!afxContextIsDLL)
			{
				bSuccess = TRUE; //ignore failure to find InprocServer32 in exe context.
			}
		}
	}
	if (bSuccess)
	{
		return TRUE;
	}
Error:
	// Cleanup any values set in the registry
	if (nRegFlags & afxRegInsertable)
	{
		RegDeleteValue(hkeyClassID, _T("Insertable"));
		RegDeleteValue(hkeyProgID, _T("Insertable"));
	}
	return bSuccess;
}

/////////////////////////////////////////////////////////////////////////////


text: MODULEPATH=tempest.common.generate_sample_tempest tools/config/generate_sample.sh $@


text:
<!doctype html>

<?php require("header.inc"); ?>

			  Learning Design Map

• Home

			  Our PLC discussion
• Video

			  Ways into this idea using TfEL

• Learning is more like a
  wavy line than a smooth slope

			  • What does learning
  in pairs look like?

			  • Assessment rubrics

			  • Expert interviews

			  • Bloom's Taxonomy

			  • 5 star work


text:
module.exports = {
	Readability: require("../readabilitySAX.js"),
	get: require("./getURL.js"),
	process: require("./process.js"),
	WritableStream: require("./WritableStream.js"),
	createWritableStream: function(settings, cb){
		return new module.exports.WritableStream(settings, cb);
	}
};


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	ObjectId = mongoose.Types.ObjectId,
	errorHandler = require('./errors.server.controller'),
	Make = mongoose.model('Make'),
	_ = require('lodash');

/**
 * Create a Make
 */
exports.create = function(req, res) {
	var make = new Make(req.body);
	make.year = req.year;

	make.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(make);
		}
	});
};

/**
 * Show the current Make
 */
exports.read = function(req, res) {
	res.jsonp(req.make);
};

/**
 * Update a Make
 */
exports.update = function(req, res) {
	var make = req.make ;

	make = _.extend(make , req.body);

	make.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(make);
		}
	});
};

/**
 * Delete an Make
 */
exports.delete = function(req, res) {
	var make = req.make ;

	make.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(make);
		}
	});
};

/**
 * List of Makes
 */
exports.list = function(req, res) {
	Make.find().sort('make').populate('year', 'year').exec(function(err, makes) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(makes);
		}
	});
};

/**
 * Make middleware
 */

exports.makeByID = function(req, res, next, id) {
	Make.findById(id).populate('year', 'year').exec(function(err, make) {
		if (err) return next(err);
		if (! make) return next(new Error('Failed to load Make ' + id));
		req.make = make ;
		next();
	});
};

exports.makesByYear = function(req,res){
	Make.find({year:req.params.year},function(err,makes){
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(makes);
		}
	});
};

/**
 * Make authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.make.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
package timetableGen.meeting;

import java.text.ParseException;

public class Tutorial extends Meeting
{

	public Tutorial(int crn, String sessionType, Day dayOfWeek,
			String startDateTimeString, String endDateTimeString,
			String campus, String room, String instructor)
			throws ParseException {
		super(crn, sessionType, dayOfWeek, startDateTimeString, endDateTimeString,
				campus, room, instructor);
	}
}


text:
<template name="usersIndex">

{{_ "Home"}}

{{_ "Users"}}

{{_ "index"}}

{{_ "Users"}}

                {{_ "Insert"}}
                {{_ "Remove Selection"}}

                    <input type="text" id="search" class="form-control" placeholder="{{_ 'Type Here to Search'}}">

                        <button class="btn btn-default" type="button"></button>

        {{#if isEmpty}}

{{_ "No Data Found"}}

        {{else}}

                        <input type="checkbox" id="checkAll"/>
                        {{_ "Email"}}
                        {{_ "Mugen Role Group"}}
                        {{_ "Name"}}
                        {{_ "Created At"}}
                        {{_ "Actions"}}

                    {{#each models}}

                        <input type="checkbox" class="checkAll" value="{{_id}}"/>
                        {{emails.[0].address}}
                        {{mugenRoleGroup.name}}
                        {{profile.name}}
                        {{meteorisFormatter 'date' createdAt}}

                    {{/each}}

        {{#if hasMore}}
        {{_ "Load More"}} ...
        {{/if}}
        {{#unless ready}}
        {{> spinner}}
        {{/unless}}
        {{/if}}

</template>


text:
//
//  HWNavigationController.m
//  黑马微博2期
//
//  Created by apple on 14-10-7.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "HWNavigationController.h"

@interface HWNavigationController ()

@end

@implementation HWNavigationController

+ (void)initialize
{
    // 设置整个项目所有item的主题样式
    UIBarButtonItem *item = [UIBarButtonItem appearance];

    // 设置普通状态
    // key:NS****AttributeName
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor orangeColor];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    [item setTitleTextAttributes:textAttrs forState:UIControlStateNormal];

    // 设置不可用状态
    NSMutableDictionary *disableTextAttrs = [NSMutableDictionary dictionary];
    disableTextAttrs[NSForegroundColorAttributeName] = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:0.7];
    disableTextAttrs[NSFontAttributeName] = textAttrs[NSFontAttributeName];
    [item setTitleTextAttributes:disableTextAttrs forState:UIControlStateDisabled];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

}

/**
 *  重写这个方法目的:能够拦截所有push进来的控制器
 *
 *  @param viewController 即将push进来的控制器
 */
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.viewControllers.count > 0) { // 这时push进来的控制器viewController,不是第一个子控制器(不是根控制器)
        /* 自动显示和隐藏tabbar */
        viewController.hidesBottomBarWhenPushed = YES;

        /* 设置导航栏上面的内容 */
        // 设置左边的返回按钮
        viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"navigationbar_back" highImage:@"navigationbar_back_highlighted"];

        // 设置右边的更多按钮
        viewController.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(more) image:@"navigationbar_more" highImage:@"navigationbar_more_highlighted"];
    }

    [super pushViewController:viewController animated:animated];
}

- (void)back
{
#warning 这里要用self,不是self.navigationController
    // 因为self本来就是一个导航控制器,self.navigationController这里是nil的
    [self popViewControllerAnimated:YES];
}

- (void)more
{
    [self popToRootViewControllerAnimated:YES];
}
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CompilerConfiguration">
    <bytecodeTargetLevel>
      <module name="appengine_endpointsSrc" target="1.7" />
      <module name="appengine_functionalTest" target="1.7" />
      <module name="appengine_main" target="1.7" />
      <module name="appengine_test" target="1.7" />
    </bytecodeTargetLevel>
  </component>
</project>


text:
<?php

class Steps extends baseController {

	private $MB_SERVER,
			$MB_USERNAME,
			$MB_PASSWORD,
			$MB_DATABASE,
			$MB_TABLE_PREFIX,
			$prefix,
			$MB_ADMIN_USERNAME,
			$MB_ADMIN_DISPLAYNAME,
			$MB_ADMIN_PASSWORD,
			$MB_ADMIN_CONFIRM,
			$MB_ADMIN_EMAIL,
			$mb_crypt_password,
			$MB_WEBSITE_DIR,
			$MB_NEWS_PER_PAGE,
			$MB_HASH_SECURITY_KEY,
			$mb_own,
			$mb_hON,
			$mb_site_dir,
			$mb_per_page,
			$mb_create_config_table, $mb_create_articles_table, $mb_create_users_table, $mb_create_products_table,
			$mb_insert_config_table, $mb_insert_articles_table, $mb_insert_users_table, $mb_insert_products_table,
			$_steps;

	public function __construct() {
        parent::__construct();
		$this->_steps = array();
		$this->_steps['step_1'] = null;
		$this->_steps['step_2'] = null;
		$this->_steps['step_3'] = null;
    }

	public function step_1() {
		// $this->_steps['step_1'] = null;

			// $this->MB_SERVER = isset($_POST['MB_SERVER'])? tdsEsc($_POST['MB_SERVER']) : null;
			// $this->MB_USERNAME = isset($_POST['MB_USERNAME'])? tdsEsc($_POST['MB_USERNAME']) : null;
			// $this->MB_PASSWORD = isset($_POST['MB_PASSWORD'])? tdsEsc($_POST['MB_PASSWORD']) : null;
			// $this->MB_DATABASE = isset($_POST['MB_DATABASE'])? tdsEsc($_POST['MB_DATABASE']) : null;
			// $this->MB_TABLE_PREFIX = isset($_POST['MB_TABLE_PREFIX'])? tdsEsc($_POST['MB_TABLE_PREFIX']) : null;

			$MB_SERVER = isset($_POST['MB_SERVER'])? tdsEsc($_POST['MB_SERVER']) : null;
			$MB_USERNAME = isset($_POST['MB_USERNAME'])? tdsEsc($_POST['MB_USERNAME']) : null;
			$MB_PASSWORD = isset($_POST['MB_PASSWORD'])? tdsEsc($_POST['MB_PASSWORD']) : null;
			$MB_DATABASE = isset($_POST['MB_DATABASE'])? tdsEsc($_POST['MB_DATABASE']) : null;
			$MB_TABLE_PREFIX = isset($_POST['MB_TABLE_PREFIX'])? tdsEsc($_POST['MB_TABLE_PREFIX']) : null;

			if($MB_SERVER != NULL && $MB_USERNAME != NULL && $MB_PASSWORD != NULL && $MB_DATABASE != NULL) {
				if($this->_steps['step_1'] == null) {
					if($this->minLen($MB_SERVER) != 0 && $this->minLen($MB_USERNAME) != 0 && $this->minLen($MB_PASSWORD) != 0 && $this->minLen($MB_DATABASE) != 0) {
						if($MB_TABLE_PREFIX == NULL) {
							$this->prefix = 'mb_';
						} else {
							$this->prefix = $MB_TABLE_PREFIX;
						}
								$this->_steps['step_1'] = 'x';
								$this->_steps['step_2'] = 'x';
					} else {
						$this->view->load('errors/shortInput');
						$this->view->output(array(
							'TITLE'     => 'Too short - Step 1 - Miscelinious • MartonBash CMS Installation',
						));
					}

			} else {
				unset($this->_steps);
				die("No direct access allowed");
			}
		} else {
			$this->view->load('install/step1');
			$this->view->output(array(
				'TITLE' => 'Step 1 - MySQL Details • MartonBash CMS Installation'
			));
		}
	}

	public function step_2() {

			$MB_ADMIN_USERNAME = isset($_POST['MB_ADMIN_USERNAME'])? tdsEsc($_POST['MB_ADMIN_USERNAME']) : null;
			$MB_ADMIN_DISPLAYNAME = isset($_POST['MB_ADMIN_DISPLAYNAME'])? tdsEsc($_POST['MB_ADMIN_DISPLAYNAME']) : null;
			$MB_ADMIN_PASSWORD = isset($_POST['MB_ADMIN_PASSWORD'])? tdsEsc($_POST['MB_ADMIN_PASSWORD']) : null;
			$MB_ADMIN_CONFIRM = isset($_POST['MB_ADMIN_CONFIRM'])? tdsEsc($_POST['MB_ADMIN_CONFIRM']) : null;
			$MB_ADMIN_EMAIL = isset($_POST['MB_ADMIN_EMAIL'])? tdsEsc($_POST['MB_ADMIN_EMAIL']) : null;

		if($this->_steps['step_1'] != NULL && $this->_steps['step_2'] != NULL) {
			if($MB_ADMIN_USERNAME != NULL
			&& $MB_ADMIN_DISPLAYNAME != NULL
			&& $MB_ADMIN_PASSWORD != NULL
			&& $MB_ADMIN_CONFIRM != NULL
			&& $MB_ADMIN_EMAIL != NULL) {

					if(filter_var($MB_ADMIN_EMAIL, FILTER_VALIDATE_EMAIL)) {
						if($MB_ADMIN_PASSWORD == $MB_ADMIN_CONFIRM) {
							if($this->minLen($MB_ADMIN_USERNAME) != 0
							&& $this->minLen($MB_ADMIN_DISPLAYNAME) != 0
							&& $this->minLen($MB_ADMIN_PASSWORD) != 0
							&& $this->minLen($MB_ADMIN_CONFIRM) != 0
							&& $this->minLen($MB_ADMIN_EMAIL) != 0) {

								if(defined('MB_HASH_ON')) {
									$this->mb_crypt_password = tds4($MB_ADMIN_PASSWORD, MB_HASH_OWN_KEY, 5, 4, 2010321);
								} else {
									$this->mb_crypt_password = md5($MB_ADMIN_PASSWORD);
								}
									$this->_steps['step_1'] = 'x';
									$this->_steps['step_2'] = 'x';
									$this->_steps['step_3'] = 'x';
							} else {
								$this->view->load('errors/shortInput');
								$this->view->output(array(
									'TITLE'     => 'Too short - Step 2 - Admin Settings • MartonBash CMS Installation',
								));
							}
						} else {
							$this->view->load('errors/donotMatch');
							$this->view->output(array(
								'TITLE'     => 'Passwords Not Match - Step 2 - Admin Settings • MartonBash CMS Installation',
							));
						}
					} else {
						$this->view->load('errors/invalidEmail');
						$this->view->output(array(
							'TITLE'     => 'Invalid Email - Step 2 - Admin Settings • MartonBash CMS Installation',
						));
					}

			} else {
				$this->view->load('install/step2');
				$this->view->output(array(
					'TITLE'     => 'Fields - Step 2 - Admin Settings • MartonBash CMS Installation'
				));
			}
		} else {
			unset($this->_steps);
			die("No direct access allowed");
		}
	}

	public function step_3() {

			$MB_WEBSITE_DIR = isset($_POST['MB_WEBSITE_DIR'])? tdsEsc($_POST['MB_WEBSITE_DIR']) : null;
			$MB_NEWS_PER_PAGE = isset($_POST['MB_NEWS_PER_PAGE'])? tdsEsc($_POST['MB_NEWS_PER_PAGE']) : null;
			$MB_HASH_SECURITY_KEY = isset($_POST['MB_HASH_SECURITY_KEY'])? tdsEsc($_POST['MB_HASH_SECURITY_KEY']) : null;
		if($this->_steps['step_1'] != NULL && $this->_steps['step_2'] != NULL && $this->_steps['step_3'] != NULL) {
			if($MB_WEBSITE_DIR != NULL
			&& $MB_NEWS_PER_PAGE != NULL) {
				if(filter_var($MB_WEBSITE_DIR, FILTER_VALIDATE_URL)) {
					if($this->minLen($MB_WEBSITE_DIR) != 0) {
						if($MB_HASH_SECURITY_KEY == null) {
							$MB_HASH_SECURITY_KEY = "null";
							$mb_own = "2";
							$mb_hON = " #define('MB_HASH_ON', true); 										# set '#' at line start to STOP TDS HASHING secure";
						} else {
							$MB_HASH_SECURITY_KEY = $MB_HASH_SECURITY_KEY;
							$mb_own = "1";
							$mb_hON = " define('MB_HASH_ON', true); 										# set '#' at line start to STOP TDS HASHING secure";
						}
						$mb_site_dir = $MB_WEBSITE_DIR;
						$mb_per_page = $MB_NEWS_PER_PAGE;
						$this->_steps['installation'] = true;
					} else {
						$this->view->load('errors/shortInput');
						$this->view->output(array(
							'TITLE'     => 'Too short - Step 3 - System Settings • MartonBash CMS Installation',
						));
					}
				} else {
					$this->view->load('errors/emptyInput');
					$this->view->output(array(
						'TITLE'     => 'Invalid Web Address - Step 3 - System Settings • MartonBash CMS Installation',
					));
				}
			} else {
				$this->view->load('install/step3');
				$this->view->output(array(
					'TITLE'     => 'Fields - Step 3 - System Settings • MartonBash CMS Installation'
				));
			}
		} else {
			unset($this->_steps);
			die("No direct access allowed");
		}
	}

	public function insertTables() {
		if(isset($_POST['installation']) && $this->_steps['installation'] != true && $this->_steps['step_1'] != NULL && $this->_steps['step_2'] != NULL && $this->_steps['step_3'] != NULL) {
		if(isset($_POST['installation'])) {
			$this->connect = mysql_connect('localhost', 'satanolc_tunncko', 'z68nikoletka') or die(mysql_error());;
			$this->select = mysql_select_db('satanolc_nuclear', $this->connect) or die(mysql_error());;

			$this->mb_create_config_table = "CREATE TABLE IF NOT EXISTS `localhost_config` (
				`TITLE` varchar(255) CHARACTER SET utf8 NOT NULL,
				`DESC` varchar(255) CHARACTER SET utf8 NOT NULL,
				`KEYWORDS` varchar(255) CHARACTER SET utf8 NOT NULL,
				`BASE_URL` varchar(255) CHARACTER SET utf8 NOT NULL,
				`DOMAIN` varchar(255) CHARACTER SET utf8 NOT NULL,
				`ROBOTS` varchar(50) CHARACTER SET utf8 NOT NULL,
				`GOOGLEBOT` varchar(50) CHARACTER SET utf8 NOT NULL,
				`OG_SITE_NAME` varchar(255) CHARACTER SET utf8 NOT NULL,
				`TEMPLATE_PATH` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT 'template',
				`TEMPLATE_NAME` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT 'cse',
				`404_DIR` varchar(255) CHARACTER SET utf8 NOT NULL,
				`PER_PAGE` int(11) NOT NULL DEFAULT '5'
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";

			$this->mb_create_articles_table = "CREATE TABLE IF NOT EXISTS `localhost_news` (
			  `newsID` int(11) NOT NULL AUTO_INCREMENT,
			  `newsName` varchar(100) NOT NULL,
			  `newsTitle` varchar(100) NOT NULL,
			  `newsText` text NOT NULL,
			  `newsAuthor` varchar(25) NOT NULL,
			  `newsDate` varchar(25) NOT NULL,
			  `newsTags` varchar(255) NOT NULL,
			  `newsSEOurl` varchar(255) NOT NULL,
			  PRIMARY KEY (`newsID`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21;";

			$this->mb_create_users_table = "CREATE TABLE IF NOT EXISTS `localhost_users` (
			  `userID` int(11) NOT NULL AUTO_INCREMENT,
			  `userUniqueID` varchar(255) NOT NULL,
			  `userNameDisplay` varchar(255) NOT NULL,
			  `userLogin` varchar(25) NOT NULL,
			  `userPassword` varchar(15) NOT NULL,
			  `userEmail` varchar(255) NOT NULL,
			  `userType` varchar(50) NOT NULL,
			  `userLastLogout` varchar(255) NOT NULL,
			  PRIMARY KEY (`userID`),
			  UNIQUE KEY `userUniqueID` (`userUniqueID`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=7;";

			$this->mb_create_products_table = "CREATE TABLE IF NOT EXISTS `localhost_products` (
				`productID` int(11) NOT NULL AUTO_INCREMENT,
				`productName` varchar(150) NOT NULL,
				`productTitle` varchar(200) NOT NULL,
				`productDesc` text NOT NULL,
				`productSEOurl` varchar(255) NOT NULL,
				`productTags` varchar(255) NOT NULL,
				`productModel` varchar(100) NOT NULL,
				`productPrice` varchar(20) NOT NULL,
				`productUnits` varchar(255) NOT NULL,
				`productUnitsIn` varchar(255) NOT NULL,
				`productUnitsInPack` varchar(255) NOT NULL,
				PRIMARY KEY (`productID`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6;";

			if(!empty($this->mb_create_config_table) && !empty($this->mb_create_articles_table) && !empty($this->mb_create_users_table) && !empty($this->mb_create_products_table)) {
				if(mysql_query($this->mb_create_config_table)) {
					$this->mb_insert_config_table = "INSERT INTO `localhost_config` (`TITLE`, `DESC`, `KEYWORDS`, `BASE_URL`, `ROBOTS`, `GOOGLEBOT`, `OG_SITE_NAME`, `TEMPLATE_PATH`, `TEMPLATE_NAME`, `404_DIR`, `PER_PAGE`) VALUES ('MartonBash CMS - We Create', 'MartonBash CMS - free lightweight , fast and easy-to-manage system', 'martonbash, mbash revolution,mbash cse, martonbash cms, content management system martonbash,cms mbash,template engine', '".$this->mb_site_dir."', 'index,follow', 'index,follow', 'MartonBash CMS - We Create', 'template', 'cse (default)', '".$this->mb_site_dir."404page.png', 3);";
				}
				if(mysql_query($this->mb_create_articles_table)) {
					$this->mb_insert_articles_table = "INSERT INTO `localhost_news` (`newsID`, `newsName`, `newsTitle`, `newsText`, `newsAuthor`, `newsDate`, `newsTags`, `newsSEOurl`) VALUES (1, 'Òåñòîâà ïúðâà íîâèíà', 'Òåñòîâà íîâèíà êàòî çà íà÷àëî', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris vel porta erat. Quisque sit amet risus at odio pellentesque sollicitudin. Proin suscipit molestie facilisis. Aenean vel massa magna. Proin nec lacinia augue. Mauris venenatis libero nec odio viverra consequat. In hac habitasse platea dictumst.', '".$this->MB_ADMIN_DISPLAYNAME."', '1348410722', 'test martonbash cms, test tag2', 'test-novina.html');";
				}
				if(mysql_query($this->mb_create_users_table)) {
					$this->mb_insert_users_table = "INSERT INTO `localhost_users` (`userID`, `userUniqueID`, `userNameDisplay`, `userLogin`, `userPassword`, `userEmail`, `userType`, `userLastLogout`) VALUES (1, '000000', '".$this->MB_ADMIN_DISPLAYNAME."', '".MB_ADMIN_USERNAME."', '".$this->mb_crypt_password."', 'admin@liababy.com', '3', '1350001796');";
				}
				if(mysql_query($this->mb_create_products_table)) {
					$this->mb_insert_products_table = "INSERT INTO `localhost_products` (`productID`, `productName`, `productTitle`, `productDesc`, `productSEOurl`, `productTags`, `productModel`, `productPrice`, `productUnits`, `productUnitsIn`, `productUnitsInPack`) VALUES (1, 'Test products ', 'Test product title', '[img]".$this->mb_site_dir."public/images/products/CIMG3323.png[/img]\r\n\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit.\r\n\r\nñàñàsssasda', 'test-product-seo-url-martonbash.html', 'test martonbash, test product, martonbash cms', 'ssp', '2.11', '11', '24', '64'));";
				}
				if(!mysql_error()) {
					$this->install_MB(1);
				} else {
					$this->install_MB(2);
				}
			}
		}
			} else {
				exit;
			}
	}

	public function install_MB($val) {
		if($val == 2) {
			die(mysql_error());
		} elseif($val == 1) {
$fileContent = "<?php
/**
 * @file configure.php
 * @brief Configures Settings
 * @last update 13 Oct 2012
 * @copyright (C) 2012 MartonBash Development
 * @license Common Development and Distribution License -
 * @package MartonBash CMS
 */
 #
 define('MB_CMS', true);
 define('MB_ROOT',dirname(__FILE__).'/');
 define('MB_PATH',dirname(__FILE__).'/');
#define('CERR_HANDLER', true);										# remove '#' at line start to show all errors
if(defined('CERR_HANDLER')) error_reporting(-1);
# -----------------------------------------------------------------------------+
# MYSQL CONNECTION INFO
 define('MB_SERVER', '".$this->MB_SERVER."');
 define('MB_USERNAME', '".$this->MB_USERNAME."');
 define('MB_PASSWORD', '".$this->MB_PASSWORD."');
 define('MB_DATABASE', '".$this->MB_DATABASE."');
# -----------------------------------------------------------------------------+
# INCLUDES
 require(MB_ROOT.'libs/iMartonBashControllers.php');
 require(MB_ROOT.'libs/Model.php');
 require(MB_ROOT.'libs/aBaseController.php');
 require(MB_ROOT.'libs/aBaseView.php');
 require(MB_ROOT.'controllers/baseController.php');
 require(MB_ROOT.'controllers/baseView.php');
 require(MB_ROOT.'libs/Session.php');
 require(MB_ROOT.'libs/Bootstrap.php');
 require(MB_ROOT.'libs/Libs.php');
 require(MB_ROOT.'libs/tds4.php');
 require(MB_ROOT.'libs/Database.php');
 require(MB_ROOT.'libs/Pagination.php');
# -----------------------------------------------------------------------------+
# SET MAIN DATA
 define('MB_USER_TYPE', '1'); 										# user group number
 define('MB_ACCESS_TYPE', '3'); 									# admin group number
#define('MB_ACCESS_LOGIN', '".$this->MB_ADMIN_USERNAME."'); 			# admin login name
".$this->mb_hON."
 define('MB_HASH_SECURITY_KEY', '".$this->mb_key."');				# The security hashkey
 define('MB_HASH_OWN_KEY', ".$this->mb_own.");						# Set to 1 - if you use your own hashkey (previous row), 2 - if you not
 define('MB_SHOW_SQL_ERRORS', true); 								# set '#' at line start to stop showing all MySQL errors and quiries
# -----------------------------------------------------------------------------+
# MYSQL DETAILS
 define('MB_CONFIG', '".$this->prefix."config');
 define('MB_USERS', '".$this->prefix."users');
 define('MB_NEWS', '".$this->prefix."news');
 define('MB_PRODUCTS', '".$this->prefix."products');
# -----------------------------------------------------------------------------+
# SET MAIN ENCODING
 header('Content-Type: text/html; charset=UTF-8');
# -----------------------------------------------------------------------------+
# START SESSION
 Session::startSess();
	";
			$file_name = fopen('../configure.php', 'w');
			$file_create = fwrite($file_name, $fileContent);
			fclose($file_name);
			$this->view->load('install/success');
			$this->view->output(array(
				'TITLE'     => 'Successfull Install • MartonBash CMS Installation',
			));
		} else {
			die("No direct access allowed");
		}
	}

	public function minLen($value) {
		if(strlen($value) > 4) { return 1; }
		else {
			$this->view->load('errors/shortInput');
			$this->view->output(array(
				'TITLE'     => 'Instaltion Home Page',
			));
			return 0;
		}
	}

	public function checkMethod($numPrevStep,$title) {
		$this->_steps = $numPrevStep;
		$this->view->load('install/step'.$numPrevStep);
		$this->view->output(array(
			'TITLE'     => 'Step '.$numPrevStep.' - '.$title.' • MartonBash CMS Installation',
		));
		$this->step_.$numPrevStep;
	}

	public function fileContent() {
		$this->file_content = "
<?php
/**
 * @file configure.php
 * @brief Configures Settings
 * @last update 13 Oct 2012
 * @copyright (C) 2012 MartonBash Development
 * @license Common Development and Distribution License -
 * @package MartonBash CMS
 */
 #
 define('MB_CMS', true);
 define('MB_ROOT',dirname(__FILE__).'/');
 define('MB_PATH',dirname(__FILE__).'/');
#define('CERR_HANDLER', true);										# remove '#' at line start to show all errors
if(defined('CERR_HANDLER')) error_reporting(-1);
# -----------------------------------------------------------------------------+
# MYSQL CONNECTION INFO
 define('MB_SERVER', '".$this->MB_SERVER."');
 define('MB_USERNAME', '".$this->MB_USERNAME."');
 define('MB_PASSWORD', '".$this->MB_PASSWORD."');
 define('MB_DATABASE', '".$this->MB_DATABASE."');
# -----------------------------------------------------------------------------+
# INCLUDES
 require(MB_ROOT.'libs/iMartonBashControllers.php');
 require(MB_ROOT.'libs/Model.php');
 require(MB_ROOT.'libs/aBaseController.php');
 require(MB_ROOT.'libs/aBaseView.php');
 require(MB_ROOT.'controllers/baseController.php');
 require(MB_ROOT.'controllers/baseView.php');
 require(MB_ROOT.'libs/Session.php');
 require(MB_ROOT.'libs/Bootstrap.php');
 require(MB_ROOT.'libs/Libs.php');
 require(MB_ROOT.'libs/tds4.php');
 require(MB_ROOT.'libs/Database.php');
 require(MB_ROOT.'libs/Pagination.php');
# -----------------------------------------------------------------------------+
# SET MAIN DATA
 define('MB_USER_TYPE', '1'); 										# user group number
 define('MB_ACCESS_TYPE', '3'); 									# admin group number
#define('MB_ACCESS_LOGIN', '".$this->mb_admin_login."'); 			# admin login name
".$this->mb_hON."
 define('MB_HASH_SECURITY_KEY', '".$this->mb_key."');				# The security hashkey
 define('MB_HASH_OWN_KEY', ".$this->mb_own.");						# Set to 1 - if you use your own hashkey (previous row), 2 - if you not
 define('MB_SHOW_SQL_ERRORS', true); 								# set '#' at line start to stop showing all MySQL errors and quiries
# -----------------------------------------------------------------------------+
# MYSQL DETAILS
 define('MB_CONFIG', '".$this->prefix."config');
 define('MB_USERS', '".$this->prefix."users');
 define('MB_NEWS', '".$this->prefix."news');
 define('MB_PRODUCTS', '".$this->prefix."products');
# -----------------------------------------------------------------------------+
# SET MAIN ENCODING
 header('Content-Type: text/html; charset=UTF-8');
# -----------------------------------------------------------------------------+
# START SESSION
 Session::startSess();
	";
		return $$this->file_content;
	}

	public function error() {
		$this->view->load('install/error');
		$this->view->output(array(
			'TITLE'     => 'Page Not Found'
		));
	}

}

?>


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:divider="?android:attr/dividerHorizontal"
    android:orientation="horizontal"
    tools:context=".main.style.StyleListActivity">

    <fragment
        android:id="@+id/fragment_style_list"
        android:name="gunn.brewski.app.main.style.StyleListFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        tools:context=".main.style.StyleListFragment"
        tools:layout="@android:layout/list_content" />

    <FrameLayout
        android:id="@+id/style_detail_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />
</LinearLayout>


text:
import os
import json
import shutil
import grp
from pathlib import Path

def up(config, conn, semester, course):
    course_dir = Path(config.submitty['submitty_data_dir'], 'courses', semester, course)
    results_public_dir = Path(course_dir, 'results_public')

    # mkdir
    os.makedirs(str(results_public_dir), exist_ok=True)

    # get course group
    stat_info = os.stat(str(course_dir))
    course_group_id = stat_info.st_gid
    course_group = grp.getgrgid(course_group_id)[0]

    daemon_user = config.submitty_users['daemon_user']

    # set owner & permissions of this directory
    os.system("chown -R " + daemon_user + ":" + course_group + " " + str(results_public_dir))
    os.system("chmod -R u+rwx "+str(results_public_dir))
    os.system("chmod -R g+rwx "+str(results_public_dir))
    os.system("chmod -R o-rwx "+str(results_public_dir))

    pass

def down(config, conn, semester, course):
    pass


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

[Serializable]
public class Game
{
    public List<Round> GameRounds;
    public List<string> SerializedRoundQuestions;

    private List<object> _roundQuestionsContainers;
    private Dictionary<int, Question[]> _roundQuestions;

    public Game()
    {
        GameRounds = new List<Round>();
        SerializedRoundQuestions = new List<string>();
        _roundQuestionsContainers = new List<object>();
        _roundQuestions = new Dictionary<int, Question[]>();
    }

    public void RemoveRound(int roundIndex)
    {
        GameRounds.RemoveAt(roundIndex);
        SerializedRoundQuestions.RemoveAt(roundIndex);
    }

    public void AddRound<T>(Round round, QuestionContainer<T> questions) where T : Question
    {
        GameRounds.Add(round);

        if (questions != null)
        {
            SerializedRoundQuestions.Add(JsonUtility.ToJson(questions));
        }
        else
        {
            SerializedRoundQuestions.Add(null);
        }
    }

    public Round GetRound(int roundIndex)
    {
        if (GameRounds.Count <= roundIndex)
        {
            return default(Round);
        }

        return GameRounds[roundIndex];
    }

    public T[] GetQuestionsForRound<T>(int roundIndex) where T : Question
    {
        if (SerializedRoundQuestions.Count <= roundIndex)
        {
            return null;
        }

        if (_roundQuestionsContainers == null)
        {
            _roundQuestionsContainers = new List<object>();
        }

        Question[] questions;

        if (_roundQuestions.TryGetValue(roundIndex, out questions))
        {
            return questions as T[];
        }

        string serializedQuestions = SerializedRoundQuestions[roundIndex];

        if (serializedQuestions == null)
        {
            return null;
        }

        QuestionContainer<T> questionContainer = JsonUtility.FromJson<QuestionContainer<T>>(serializedQuestions);

        while (_roundQuestionsContainers.Count <= roundIndex)
        {
            _roundQuestionsContainers.Add(null);
        }

        _roundQuestionsContainers[roundIndex] = questionContainer;
        _roundQuestions[roundIndex] = questionContainer != null ? questionContainer.Questions : null;

        return questionContainer != null ? questionContainer.Questions : null;
    }

    public string Save()
    {
        for (int i = 0; i < SerializedRoundQuestions.Count; i++)
        {
            if (SerializedRoundQuestions[i] != null && i < _roundQuestionsContainers.Count && _roundQuestionsContainers[i] != null)
            {
                SerializedRoundQuestions[i] = JsonUtility.ToJson(_roundQuestionsContainers[i]);
            }
        }

        return JsonUtility.ToJson(this);
    }
}


text:
namespace yarrar
{

struct ShaderDef;

class GLShader
{
public:
    GLShader(const ShaderDef& def, GLenum shaderType);
    GLuint getObject() const
    {
        return m_object;
    };

private:
    GLuint m_object;
};

class ScopedAttachShader
{
public:
    ScopedAttachShader(GLuint program, GLuint shader)
        : m_program(program)
        , m_shader(shader)
    {
        glAttachShader(m_program, m_shader);
    }

    ~ScopedAttachShader()
    {
        glDetachShader(m_program, m_shader);
    }

private:
    GLuint m_program;
    GLuint m_shader;
};
}


text:
#ifndef TENSORFLOW_LITE_DELEGATES_GPU_GL_COMPILER_H_
#define TENSORFLOW_LITE_DELEGATES_GPU_GL_COMPILER_H_

#include <functional>
#include <memory>
#include <unordered_set>

#include "tensorflow/lite/delegates/gpu/common/gpu_info.h"
#include "tensorflow/lite/delegates/gpu/common/model.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/gl/compiler/shader_code.h"
#include "tensorflow/lite/delegates/gpu/gl/compiler_options.h"
#include "tensorflow/lite/delegates/gpu/gl/node_shader.h"

namespace tflite {
namespace gpu {
namespace gl {

using ShaderCodeCallback = std::function<absl::Status(ShaderCode code)>;

class Compiler {
 public:
  virtual ~Compiler() = default;

  // Goes over a graph and generates OpenGL shaders for the given graph.
  // Callback is called for every generated shader. Callback may execute shaders
  // as they come or store them elsewhere to execute later.
  virtual absl::Status Compile(
      const GraphFloat32& graph,
      const std::unordered_set<int>& tflite_graph_io,  // NOLINT
      const ShaderCodeCallback& callback) = 0;
};

std::unique_ptr<Compiler> NewCompiler(
    const NodeShader* node_shader, const GpuInfo* gpu_info,
    const CompilationOptions& options);

}  // namespace gl
}  // namespace gpu
}  // namespace tflite

#endif  // TENSORFLOW_LITE_DELEGATES_GPU_GL_COMPILER_H_