text:
<?php

use Embark\CMS\Structures\ParameterPool as Context;

	if (!defined('__IN_SYMPHONY__')) die('
Symphony Error

You cannot directly access this file
');

	class FieldTextBox extends Field {
		const DISABLE_PROPOGATION = 1;

		protected $sizes = array();
		protected $filters = array();

	/*-------------------------------------------------------------------------
		Definition:
	-------------------------------------------------------------------------*/

		public function __construct() {
			parent::__construct();

			$this->_name = 'Text Box';

			// Set defaults:
			$this->{'text-size'} = 'medium';

			$this->sizes = array(
				array('single', false, __('Single Line')),
				array('small', false, __('Small Box')),
				array('medium', false, __('Medium Box')),
				array('large', false, __('Large Box')),
				array('huge', false, __('Huge Box'))
			);

			$this->filters = array(
				'is'				=> 'Is',
				'is-not'			=> 'Is not',
				'contains'			=> 'Contains',
				'does-not-contain'	=> 'Does not contain',
				'boolean-search'	=> 'Boolean search',
				'regex-search'		=> 'Regex search'
			);
		}

		public function create() {
			return Symphony::Database()->query(sprintf(
				"
					CREATE TABLE IF NOT EXISTS `data_%s_%s` (
						`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
						`entry_id` INT(11) UNSIGNED NOT NULL,
						`handle` VARCHAR(255) DEFAULT NULL,
						`value` TEXT DEFAULT NULL,
						`value_formatted` TEXT DEFAULT NULL,
						`word_count` INT(11) UNSIGNED DEFAULT NULL,
						PRIMARY KEY (`id`),
						KEY `entry_id` (`entry_id`),
						FULLTEXT KEY `value` (`value`),
						FULLTEXT KEY `value_formatted` (`value_formatted`)
					) ENGINE=MyISAM;
				",
				$this->{'section'},
				$this->{'element-name'}
			));
		}

		public function allowDatasourceOutputGrouping() {
			return true;
		}

		public function allowDatasourceParamOutput() {
			return true;
		}

		public function canFilter() {
			return true;
		}

		public function canPrePopulate() {
			return true;
		}

		public function isSortable() {
			return true;
		}

	/*-------------------------------------------------------------------------
		Utilities:
	-------------------------------------------------------------------------*/

		public function createHandle($value, $entry_id) {
			$handle = Lang::createHandle(strip_tags(html_entity_decode($value)));

			if ($this->isHandleLocked($handle, $entry_id)) {
				if ($this->isHandleFresh($handle, $value, $entry_id)) {
					return $this->getCurrentHandle($entry_id);
				}

				else {
					$count = 2;

 					while ($this->isHandleLocked("{$handle}-{$count}", $entry_id)) $count++;

					return "{$handle}-{$count}";
				}
			}

			return $handle;
		}

		public function getCurrentHandle($entry_id) {
			return Symphony::Database()->fetchVar('handle', 0, sprintf(
				"
					SELECT
						f.handle
					FROM
						`entries_data_%s` AS f
					WHERE
						f.entry_id = '%s'
					LIMIT 1
				",
				$this->{'id'}, $entry_id
			));
		}

		public function isHandleLocked($handle, $entry_id) {
			return (boolean)Symphony::Database()->query(
				"
					SELECT
						f.id
					FROM
						`entries_data_%s` AS f
					WHERE
						f.handle = '%s'
						%s
					LIMIT 1
				",
				array(
					$this->{'id'}, $handle,
					(!is_null($entry_id) ? "AND f.entry_id != '{$entry_id}'" : '')
				)
			);
		}

		public function isHandleFresh($handle, $value, $entry_id) {
			return (boolean)Symphony::Database()->fetchVar('id', 0, sprintf(
				"
					SELECT
						f.id
					FROM
						`entries_data_%s` AS f
					WHERE
						f.entry_id = '%s'
						AND f.value = '%s'
					LIMIT 1
				",
				$this->{'id'}, $entry_id,
				$this->cleanValue(General::sanitize($value))
			));
		}

		public function repairEntities($value) {
			return preg_replace('/&(?!(#[0-9]+|#x[0-9a-f]+|amp|lt|gt);)/i', '&', trim($value));
		}

		public function repairMarkup($value) {
			$tidy = new Tidy();
			$tidy->parseString(
				$value, array(
					'drop-font-tags'				=> true,
					'drop-proprietary-attributes'	=> true,
					'enclose-text'					=> true,
					'enclose-block-text'			=> true,
					'hide-comments'					=> true,
					'numeric-entities'				=> true,
					'output-xhtml'					=> true,
					'wrap'							=> 0,

					// HTML5 Elements:
					'new-blocklevel-tags'			=> 'section nav article aside hgroup header footer figure figcaption ruby video audio canvas details datagrid summary menu',
					'new-inline-tags'				=> 'time mark rt rp output progress meter',
					'new-empty-tags'				=> 'wbr source keygen command'
				), 'utf8'
			);

			return $tidy->body()->value;
		}

	/*-------------------------------------------------------------------------
		Settings:
	-------------------------------------------------------------------------*/

		public function findDefaultSettings(&$fields) {
			$fields['column-length'] = 75;
			$fields['text-size'] = 'medium';
			$fields['text-length'] = 'none';
			$fields['text-handle'] = 'yes';
			$fields['text-cdata'] = 'no';
		}

		public function validateSettings(MessageStack $errors, $checkForDuplicates = true) {
/*			if (trim((string)$this->{'text-length'}) == '') {
				$errors->append('text-length', __('This is a required field.'));
			}*/

			if (trim((string)$this->{'column-length'}) == '') {
				$errors->append('column-length', __('This is a required field.'));
			}

			return parent::validateSettings($errors, $checkForDuplicates);
		}

		public function displaySettingsPanel(SymphonyDOMElement $wrapper, MessageStack $errors) {
			parent::displaySettingsPanel($wrapper, $errors);

			$document = $wrapper->ownerDocument;
			$driver = Extension::load('field_textbox');
			$driver->addSettingsHeaders($document);

		/*---------------------------------------------------------------------
			Expression
		---------------------------------------------------------------------*/

			$group = $document->createElement('div');
			$group->setAttribute('class', 'group');

			$values = $this->sizes;

			foreach ($values as &$value) {
				$value[1] = $value[0] == $this->{'text-size'};
			}

			$label = Widget::Label('Size');
			$label->appendChild(Widget::Select('text-size', $values));

			$group->appendChild($label);

		/*---------------------------------------------------------------------
			Text Formatter
		---------------------------------------------------------------------*/

			$this->appendFormatterSelect(
				$group, $this->{'text-formatter'}, 'text-formatter'
			);
			$wrapper->appendChild($group);

		/*---------------------------------------------------------------------
			Validator
		---------------------------------------------------------------------*/

			$this->appendValidationSelect(
				$wrapper, $this->{'text-validator'}, 'text-validator'
			);

		/*---------------------------------------------------------------------
			Limiting
		---------------------------------------------------------------------*/

			$group = $document->createElement('div');
			$group->setAttribute('class', 'group');

			$label = Widget::Label(__('Limit'));
			$label->appendChild($document->createElement('em', __('Number of characters')));
			$input = Widget::Input('text-length', $this->{'text-length'});
			$label->appendChild($input);

			if ($errors->{'text-length'}) {
				$label = Widget::wrapFormElementWithError($label, $errors->{'text-length'});
			}

			$group->appendChild($label);

		/*---------------------------------------------------------------------
			Show characters
		---------------------------------------------------------------------*/

			$label = Widget::Label(__('Preview'));
			$label->appendChild($document->createElement('em', __('Number of characters')));
			$input = Widget::Input('column-length', $this->{'column-length'});
			$label->appendChild($input);

			if ($errors->{'column-length'}) {
				$label = Widget::wrapFormElementWithError($label, $errors->{'column-length'});
			}

			$group->appendChild($label);
			$wrapper->appendChild($group);

		/*---------------------------------------------------------------------
			Options
		---------------------------------------------------------------------*/

			$options_list = $document->createElement('ul');
			$options_list->setAttribute('class', 'options-list');

			$this->appendShowColumnCheckbox($options_list);
			$this->appendRequiredCheckbox($options_list);

			$label = Widget::Label(__('Output with handles'));
			$input = Widget::Input('text-handle', 'yes', 'checkbox');

			if ($this->{'text-handle'} == 'yes') {
				$input->setAttribute('checked', 'checked');
			}

			$label->prependChild($input);
			$item = $document->createElement('li');
			$item->appendChild($label);
			$options_list->appendChild($item);

			$label = Widget::Label(__('Output as CDATA'));
			$input = Widget::Input("text-cdata", 'yes', 'checkbox');

			if ($this->{'text-cdata'} == 'yes') {
				$input->setAttribute('checked', 'checked');
			}

			$label->prependChild($input);
			$item = $document->createElement('li');
			$item->appendChild($label);
			$options_list->appendChild($item);

			$wrapper->appendChild($options_list);
			$wrapper->setAttribute('class', $wrapper->getAttribute('class') . ' field-textbox');
		}

	/*-------------------------------------------------------------------------
		Publish:
	-------------------------------------------------------------------------*/

		public function displayPublishPanel(SymphonyDOMElement $wrapper, MessageStack $errors, Entry $entry=NULL, $data=NULL) {
			$document = $wrapper->ownerDocument;
			$driver = Extension::load('field_textbox');
			$driver->addPublishHeaders($document);

			$sortorder = $this->{'sortorder'};
			$element_name = $this->{'element-name'};
			$classes = array();

			$label = Widget::Label(
				(isset($this->{'publish-label'}) && strlen(trim($this->{'publish-label'})) > 0
					? $this->{'publish-label'}
					: $this->name)
			);

			$optional = '';

			if ($this->{'required'} != 'yes') {
				if ((integer)$this->{'text-length'} > 0) {
					$optional = $document->createDocumentFragment();
					$optional->appendChild($document->createTextNode(__('$1 of $2 remaining') . ' '));
					$optional->appendChild($document->createEntityReference('ndash'));
					$optional->appendChild($document->createTextNode(' ' . __('Optional')));
				}

				else {
					$optional = __('Optional');
				}
			}

			else if ((integer)$this->{'text-length'} > 0) {
				$optional = __('$1 of $2 remaining');
			}

			if ($optional) {
				$label->appendChild($wrapper->ownerDocument->createElement('em', $optional));
			}

			// Input box:
			if ($this->{'text-size'} == 'single') {
				$input = Widget::Input(
					"fields[$element_name]", $data->value
				);

				###
				# Delegate: ModifyTextBoxInlineFieldPublishWidget
				# Description: Allows developers modify the textbox before it is rendered in the publish forms
				$delegate = 'ModifyTextBoxInlineFieldPublishWidget';
			}

			// Text Box:
			else {
				$input = Widget::Textarea(
					"fields[$element_name]", $data->value, array('rows' => 20, 'cols' => 50)
				);

				###
				# Delegate: ModifyTextBoxFullFieldPublishWidget
				# Description: Allows developers modify the textbox before it is rendered in the publish forms
				$delegate = 'ModifyTextBoxFullFieldPublishWidget';
			}

			// Add classes:
			$classes[] = 'size-' . $this->{'text-size'};

			if ($this->{'text-formatter'} != 'none') {
				$classes[] = $this->{'text-formatter'};
			}

			$input->setAttribute('class', implode(' ', $classes));
			$input->setAttribute('length', (integer)$this->{'text-length'});

			Extension::notify(
				$delegate, '/administration/',
				array(
					'field'		=> &$this,
					'label'		=> &$label,
					'input'		=> &$input
				)
			);

			if (is_null($label)) return;

			$label->appendChild($input);

			if ($errors->valid()) {
				$label = Widget::wrapFormElementWithError($label, $errors->current()->message);
			}

			$wrapper->appendChild($label);
		}

	/*-------------------------------------------------------------------------
		Input:
	-------------------------------------------------------------------------*/

		public function validateData(MessageStack $errors, Entry $entry, $data = null) {
			$length = (integer)$this->{'text-length'};

			if(self::STATUS_OK != parent::validateData($errors, $entry, $data)) {
				return self::STATUS_ERROR;
			}

			if (!isset($data->value)) return self::STATUS_OK;

			if (!$this->applyValidationRules($data->value)) {
				$errors->append(
					null, (object)array(
					 	'message' => __("'%s' contains invalid data. Please check the contents.", array($this->{'publish-label'})),
						'code' => self::ERROR_INVALID
					)
				);

				return self::STATUS_ERROR;
			}

			if ($length > 0 and $length < strlen($data->value)) {
				$errors->append(
					null, (object)array(
					 	'message' => __("'%s' must be no longer than %s characters.", array(
							$this->{'publish-label'}, $length
						)),
						'code' => self::ERROR_INVALID
					)
				);

				return self::STATUS_ERROR;
			}

			return self::STATUS_OK;
		}

		public function applyFormatting($value) {
			if (isset($this->{'text-formatter'}) && $this->{'text-formatter'} != TextFormatter::NONE) {
				try {
					$formatter = TextFormatter::loadFromHandle($this->{'text-formatter'});
					$result = $formatter->run($value);
					$result = preg_replace('/&(?![a-z]{0,4}\w{2,3};|#[x0-9a-f]{2,6};)/i', '&', $result);

					return $result;
				}

				catch (Exception $e) {
					// Problem loading the formatter
					// TODO: Decide is we should be handling this better.
				}
			}

			return General::sanitize($value);
		}

		public function applyValidationRules($data) {
			$rule = $this->{'text-validator'};

			return ($rule ? General::validateString($data, $rule) : true);
		}

		// TODO: Fix the createHandle function
		public function processData($data, Entry $entry = null) {
			if (isset($entry->data()->{$this->{'element-name'}})) {
				$result = $entry->data()->{$this->{'element-name'}};
			}

			else {
				$result = (object)array(
					'handle'			=> null,
					'value'				=> null,
					'value_formatted'	=> null,
				);
			}

			if (!is_null($data)) {
				$data = stripslashes($data);

				$result->handle = Lang::createHandle($data);
				$result->value = $data;
				$result->value_formatted = $this->applyFormatting($data);
			}

			return $result;
		}

	/*-------------------------------------------------------------------------
		Output:
	-------------------------------------------------------------------------*/

		public function fetchIncludableElements() {
			return array(
				[
					'type' =>	'Embark\CMS\Fields\Textbox\FormattedElement',
					'handle' =>	$this->{'element-name'} . ': formatted',
					'name' =>	$this->name,
					'mode' =>	'Formatted'
				],
				[
					'type' =>	'Embark\CMS\Fields\Textbox\UnformattedElement',
					'handle' =>	$this->{'element-name'} . ': unformatted',
					'name' =>	$this->name,
					'mode' =>	'Unformatted'
				]
			);
		}

		public function appendFormattedElement(DOMElement $wrapper, $data, $encode=false, $mode=NULL, Entry $entry=NULL) {
			if ($mode == 'unformatted') {
				$value = trim($data->value);
			}

			else {
				$mode = 'formatted';
				$value = trim($data->value_formatted);
			}

			if(is_null($value) || empty($value)) return;

			$result = $wrapper->ownerDocument->createElement($this->{'element-name'});

			if ($mode == 'unformatted' or $this->{'text-cdata'} == 'yes') {
				$value = $wrapper->ownerDocument->createCDATASection($value);
				$result->appendChild($value);
			}

			else if ($value) {
				$value = $this->repairEntities($value);
				$fragment = $wrapper->ownerDocument->createDocumentFragment();

				try {
					$fragment->appendXML($value);
				}

				catch (Exception $e) {
					$value = $this->repairMarkup($value);
					$fragment->appendXML($value);
				}

				try {
					$result->appendChild($fragment);
				}

				catch (Exception $e) {
					// Only get 'Document Fragment is empty' errors here.
				}
			}

			$attributes = array(
				'mode'			=> $mode,
				'handle'		=> $data->handle,
			);

			if ($this->{'text-handle'} != 'yes') {
				unset($attributes['handle']);
			}

			foreach($attributes as $name => $value){
				$result->setAttribute($name, $value);
			}

			$wrapper->appendChild($result);
		}

		public function getParameterOutputValue($data, Entry $entry=NULL) {
			return $data->handle;
		}

	/*-------------------------------------------------------------------------
		Filtering:
	-------------------------------------------------------------------------*/

		public function getFilterTypes($data) {
			$filters = parent::getFilterTypes($data);
			$filters[] = array(
				'boolean-search', $data->type == 'boolean-search', 'Boolean Search'
			);

			return $filters;
		}

		public function buildFilterQuery($filter, &$joins, array &$where, Context $parameter_output) {
			$filter = $this->processFilter($filter);
			$filter_join = DataSource::FILTER_OR;
			$db = Symphony::Database();

			// Boolean searches:
			if ($filter->type == 'boolean-search') {
				$handle = $this->buildFilterJoin($joins);
				$value = DataSource::replaceParametersInString(
					trim($filter->value), $parameter_output
				);
				$mode = (preg_match('/^not(\W)/i', $value) ? '-' : '+');

				// Replace ' and ' with ' +':
				$value = preg_replace('/(\W)and(\W)/i', '\\1+\\2', $value);
				$value = preg_replace('/(^)and(\W)|(\W)and($)/i', '\\2\\3', $value);
				$value = preg_replace('/(\W)not(\W)/i', '\\1-\\2', $value);
				$value = preg_replace('/(^)not(\W)|(\W)not($)/i', '\\2\\3', $value);
				$value = preg_replace('/([\+\-])\s*/', '\\1', $mode . $value);

				$statement = $db->prepareQuery("MATCH ({$handle}.value) AGAINST ('%s' IN BOOLEAN MODE)", array($value));

				$where[] = "(\n\t{$statement}\n)";

				return true;
			}

			return parent::buildFilterQuery($filter, $joins, $where, $parameter_output);
		}

	/*-------------------------------------------------------------------------
		Grouping:
	-------------------------------------------------------------------------*/

		public function groupRecords($records) {
			if (!is_array($records) or empty($records)) return;

			$groups = array(
				$this->{'element-name'} => array()
			);

			foreach ($records as $record) {
				$data = $record->getData($this->{'id'});

				$value = $data['value_formatted'];
				$handle = $data['handle'];
				$element = $this->{'element-name'};

				if (!isset($groups[$element][$handle])) {
					$groups[$element][$handle] = array(
						'attr'		=> array(
							'handle'	=> $handle
						),
						'records'	=> array(),
						'groups'	=> array()
					);
				}

				$groups[$element][$handle]['records'][] = $record;
			}

			return $groups;
		}
	}

	return 'FieldTextBox';


text:
#include "config.h"

#if ENABLE(INSPECTOR)

#include "InspectorFrontendHost.h"

#include "ContextMenu.h"
#include "ContextMenuController.h"
#include "ContextMenuItem.h"
#include "ContextMenuProvider.h"
#include "DOMWrapperWorld.h"
#include "Document.h"
#include "Event.h"
#include "HitTestResult.h"
#include "InspectorFrontendClient.h"
#include "JSMainThreadExecState.h"
#include "MainFrame.h"
#include "MouseEvent.h"
#include "Node.h"
#include "Page.h"
#include "Pasteboard.h"
#include "ScriptGlobalObject.h"
#include "ScriptState.h"
#include "Sound.h"
#include "UserGestureIndicator.h"
#include <bindings/ScriptFunctionCall.h>
#include <wtf/StdLibExtras.h>

using namespace Inspector;

namespace WebCore {

#if ENABLE(CONTEXT_MENUS)
class FrontendMenuProvider : public ContextMenuProvider {
public:
    static PassRefPtr<FrontendMenuProvider> create(InspectorFrontendHost* frontendHost, Deprecated::ScriptObject frontendApiObject, const Vector<ContextMenuItem>& items)
    {
        return adoptRef(new FrontendMenuProvider(frontendHost, frontendApiObject, items));
    }

    void disconnect()
    {
        m_frontendApiObject = Deprecated::ScriptObject();
        m_frontendHost = nullptr;
    }

private:
    FrontendMenuProvider(InspectorFrontendHost* frontendHost, Deprecated::ScriptObject frontendApiObject, const Vector<ContextMenuItem>& items)
        : m_frontendHost(frontendHost)
        , m_frontendApiObject(frontendApiObject)
        , m_items(items)
    {
    }

    virtual ~FrontendMenuProvider()
    {
        contextMenuCleared();
    }

    virtual void populateContextMenu(ContextMenu* menu) override
    {
        for (size_t i = 0; i < m_items.size(); ++i)
            menu->appendItem(m_items[i]);
    }

    virtual void contextMenuItemSelected(ContextMenuItem* item) override
    {
        if (m_frontendHost) {
            UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
            int itemNumber = item->action() - ContextMenuItemBaseCustomTag;

            Deprecated::ScriptFunctionCall function(m_frontendApiObject, "contextMenuItemSelected", WebCore::functionCallHandlerFromAnyThread);
            function.appendArgument(itemNumber);
            function.call();
        }
    }

    virtual void contextMenuCleared() override
    {
        if (m_frontendHost) {
            Deprecated::ScriptFunctionCall function(m_frontendApiObject, "contextMenuCleared", WebCore::functionCallHandlerFromAnyThread);
            function.call();

            m_frontendHost->m_menuProvider = nullptr;
        }
        m_items.clear();
    }

    InspectorFrontendHost* m_frontendHost;
    Deprecated::ScriptObject m_frontendApiObject;
    Vector<ContextMenuItem> m_items;
};
#endif

InspectorFrontendHost::InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage)
    : m_client(client)
    , m_frontendPage(frontendPage)
#if ENABLE(CONTEXT_MENUS)
    , m_menuProvider(nullptr)
#endif
{
}

InspectorFrontendHost::~InspectorFrontendHost()
{
    ASSERT(!m_client);
}

void InspectorFrontendHost::disconnectClient()
{
    m_client = nullptr;
#if ENABLE(CONTEXT_MENUS)
    if (m_menuProvider)
        m_menuProvider->disconnect();
#endif
    m_frontendPage = nullptr;
}

void InspectorFrontendHost::loaded()
{
    if (m_client)
        m_client->frontendLoaded();
}

void InspectorFrontendHost::requestSetDockSide(const String& side)
{
    if (!m_client)
        return;
    if (side == "undocked")
        m_client->requestSetDockSide(InspectorFrontendClient::UNDOCKED);
    else if (side == "right")
        m_client->requestSetDockSide(InspectorFrontendClient::DOCKED_TO_RIGHT);
    else if (side == "bottom")
        m_client->requestSetDockSide(InspectorFrontendClient::DOCKED_TO_BOTTOM);
}

void InspectorFrontendHost::closeWindow()
{
    if (m_client) {
        m_client->closeWindow();
        disconnectClient(); // Disconnect from client.
    }
}

void InspectorFrontendHost::bringToFront()
{
    if (m_client)
        m_client->bringToFront();
}

void InspectorFrontendHost::setZoomFactor(float zoom)
{
    m_frontendPage->mainFrame().setPageAndTextZoomFactors(zoom, 1);
}

void InspectorFrontendHost::inspectedURLChanged(const String& newURL)
{
    if (m_client)
        m_client->inspectedURLChanged(newURL);
}

void InspectorFrontendHost::setAttachedWindowHeight(unsigned height)
{
    if (m_client)
        m_client->changeAttachedWindowHeight(height);
}

void InspectorFrontendHost::setAttachedWindowWidth(unsigned width)
{
    if (m_client)
        m_client->changeAttachedWindowWidth(width);
}

void InspectorFrontendHost::setToolbarHeight(unsigned height)
{
    if (m_client)
        m_client->setToolbarHeight(height);
}

void InspectorFrontendHost::moveWindowBy(float x, float y) const
{
    if (m_client)
        m_client->moveWindowBy(x, y);
}

String InspectorFrontendHost::localizedStringsURL()
{
    return m_client ? m_client->localizedStringsURL() : "";
}

String InspectorFrontendHost::debuggableType()
{
    return ASCIILiteral("web");
}

void InspectorFrontendHost::copyText(const String& text)
{
    Pasteboard::createForCopyAndPaste()->writePlainText(text, Pasteboard::CannotSmartReplace);
}

void InspectorFrontendHost::openInNewTab(const String& url)
{
    if (m_client)
        m_client->openInNewTab(url);
}

bool InspectorFrontendHost::canSave()
{
    if (m_client)
        return m_client->canSave();
    return false;
}

void InspectorFrontendHost::save(const String& url, const String& content, bool base64Encoded, bool forceSaveAs)
{
    if (m_client)
        m_client->save(url, content, base64Encoded, forceSaveAs);
}

void InspectorFrontendHost::append(const String& url, const String& content)
{
    if (m_client)
        m_client->append(url, content);
}

void InspectorFrontendHost::close(const String&)
{
}

void InspectorFrontendHost::sendMessageToBackend(const String& message)
{
    if (m_client)
        m_client->sendMessageToBackend(message);
}

#if ENABLE(CONTEXT_MENUS)
void InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMenuItem>& items)
{
    if (!event)
        return;

    ASSERT(m_frontendPage);
    JSC::ExecState* frontendExecState = execStateFromPage(debuggerWorld(), m_frontendPage);
    Deprecated::ScriptObject frontendApiObject;
    if (!ScriptGlobalObject::get(frontendExecState, "InspectorFrontendAPI", frontendApiObject)) {
        ASSERT_NOT_REACHED();
        return;
    }
    RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items);
    m_frontendPage->contextMenuController().showContextMenu(event, menuProvider);
    m_menuProvider = menuProvider.get();
}
#endif

void InspectorFrontendHost::dispatchEventAsContextMenuEvent(Event* event)
{
#if ENABLE(CONTEXT_MENUS) && USE(ACCESSIBILITY_CONTEXT_MENUS)
    if (!event || !event->isMouseEvent())
        return;

    Frame* frame = event->target()->toNode()->document().frame();
    MouseEvent* mouseEvent = toMouseEvent(event);
    IntPoint mousePoint = IntPoint(mouseEvent->clientX(), mouseEvent->clientY());

    m_frontendPage->contextMenuController().showContextMenuAt(frame, mousePoint);
#else
    UNUSED_PARAM(event);
#endif
}

bool InspectorFrontendHost::isUnderTest()
{
    return m_client && m_client->isUnderTest();
}

void InspectorFrontendHost::beep()
{
    systemBeep();
}

bool InspectorFrontendHost::canSaveAs()
{
    return false;
}

bool InspectorFrontendHost::canInspectWorkers()
{
    return false;
}

} // namespace WebCore

#endif // ENABLE(INSPECTOR)

redpajama_set_name: RedPajamaGithub


text:
@interface SPLoginWayViewController () <WXApiManagerDelegate,TencentSessionDelegate> {
    TencentOAuth *_tencentOAuth;
}

@property (weak, nonatomic) IBOutlet UIButton *qqLoginButton;

@property (weak, nonatomic) IBOutlet UIButton *weChatLoginButton;
@property (weak, nonatomic) IBOutlet UIView *orView;

@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UILabel *loginLabel;

@property (weak, nonatomic) IBOutlet UILabel *protocolLabel;

@end

@implementation SPLoginWayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUp];
}

- (void)setUp {

    if ([TencentOAuth iphoneQQInstalled]) {
        _qqLoginButton.layer.cornerRadius = 20;
        _qqLoginButton.layer.masksToBounds = true;
        [_qqLoginButton setBackgroundColor:[SPGlobalConfig themeColor]];
        [_qqLoginButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    } else {
        _qqLoginButton.hidden = true;
    }

    [WXApiManager sharedManager].delegate = self;

    if ([WXApi isWXAppInstalled]) {
        _weChatLoginButton.layer.cornerRadius = 20;
        _weChatLoginButton.layer.masksToBounds = true;
        [_weChatLoginButton setBackgroundColor:[SPGlobalConfig themeColor]];
        [_weChatLoginButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    } else {
        _weChatLoginButton.hidden = true;
        _orView.hidden = true;
    }

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLoginLabelAction:)];
    [_loginLabel addGestureRecognizer:tapGesture];
    _loginLabel.userInteractionEnabled = true;

    NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:@"登录注册表明您同意【运动页服务协议】"];
    NSRange contentRange = {10,7};
    [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
    _protocolLabel.attributedText = content;
    _protocolLabel.userInteractionEnabled = true;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(protocolAction:)];
    [_protocolLabel addGestureRecognizer:tap];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)protocolAction:(id)sender {
    SPProtocolViewController *protocolVC = [[SPProtocolViewController alloc] init];
    [self presentViewController:protocolVC animated:true completion:nil];
}

- (IBAction)qqLoginAction:(id)sender {
    if ([TencentOAuth iphoneQQInstalled]) {

        _tencentOAuth = [[TencentOAuth alloc] initWithAppId:KEY_TENCENT andDelegate:self];
        NSArray *permissions = @[kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO];
        [_tencentOAuth authorize:permissions];

    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有安装QQ" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:true completion:nil];
    }
}

- (IBAction)weChatLoginAction:(id)sender {
    if ([WXApi isWXAppInstalled]) {
        [WXApiRequestHandler sendAuthRequestScope:@"snsapi_userinfo"
                                            State:@"sportspage"
                                           OpenID:@""
                                 InViewController:self];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有安装微信" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:true completion:nil];
    }
}

- (IBAction)registerAction:(id)sender {
    SPRegisterViewController *registerViewController = [[SPRegisterViewController alloc] init];
    [self.navigationController pushViewController:registerViewController animated:true];
}

- (void)tapLoginLabelAction:(UITapGestureRecognizer *)sender {
    SPLoginViewController *loginViewController = [[SPLoginViewController alloc] init];
    [self.navigationController pushViewController:loginViewController animated:true];
}

#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
    if(response.errCode == 0) {
        NSLog(@"用户同意授权");
        [self getAccesToken:response.code];
    } else if(response.errCode == -2) {
        NSLog(@"用户取消授权");
    } else if(response.errCode == -4) {
        NSLog(@"用户拒绝授权");
    } else {
        NSLog(@"todo");
    }
}

-(void)getAccesToken:(NSString *)code {
    NSString* base = @"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code";
    NSString *url =[NSString stringWithFormat:base,KEY_WEIXIN,KEY_SECRET,code];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                [MBProgressHUD showHUDAddedTo:self.view animated:true];
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

                NSString *access_token = [dic objectForKey:@"access_token"];
                NSString *openid = [dic objectForKey:@"openid"];
                NSString *unionid = dic[@"unionid"];

                [[SPAuthBusinessUnit shareInstance] checkWxRegisterWithOpenid:openid successful:^(NSString *successsfulString) {
                    if ([successsfulString isEqualToString:@"600"]) {
                        [MBProgressHUD hideHUDForView:self.view animated:true];
                        [self getUserInfo:access_token withOpenId:openid];
                    } else if ([successsfulString isEqualToString:@"200"]) {

                        [[SPAuthBusinessUnit shareInstance] registerWithWeChatByUnionId:unionid openid:openid successful:^(NSString *successsfulString) {

                            if ([successsfulString isEqualToString:@"600"] || [successsfulString isEqualToString:@"200"]) {

                                [[SPAuthBusinessUnit shareInstance] loginWithWeChatByOpenid:openid successful:^(SPUserInfoModel *model) {
                                    if (model) {
                                        [MBProgressHUD hideHUDForView:self.view animated:true];
                                        [self loginRongCloudServerWithToken:model.token];
                                    } else {
                                        [MBProgressHUD hideHUDForView:self.view animated:true];
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
                                        });
                                    }
                                } failure:^(NSString *errorString) {
                                    NSLog(@"%@",successsfulString);
                                    NSLog(@"loginWithWeChatByOpenid AFN ERROR");
                                    [MBProgressHUD hideHUDForView:self.view animated:true];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                                    });
                                }];
                            } else {
                                NSLog(@"%@",successsfulString);
                                [MBProgressHUD hideHUDForView:self.view animated:true];
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
                                });
                            }

                        } failure:^(NSString *errorString) {
                            NSLog(@"registerWithWeChatByUnionId AFN ERROR");
                            NSLog(@"%@",successsfulString);
                            [MBProgressHUD hideHUDForView:self.view animated:true];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                            });
                        }];

                    } else {
                        NSLog(@"%@",successsfulString);
                        [MBProgressHUD hideHUDForView:self.view animated:true];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                        });
                    }
                } failure:^(NSString *errorString) {
                    NSLog(@"checkWxRegisterWithOpenid AFN ERROR");
                    [MBProgressHUD hideHUDForView:self.view animated:true];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                    });
                }];
            } else {
                [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
            }
        });
    });
}

//通过AccessToken获取用户信息
-(void)getUserInfo:(NSString *)access_token withOpenId:(NSString *)openid {
    NSString* base = @"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@";
    NSString *url =[NSString stringWithFormat:base,access_token,openid];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

                NSString *jsonStr = [self DataTOjsonString:dic];
                [MBProgressHUD showHUDAddedTo:self.view animated:true];
                [[SPAuthBusinessUnit shareInstance] addWxclientWithJsonStr:jsonStr openid:openid successful:^(NSString *successsfulString) {
                    if ([successsfulString isEqualToString:@"200"]) {

                        [[SPAuthBusinessUnit shareInstance] registerWithWeChatByUnionId:dic[@"unionid"] openid:openid successful:^(NSString *successsfulString) {

                            if ([successsfulString isEqualToString:@"200"] || [successsfulString isEqualToString:@"600"]) {
                                [[SPAuthBusinessUnit shareInstance] loginWithWeChatByOpenid:openid successful:^(SPUserInfoModel *model) {

                                    if (model) {
                                        [MBProgressHUD hideHUDForView:self.view animated:true];
                                        [self loginRongCloudServerWithToken:model.token];
                                    } else {
                                        [MBProgressHUD hideHUDForView:self.view animated:true];
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
                                        });
                                    }

                                } failure:^(NSString *errorString) {
                                    NSLog(@"loginWithWeChatByOpenid AFN ERROR");
                                    NSLog(@"%@",successsfulString);
                                    [MBProgressHUD hideHUDForView:self.view animated:true];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                                    });
                                }];
                            } else {
                                [MBProgressHUD hideHUDForView:self.view animated:true];
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    [SPGlobalConfig showTextOfHUD:@"注册失败" ToView:self.view];
                                });
                            }

                        } failure:^(NSString *errorString) {
                            NSLog(@"registerWithWeChatByUnionId AFN ERROR");
                            [MBProgressHUD hideHUDForView:self.view animated:true];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                            });
                        }];
                    } else {
                        NSLog(@"%@",successsfulString);
                        [MBProgressHUD hideHUDForView:self.view animated:true];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                        });
                    }
                } failure:^(NSString *errorString) {
                    NSLog(@"addWxclientWithJsonStr AFN ERROR");
                    [MBProgressHUD hideHUDForView:self.view animated:true];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                    });
                }];

            }
        });
    });
}

#pragma mark - InitRongCloud
- (void)loginRongCloudServerWithToken:(NSString *)token {
    [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
        NSLog(@"登陆成功,当前登录用户ID:%@",userId);

        [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
        [[NSUserDefaults standardUserDefaults] setBool:true forKey:@"isAlreadyLogin"];
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        //向后台发送CID
        NSString *CID = [[NSUserDefaults standardUserDefaults] stringForKey:@"CID"];
        if (CID) {
            [[SPUserBusinessUnit shareInstance] regPushServiceWithUserId:userId cid:CID platform:@"iOS" successful:^(NSString *successsfulString) {
                if ([successsfulString isEqualToString:@"successful"]) {
                    NSLog(@"regPushService successful:%@",successsfulString);
                } else {
                    NSLog(@"regPushService failure:%@",successsfulString);
                }
            } failure:^(NSString *errorString) {
                NSLog(@"regPushService AFN ERROR:%@",errorString);
            }];
        } else {
            NSLog(@"CID为空");
        }

        //通过userId搜索user用户的好友,全局缓存
        [[SPIMBusinessUnit shareInstance] getFriendsListWithUserId:userId successful:^(NSMutableArray *friendsSortedList, NSMutableArray *friendsList) {
            if (friendsList.count != 0 && friendsSortedList.count != 0) {
                AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                delegate.friendsSortedListArray = friendsSortedList;
                delegate.friendsListArray = friendsList;
                NSLog(@"获取好友缓存成功");
            }
        } failure:^(NSString *errorString) {
            NSLog(@"网络请求好友数据失败:%@",errorString);
        }];

        //todo 群组缓存

        //模态跳转回rootViewController,登录完成
        [self.navigationController dismissViewControllerAnimated:true completion:nil];

    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%ld", (long)status);
        dispatch_async(dispatch_get_main_queue(), ^{
            [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
        });
    } tokenIncorrect:^{
        NSLog(@"token错误");
        dispatch_async(dispatch_get_main_queue(), ^{
            [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
        });
    }];
}

- (NSString*)DataTOjsonString:(id)object {
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

#pragma mark - Config
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - TencentSessionDelegate
- (void)tencentDidLogin {
    if (_tencentOAuth.accessToken.length != 0) {
        [_tencentOAuth getUserInfo];
    } else {
        [SPGlobalConfig showTextOfHUD:@"获取用户信息失败" ToView:self.view];
    }
}

- (void)tencentDidNotLogin:(BOOL)cancelled {
    if (cancelled) {
        NSLog(@"用户登录取消");
    } else {
        [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
    }
}

- (void)tencentDidNotNetWork {
    [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
}

- (void)getUserInfoResponse:(APIResponse *) response {
    if (response && response.retCode == URLREQUEST_SUCCEED) {
        NSLog(@"json:%@",response.jsonResponse);

        [self tencentAction:response];

    } else {
        [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
    }
}

- (void)tencentAction:(APIResponse *)response {

    [MBProgressHUD showHUDAddedTo:self.view animated:true];

    [[SPAuthBusinessUnit shareInstance] checkQQRegisterWithOpenid:_tencentOAuth.openId successful:^(NSString *successsfulString) {

        if ([successsfulString isEqualToString:@"600"]) {
            [MBProgressHUD hideHUDForView:self.view animated:true];

            [self getQQUserInfo:response.jsonResponse];

        } else if ([successsfulString isEqualToString:@"200"]) {

            [[SPAuthBusinessUnit shareInstance] registerWithQQByOpenid:_tencentOAuth.openId successful:^(NSString *successsfulString) {

                if ([successsfulString isEqualToString:@"600"] || [successsfulString isEqualToString:@"200"]) {

                    [[SPAuthBusinessUnit shareInstance] loginWithQQByOpenid:_tencentOAuth.openId successful:^(SPUserInfoModel *model) {

                        [MBProgressHUD hideHUDForView:self.view animated:true];
                        [self loginRongCloudServerWithToken:model.token];

                    } failure:^(NSString *errorString) {

                        [MBProgressHUD hideHUDForView:self.view animated:true];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
                        });

                    }];

                } else {

                    NSLog(@"%@",successsfulString);
                    [MBProgressHUD hideHUDForView:self.view animated:true];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
                    });

                }

            } failure:^(NSString *errorString) {
                NSLog(@"registerWithQQByOpenid AFN ERROR");
                NSLog(@"%@",successsfulString);
                [MBProgressHUD hideHUDForView:self.view animated:true];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                });
            }];

        } else {
            NSLog(@"%@",successsfulString);
            [MBProgressHUD hideHUDForView:self.view animated:true];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
            });
        }

    } failure:^(NSString *errorString) {
        NSLog(@"checkQQRegisterWithOpenid AFN ERROR");
        [MBProgressHUD hideHUDForView:self.view animated:true];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
        });
    }];

}

- (void)getQQUserInfo:(NSDictionary *)jsonDic {

    NSString *jsonStr = [self DataTOjsonString:jsonDic];

    [MBProgressHUD showHUDAddedTo:self.view animated:true];

    [[SPAuthBusinessUnit shareInstance] addQQclientWithJsonStr:jsonStr openid:_tencentOAuth.openId successful:^(NSString *successsfulString) {

        if ([successsfulString isEqualToString:@"200"]) {

            [[SPAuthBusinessUnit shareInstance] registerWithQQByOpenid:_tencentOAuth.openId successful:^(NSString *successsfulString) {

                if ([successsfulString isEqualToString:@"200"] || [successsfulString isEqualToString:@"600"]) {

                    [[SPAuthBusinessUnit shareInstance] loginWithQQByOpenid:_tencentOAuth.openId successful:^(SPUserInfoModel *model) {

                        if (model) {
                            [MBProgressHUD hideHUDForView:self.view animated:true];
                            [self loginRongCloudServerWithToken:model.token];
                        } else {
                            [MBProgressHUD hideHUDForView:self.view animated:true];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [SPGlobalConfig showTextOfHUD:@"登录失败" ToView:self.view];
                            });
                        }

                    } failure:^(NSString *errorString) {
                        NSLog(@"loginWithQQByOpenid AFN ERROR");
                        NSLog(@"%@",successsfulString);
                        [MBProgressHUD hideHUDForView:self.view animated:true];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                        });
                    }];

                } else {
                    [MBProgressHUD hideHUDForView:self.view animated:true];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SPGlobalConfig showTextOfHUD:@"注册失败" ToView:self.view];
                    });
                }

            } failure:^(NSString *errorString) {
                NSLog(@"registerWithQQByOpenid AFN ERROR");
                [MBProgressHUD hideHUDForView:self.view animated:true];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
                });
            }];

        } else {
            NSLog(@"%@",successsfulString);
            [MBProgressHUD hideHUDForView:self.view animated:true];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
            });
        }

    } failure:^(NSString *errorString) {
        NSLog(@"addQQclientWithJsonStr AFN ERROR");
        [MBProgressHUD hideHUDForView:self.view animated:true];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SPGlobalConfig showTextOfHUD:@"网络请求失败" ToView:self.view];
        });
    }];

}

@end


text:
Evature Voice Recognition
--------------------------

Classes in this folder have confusing names and it is hard to tell how one is dependent on an another,
so to make it clearer here is a short summary, from top level to the lower levels:

  Activate voice recognition - without GUI
  this is the responsibility of the class "EvaVoiceComponent"

  SoundLevelView -
  The application can use the "SoundLevelView" class if it wants to integrate the "wavy recording volume" lines visualization in its.

The rest of the classes are lower level for internal use only.

1. SpeechAudioStreamer -
this class listens to the microphone in a different thread, its output is an encoded stream of audio.
The class uses VAD algorithm to detect silence and stop the recording.
The actual encoding is done in the class FLACStreamEncoder - which is actually a bridge to the C++ Flac library.

2. FLACStreamEncoder - see above - encodes a stream of PCM audio into FLAC audio (in its own thread).

3. EvaVoiceClient - this class is responsible to upload a stream using chunked HTTP POST.
4. EvaTextClient - responsible for sending Eva requests via text (eg. when undo'ing or editing last utterance).
5. EvaSpeak - responsible for TTS (Text to Speech) initalizing, speech queue and speech callbacks.
6. EvaLocationUpdater - responsible for updating location from GPS or other location provider.
7. DebugStream - this is a class that wraps the encoding stream -
it helped debug the process, and also it adds profiling data such as when the streaming actually started and when it actually finished.
These timestamps are hidden when the wiring goes directly from the Encoder to the Uploader - both are 3rd party code (FLAC lib and Android platform).


text:
import { useCallback } from 'haunted';
import { useWeakState } from './use-weak-state';
import { isGroup } from './utils';

export const useCollapsibleItems = (callback, foldCallback) => {
	const { setItemState, state, signal } = useWeakState(),
		toggleFold = useCallback((item, folded) => {
			if (!isGroup(item)) {
				return;
			}

			setItemState(item, state => ({
				folded: folded !== undefined ? folded : !state.folded
			}));

			foldCallback(item);
		}, []),
		toggleCollapse = useCallback((item, collapsed) => {
			if (isGroup(item)) {
				return;
			}

			setItemState(item, state => ({
				expanded: collapsed !== undefined ? !collapsed : !state.expanded
			}));

			callback(item);
		}, []);

	return {
		state,
		signal,
		toggleFold,
		toggleCollapse
	};
};


text:
module Refinery
  module Crud

    def self.default_options(model_name)
      singular_name = model_name.to_s
      class_name = singular_name.camelize
      plural_name = singular_name.pluralize
      this_class = class_name.constantize.base_class

      {
        :title_attribute => "title",
        :order => ('position ASC' if this_class.table_exists? and this_class.column_names.include?('position')),
        :conditions => '',
        :sortable => true,
        :searchable => true,
        :include => [],
        :paging => true,
        :search_conditions => '',
        :redirect_to_url => "admin_#{plural_name}_url"
      }
    end

    def self.append_features(base)
      super
      base.extend(ClassMethods)
    end

    module ClassMethods

      def crudify(model_name, options = {})
        options = ::Refinery::Crud.default_options(model_name).merge(options)

        singular_name = model_name.to_s
        class_name = singular_name.camelize
        plural_name = singular_name.pluralize

        module_eval %(
          prepend_before_filter :find_#{singular_name},
                                :only => [:update, :destroy, :edit, :show]

          def new
            @#{singular_name} = #{class_name}.new
          end

          def create
            # if the position field exists, set this object as last object, given the conditions of this class.
            if #{class_name}.column_names.include?("position")
              params[:#{singular_name}].merge!({
                :position => ((#{class_name}.maximum(:position, :conditions => #{options[:conditions].inspect})||-1) + 1)
              })
            end

            if (@#{singular_name} = #{class_name}.create(params[:#{singular_name}])).valid?
              (request.xhr? ? flash.now : flash).notice = t(
                'refinery.crudify.created',
                :what => "'\#{@#{singular_name}.#{options[:title_attribute]}}'"
              )

              unless from_dialog?
                unless params[:continue_editing] =~ /true|on|1/
                  redirect_back_or_default(#{options[:redirect_to_url]})
                else
                  unless request.xhr?
                    redirect_to :back
                  else
                    render :partial => "/shared/message"
                  end
                end
              else
                render :text => "<script>parent.window.location = '\#{#{options[:redirect_to_url]}}';</script>"
              end
            else
              unless request.xhr?
                render :action => 'new'
              else
                render :partial => "/shared/admin/error_messages",
                       :locals => {
                         :object => @#{singular_name},
                         :include_object_name => true
                       }
              end
            end
          end

          def edit
            # object gets found by find_#{singular_name} function
          end

          def update
            if @#{singular_name}.update_attributes(params[:#{singular_name}])
              (request.xhr? ? flash.now : flash).notice = t(
                'refinery.crudify.updated',
                :what => "'\#{@#{singular_name}.#{options[:title_attribute]}}'"
              )

              unless from_dialog?
                unless params[:continue_editing] =~ /true|on|1/
                  redirect_back_or_default(#{options[:redirect_to_url]})
                else
                  unless request.xhr?
                    redirect_to :back
                  else
                    render :partial => "/shared/message"
                  end
                end
              else
                render :text => "<script>parent.window.location = '\#{#{options[:redirect_to_url]}}';</script>"
              end
            else
              unless request.xhr?
                render :action => 'edit'
              else
                render :partial => "/shared/admin/error_messages",
                       :locals => {
                         :object => @#{singular_name},
                         :include_object_name => true
                       }
              end
            end
          end

          def destroy
            # object gets found by find_#{singular_name} function
            title = @#{singular_name}.#{options[:title_attribute]}
            if @#{singular_name}.destroy
              flash.notice = t('destroyed', :scope => 'refinery.crudify', :what => "'\#{title}'")
            end

            redirect_to #{options[:redirect_to_url]}
          end

          # Finds one single result based on the id params.
          def find_#{singular_name}
            @#{singular_name} = #{class_name}.find(params[:id],
                                                   :include => #{options[:include].map(&:to_sym).inspect})
          end

          # Find the collection of @#{plural_name} based on the conditions specified into crudify
          # It will be ordered based on the conditions specified into crudify
          # And eager loading is applied as specified into crudify.
          def find_all_#{plural_name}(conditions = #{options[:conditions].inspect})
            @#{plural_name} = #{class_name}.where(conditions).includes(
                                #{options[:include].map(&:to_sym).inspect}
                              ).order("#{options[:order]}")
          end

          # Paginate a set of @#{plural_name} that may/may not already exist.
          def paginate_all_#{plural_name}
            # If we have already found a set then we don't need to again
            find_all_#{plural_name} if @#{plural_name}.nil?

            paging_options = {:page => params[:page]}

            # Seems will_paginate doesn't always use the implicit method.
            if #{class_name}.methods.map(&:to_sym).include?(:per_page)
              paging_options.update({:per_page => #{class_name}.per_page})
            end

            @#{plural_name} = @#{plural_name}.paginate(paging_options)
          end

          # Returns a weighted set of results based on the query specified by the user.
          def search_all_#{plural_name}
            # First find normal results.
            find_all_#{plural_name}(#{options[:search_conditions].inspect})

            # Now get weighted results by running the query against the results already found.
            @#{plural_name} = @#{plural_name}.with_query(params[:search])
          end

          # Ensure all methods are protected so that they should only be called
          # from within the current controller.
          protected :find_#{singular_name},
                    :find_all_#{plural_name},
                    :paginate_all_#{plural_name},
                    :search_all_#{plural_name}
        )

        # Methods that are only included when this controller is searchable.
        if options[:searchable]
          if options[:paging]
            module_eval %(
              def index
                search_all_#{plural_name} if searching?
                paginate_all_#{plural_name}
              end
            )
          else
            module_eval %(
              def index
                unless searching?
                  find_all_#{plural_name}
                else
                  search_all_#{plural_name}
                end
              end
            )
          end

        else
          if options[:paging]
            module_eval %(
              def index
                paginate_all_#{plural_name}
              end
            )
          else
            module_eval %(
              def index
                find_all_#{plural_name}
              end
            )
          end

        end

        if options[:sortable]
          module_eval %(
            def reorder
              find_all_#{plural_name}
            end

            # Based upon http://github.com/matenia/jQuery-Awesome-Nested-Set-Drag-and-Drop
            def update_positions
              previous = nil
              # The list doesn't come to us in the correct order. Frustration.
              0.upto((newlist ||= params[:ul]).length - 1) do |index|
                hash = newlist[index.to_s]
                moved_item_id = hash['id'].split(/#{singular_name}\\_?/)
                @current_#{singular_name} = #{class_name}.find_by_id(moved_item_id)

                if @current_#{singular_name}.respond_to?(:move_to_root)
                  if previous.present?
                    @current_#{singular_name}.move_to_right_of(#{class_name}.find_by_id(previous))
                  else
                    @current_#{singular_name}.move_to_root
                  end
                else
                  @current_#{singular_name}.update_attribute(:position, index)
                end

                if hash['children'].present?
                  update_child_positions(hash, @current_#{singular_name})
                end

                previous = moved_item_id
              end

              #{class_name}.rebuild! if #{class_name}.respond_to?(:rebuild!)
              render :nothing => true
            end

            def update_child_positions(node, #{singular_name})
              0.upto(node['children'].length - 1) do |child_index|
                child = node['children'][child_index.to_s]
                child_id = child['id'].split(/#{singular_name}\_?/)
                child_#{singular_name} = #{class_name}.find_by_id(child_id)
                child_#{singular_name}.move_to_child_of(#{singular_name})

                if child['children'].present?
                  update_child_positions(child, child_#{singular_name})
                end
              end
            end

          )
        end

        module_eval %(
          def self.sortable?
            #{options[:sortable].to_s}
          end

          def self.searchable?
            #{options[:searchable].to_s}
          end
        )

      end

    end

  end
end


text:
package graph

import (
	"github.com/serulian/compiler/compilercommon"
	"github.com/serulian/compiler/compilergraph"
	"github.com/serulian/compiler/webidl/parser"
)

// IRGParameter wraps a WebIDL parameter.
type IRGParameter struct {
	compilergraph.GraphNode
	irg *WebIRG // The parent IRG.
}

// Name returns the name of the parameter.
func (i *IRGParameter) Name() string {
	return i.GraphNode.Get(parser.NodePredicateParameterName)
}

// IsOptional returns true if this parameter is optional.
func (i *IRGParameter) IsOptional() bool {
	_, isOptional := i.GraphNode.TryGet(parser.NodePredicateParameterOptional)
	return isOptional
}

// DeclaredType returns the declared type of the parameter.
func (i *IRGParameter) DeclaredType() string {
	return i.GraphNode.Get(parser.NodePredicateParameterType)
}

// SourceRange returns the source range of the parameter in source.
func (i *IRGParameter) SourceRange() (compilercommon.SourceRange, bool) {
	return i.irg.SourceRangeOf(i.GraphNode)
}


text:
include_recipe 'osx::common'

osx_userdefaults 'Dock :: Automatically hide the dock?' do
  domain 'com.apple.dock'
  key 'autohide'
  type 'bool'
  value node['osx']['settings']['dock']['autohide']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Enable dock magnification on mouse over?' do
  domain 'com.apple.dock'
  key 'magnification'
  type 'bool'
  value node['osx']['settings']['dock']['magnification']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Minimize applications into their dock launcher?' do
  domain 'com.apple.dock'
  key 'minimize-to-application'
  type 'bool'
  value node['osx']['settings']['dock']['minimize-to-app']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Show the indicator lights under running applications?' do
  domain 'com.apple.dock'
  key 'show-process-indicators'
  type 'bool'
  value node['osx']['settings']['dock']['process-indicators']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Use a flat 2D style?' do
  domain 'com.apple.dock'
  key 'no-glass'
  type 'bool'
  value node['osx']['settings']['dock']['flat-2d-style']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Show shadows behind items?' do
  domain 'com.apple.dock'
  key 'showshadow'
  type 'bool'
  value node['osx']['settings']['dock']['shadows']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults "Dock :: Apply the 'scale' effect to minimizing applications" do
  domain 'com.apple.dock'
  key 'mineffect'
  type 'string'
  value node['osx']['settings']['dock']['minimize_effect']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Icon Size (Normal)' do
  domain 'com.apple.dock'
  key 'tilesize'
  type 'int'
  value node['osx']['settings']['dock']['iconsize_normal']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Icon Size (Magnified)' do
  domain 'com.apple.dock'
  key 'largesize'
  type 'int'
  value node['osx']['settings']['dock']['iconsize_magnified']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Disable animated transition between Spaces' do
  domain 'com.apple.dock'
  key 'workspaces-swoosh-animation-off'
  type 'bool'
  value node['osx']['settings']['dock']['disable_spaces_swoosh']
  notifies :run, 'execute[killall Dock]', :delayed
end

osx_userdefaults 'Dock :: Position of the Dock on screen' do
  domain 'com.apple.dock'
  key 'orientation'
  type 'string'
  value node['osx']['settings']['dock']['orientation']
  notifies :run, 'execute[killall Dock]', :delayed
end


text:
package org.deeplearning4j.nn.modelimport.keras.layers.convolutional;

import org.deeplearning4j.nn.conf.ConvolutionMode;
import org.deeplearning4j.nn.modelimport.keras.config.KerasLayerConfiguration;
import org.deeplearning4j.nn.modelimport.keras.exceptions.InvalidKerasConfigurationException;
import org.deeplearning4j.nn.modelimport.keras.exceptions.UnsupportedKerasConfigurationException;
import org.deeplearning4j.nn.modelimport.keras.utils.KerasLayerUtils;
import org.nd4j.linalg.util.ArrayUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Utility functionality for Keras convolution layers.
 *
 * @author Max Pumperla
 */
public class KerasConvolutionUtils {

    /**
     * Get (convolution) stride from Keras layer configuration.
     *
     * @param layerConfig dictionary containing Keras layer configuration
     * @return
     * @throws InvalidKerasConfigurationException
     */
    public static int[] getStrideFromConfig(Map<String, Object> layerConfig, int dimension,
                                            KerasLayerConfiguration conf)
            throws InvalidKerasConfigurationException {
        Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
        int[] strides = null;
        if (innerConfig.containsKey(conf.getLAYER_FIELD_CONVOLUTION_STRIDES()) && dimension == 2) {
            /* 2D Convolutional layers. */
            List<Integer> stridesList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_CONVOLUTION_STRIDES());
            strides = ArrayUtil.toArray(stridesList);
        } else if (innerConfig.containsKey(conf.getLAYER_FIELD_SUBSAMPLE_LENGTH()) && dimension == 1) {
           /* 1D Convolutional layers. */
            int subsampleLength = (int) innerConfig.get(conf.getLAYER_FIELD_SUBSAMPLE_LENGTH());
            strides = new int[]{subsampleLength};
        } else if (innerConfig.containsKey(conf.getLAYER_FIELD_POOL_STRIDES()) && dimension == 2) {
            /* 2D Pooling layers. */
            List<Integer> stridesList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_POOL_STRIDES());
            strides = ArrayUtil.toArray(stridesList);
        } else if (innerConfig.containsKey(conf.getLAYER_FIELD_POOL_1D_STRIDES()) && dimension == 1) {
            /* 1D Pooling layers. */
            int stride = (int) innerConfig.get(conf.getLAYER_FIELD_POOL_1D_STRIDES());
            strides = new int[]{ stride };
        } else
            throw new InvalidKerasConfigurationException("Could not determine layer stride: no "
                    + conf.getLAYER_FIELD_CONVOLUTION_STRIDES() + " or "
                    + conf.getLAYER_FIELD_POOL_STRIDES() + " field found");
        return strides;
    }

    /**
     * Get atrous / dilation rate from config
     *
     * @param layerConfig dictionary containing Keras layer configuration
     * @param dimension dimension of the convolution layer (1 or 2)
     * @param conf Keras layer configuration
     * @param forceDilation boolean to indicate if dilation argument should be in config
     * @return list of integers with atrous rates
     *
     * @throws InvalidKerasConfigurationException
     */
    public static int[] getDilationRate(Map<String, Object> layerConfig, int dimension, KerasLayerConfiguration conf,
                                        boolean forceDilation)
            throws InvalidKerasConfigurationException {
        Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
        int[] atrousRate;
        if (innerConfig.containsKey(conf.getLAYER_FIELD_DILATION_RATE()) && dimension == 2) {
            List<Integer> atrousRateList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_DILATION_RATE());
            atrousRate = ArrayUtil.toArray(atrousRateList);
        } else if (innerConfig.containsKey(conf.getLAYER_FIELD_DILATION_RATE()) && dimension == 1) {
            int atrousValue = (int) innerConfig.get(conf.getLAYER_FIELD_DILATION_RATE());
            atrousRate = new int[]{ atrousValue };
        } else {
            // If we are using keras 1, for regular convolutions, there is no "atrous" argument, for keras
            // 2 there always is.
            if (forceDilation)
            throw new InvalidKerasConfigurationException("Could not determine dilation rate: no "
                    + conf.getLAYER_FIELD_DILATION_RATE() + " field found");
            else
                atrousRate = null;
        }
        return atrousRate;

    }

    /**
     * Get upsampling size from Keras layer configuration.
     *
     * @param layerConfig dictionary containing Keras layer configuration
     * @return
     * @throws InvalidKerasConfigurationException
     */
    public static int[] getUpsamplingSizeFromConfig(Map<String, Object> layerConfig, int dimension,
                                                KerasLayerConfiguration conf)
            throws InvalidKerasConfigurationException {
        Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
        int[] size;
            if (innerConfig.containsKey(conf.getLAYER_FIELD_UPSAMPLING_2D_SIZE()) && dimension == 2) {
                List<Integer> sizeList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_UPSAMPLING_2D_SIZE());
                size = ArrayUtil.toArray(sizeList);
            } else if (innerConfig.containsKey(conf.getLAYER_FIELD_UPSAMPLING_1D_SIZE()) && dimension == 1) {
                int upsamplingSize1D = (int) innerConfig.get(conf.getLAYER_FIELD_UPSAMPLING_1D_SIZE());
                size = new int[]{ upsamplingSize1D };
            } else {
                throw new InvalidKerasConfigurationException("Could not determine kernel size: no "
                        + conf.getLAYER_FIELD_UPSAMPLING_1D_SIZE() + ", "
                        + conf.getLAYER_FIELD_UPSAMPLING_2D_SIZE());
            }
        return size;
    }

    /**
     * Get (convolution) kernel size from Keras layer configuration.
     *
     * @param layerConfig dictionary containing Keras layer configuration
     * @return
     * @throws InvalidKerasConfigurationException
     */
    public static int[] getKernelSizeFromConfig(Map<String, Object> layerConfig, int dimension,
                                                KerasLayerConfiguration conf, int kerasMajorVersion)
            throws InvalidKerasConfigurationException {
        Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
        int[] kernelSize;
        if (kerasMajorVersion != 2) {
            if (innerConfig.containsKey(conf.getLAYER_FIELD_NB_ROW()) && dimension == 2
                    && innerConfig.containsKey(conf.getLAYER_FIELD_NB_COL())) {
            /* 2D Convolutional layers. */
                List<Integer> kernelSizeList = new ArrayList<Integer>();
                kernelSizeList.add((Integer) innerConfig.get(conf.getLAYER_FIELD_NB_ROW()));
                kernelSizeList.add((Integer) innerConfig.get(conf.getLAYER_FIELD_NB_COL()));
                kernelSize = ArrayUtil.toArray(kernelSizeList);
            } else if (innerConfig.containsKey(conf.getLAYER_FIELD_FILTER_LENGTH()) && dimension == 1) {
            /* 1D Convolutional layers. */
                int filterLength = (int) innerConfig.get(conf.getLAYER_FIELD_FILTER_LENGTH());
                kernelSize = new int[]{ filterLength };
            } else if (innerConfig.containsKey(conf.getLAYER_FIELD_POOL_SIZE()) && dimension == 2) {
            /* 2D Pooling layers. */
                List<Integer> kernelSizeList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_POOL_SIZE());
                kernelSize = ArrayUtil.toArray(kernelSizeList);
            } else if (innerConfig.containsKey(conf.getLAYER_FIELD_POOL_1D_SIZE()) && dimension == 1) {
            /* 1D Pooling layers. */
                int poolSize1D = (int) innerConfig.get(conf.getLAYER_FIELD_POOL_1D_SIZE());
                kernelSize = new int[]{ poolSize1D };
            } else {
                throw new InvalidKerasConfigurationException("Could not determine kernel size: no "
                        + conf.getLAYER_FIELD_NB_ROW() + ", "
                        + conf.getLAYER_FIELD_NB_COL() + ", or "
                        + conf.getLAYER_FIELD_FILTER_LENGTH() + ", or "
                        + conf.getLAYER_FIELD_POOL_1D_SIZE() + ", or "
                        + conf.getLAYER_FIELD_POOL_SIZE() + " field found");
            }
        } else {
            /* 2D Convolutional layers. */
            if (innerConfig.containsKey(conf.getLAYER_FIELD_KERNEL_SIZE()) && dimension == 2) {
                List<Integer> kernelSizeList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_KERNEL_SIZE());
                kernelSize = ArrayUtil.toArray(kernelSizeList);
            } else if (innerConfig.containsKey(conf.getLAYER_FIELD_FILTER_LENGTH()) && dimension == 1) {
            /* 1D Convolutional layers. */
                int filterLength = (int) innerConfig.get(conf.getLAYER_FIELD_FILTER_LENGTH());
                kernelSize = new int[]{ filterLength };
            } else if (innerConfig.containsKey(conf.getLAYER_FIELD_POOL_SIZE()) && dimension == 2) {
            /* 2D Pooling layers. */
                List<Integer> kernelSizeList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_POOL_SIZE());
                kernelSize = ArrayUtil.toArray(kernelSizeList);
            } else if (innerConfig.containsKey(conf.getLAYER_FIELD_POOL_1D_SIZE()) && dimension == 1) {
            /* 1D Pooling layers. */
                int poolSize1D = (int) innerConfig.get(conf.getLAYER_FIELD_POOL_1D_SIZE());
                kernelSize = new int[]{ poolSize1D };
            } else {
                throw new InvalidKerasConfigurationException("Could not determine kernel size: no "
                        + conf.getLAYER_FIELD_KERNEL_SIZE() + ", or "
                        + conf.getLAYER_FIELD_FILTER_LENGTH() + ", or "
                        + conf.getLAYER_FIELD_POOL_SIZE() + " field found");
            }
        }

        return kernelSize;
    }

    /**
     * Get convolution border mode from Keras layer configuration.
     *
     * @param layerConfig dictionary containing Keras layer configuration
     * @return
     * @throws InvalidKerasConfigurationException
     */
    public static ConvolutionMode getConvolutionModeFromConfig(Map<String, Object> layerConfig,
                                                        KerasLayerConfiguration conf)
            throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException {
        Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
        if (!innerConfig.containsKey(conf.getLAYER_FIELD_BORDER_MODE()))
            throw new InvalidKerasConfigurationException("Could not determine convolution border mode: no "
                    + conf.getLAYER_FIELD_BORDER_MODE() + " field found");
        String borderMode = (String) innerConfig.get(conf.getLAYER_FIELD_BORDER_MODE());
        ConvolutionMode convolutionMode = null;
        if (borderMode.equals(conf.getLAYER_BORDER_MODE_SAME())) {
            /* Keras relies upon the Theano and TensorFlow border mode definitions and operations:
             * TH: http://deeplearning.net/software/theano/library/tensor/nnet/conv.html#theano.tensor.nnet.conv.conv2d
             * TF: https://www.tensorflow.org/api_docs/python/nn/convolution#conv2d
             */
            convolutionMode = ConvolutionMode.Same;

        } else if (borderMode.equals(conf.getLAYER_BORDER_MODE_VALID()) ||
                borderMode.equals(conf.getLAYER_BORDER_MODE_FULL())) {
            convolutionMode = ConvolutionMode.Truncate;

        } else {
            throw new UnsupportedKerasConfigurationException("Unsupported convolution border mode: " + borderMode);
        }
        return convolutionMode;
    }

    /**
     * Get (convolution) padding from Keras layer configuration.
     *
     * @param layerConfig dictionary containing Keras layer configuration
     * @return
     * @throws InvalidKerasConfigurationException
     */
    public static int[] getPaddingFromBorderModeConfig(Map<String, Object> layerConfig, int dimension,
                                                KerasLayerConfiguration conf, int kerasMajorVersion)
            throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException {
        Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
        int[] padding = null;
        if (!innerConfig.containsKey(conf.getLAYER_FIELD_BORDER_MODE()))
            throw new InvalidKerasConfigurationException("Could not determine convolution border mode: no "
                    + conf.getLAYER_FIELD_BORDER_MODE() + " field found");
        String borderMode = (String) innerConfig.get(conf.getLAYER_FIELD_BORDER_MODE());
        if (borderMode == conf.getLAYER_FIELD_BORDER_MODE()) {
            padding = getKernelSizeFromConfig(layerConfig, dimension, conf, kerasMajorVersion);
            for (int i = 0; i < padding.length; i++)
                padding[i]--;
        }
        return padding;
    }

    /**
     * Get zero padding from Keras layer configuration.
     *
     * @param layerConfig       dictionary containing Keras layer configuration
     * @param conf              KerasLayerConfiguration
     * @param dimension         Dimension of the padding layer
     * @return padding list of integers
     * @throws InvalidKerasConfigurationException Invalid keras configuration
     */
    public static int[] getZeroPaddingFromConfig(Map<String, Object> layerConfig, KerasLayerConfiguration conf, int dimension)
            throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException {
        Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf);
        if (!innerConfig.containsKey(conf.getLAYER_FIELD_ZERO_PADDING()))
            throw new InvalidKerasConfigurationException(
                    "Field " + conf.getLAYER_FIELD_ZERO_PADDING() + " not found in Keras ZeroPadding layer");
        int[] padding;
        if (dimension == 2) {
            List<Integer> paddingList;
            // For 2D layers, padding can either be a pair [x, y] or a single integer x.
            try {
                paddingList = (List<Integer>) innerConfig.get(conf.getLAYER_FIELD_ZERO_PADDING());
                if (paddingList.size() == 2) {
                    paddingList.add(paddingList.get(1));
                    paddingList.add(1, paddingList.get(0));
                    padding = ArrayUtil.toArray(paddingList);
                }
                else
                    throw new InvalidKerasConfigurationException("Found Keras ZeroPadding2D layer with invalid "
                            + paddingList.size() + "D padding.");
            } catch (Exception e) {
                int paddingInt = (int) innerConfig.get(conf.getLAYER_FIELD_ZERO_PADDING());
                padding = new int[]{ paddingInt, paddingInt };
            }

        } else if (dimension == 1) {
            int paddingInt = (int) innerConfig.get(conf.getLAYER_FIELD_ZERO_PADDING());
            padding = new int[]{ paddingInt };
        } else {
            throw new UnsupportedKerasConfigurationException(
                    "Keras padding layer not supported");
        }
        return padding;
    }
}


text:
$("#dialog_updated_fide_data")
  .html("<%= j render('admin/tournaments/fide/updated_data') %>")
  .dialog("option", "title", "Updated FIDE Data")
  .dialog("open");


text:
namespace Abc.NCrafts.Quizz.Performance2018.Questions._015
{
    public class Answer2
    {
        public decimal Run()
        {
            // begin
            var n = new NCrafts();
            return DoSomething(n);
            // end
        }

        private decimal DoSomething(in NCrafts s) => s.Sum;

        public struct NCrafts
        {
            public decimal Field1;
            public decimal Field2;
            public decimal Field3;

            public decimal Sum => Field1 + Field2 + Field3;
        }
    }
}


text:
from datetime import datetime
from dimagi.utils.couch.database import iter_docs
from django.core.management.base import BaseCommand
from corehq import Domain
from corehq.apps.receiverwrapper.models import RepeatRecord

class Command(BaseCommand):
    """
    Prints the approximate last time a repeater was created/touched.
    """

    def handle(self, *args, **options):
        domain = args[0]
        db = Domain.get_db()
        doc_ids = [r['id'] for r in db.view('domain/docs',
            startkey=[domain, 'RepeatRecord'],
            endkey=[domain, 'RepeatRecord', {}],
            reduce=False,
        )]
        count = len(doc_ids)
        print 'found %s doc ids' % count
        latest = datetime.min
        latest_doc = None
        for i, doc in enumerate(iter_docs(db, doc_ids)):
            wrapped = RepeatRecord.wrap(doc)
            if i % 100 == 0:
                print 'checked %s / %s' % (i, count)
            if wrapped.last_checked and wrapped.last_checked > latest:
                latest = wrapped.last_checked
                latest_doc = wrapped
                print 'new latest: %s' % latest

        if latest_doc:
            print 'latest repeater date is %s' % latest
            print 'latest repeater is %s' % latest_doc._id
        else:
            print 'no relevant repeaters found'