text:
var Promise = require('bluebird');
var Configuration = require('../configuration');

var dropsIdemanTables = function() {
  return new Promise(function(resolve, reject) {
    var config = Configuration.getConfig();
    var tables = config.tables.entities;
    var prefix = config.tables.prefix;
    var knex = require('knex')(config.database);

    return knex.schema.hasTable(prefix + tables.policy.table)
    .then(function(exists) {
      if (exists) {
        console.log('[DROP] drop ' + tables.policy.table + ' table');
        return knex.schema.dropTable(prefix + tables.policy.table);
      }
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.permission.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.permission.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.permission.table);
        }
      });
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.resource.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.resource.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.resource.table);
        }
      });
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.code.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.code.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.code.table);
        }
      });
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.token.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.token.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.token.table);
        }
      });
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.client.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.client.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.client.table);
        }
      });
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.userRole.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.userRole.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.userRole.table);
        }
      });
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.role.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.role.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.role.table);
        }
      });
    })
    .then(function() {
      return knex.schema.hasTable(prefix + tables.user.table)
      .then(function(exists) {
        if (exists) {
          console.log('[DROP] drop ' + tables.user.table + ' table');
          return knex.schema.dropTableIfExists(prefix + tables.user.table);
        }
      });
    })
    .then(function() {
      return resolve(true);
    })
    .catch(function(err) {
      return reject(err);
    });
  });
}

exports.idemanTables = dropsIdemanTables;


text:
@class CrTrackingArea;
@class HoverImageButton;
@class MouseDragController;
@class PanelWindowControllerCocoa;

// A class that works as a custom titlebar for Panels. It is placed on top of
// the regular Cocoa titlebar. We paint theme image on it, and it's
// the place for the close button, page favicon, title label and a button to
// minimize/restore the panel.
// It also facilitates dragging and minimization of the panels, and changes
// color as 'new activity' indicator.
// One way to have custom titlebar would be to use NSBorderlessWindow,
// but it seems to affect too many other behaviors (for example, it draws shadow
// differently based on being key window) so it appears easier to simply overlay
// the standard titlebar.

// This view overlays the titlebar on top. It is used to intercept
// mouse input to prevent reordering of the other browser windows when clicking
// on the titlebar (to minimize or reorder) while in a docked collection.
@interface PanelTitlebarOverlayView : NSView {
 @private
  IBOutlet PanelWindowControllerCocoa* controller_;
  BOOL disableReordering_;
}
@end

@interface RepaintAnimation : NSAnimation {
 @private
  NSView* targetView_;
}
- (id)initWithView:(NSView*)targetView duration:(double) duration;
- (void)setCurrentProgress:(NSAnimationProgress)progress;
@end

@interface PanelTitlebarViewCocoa : NSView
                                   <NSAnimationDelegate,
                                    MouseDragControllerClient> {
 @private
  IBOutlet PanelWindowControllerCocoa* controller_;
  IBOutlet NSView* icon_;
  IBOutlet NSTextField* title_;
  IBOutlet HoverImageButton* minimizeButton_;
  IBOutlet HoverImageButton* restoreButton_;
  IBOutlet HoverImageButton* customCloseButton_;
  // Transparent view on top of entire titlebar. It catches mouse events to
  // prevent window activation by the system on mouseDown.
  IBOutlet NSView* overlay_;
  NSButton* closeButton_;  // Created explicitly, not from NIB. Weak, destroyed
                           // when view is destroyed, as a subview.
  ScopedCrTrackingArea closeButtonTrackingArea_;
  BOOL isDrawingAttention_;

  // "Glint" animation is used in "Draw Attention" mode.
  scoped_nsobject<RepaintAnimation> glintAnimation_;
  scoped_nsobject<NSTimer> glintAnimationTimer_;
  double glintInterval_;

  // Drag support.
  scoped_nsobject<MouseDragController> dragController_;
}

// Callbacks from Close, Minimize, and Restore buttons.
- (void)onCloseButtonClick:(id)sender;
- (void)onMinimizeButtonClick:(id)sender;
- (void)onRestoreButtonClick:(id)sender;

// Attaches this view to the controller_'s window as a titlebar.
- (void)attach;

- (void)setTitle:(NSString*)newTitle;
- (void)setIcon:(NSView*)newIcon;

- (NSView*)icon;

// Set the visibility of the minimize and restore buttons.
- (void)setMinimizeButtonVisibility:(BOOL)visible;
- (void)setRestoreButtonVisibility:(BOOL)visible;

// Should be called when size of the titlebar changes.
- (void)updateCustomButtonsLayout;
- (void)updateIconAndTitleLayout;

// Various events that we'll need to redraw our titlebar for.
- (void)didChangeFrame:(NSNotification*)notification;
- (void)didChangeTheme:(NSNotification*)notification;
- (void)didChangeMainWindow:(NSNotification*)notification;

// Draw Attention methods - change appearance of titlebar to attract user.
- (void)drawAttention;
- (void)stopDrawingAttention;
- (BOOL)isDrawingAttention;
- (void)startGlintAnimation;
- (void)restartGlintAnimation:(NSTimer*)timer;
- (void)stopGlintAnimation;

@end  // @interface PanelTitlebarView

// Methods which are either only for testing, or only public for testing.
@interface PanelTitlebarViewCocoa(TestingAPI)

- (PanelWindowControllerCocoa*)controller;

- (NSTextField*)title;
- (NSButton*)closeButton;
- (NSButton*)minimizeButton;
- (NSButton*)restoreButton;

// Simulates click on a close button. Used to test panel closing.
- (void)simulateCloseButtonClick;

// NativePanelTesting support.
// |mouseLocation| is in Cocoa's screen coordinates.
- (void)pressLeftMouseButtonTitlebar:(NSPoint)mouseLocation
                           modifiers:(int)modifierFlags;
- (void)releaseLeftMouseButtonTitlebar:(int)modifierFlags;
- (void)dragTitlebar:(NSPoint)mouseLocation;
- (void)cancelDragTitlebar;
- (void)finishDragTitlebar;

@end  // @interface PanelTitlebarViewCocoa(TestingAPI)

#endif  // CHROME_BROWSER_UI_COCOA_PANELS_PANEL_TITLEBAR_VIEW_COCOA_H_

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import { findDOMNode } from 'react-dom'
import classnames from 'classnames'

import { CameraMetrics, PhotoPosition, maxZoom, RequestedPhotoPosition, limitPhotoPosition } from 'common/util/CameraMetrics'
import { bindMany, isShallowEqual } from 'common/util/LangUtil'

import DragDropController from 'app/util/DragDropController'
import { Point } from 'common/util/GeometryTypes'

import './ViewModeOverlay.less'

export interface Props {
    className?: any
    cameraMetrics: CameraMetrics | null
    setPhotoPosition(photoPosition: RequestedPhotoPosition): void
}

interface State {
    dragStart: { x: number, y: number, photoPosition: PhotoPosition } | null
}

export default class ViewModeOverlay extends React.Component<Props, State> {

    private dragDropController: DragDropController

    constructor(props: Props) {
        super(props)
        bindMany(this, 'onWheel')
        this.state = { dragStart: null }

        this.dragDropController = new DragDropController({
            onDragStart: (point: Point) => {
                const { cameraMetrics } = this.props
                if (this.state.dragStart || !cameraMetrics || cameraMetrics.requestedPhotoPosition === 'contain') {
                    return
                }

                const dragStart = { ...point, photoPosition: cameraMetrics.photoPosition }
                this.setState({ dragStart })
            },
            onDrag: (point: Point, isFinished: boolean) => {
                const { dragStart } = this.state
                const { cameraMetrics } = this.props
                if (dragStart && cameraMetrics) {
                    const startPhotoPosition = dragStart.photoPosition
                    const zoom = startPhotoPosition.zoom

                    let centerX = startPhotoPosition.centerX - (point.x - dragStart.x) / cameraMetrics.displayScaling / zoom
                    let centerY = startPhotoPosition.centerY - (point.y - dragStart.y) / cameraMetrics.displayScaling / zoom
                    const nextPhotoPosition = limitPhotoPosition(cameraMetrics, { centerX, centerY, zoom }, true)

                    if (!isShallowEqual(nextPhotoPosition, cameraMetrics.photoPosition)) {
                        this.props.setPhotoPosition(nextPhotoPosition)
                    }
                }

                if (isFinished) {
                    this.setState({ dragStart: null })
                }
            }
        })
    }

    componentWillUnmount() {
        this.dragDropController.cancel()
    }

    private onWheel(event: React.WheelEvent<HTMLDivElement>) {
        const { cameraMetrics } = this.props
        if (!cameraMetrics) {
            return
        }

        const { photoPosition } = cameraMetrics
        const zoom = Math.min(maxZoom, photoPosition.zoom * Math.pow(1.01, -event.deltaY))
            // One wheel tick has a deltaY of ~ 4
        if (zoom === photoPosition.zoom) {
            // Nothing to do
        } else if (zoom < cameraMetrics.minZoom) {
            this.props.setPhotoPosition('contain')
        } else {
            const mainElem = findDOMNode(this.refs.main) as HTMLDivElement
            const mainRect = mainElem.getBoundingClientRect()

            // The mouse position in the canvas (in device pixels, relative to the center of the canvas)
            const mouseX = event.clientX - mainRect.left - mainRect.width / 2
            const mouseY = event.clientY - mainRect.top - mainRect.height / 2

            // The photo pixel where the mouse is aiming relative (in photo pixels, relative to the top/left corner of the photo)
            const mousePhotoX = photoPosition.centerX + mouseX / cameraMetrics.displayScaling / photoPosition.zoom
            const mousePhotoY = photoPosition.centerY + mouseY / cameraMetrics.displayScaling / photoPosition.zoom

            // The new center (in photo pixels)
            const centerX = mousePhotoX - mouseX / cameraMetrics.displayScaling / zoom
            const centerY = mousePhotoY - mouseY / cameraMetrics.displayScaling / zoom

            this.props.setPhotoPosition({ centerX, centerY, zoom })
        }
    }

    render() {
        const { props, state } = this
        const requestedPhotoPosition = props.cameraMetrics && props.cameraMetrics.requestedPhotoPosition
        const isZoomed = requestedPhotoPosition && requestedPhotoPosition !== 'contain'
        return (
            <div
                ref='main'
                className={classnames(props.className, 'ViewModeOverlay', { isZoomed, isDragging: state.dragStart })}
                onMouseDown={this.dragDropController.onMouseDown}
                onWheel={this.onWheel}
            />
        )
    }

}


text:
<?php if (!defined('IDIR')) { die; }

/**
* thwboard_004 Import User module
*
* @package			ImpEx.thwboard
*
*/
class thwboard_004 extends thwboard_000
{
	var $_version 		= '0.0.1';
	var $_dependent 	= '003';
	var $_modulestring 	= 'Import User';

	function thwboard_004()
	{
		// Constructor
	}

	function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		if ($this->check_order($sessionobject,$this->_dependent))
		{
			if ($this->_restart)
			{
				if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_users'))
				{
					$displayobject->display_now('
Imported users have been cleared
');
					$this->_restart = true;
				}
				else
				{
					$sessionobject->add_error('fatal',
											 $this->_modulestring,
											 get_class($this) . '::restart failed , clear_imported_users','Check database permissions');
				}
			}

			// Start up the table
			$displayobject->update_basic('title','Import User');
			$displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3)));
			$displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING'));
			$displayobject->update_html($displayobject->make_hidden_code('import_user','working'));
			$displayobject->update_html($displayobject->make_table_header($this->_modulestring));

			// Ask some questions
			$displayobject->update_html($displayobject->make_input_code('Users to import per cycle (must be greater than 1)','userperpage', 2000));

			// End the table
			$displayobject->update_html($displayobject->do_form_footer('Continue','Reset'));

			// Reset/Setup counters for this
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0');
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0');
			$sessionobject->add_session_var('userstartat','0');
			$sessionobject->add_session_var('userdone','0');
		}
		else
		{
			// Dependant has not been run
			$displayobject->update_html($displayobject->do_form_header('index',''));
			$displayobject->update_html($displayobject->make_description('
This module is dependent on ' . $sessionobject->get_module_title($this->_dependent) . ' cannot run until that is complete.'));
			$displayobject->update_html($displayobject->do_form_footer('Continue',''));
			$sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE');
			$sessionobject->set_session_var('module','000');
		}
	}

	function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		// Set up working variables.
		$displayobject->update_basic('displaymodules','FALSE');
		$target_database_type	= $sessionobject->get_session_var('targetdatabasetype');
		$target_table_prefix	= $sessionobject->get_session_var('targettableprefix');
		$source_database_type	= $sessionobject->get_session_var('sourcedatabasetype');
		$source_table_prefix	= $sessionobject->get_session_var('sourcetableprefix');

		// Per page vars
		$user_start_at			= $sessionobject->get_session_var('userstartat');
		$user_per_page			= $sessionobject->get_session_var('userperpage');
		$class_num				= substr(get_class($this) , -3);

		// Start the timing
		if(!$sessionobject->get_session_var($class_num . '_start'))
		{
			$sessionobject->timing($class_num ,'start' ,$sessionobject->get_session_var('autosubmit'));
		}

		// Get an array of user details
		$user_array 	= $this->get_thwboard_user_details($Db_source, $source_database_type, $source_table_prefix, $user_start_at, $user_per_page);

		// Groups info
		$user_group_ids_array = $this->get_imported_group_ids($Db_target, $target_database_type, $target_table_prefix);

		// Display count and pass time
		$displayobject->display_now('
Importing ' . count($user_array) . ' users

From : ' . $user_start_at . ' ::  To : ' . ($user_start_at + count($user_array)) . '
');

		$user_object = new ImpExData($Db_target, $sessionobject, 'user');

		foreach ($user_array as $user_id => $user_details)
		{
			$try = (phpversion() < '5' ? $user_object : clone($user_object));
			// Mandatory
			$bits = explode(',', $user_details['groupids']);

			if ($user_details['useractivate'] == '0')
			{
				$try->set_value('mandatory', 'usergroupid',				$user_group_ids_array[70]);
			}
			else
			{
				$try->set_value('mandatory', 'usergroupid',				$user_group_ids_array["$bits[1]"]);
			}

			$try->set_value('mandatory', 'username',				$user_details['username']);
			$try->set_value('mandatory', 'email',					$user_details['useremail']);
			$try->set_value('mandatory', 'importuserid',			$user_id);

			// Non Mandatory
			$old_groups = explode(',', $user_details['groupids']);
			$new_groups = array();

			foreach($old_groups AS $old_group_id)
			{
				$new_groups[] = $user_group_ids_array[$old_group_id];
			}
			$new_groups = implode(',', $new_groups);

			$try->set_value('nonmandatory', 'membergroupids',		$new_groups);
			$try->_password_md5_already = true;
			$try->set_value('nonmandatory', 'password',				$user_details['userpassword']);
			$try->set_value('nonmandatory', 'styleid',				$user_details['styleid']);
			$try->set_value('nonmandatory', 'homepage',				$user_details['userhomepage']);
			$try->set_value('nonmandatory', 'icq',					$user_details['usericq']);
			$try->set_value('nonmandatory', 'aim',					$user_details['useraim']);
			$try->set_value('nonmandatory', 'usertitle',			$user_details['usertitle']);
			$try->set_value('nonmandatory', 'joindate',				$user_details['userjoin']);
			$try->set_value('nonmandatory', 'options',				$this->_default_user_permissions);

			$other_one = explode('-', $user_details['userbday']); #dd-mm-yyyy

			$day 	= $other_one[0];
			$month	= $other_one[1];
			$year 	= $other_one[2];

			if($year AND $month AND $day)
			{
				$try->set_value('nonmandatory', 'birthday',			"{$month}-{$day}-{$year}");
				$try->set_value('nonmandatory', 'birthday_search',	"{$year}-{$month}-{$day}");
			}

			$try->set_value('nonmandatory', 'msn',					$user_details['usermsn']);
			$try->add_default_value('Location', 					$user_details['userlocation']);
			$try->add_default_value('Interests', 					$user_details['userinterests']);
			$try->add_default_value('Occupation', 					$user_details['useroccupation']);
			$try->add_default_value('signature', 					$user_details['usersignature']);

			// Check if user object is valid
			if($try->is_valid())
			{
				if($try->import_user($Db_target, $target_database_type, $target_table_prefix))
				{
					$displayobject->display_now('
' . $try->how_complete() . '% :: user -> ' . $user_details['username']);
					$sessionobject->add_session_var($class_num . '_objects_done',intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1 );
				}
				else
				{
					$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
					$sessionobject->add_error('warning', $this->_modulestring, get_class($this) . '::import_custom_profile_pic failed.', 'Check database permissions and database table');
					$displayobject->display_now("
Found avatar user and DID NOT imported to the  {$target_database_type} database");
				}
			}
			else
			{
				$displayobject->display_now("
Invalid user object, skipping." . $try->_failedon);
			}
			unset($try);
		}// End foreach

		// Check for page end
		if (count($user_array) == 0 OR count($user_array) < $user_per_page)
		{
			$sessionobject->timing($class_num,'stop', $sessionobject->get_session_var('autosubmit'));
			$sessionobject->remove_session_var($class_num . '_start');

			$this->build_user_statistics($Db_target, $target_database_type, $target_table_prefix);

			$displayobject->update_html($displayobject->module_finished($this->_modulestring,
				$sessionobject->return_stats($class_num, '_time_taken'),
				$sessionobject->return_stats($class_num, '_objects_done'),
				$sessionobject->return_stats($class_num, '_objects_failed')
			));

			$sessionobject->set_session_var($class_num ,'FINISHED');
			$sessionobject->set_session_var('import_user','done');
			$sessionobject->set_session_var('module','000');
			$sessionobject->set_session_var('autosubmit','0');
		}

		$sessionobject->set_session_var('userstartat',$user_start_at+$user_per_page);
		$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
	}// End resume
}//End Class
# Autogenerated on : June 24, 2004, 2:27 pm
# By ImpEx-generator 1.0.
/*======================================================================*/
?>


text:
from time import monotonic

from app.clients import Client, ClientException

class SmsClientResponseException(ClientException):
    """
    Base Exception for SmsClientsResponses
    """

    def __init__(self, message):
        self.message = message

    def __str__(self):
        return f"SMS client error ({self.message})"

class SmsClient(Client):
    """
    Base Sms client for sending smss.
    """

    def init_app(self, current_app, statsd_client):
        self.current_app = current_app
        self.statsd_client = statsd_client

    def record_outcome(self, success):
        log_message = "Provider request for {} {}".format(
            self.name,
            "succeeded" if success else "failed",
        )

        if success:
            self.current_app.logger.info(log_message)
            self.statsd_client.incr(f"clients.{self.name}.success")
        else:
            self.statsd_client.incr(f"clients.{self.name}.error")
            self.current_app.logger.warning(log_message)

    def send_sms(self, to, content, reference, international, sender):
        start_time = monotonic()

        try:
            response = self.try_send_sms(to, content, reference, international, sender)
            self.record_outcome(True)
        except SmsClientResponseException as e:
            self.record_outcome(False)
            raise e
        finally:
            elapsed_time = monotonic() - start_time
            self.statsd_client.timing(f"clients.{self.name}.request-time", elapsed_time)
            self.current_app.logger.info(f"{self.name} request for {reference} finished in {elapsed_time}")

        return response

    def try_send_sms(self, *args, **kwargs):
        raise NotImplementedError("TODO Need to implement.")

    @property
    def name(self):
        raise NotImplementedError("TODO Need to implement.")


text:
#pragma once
#include <aws/managedblockchain/ManagedBlockchain_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/managedblockchain/model/NodeLogPublishingConfiguration.h>
#include <aws/managedblockchain/model/StateDBType.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ManagedBlockchain
{
namespace Model
{

  /**
   *
Configuration properties of a node.

See Also:
   AWS
   * API Reference

   */
  class AWS_MANAGEDBLOCKCHAIN_API NodeConfiguration
  {
  public:
    NodeConfiguration();
    NodeConfiguration(Aws::Utils::Json::JsonView jsonValue);
    NodeConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline const Aws::String& GetInstanceType() const{ return m_instanceType; }

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline bool InstanceTypeHasBeenSet() const { return m_instanceTypeHasBeenSet; }

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline void SetInstanceType(const Aws::String& value) { m_instanceTypeHasBeenSet = true; m_instanceType = value; }

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline void SetInstanceType(Aws::String&& value) { m_instanceTypeHasBeenSet = true; m_instanceType = std::move(value); }

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline void SetInstanceType(const char* value) { m_instanceTypeHasBeenSet = true; m_instanceType.assign(value); }

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline NodeConfiguration& WithInstanceType(const Aws::String& value) { SetInstanceType(value); return *this;}

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline NodeConfiguration& WithInstanceType(Aws::String&& value) { SetInstanceType(std::move(value)); return *this;}

    /**
     *
The Amazon Managed Blockchain instance type for the node.

     */
    inline NodeConfiguration& WithInstanceType(const char* value) { SetInstanceType(value); return *this;}

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline const Aws::String& GetAvailabilityZone() const{ return m_availabilityZone; }

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline bool AvailabilityZoneHasBeenSet() const { return m_availabilityZoneHasBeenSet; }

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline void SetAvailabilityZone(const Aws::String& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = value; }

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline void SetAvailabilityZone(Aws::String&& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = std::move(value); }

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline void SetAvailabilityZone(const char* value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone.assign(value); }

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline NodeConfiguration& WithAvailabilityZone(const Aws::String& value) { SetAvailabilityZone(value); return *this;}

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline NodeConfiguration& WithAvailabilityZone(Aws::String&& value) { SetAvailabilityZone(std::move(value)); return *this;}

    /**
     *
The Availability Zone in which the node exists. Required for Ethereum nodes.
     *

     */
    inline NodeConfiguration& WithAvailabilityZone(const char* value) { SetAvailabilityZone(value); return *this;}

    /**
     *
Configuration properties for logging events associated with a peer node on a
     * Hyperledger Fabric network on Managed Blockchain.

     */
    inline const NodeLogPublishingConfiguration& GetLogPublishingConfiguration() const{ return m_logPublishingConfiguration; }

    /**
     *
Configuration properties for logging events associated with a peer node on a
     * Hyperledger Fabric network on Managed Blockchain.

     */
    inline bool LogPublishingConfigurationHasBeenSet() const { return m_logPublishingConfigurationHasBeenSet; }

    /**
     *
Configuration properties for logging events associated with a peer node on a
     * Hyperledger Fabric network on Managed Blockchain.

     */
    inline void SetLogPublishingConfiguration(const NodeLogPublishingConfiguration& value) { m_logPublishingConfigurationHasBeenSet = true; m_logPublishingConfiguration = value; }

    /**
     *
Configuration properties for logging events associated with a peer node on a
     * Hyperledger Fabric network on Managed Blockchain.

     */
    inline void SetLogPublishingConfiguration(NodeLogPublishingConfiguration&& value) { m_logPublishingConfigurationHasBeenSet = true; m_logPublishingConfiguration = std::move(value); }

    /**
     *
Configuration properties for logging events associated with a peer node on a
     * Hyperledger Fabric network on Managed Blockchain.

     */
    inline NodeConfiguration& WithLogPublishingConfiguration(const NodeLogPublishingConfiguration& value) { SetLogPublishingConfiguration(value); return *this;}

    /**
     *
Configuration properties for logging events associated with a peer node on a
     * Hyperledger Fabric network on Managed Blockchain.

     */
    inline NodeConfiguration& WithLogPublishingConfiguration(NodeLogPublishingConfiguration&& value) { SetLogPublishingConfiguration(std::move(value)); return *this;}

    /**
     *
The state database that the node uses. Values are LevelDB or
     * CouchDB. When using an Amazon Managed Blockchain network with
     * Hyperledger Fabric version 1.4 or later, the default is
     * CouchDB.

Applies only to Hyperledger Fabric.

     */
    inline const StateDBType& GetStateDB() const{ return m_stateDB; }

    /**
     *
The state database that the node uses. Values are LevelDB or
     * CouchDB. When using an Amazon Managed Blockchain network with
     * Hyperledger Fabric version 1.4 or later, the default is
     * CouchDB.

Applies only to Hyperledger Fabric.

     */
    inline bool StateDBHasBeenSet() const { return m_stateDBHasBeenSet; }

    /**
     *
The state database that the node uses. Values are LevelDB or
     * CouchDB. When using an Amazon Managed Blockchain network with
     * Hyperledger Fabric version 1.4 or later, the default is
     * CouchDB.

Applies only to Hyperledger Fabric.

     */
    inline void SetStateDB(const StateDBType& value) { m_stateDBHasBeenSet = true; m_stateDB = value; }

    /**
     *
The state database that the node uses. Values are LevelDB or
     * CouchDB. When using an Amazon Managed Blockchain network with
     * Hyperledger Fabric version 1.4 or later, the default is
     * CouchDB.

Applies only to Hyperledger Fabric.

     */
    inline void SetStateDB(StateDBType&& value) { m_stateDBHasBeenSet = true; m_stateDB = std::move(value); }

    /**
     *
The state database that the node uses. Values are LevelDB or
     * CouchDB. When using an Amazon Managed Blockchain network with
     * Hyperledger Fabric version 1.4 or later, the default is
     * CouchDB.

Applies only to Hyperledger Fabric.

     */
    inline NodeConfiguration& WithStateDB(const StateDBType& value) { SetStateDB(value); return *this;}

    /**
     *
The state database that the node uses. Values are LevelDB or
     * CouchDB. When using an Amazon Managed Blockchain network with
     * Hyperledger Fabric version 1.4 or later, the default is
     * CouchDB.

Applies only to Hyperledger Fabric.

     */
    inline NodeConfiguration& WithStateDB(StateDBType&& value) { SetStateDB(std::move(value)); return *this;}

  private:

    Aws::String m_instanceType;
    bool m_instanceTypeHasBeenSet = false;

    Aws::String m_availabilityZone;
    bool m_availabilityZoneHasBeenSet = false;

    NodeLogPublishingConfiguration m_logPublishingConfiguration;
    bool m_logPublishingConfigurationHasBeenSet = false;

    StateDBType m_stateDB;
    bool m_stateDBHasBeenSet = false;
  };

} // namespace Model
} // namespace ManagedBlockchain
} // namespace Aws


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30249_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">TABLE OF CONTENTS

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">VH.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">VIII.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">mmvw.


text:
package nikuyoshi.com.github.calculator;

/**
 * @author nikuyoshi
 */
public class Calculator {
}


text:
from toee import *
import race_defs

###################################################

raceEnum = race_dwarf + (5 << 5)

raceSpec = race_defs.RaceSpec()
raceSpec.hit_dice        = dice_new("0d0")
raceSpec.level_modifier  = 0
raceSpec.help_topic      = "TAG_GOLD_DWARF"
raceSpec.flags           = 4
raceSpec.modifier_name   = "Gold Dwarf"
raceSpec.height_male     = [45, 53]
raceSpec.height_female   = [43, 51]
raceSpec.weight_male     = [148, 178]
raceSpec.weight_female   = [104, 134]
raceSpec.stat_modifiers  = [0, -2, 2, 0, 0, 0]   # str, dex, con, int, wis, cha
raceSpec.proto_id        = 13036
raceSpec.material_offset = 6         # offset into rules/material_ext.mes file
raceSpec.use_base_race_for_deity = 1

###################################################
def RegisterRace():
	print "Registering race: Gold Dwarf"
	raceSpec.register(raceEnum)

def GetFavoredClass(obj = OBJ_HANDLE_NULL):
	return stat_level_fighter

def GetLevelModifier(obj = OBJ_HANDLE_NULL):
	return 0


text:
RSpec.configure do |config|
  config.include SunspotMatchers

  config.before(:all) do
    Sunspot.session = SunspotMatchers::SunspotSessionSpy.new(Sunspot.session)
  end

  config.after(:all) do
    Sunspot.session = Sunspot.session.original_session if Sunspot.session.respond_to?(:original_session)
  end

  config.before(:all, search: true) do
    require 'sunspot_test/rspec'
    Sunspot.session = Sunspot.session.original_session
    SunspotTest.solr_startup_timeout = 60
  end
end


text:
'use strict';

import React from 'react';
import SectionActionCreators from '../../actions/SectionActionCreators';

const NewSection = React.createClass({

  getInitialState() {
    return {
      sectionName: ''
    };
  },

  handleSubmit(e) {
    e.preventDefault();
    let categoryId = this.props.categoryId;
    let sectionName = this.state.sectionName;
    if (sectionName) {
      SectionActionCreators.createSection(categoryId, sectionName);
      this.setState({
        sectionName: ''
      });
    }
  },

  handleChange(event) {
    this.setState({
      sectionName: event.target.value
    });
  },

  render() {
    if (this.props.userIsAdmin) {
      return (
        <form onSubmit={this.handleSubmit}>

            <input type='text' onChange={this.handleChange} placeholder='Add new section' maxLength='20' name='title' value={this.state.sectionName} />

        </form>
      );
    } else {
      return null;
    }
  }
});

module.exports = NewSection;


text:
#include <ngx_http.h>
#include <apr_bucket_nginx.h>
#include <ngx_pool_context.h>

#include <apr_base64.h>

#undef CR
#undef LF
#undef CRLF

#include "api.h"

#define NOTE_NGINX_REQUEST_CTX "nginx-ctx"

typedef struct {
    ngx_flag_t                  enable;
    directory_config            *config;

    ngx_str_t                   *file;
    ngx_uint_t                   line;
} ngx_http_modsecurity_loc_conf_t;

typedef struct {
    ngx_http_request_t  *r;
    conn_rec            *connection;
    request_rec         *req;

    apr_bucket_brigade  *brigade;
    unsigned             complete;
} ngx_http_modsecurity_ctx_t;

/*
** Module's registred function/handlers.
*/
static ngx_int_t ngx_http_modsecurity_handler(ngx_http_request_t *r);
static void ngx_http_modsecurity_body_handler(ngx_http_request_t *r);
static ngx_int_t ngx_http_modsecurity_header_filter(ngx_http_request_t *r);
static ngx_int_t ngx_http_modsecurity_body_filter(ngx_http_request_t *r, ngx_chain_t *in);
static ngx_int_t ngx_http_modsecurity_preconfiguration(ngx_conf_t *cf);
static ngx_int_t ngx_http_modsecurity_init(ngx_conf_t *cf);
static ngx_int_t ngx_http_modsecurity_init_process(ngx_cycle_t *cycle);
static void *ngx_http_modsecurity_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_modsecurity_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child);
static char *ngx_http_modsecurity_config(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static char *ngx_http_modsecurity_enable(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);

static ngx_http_modsecurity_ctx_t * ngx_http_modsecurity_create_ctx(ngx_http_request_t *r);
static int ngx_http_modsecurity_drop_action(request_rec *r);
static void ngx_http_modsecurity_terminate(ngx_cycle_t *cycle);
static void ngx_http_modsecurity_cleanup(void *data);

static int ngx_http_modsecurity_save_headers_in_visitor(void *data, const char *key, const char *value);
static int ngx_http_modsecurity_save_headers_out_visitor(void *data, const char *key, const char *value);

/* command handled by the module */
static ngx_command_t  ngx_http_modsecurity_commands[] =  {
  { ngx_string("ModSecurityConfig"),
    NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
    ngx_http_modsecurity_config,
    NGX_HTTP_LOC_CONF_OFFSET,
    0,
    NULL },
  { ngx_string("ModSecurityEnabled"),
    NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_SIF_CONF
        |NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF|NGX_CONF_TAKE1,
    ngx_http_modsecurity_enable,
    NGX_HTTP_LOC_CONF_OFFSET,
    offsetof(ngx_http_modsecurity_loc_conf_t, enable),
    NULL },
  ngx_null_command
};

/*
** handlers for configuration phases of the module
*/

static ngx_http_module_t ngx_http_modsecurity_ctx = {
    ngx_http_modsecurity_preconfiguration, /* preconfiguration */
    ngx_http_modsecurity_init, /* postconfiguration */

    NULL, /* create main configuration */
    NULL, /* init main configuration */

    NULL, /* create server configuration */
    NULL, /* merge server configuration */

    ngx_http_modsecurity_create_loc_conf, /* create location configuration */
    ngx_http_modsecurity_merge_loc_conf /* merge location configuration */
};

ngx_module_t ngx_http_modsecurity = {
    NGX_MODULE_V1,
    &ngx_http_modsecurity_ctx, /* module context */
    ngx_http_modsecurity_commands, /* module directives */
    NGX_HTTP_MODULE, /* module type */
    NULL, /* init master */
    NULL, /* init module */
    ngx_http_modsecurity_init_process, /* init process */
    NULL, /* init thread */
    NULL, /* exit thread */
    ngx_http_modsecurity_terminate, /* exit process */
    ngx_http_modsecurity_terminate, /* exit master */
    NGX_MODULE_V1_PADDING
};

static ngx_http_output_header_filter_pt  ngx_http_next_header_filter;
static ngx_http_output_body_filter_pt    ngx_http_next_body_filter;

static ngx_http_upstream_t ngx_http_modsecurity_upstream;

static struct {
    char      *name;
    ngx_str_t  variable_name;
} special_headers_out[] = {
    {"Content-Type",      ngx_string("sent_http_content_type")  },
    {"Content-Length",    ngx_string("sent_http_content_length")},
    {"Location",          ngx_string("sent_http_location")},
    {"Last-Modified",     ngx_string("sent_http_last_modified")},
    {"Connection",        ngx_string("sent_http_connection")},
    {"Keep-Alive",        ngx_string("sent_http_keep_alive")},
    {"Transfer-Encoding", ngx_string("sent_http_transfer_encoding")},
    {"Cache-Control",     ngx_string("sent_http_cache_control")},
    {NULL,                ngx_null_string}
};

static inline u_char *
ngx_pstrdup0(ngx_pool_t *pool, ngx_str_t *src)
{
    u_char  *dst;

    dst = ngx_pnalloc(pool, src->len + 1);
    if (dst == NULL) {
        return NULL;
    }

    ngx_memcpy(dst, src->data, src->len);
    dst[src->len] = '\0';

    return dst;
}

static inline int
ngx_http_modsecurity_method_number(unsigned int nginx)
{
    /*
     * http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
     */
    static const int MultiplyDeBruijnBitPosition[32] = {
        M_INVALID, /* 1 >> 0 */
        M_GET,
        M_INVALID, /* 1 >> 28 */
        M_GET,     /* NGX_HTTP_HEAD */
        M_INVALID, /* 1 >> 29 */
        M_PATCH,
        M_INVALID, /* 1 >> 24 */
        M_POST,
        M_INVALID, /* 1 >> 30 */
        M_INVALID, /* 1 >> 22 */
        M_INVALID, /* 1 >> 20 */
        M_TRACE,
        M_INVALID, /* 1 >> 25 */
        M_INVALID, /* 1 >> 17 */
        M_PUT,
        M_MOVE,
        M_INVALID, /* 1 >> 31 */
        M_INVALID, /* 1 >> 27 */
        M_UNLOCK,
        M_INVALID, /* 1 >> 23 */
        M_INVALID, /* 1 >> 21 */
        M_INVALID, /* 1 >> 19 */
        M_INVALID, /* 1 >> 16 */
        M_COPY,
        M_INVALID, /* 1 >> 26 */
        M_LOCK,
        M_INVALID, /* 1 >> 18 */
        M_MKCOL,
        M_PROPPATCH,
        M_DELETE,
        M_PROPFIND,
        M_OPTIONS
    };

    return MultiplyDeBruijnBitPosition[((uint32_t)((nginx & -nginx) * 0x077CB531U)) >> 27];
}

static ngx_inline ngx_int_t
ngx_http_modsecurity_load_request(ngx_http_request_t *r)
{
    ngx_http_modsecurity_ctx_t  *ctx;
    request_rec                 *req;
    ngx_str_t                    str;
    size_t                       root;
    ngx_str_t                    path;

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);
    req = ctx->req;

    /* request line */
    req->method = (char *)ngx_pstrdup0(r->pool, &r->method_name);

    /* TODO: how to use ap_method_number_of ?
     * req->method_number = ap_method_number_of(req->method);
     */

    req->method_number = ngx_http_modsecurity_method_number(r->method);

    /* ngx_http_map_uri_to_path() allocates memory for terminating '\0' */
    if (ngx_http_map_uri_to_path(r, &path, &root, 0) == NULL) {
        return NGX_ERROR;
    }

    req->filename = (char *) path.data;
    req->path_info = req->filename;

    req->args = (char *)ngx_pstrdup0(r->pool, &r->args);

    req->proto_num = r->http_major *1000 + r->http_minor;
    req->protocol = (char *)ngx_pstrdup0(r->pool, &r->http_protocol);
    req->request_time = apr_time_make(r->start_sec, r->start_msec);
    req->the_request = (char *)ngx_pstrdup0(r->pool, &r->request_line);

    req->unparsed_uri = (char *)ngx_pstrdup0(r->pool, &r->unparsed_uri);
    req->uri = (char *)ngx_pstrdup0(r->pool, &r->uri);

    req->parsed_uri.scheme = "http";

#if (NGX_HTTP_SSL)
    if (r->connection->ssl) {
        req->parsed_uri.scheme = "https";
    }
#endif

    req->parsed_uri.path = (char *)ngx_pstrdup0(r->pool, &r->uri);
    req->parsed_uri.is_initialized = 1;

    str.data = r->port_start;
    str.len = r->port_end - r->port_start;
    req->parsed_uri.port = ngx_atoi(str.data, str.len);
    req->parsed_uri.port_str = (char *)ngx_pstrdup0(r->pool, &str);

    req->parsed_uri.query = r->args.len ? req->args : NULL;
    req->parsed_uri.dns_looked_up = 0;
    req->parsed_uri.dns_resolved = 0;

    // req->parsed_uri.password = (char *)ngx_pstrdup0(r->pool, &r->headers_in.passwd);
    // req->parsed_uri.user = (char *)ngx_pstrdup0(r->pool, &r->headers_in.user);
    req->parsed_uri.fragment = (char *)ngx_pstrdup0(r->pool, &r->exten);

    req->hostname = (char *)ngx_pstrdup0(r->pool, (ngx_str_t *)&ngx_cycle->hostname);

    req->header_only = r->header_only ? r->header_only : (r->method == NGX_HTTP_HEAD);

    return NGX_OK;
}

/*
 * TODO: deal more headers.
 */

static ngx_inline ngx_int_t
ngx_http_modsecurity_load_headers_in(ngx_http_request_t *r)
{
    ngx_http_modsecurity_ctx_t  *ctx;
    const char                  *lang;
    request_rec                 *req;
    ngx_list_part_t             *part;
    ngx_table_elt_t             *h;
    ngx_uint_t                   i;

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);
    req = ctx->req;

    part = &r->headers_in.headers.part;
    h = part->elts;

    for (i = 0; ; i++) {
        if (i >= part->nelts) {
            if (part->next == NULL)
                break;

            part = part->next;
            h = part->elts;
            i = 0;
        }

        apr_table_setn(req->headers_in, (char *)h[i].key.data, (char *)h[i].value.data);
        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "ModSecurity: load headers in: \"%V: %V\"",
                       &h[i].key, &h[i].value);
    }

    req->clength = r->headers_in.content_length_n;

    req->range = apr_table_get(req->headers_in, "Range");
    req->content_type = apr_table_get(req->headers_in, "Content-Type");
    req->content_encoding = apr_table_get(req->headers_in, "Content-Encoding");

    lang = apr_table_get(ctx->req->headers_in, "Content-Languages");
    if(lang != NULL)
    {
        ctx->req->content_languages = apr_array_make(ctx->req->pool, 1, sizeof(const char *));

        *(const char **)apr_array_push(ctx->req->content_languages) = lang;
    }

    req->ap_auth_type = (char *)apr_table_get(req->headers_in, "Authorization");

    req->user = (char *)ngx_pstrdup0(r->pool, &r->headers_in.user);

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "ModSecurity: load headers in done");

    return NGX_OK;
}

static ngx_inline ngx_int_t
ngx_http_modsecurity_save_headers_in(ngx_http_request_t *r)
{
    ngx_http_modsecurity_ctx_t  *ctx;

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);

    /* clean up headers_in */
    ngx_memzero(&r->headers_in, sizeof(ngx_http_headers_in_t));

    if (ngx_list_init(&r->headers_in.headers, r->pool, 20,
                      sizeof(ngx_table_elt_t))
            != NGX_OK)
    {
        return NGX_ERROR;
    }

    if (ngx_array_init(&r->headers_in.cookies, r->pool, 2,
                       sizeof(ngx_table_elt_t *))
            != NGX_OK)
    {
        return NGX_ERROR;
    }

    r->headers_in.content_length_n = -1;
    r->headers_in.keep_alive_n = -1;

    r->headers_in.headers.part.nelts = 0;
    r->headers_in.headers.part.next = NULL;
    r->headers_in.headers.last = &r->headers_in.headers.part;

    /* shadow copy */
    if (apr_table_do(ngx_http_modsecurity_save_headers_in_visitor,
                     r, ctx->req->headers_in, NULL) == 0) {

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "ModSecurity: save headers in error");

        return NGX_ERROR;
    }

    if (r->headers_in.content_length) {
        r->headers_in.content_length_n =
            ngx_atoof(r->headers_in.content_length->value.data,
                      r->headers_in.content_length->value.len);

        if (r->headers_in.content_length_n == NGX_ERROR) {
            ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                          "ModSecurity: invalid \"Content-Length\" header");
            return NGX_ERROR;
        }
    }

    if (r->headers_in.connection_type == NGX_HTTP_CONNECTION_KEEP_ALIVE) {
        if (r->headers_in.keep_alive) {
            r->headers_in.keep_alive_n =
                ngx_atotm(r->headers_in.keep_alive->value.data,
                          r->headers_in.keep_alive->value.len);
        }
    }

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "ModSecurity: save headers in done");

    return NGX_OK;
}

static int
ngx_http_modsecurity_save_headers_in_visitor(void *data, const char *key, const char *value)
{
    ngx_http_request_t         *r = data;
    ngx_table_elt_t            *h;
    ngx_http_header_t          *hh;
    ngx_http_core_main_conf_t  *cmcf;

    h = ngx_list_push(&r->headers_in.headers);
    if (h == NULL) {
        return 0;
    }

    h->key.data = (u_char *)key;
    h->key.len = ngx_strlen(key);

    h->value.data = (u_char *)value;
    h->value.len = ngx_strlen(value);

    h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);

    if (h->lowcase_key == NULL) {
        return 0;
    }

    ngx_strlow(h->lowcase_key, h->key.data, h->key.len);

    h->hash = ngx_hash_key(h->lowcase_key, h->key.len);

    cmcf = ngx_http_get_module_main_conf(r, ngx_http_core_module);

    hh = ngx_hash_find(&cmcf->headers_in_hash, h->hash,
                       h->lowcase_key, h->key.len);

    if (hh && hh->handler(r, h, hh->offset) != NGX_OK) {
        return 0;
    }

    ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "ModSecurity: save headers in: \"%V: %V\"",
                   &h->key, &h->value);

    return 1;
}

static ngx_inline ngx_int_t
ngx_http_modsecurity_load_request_body(ngx_http_request_t *r)
{
    ngx_http_modsecurity_ctx_t    *ctx;

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);

    modsecSetBodyBrigade(ctx->req, ctx->brigade);

    if (r->request_body == NULL || r->request_body->bufs == NULL) {

        return move_chain_to_brigade(NULL, ctx->brigade, r->pool, 1);
    }

    if (move_chain_to_brigade(r->request_body->bufs, ctx->brigade, r->pool, 1) != NGX_OK) {
        return NGX_ERROR;
    }

    r->request_body = NULL;

    return NGX_OK;
}

static ngx_inline ngx_int_t
ngx_http_modsecurity_save_request_body(ngx_http_request_t *r)
{
    ngx_http_modsecurity_ctx_t    *ctx;
    apr_off_t                      content_length;
    ngx_buf_t                     *buf;
    ngx_http_core_srv_conf_t      *cscf;
    size_t                         size;
    ngx_http_connection_t         *hc;

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);

    apr_brigade_length(ctx->brigade, 0, &content_length);

    if (r->header_in->end - r->header_in->last >= content_length) {
        /* use r->header_in */

        if (ngx_buf_size(r->header_in)) {
            /* move to the end */
            ngx_memmove(r->header_in->pos + content_length,
                        r->header_in->pos,
                        ngx_buf_size(r->header_in));
        }

        if (apr_brigade_flatten(ctx->brigade,
                                (char *)r->header_in->pos,
                                (apr_size_t *)&content_length) != APR_SUCCESS) {
            return NGX_ERROR;
        }

        apr_brigade_cleanup(ctx->brigade);

        r->header_in->last += content_length;

        return NGX_OK;
    }

    if (ngx_buf_size(r->header_in)) {

        /*
         * ngx_http_set_keepalive will reuse r->header_in if
         * (r->header_in != c->buffer && r->header_in.last != r->header_in.end),
         * so we need this code block.
         * see ngx_http_set_keepalive, ngx_http_alloc_large_header_buffer
         */
        cscf = ngx_http_get_module_srv_conf(r, ngx_http_core_module);

        size = ngx_max(cscf->large_client_header_buffers.size,
                       (size_t)content_length + ngx_buf_size(r->header_in));

        hc = r->http_connection;

        if (hc->nfree && size == cscf->large_client_header_buffers.size) {

            buf = hc->free[--hc->nfree];

            ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                           "ModSecurity: use http free large header buffer: %p %uz",
                           buf->pos, buf->end - buf->last);

        } else if (hc->nbusy < cscf->large_client_header_buffers.num) {

            if (hc->busy == NULL) {
                hc->busy = ngx_palloc(r->connection->pool,
                                      cscf->large_client_header_buffers.num * sizeof(ngx_buf_t *));
            }

            if (hc->busy == NULL) {
                return NGX_ERROR;
            } else {
                buf = ngx_create_temp_buf(r->connection->pool, size);
            }
        } else {
            /* TODO: how to deal this case ? */
            return NGX_ERROR;
        }

    } else {

        buf = ngx_create_temp_buf(r->pool, (size_t) content_length);
    }

    if (buf == NULL) {
        return NGX_ERROR;
    }

    if (apr_brigade_flatten(ctx->brigade, (char *)buf->pos,
                            (apr_size_t *)&content_length) != APR_SUCCESS) {
        return NGX_ERROR;
    }

    apr_brigade_cleanup(ctx->brigade);
    buf->last += content_length;

    ngx_memcpy(buf->last, r->header_in->pos, ngx_buf_size(r->header_in));
    buf->last += ngx_buf_size(r->header_in);

    r->header_in = buf;

    return NGX_OK;
}

static ngx_inline ngx_int_t
ngx_http_modsecurity_load_headers_out(ngx_http_request_t *r)
{

    ngx_http_modsecurity_ctx_t  *ctx;
    char                        *data;
    request_rec                 *req;
    ngx_http_variable_value_t   *vv;
    ngx_list_part_t             *part;
    ngx_table_elt_t             *h;
    ngx_uint_t                   i;
    char                        *key, *value;
    u_char                      *buf = NULL;
    size_t                       size = 0;

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);
    req = ctx->req;

    req->status = r->headers_out.status;
    req->status_line = (char *)ngx_pstrdup0(r->pool, &r->headers_out.status_line);

    /* deep copy */
    part = &r->headers_out.headers.part;
    h = part->elts;

    for (i = 0; ; i++) {
        if (i >= part->nelts) {
            if (part->next == NULL)
                break;

            part = part->next;
            h = part->elts;
            i = 0;
        }
        size += h[i].key.len + h[i].value.len + 2;

        buf = ngx_palloc(r->pool, size);

        if (buf == NULL) {
            return NGX_ERROR;
        }

        key = (char *)buf;
        buf = ngx_cpymem(buf, h[i].key.data, h[i].key.len);
        *buf++ = '\0';

        value = (char *)buf;
        buf = ngx_cpymem(buf, h[i].value.data, h[i].value.len);
        *buf++ = '\0';

        apr_table_addn(req->headers_out, key, value);
        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "ModSecurity: load headers out: \"%V: %V\"",
                       &h[i].key, &h[i].value);

    }

    for (i = 0; special_headers_out[i].name; i++) {

        vv = ngx_http_get_variable(r, &special_headers_out[i].variable_name,
                                   ngx_hash_key(special_headers_out[i].variable_name.data,
                                                special_headers_out[i].variable_name.len));

        if (vv && !vv->not_found) {

            data = ngx_palloc(r->pool, vv->len + 1);
            if (data == NULL) {
                return NGX_ERROR;
            }

            ngx_memcpy(data,vv->data, vv->len);
            data[vv->len] = '\0';

            apr_table_setn(req->headers_out, special_headers_out[i].name, data);
            ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                           "ModSecurity: load headers out: \"%s: %s\"",
                           special_headers_out[i].name, data);
        }
    }

    req->content_type = apr_table_get(ctx->req->headers_out, "Content-Type");
    req->content_encoding = apr_table_get(ctx->req->headers_out, "Content-Encoding");

    data = (char *)apr_table_get(ctx->req->headers_out, "Content-Languages");

    if(data != NULL)
    {
        ctx->req->content_languages = apr_array_make(ctx->req->pool, 1, sizeof(const char *));
        *(const char **)apr_array_push(ctx->req->content_languages) = data;
    }

    /* req->chunked = r->chunked; may be useless */
    req->clength = r->headers_out.content_length_n;
    req->mtime = apr_time_make(r->headers_out.last_modified_time, 0);

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "ModSecurity: load headers out done");

    return NGX_OK;
}

static ngx_inline ngx_int_t
ngx_http_modsecurity_save_headers_out(ngx_http_request_t *r)
{
    ngx_http_modsecurity_ctx_t      *ctx;
    ngx_http_upstream_t             *upstream;

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);

    /* r->chunked = ctx->req->chunked; */

    ngx_http_clean_header(r);

    upstream = r->upstream;
    r->upstream = &ngx_http_modsecurity_upstream;

    /* case SecServerSignature was used, the "Server: ..." header is added
     * here, overwriting the default header supplied by nginx.
     */
    if (modsecIsServerSignatureAvailale() != NULL) {
        apr_table_add(ctx->req->headers_out, "Server",
                modsecIsServerSignatureAvailale());
    }

    if (apr_table_do(ngx_http_modsecurity_save_headers_out_visitor,
                     r, ctx->req->headers_out, NULL) == 0) {

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "ModSecurity: save headers out error");

        return NGX_ERROR;
    }

    r->upstream = upstream;

    r->headers_out.status = ctx->req->status;
    r->headers_out.status_line.data = (u_char *)ctx->req->status_line;
    r->headers_out.status_line.len = ctx->req->status_line ?
                                     ngx_strlen(ctx->req->status_line) : 0;

    r->headers_out.content_length_n = ctx->req->clength;
    r->headers_out.last_modified_time = apr_time_sec(ctx->req->mtime);

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "ModSecurity: save headers out done");

    return NGX_OK;
}

static int
ngx_http_modsecurity_save_headers_out_visitor(void *data, const char *key, const char *value)
{
    ngx_http_request_t             *r = data;
    ngx_table_elt_t                *h, he;
    ngx_http_upstream_header_t     *hh;
    ngx_http_upstream_main_conf_t  *umcf;

    umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);

    h = &he;

    h->key.data = (u_char *)key;
    h->key.len = ngx_strlen(key);

    h->value.data = (u_char *)value;
    h->value.len = ngx_strlen(value);

    h->lowcase_key = ngx_palloc(r->pool, h->key.len);
    if (h->lowcase_key == NULL) {
        return 0;
    }

    ngx_strlow(h->lowcase_key, h->key.data, h->key.len);

    h->hash = ngx_hash_key(h->lowcase_key, h->key.len);

    hh = ngx_hash_find(&umcf->headers_in_hash, h->hash,
                       h->lowcase_key, h->key.len);

    if (hh) {
        /* copy all */
        if (hh->copy_handler(r, h, hh->conf) != NGX_OK) {
            return 0;
        }
    }

    ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "ModSecurity: save headers out: \"%V: %V\"",
                   &h->key, &h->value);

    return 1;
}

static ngx_inline ngx_int_t
ngx_http_modsecurity_status(ngx_http_request_t *r, int status)
{
    ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "ModSecurity: status %d", status);

    if (status == DECLINED || status == APR_SUCCESS) {
        return NGX_DECLINED;
    }

    /* nginx known status */
    if ( (status >= 300 && status < 308)       /* 3XX */
            || (status >= 400 && status < 417) /* 4XX */
            || (status >= 500 && status < 508) /* 5XX */
            || (status == NGX_HTTP_CREATED || status == NGX_HTTP_NO_CONTENT) ) {

        return status;
    }

    return NGX_HTTP_INTERNAL_SERVER_ERROR;
}

/* create loc conf struct */
static void *
ngx_http_modsecurity_create_loc_conf(ngx_conf_t *cf)
{
    ngx_http_modsecurity_loc_conf_t  *conf;

    conf = (ngx_http_modsecurity_loc_conf_t  *)
           ngx_palloc(cf->pool, sizeof(ngx_http_modsecurity_loc_conf_t));
    if (conf == NULL)
        return NULL;

    conf->config = NGX_CONF_UNSET_PTR;
    conf->enable = NGX_CONF_UNSET;

    return conf;
}

/* merge loc conf */
static char *
ngx_http_modsecurity_merge_loc_conf(ngx_conf_t *cf, void *parent,
                                    void *child)
{
    ngx_http_modsecurity_loc_conf_t  *prev = parent;
    ngx_http_modsecurity_loc_conf_t  *conf = child;

    ngx_conf_merge_value(conf->enable, prev->enable, 0);
    ngx_conf_merge_ptr_value(conf->config, prev->config, NULL);

    if (conf->enable && conf->config == NULL) {
        ngx_log_error(NGX_LOG_EMERG, cf->log, 0,
                      "\"ModSecurityEnabled\" in %V:%ui is set to \"on\""
                      " while directive \"ModSecurityConfig\" is not found"
                      " in the same location",
                      conf->file, conf->line);
        return NGX_CONF_ERROR;
    }

    return NGX_CONF_OK;
}

static void
modsecLog(void *obj, int level, char *str)
{
    if (obj != NULL) {
        level = (level & APLOG_LEVELMASK) + NGX_LOG_EMERG - APLOG_EMERG;
        if (level > NGX_LOG_DEBUG) {
            level = NGX_LOG_DEBUG;
        }
        ngx_log_error((ngx_uint_t)level, (ngx_log_t *)obj, 0, "%s", str);
    }
}

/*
** This is a temporary hack to make PCRE work with ModSecurity
** nginx hijacks pcre_malloc and pcre_free, so we have to re-hijack them
*/
extern apr_pool_t *pool;

static void *
modsec_pcre_malloc(size_t size)
{
    return apr_palloc(pool, size);
}

static void
modsec_pcre_free(void *ptr)
{
}

static server_rec *modsec_server = NULL;

static ngx_int_t
ngx_http_modsecurity_preconfiguration(ngx_conf_t *cf)
{
    /*  XXX: temporary hack, nginx uses pcre as well and hijacks these two */
    pcre_malloc = modsec_pcre_malloc;
    pcre_free = modsec_pcre_free;

    modsecSetLogHook(cf->log, modsecLog);
    modsecSetDropAction(ngx_http_modsecurity_drop_action);

    /* TODO: server_rec per server conf */
    modsec_server = modsecInit();
    if (modsec_server == NULL) {
        return NGX_ERROR;
    }

    /* set host name */
    modsec_server->server_hostname = ngx_palloc(cf->pool, ngx_cycle->hostname.len + 1);
    if (modsec_server->server_hostname == NULL) {
        return NGX_ERROR;
    }
    ngx_memcpy(modsec_server->server_hostname, ngx_cycle->hostname.data, ngx_cycle->hostname.len);
    modsec_server->server_hostname[ ngx_cycle->hostname.len] = '\0';

    modsecStartConfig();
    return NGX_OK;
}

static void
ngx_http_modsecurity_terminate(ngx_cycle_t *cycle)
{
    if (modsec_server) {
        modsecTerminate();
        modsec_server = NULL;
    }
}

static ngx_int_t
ngx_http_modsecurity_init(ngx_conf_t *cf)
{
    ngx_http_handler_pt *h;
    ngx_http_core_main_conf_t *cmcf;

    modsecFinalizeConfig();

    cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

    h = ngx_array_push(&cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers);
    if (h == NULL) {
        return NGX_ERROR;
    }
    *h = ngx_http_modsecurity_handler;

    ngx_http_next_header_filter = ngx_http_top_header_filter;
    ngx_http_top_header_filter = ngx_http_modsecurity_header_filter;

    ngx_http_next_body_filter = ngx_http_top_body_filter;
    ngx_http_top_body_filter = ngx_http_modsecurity_body_filter;

    ngx_memzero(&ngx_http_modsecurity_upstream, sizeof(ngx_http_upstream_t));
    ngx_http_modsecurity_upstream.cacheable = 1;
    return NGX_OK;
}

static ngx_int_t
ngx_http_modsecurity_init_process(ngx_cycle_t *cycle)
{
    /* must set log hook here cf->log maybe changed */
    modsecSetLogHook(cycle->log, modsecLog);
    modsecInitProcess();
    return NGX_OK;
}

/*
** [ENTRY POINT] does : this function called by nginx from the request handler
*/
static ngx_int_t
ngx_http_modsecurity_handler(ngx_http_request_t *r)
{
    ngx_http_modsecurity_loc_conf_t *cf;
    ngx_http_modsecurity_ctx_t      *ctx;
    ngx_int_t                        rc;

    cf = ngx_http_get_module_loc_conf(r, ngx_http_modsecurity);

    /* Process only main request */
    if (r != r->main || !cf->enable) {
        return NGX_DECLINED;
    }

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "modSecurity: handler");

    /* create / retrive request ctx */
    if (r->internal) {

        ctx = ngx_http_get_module_pool_ctx(r, ngx_http_modsecurity);

        if (ctx) {
            /* we have already processed the request headers */
            ngx_http_set_ctx(r, ctx, ngx_http_modsecurity);
            return NGX_DECLINED;
        }

        ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "modSecurity: request pool ctx empty");
    }

    ctx = ngx_http_modsecurity_create_ctx(r);
    if (ctx == NULL) {

        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    ngx_http_set_ctx(r, ctx, ngx_http_modsecurity);

    if (ngx_http_set_pool_ctx(r, ctx, ngx_http_modsecurity) != NGX_OK) {
        return NGX_ERROR;
    }

    /* load request to request rec */
    if (ngx_http_modsecurity_load_request(r) != NGX_OK
        || ngx_http_modsecurity_load_headers_in(r) != NGX_OK) {

        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    /* processing request headers */
    rc = ngx_http_modsecurity_status(r, modsecProcessRequestHeaders(ctx->req));

    if (rc != NGX_DECLINED) {
        return rc;
    }

    if (modsecContextState(ctx->req) == MODSEC_DISABLED) {
        return NGX_DECLINED;
    }

    if (r->method == NGX_HTTP_POST
            && modsecIsRequestBodyAccessEnabled(ctx->req) ) {

        /* read POST request body, should we process PUT? */
        rc = ngx_http_read_client_request_body(r, ngx_http_modsecurity_body_handler);
        if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
            return rc;
        }

        return NGX_DONE;
    }

    /* other method */
    return ngx_http_modsecurity_status(r, modsecProcessRequestBody(ctx->req));
}

static void
ngx_http_modsecurity_body_handler(ngx_http_request_t *r)
{
    ngx_http_modsecurity_ctx_t    *ctx;
    ngx_int_t                      rc;

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "modSecurity: body handler");

    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);

    if (ngx_http_modsecurity_load_request_body(r) != NGX_OK) {
        return ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
    }

    rc = ngx_http_modsecurity_status(r, modsecProcessRequestBody(ctx->req));

    if (rc != NGX_DECLINED) {
        return ngx_http_finalize_request(r, rc);
    }

    if (ngx_http_modsecurity_save_request_body(r) != NGX_OK
            || ngx_http_modsecurity_save_headers_in(r) != NGX_OK ) {

        return ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
    }

    r->phase_handler++;
    ngx_http_core_run_phases(r);
    ngx_http_finalize_request(r, NGX_DONE);
}

static ngx_int_t
ngx_http_modsecurity_header_filter(ngx_http_request_t *r) {
    ngx_http_modsecurity_loc_conf_t *cf;
    ngx_http_modsecurity_ctx_t      *ctx;
    const char                      *location;
    ngx_table_elt_t                 *h;

    cf = ngx_http_get_module_loc_conf(r, ngx_http_modsecurity);
    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);

    /* already processed, checking redirect action. */
    if (ctx && ctx->complete
               && r->err_status >= NGX_HTTP_MOVED_PERMANENTLY
               && r->err_status < 308) {

        /* 3XX load redirect location header so that we can do redirect in phase 3,4 */
        location = apr_table_get(ctx->req->headers_out, "Location");

        if (location == NULL) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

        h = ngx_list_push(&r->headers_out.headers);
        if (h == NULL) {
            return NGX_HTTP_INTERNAL_SERVER_ERROR;
        }

        h->hash = 1;
        h->key.data = (u_char *)"Location";
        h->key.len = ngx_strlen("Location");
        h->value.data = (u_char *)location;
        h->value.len = ngx_strlen(location);

        return ngx_http_next_header_filter(r);
    }

    if (r != r->main || !cf->enable || ctx == NULL ||ctx->complete) {
        return ngx_http_next_header_filter(r);
    }

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "modSecurity: header filter");

    r->filter_need_in_memory = 1;
    return NGX_OK;
}

static ngx_int_t
ngx_http_modsecurity_body_filter(ngx_http_request_t *r, ngx_chain_t *in)
{
    ngx_http_modsecurity_loc_conf_t *cf;
    ngx_http_modsecurity_ctx_t      *ctx;
    ngx_int_t                        rc;
    apr_off_t                        content_length;
    ngx_chain_t                     *cl, *out;
    ngx_int_t                        last_buf = 0;

    cf = ngx_http_get_module_loc_conf(r, ngx_http_modsecurity);
    ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity);

    if (r != r->main || !cf->enable || ctx == NULL || ctx->complete) {
        return ngx_http_next_body_filter(r, in);
    }

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "modSecurity: body filter");

    for (cl = in; cl; cl = cl->next) {
        apr_bucket  *e;
        ngx_buf_t   *buf = cl->buf;
        apr_bucket_brigade  *bb = ctx->brigade;
        off_t size = ngx_buf_size(buf);
        if (size) {
            char *data = apr_pmemdup(bb->p, buf->pos, size);
            if (data == NULL) {
                return ngx_http_filter_finalize_request(r,
                         &ngx_http_modsecurity, NGX_HTTP_INTERNAL_SERVER_ERROR);
            }
            e = apr_bucket_pool_create(data , size, bb->p, bb->bucket_alloc);
            if (e == NULL) {
                return ngx_http_filter_finalize_request(r,
                         &ngx_http_modsecurity, NGX_HTTP_INTERNAL_SERVER_ERROR);
            }
            APR_BRIGADE_INSERT_TAIL(bb, e);
        }

        if (buf->last_buf) {
            last_buf = 1;
            buf->last_buf = 0;
            e = apr_bucket_eos_create(bb->bucket_alloc);
            if (e == NULL) {
                return ngx_http_filter_finalize_request(r,
                         &ngx_http_modsecurity, NGX_HTTP_INTERNAL_SERVER_ERROR);
            }
            APR_BRIGADE_INSERT_TAIL(bb, e);
            break;
        }

        buf->pos = buf->last;
    }

    if (!last_buf) {
        return NGX_AGAIN;
    }

    /* last buf has been saved */
    ctx->complete = 1;
    modsecSetResponseBrigade(ctx->req, ctx->brigade);

    if (ngx_http_modsecurity_load_headers_in(r) != NGX_OK
            || ngx_http_modsecurity_load_headers_out(r) != NGX_OK) {

        return ngx_http_filter_finalize_request(r,
                 &ngx_http_modsecurity, NGX_HTTP_INTERNAL_SERVER_ERROR);
    }

    rc = ngx_http_modsecurity_status(r, modsecProcessResponse(ctx->req));

    if (rc != NGX_DECLINED) {
        return ngx_http_filter_finalize_request(r, &ngx_http_modsecurity, rc);
    }

    apr_brigade_length(ctx->brigade, 0, &content_length);

    rc = move_brigade_to_chain(ctx->brigade, &out, r->pool);
    if (rc == NGX_ERROR) {
        return ngx_http_filter_finalize_request(r,
                 &ngx_http_modsecurity, NGX_HTTP_INTERNAL_SERVER_ERROR);
    }

    if (ngx_http_modsecurity_save_headers_in(r) != NGX_OK
            ||ngx_http_modsecurity_save_headers_out(r) != NGX_OK) {

        return ngx_http_filter_finalize_request(r,
                 &ngx_http_modsecurity, NGX_HTTP_INTERNAL_SERVER_ERROR);
    }

    if (r->headers_out.content_length_n != -1) {

        r->headers_out.content_length_n = content_length;
        r->headers_out.content_length = NULL; /* header filter will set this */
    }

    r->header_sent = 0;
    rc = ngx_http_next_header_filter(r);

    if (rc == NGX_ERROR || rc > NGX_OK) {
        return ngx_http_filter_finalize_request(r, &ngx_http_modsecurity, rc);
    }

    return ngx_http_next_body_filter(r, out);
}

#define TXID_SIZE 25

static ngx_http_modsecurity_ctx_t *
ngx_http_modsecurity_create_ctx(ngx_http_request_t *r)
{
    ngx_http_modsecurity_loc_conf_t *cf;
    ngx_pool_cleanup_t              *cln;
    ngx_http_modsecurity_ctx_t      *ctx;
    apr_sockaddr_t                  *asa;
    struct sockaddr_in              *sin;
    char *txid;
    unsigned char salt[TXID_SIZE];
    int i;
#if (NGX_HAVE_INET6)
    struct sockaddr_in6             *sin6;
#endif

    ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_modsecurity_ctx_t));
    if (ctx == NULL) {
        ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "modSecurity: ctx memory allocation error");
        return NULL;
    }
    cln = ngx_pool_cleanup_add(r->pool, sizeof(ngx_http_modsecurity_ctx_t));
    if (cln == NULL) {
        ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "modSecurity: ctx memory allocation error");
        return NULL;
    }
    cln->handler = ngx_http_modsecurity_cleanup;
    cln->data = ctx;

    ctx->r = r;

    if (r->connection->requests == 0 || ctx->connection == NULL) {

        /* TODO: set server_rec, why igonre return value? */
        ctx->connection = modsecNewConnection();

        /* fill apr_sockaddr_t */
        asa = ngx_palloc(r->pool, sizeof(apr_sockaddr_t));
        asa->pool = ctx->connection->pool;
        asa->hostname = (char *)ngx_pstrdup0(r->pool, &r->connection->addr_text);
        asa->servname = asa->hostname;
        asa->next = NULL;
        asa->salen = r->connection->socklen;
        ngx_memcpy(&asa->sa, r->connection->sockaddr, asa->salen);

        asa->family = ((struct sockaddr *)&asa->sa)->sa_family;
        switch ( asa->family) {

#if (NGX_HAVE_INET6)
        case AF_INET6:
            sin6 = (struct sockaddr_in6 *)&asa->sa;
            asa->ipaddr_ptr = &sin6->sin6_addr;
            asa->ipaddr_len = sizeof(sin6->sin6_addr);
            asa->port = ntohs(sin6->sin6_port);
            asa->addr_str_len = NGX_INET6_ADDRSTRLEN + 1;
            break;
#endif

        default: /* AF_INET */
            sin = (struct sockaddr_in *) &asa->sa;
            asa->ipaddr_ptr = &sin->sin_addr;
            asa->ipaddr_len = sizeof(sin->sin_addr);
            asa->port = ntohs(sin->sin_port);
            asa->addr_str_len = NGX_INET_ADDRSTRLEN + 1;
            break;
        }

#if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER < 3
        ctx->connection->remote_addr = asa;
        ctx->connection->remote_ip = asa->hostname;
#else
        ctx->connection->client_addr = asa;
        ctx->connection->client_ip = asa->hostname;
#endif
        ctx->connection->remote_host = NULL;
        modsecProcessConnection(ctx->connection);
    }

    cf = ngx_http_get_module_loc_conf(r, ngx_http_modsecurity);

    ctx->req = modsecNewRequest(ctx->connection, cf->config);

    apr_table_setn(ctx->req->notes, NOTE_NGINX_REQUEST_CTX, (const char *) ctx);
    apr_generate_random_bytes(salt, TXID_SIZE);

    txid = apr_pcalloc (ctx->req->pool, TXID_SIZE);
    apr_base64_encode (txid, (const char*)salt, TXID_SIZE);

    for(i=0;i<TXID_SIZE;i++)        {
        if((salt[i] >= 0x30) && (salt[i] <= 0x39))      {}
        else if((salt[i] >= 0x40) && (salt[i] <= 0x5A)) {}
        else if((salt[i] >= 0x61) && (salt[i] <= 0x7A)) {}
        else {
            if((i%2)==0)
                salt[i] = 0x41;
            else
                salt[i] = 0x63;
        }
    }

    salt[TXID_SIZE-1] = '\0';

    apr_table_setn(ctx->req->subprocess_env, "UNIQUE_ID", apr_psprintf(ctx->req->pool, "%s", salt));

    ctx->brigade = apr_brigade_create(ctx->req->pool, ctx->req->connection->bucket_alloc);

    if (ctx->brigade == NULL) {
        return NULL;
    }

    return ctx;
}

    static void
ngx_http_modsecurity_cleanup(void *data)
{
    ngx_http_modsecurity_ctx_t    *ctx = data;

    if (ctx->req != NULL) {
        (void) modsecFinishRequest(ctx->req);
    }
    if (ctx->connection != NULL) {
        (void) modsecFinishConnection(ctx->connection);
    }

}

    static char *
ngx_http_modsecurity_config(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ngx_http_modsecurity_loc_conf_t *mscf = conf;
    ngx_str_t       *value;
    const char      *msg;

    if (mscf->config != NGX_CONF_UNSET_PTR) {
        return "is duplicate";
    }

    value = cf->args->elts;

    if (ngx_conf_full_name(cf->cycle, &value[1], 1) != NGX_OK) {
        return NGX_CONF_ERROR;
    }

    mscf->config = modsecGetDefaultConfig();

    if (mscf->config == NULL) {
        return NGX_CONF_ERROR;
    }

    msg = modsecProcessConfig(mscf->config, (const char *)value[1].data, NULL);
    if (msg != NULL) {
        ngx_log_error(NGX_LOG_EMERG, cf->log, 0, "ModSecurityConfig in %s:%ui: %s",
                cf->conf_file->file.name.data, cf->conf_file->line, msg);
        return NGX_CONF_ERROR;
    }

    return NGX_CONF_OK;
}

    static char *
ngx_http_modsecurity_enable(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ngx_http_modsecurity_loc_conf_t *mscf = conf;
    char                            *rc;

    rc = ngx_conf_set_flag_slot(cf, cmd, conf);
    if (rc != NGX_CONF_OK) {
        return rc;
    }
    if (mscf->enable) {
        mscf->file = &cf->conf_file->file.name;
        mscf->line = cf->conf_file->line;
    }
    return NGX_CONF_OK;
}

    static int
ngx_http_modsecurity_drop_action(request_rec *r)
{
    ngx_http_modsecurity_ctx_t     *ctx;
    ctx = (ngx_http_modsecurity_ctx_t *) apr_table_get(r->notes, NOTE_NGINX_REQUEST_CTX);

    if (ctx == NULL) {
        return -1;
    }
    ctx->r->connection->error = 1;
    return 0;
}


text:
import scala.concurrent._
import scala.concurrent.duration._
import java.util.concurrent.Executors

object Test {
  import ExecutionContext.Implicits.global
  val x = Await.result(Future(1), 1000.seconds)
  def main(args: Array[String]) = println(x)
}


text:
<resources>
    <string name="app_name">test_progress_button</string>
</resources>


text:
package com.xnfh.bjhospital.ui.main.Classify;

import com.xnfh.bjhospital.base.BaseView;

/**
 * Created by wangxuewei on 2017/10/19.
 */
public class ClassifyView implements BaseView {
    @Override
    public void showLoading(String title) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorTip(String msg) {

    }
}


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:orientation="vertical"
    tools:context="com.jahirfiquitiva.paperboard.activities.MainActivity">

    <com.jahirfiquitiva.paperboard.views.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/primary"
        android:clipToPadding="false"
        android:elevation="@dimen/toolbar_elevation"
        android:paddingLeft="@dimen/tabs_contentInset"
        android:paddingStart="@dimen/tabs_contentInset"
        tools:ignore="NewApi,RtlSymmetry,UnusedAttribute" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="@dimen/no_height"
        android:layout_weight="1" />

</LinearLayout>


text:
.class public interface abstract Landroid/opengl/GLExternalSurfaceView$EGLWindowSurfaceFactory;
.super Ljava/lang/Object;
.source "GLExternalSurfaceView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/opengl/GLExternalSurfaceView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "EGLWindowSurfaceFactory"
.end annotation

# virtual methods
.method public abstract createWindowSurface(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLConfig;Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLSurface;
.end method

.method public abstract destroySurface(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSurface;)V
.end method


text:
<?php
session_start();
require '../config/dbconnect.php';

$station=$_POST['station'];
$requester=$_SESSION['username'];
$reqdate=$_POST['reqdate'];
$date=explode(" - ", $reqdate);
$fromdate=$date[0];
$todate=$date[1];
$qty=$_POST['qty'];

$qualification=$_POST['qualification'];
$actype=$_POST['actype'];
$rating=$_POST['rating'];
$note=$_POST['note'];

$statusrequest="1";

$reason=$_POST['reason'];
$reimburstment=$_POST['reimburstment'];

$codenow="REQ".$station.date("Y").date("m").date("d");

$sql="SELECT MAX(request_id) as request_id FROM request WHERE SUBSTRING(request_id,1,14)='".$codenow."'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);

$datecode=substr($row['request_id'], 0, 14);
$num=substr($row['request_id'], 14);

$num=(int)$num;

if ($datecode==$codenow) {
	$num++;
	$num=sprintf("%04d",$num);
}
else {
	$num=1;
	$num=sprintf("%04d",$num);
}

$request_id="REQ".$station.date("Y").date("m").date("d").$num;

$sql="INSERT INTO request(request_id,station_origin,requester_id,request_date,request_total,
	start_date,finish_date,status_request,reason,reimburstment)
VALUES ('".$request_id."','".$station."','".$requester."','".date("Y-m-d")."','".$qty."',
	'".date("Y-m-d",strtotime($fromdate))."','".date("Y-m-d",strtotime($todate))."','".$statusrequest."','".$reason."','".$reimburstment."')";
$result=mysqli_query($conn,$sql);
$n=1;
for ($i=0; $i<$qty ; $i++) {
	$rqid="REQDET".$station.date("Y").date("m").date("d").$num.$n;
	$sql="INSERT INTO request_qualification(rq_id, rq_note, request_id, qualification_id, pesawat_id, rating_id)
	VALUES('".$rqid."','".$note[$i]."','".$request_id."','".$qualification[$i]."','".$actype[$i]."','".$rating[$i]."')";
	$result=mysqli_query($conn,$sql);
	$n++;
}

$sql="SELECT p.`personil_email` FROM personil_detail p, user_account u WHERE u.`user_id`=p.`personil_id` AND (u.`role_id`='3' OR u.`role_id`='5' OR u.`role_id`='7')";
$result=mysqli_query($conn,$sql);
while ($row=mysqli_fetch_array($result)) {
	require 'sentmail.php';
}

$status=1;
$pesan="Your request has been submitted";

header("Location: ../view/addrequest.php?status=$status&pesan=$pesan");
?>


text:
import json
from urllib import urlencode
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

from corehq import toggles
from corehq.apps.app_manager.dbaccessors import get_app
from corehq.apps.app_manager.decorators import require_deploy_apps

CASE_TYPE_CONFLICT_MSG = (
    "Warning: The form's new module "
    "has a different case type from the old module.<br />"
    "Make sure all case properties you are loading "
    "are available in the new case type"
)

@require_deploy_apps
def back_to_main(request, domain, app_id=None, module_id=None, form_id=None,
                 unique_form_id=None):
    """
    returns an HttpResponseRedirect back to the main page for the App Manager app
    with the correct GET parameters.

    This is meant to be used by views that process a POST request,
    which then redirect to the main page.

    """
    # TODO: Refactor this function. The length of the args matters :(

    page = None
    params = {}

    args = [domain]

    if app_id is not None:
        args.append(app_id)
        if unique_form_id is not None:
            app = get_app(domain, app_id)
            obj = app.get_form(unique_form_id, bare=False)
            module_id = obj['module'].id
            form_id = obj['form'].id
        if module_id is not None:
            args.append(module_id)
            if form_id is not None:
                args.append(form_id)

    if page:
        view_name = page
    else:
        view_name = {
            1: 'default_app',
            2: 'view_app',
            3: 'view_module',
            4: 'form_designer' if toggles.APP_MANAGER_V2.enabled(domain) else 'view_form',
        }[len(args)]

    return HttpResponseRedirect(
        "%s%s" % (
            reverse(view_name, args=args),
            "?%s" % urlencode(params) if params else ""
        )
    )

def get_langs(request, app):
    lang = request.GET.get(
        'lang',
        request.COOKIES.get('lang', app.langs[0] if hasattr(app, 'langs') and app.langs else '')
    )
    langs = None
    if app and hasattr(app, 'langs'):
        if not app.langs and not app.is_remote_app:
            # lots of things fail if the app doesn't have any languages.
            # the best we can do is add 'en' if there's nothing else.
            app.langs.append('en')
            app.save()
        if not lang or lang not in app.langs:
            lang = (app.langs or ['en'])[0]
        langs = [lang] + app.langs
    return lang, langs

def bail(request, domain, app_id, not_found=""):
    if not_found:
        messages.error(request, 'Oops! We could not find that %s. Please try again' % not_found)
    else:
        messages.error(request, 'Oops! We could not complete your request. Please try again')
    return back_to_main(request, domain, app_id)

def encode_if_unicode(s):
    return s.encode('utf-8') if isinstance(s, unicode) else s

def validate_langs(request, existing_langs):
    o = json.loads(request.body)
    langs = o['langs']
    rename = o['rename']

    assert set(rename.keys()).issubset(existing_langs)
    assert set(rename.values()).issubset(langs)
    # assert that there are no repeats in the values of rename
    assert len(set(rename.values())) == len(rename.values())
    # assert that no lang is renamed to an already existing lang
    for old, new in rename.items():
        if old != new:
            assert(new not in existing_langs)

    return (langs, rename)


text:
layout: doc
title: Mobify.js Framework Documentation
description:
    Find all necessary documentation for Mobify.js, an open source web
    framework from Mobify that helps you adapt any website to support any device.
---

# Quick Start

Mobify.js is a JavaScript framework for adapting websites for tablet and mobile.

1. Install Node.js if you don't have it already.

1. Download the [Mobify Client](https://github.com/mobify/mobify-client):

        sudo npm -g install mobify-client

1. Create a project scaffold and start the Mobify.js development server:

        mobify init myproject
        cd myproject
        mobify preview

## Install the Mobify.js Tag

Insert the Mobify.js tag **immediately** after the opening __ tag on the
website you want to adapt:

{% include paid_warning.html %}

## Preview your mobile site

1. Set your browser's User Agent to "iPhone":

    * In Chrome, open Webkit Inspector, click the gear in the bottom right, then
      the _"User agent"_ tab. Check _"Override User Agent"_ then select _"iPhone"_
      from the dropdown.
    * In Safari click _"Develop"_ > _"User Agent"_ > _"iPhone"_
    * In Firefox download the [User Agent Switcher](https://addons.mozilla.org/en-US/firefox/addon/user-agent-switcher/) extension.

1. Navigate to your page. If the demo gods are kind, you'll see this:

## How it works:

Mobify.js uses a technique called **client side adaptation** to remix HTML in
the browser. The remixed content is interpreted by the browser as if the server
had sent it in the first place!

The **Mobify.js tag** bootstraps the adaptation and loads the **Mobify.js file**,
which performs it. The tag activates in iOS, Android and BlackBerry browsers.
By default, the Mobify.js file is loaded from the development server.

The development server is part of the **Mobify Client**, a command line tool for
building Mobify.js projects. It compiles the Mobify.js file dynamically per
request. The file contains two parts, the **Mobify.js API** and site specific
adaptations.

Adaptations are expressed as a series of operations on the **source DOM**, the
DOM constructed from the page's original HTML. HTML Elements can be selected,
then rendered with a template. Finally, the rendered template is written to the
browser.

## Where to next?

* [See how to change the generated scaffold files in "Getting Started"](./getting-started/)
* [Learn about how to adapt your site using DOM operations in "Understanding the Konf"](./understanding-konf/)
* [See how templates can be used to control the adaptation in "Understanding Templates"](./understanding-templates/)
* [Read tips for debugging Mobify.js in the Appendix](./appendix/)


text:
class Name
  attr_reader :first_name, :last_name

  @@all_names = []

  define_method(:initialize) do |attributes|
    @first_name = attributes.fetch(:first_name)
    @last_name = attributes.fetch(:last_name)
    @id = @@all_names.length().+(1)
  end

  define_singleton_method(:all) do
    @@all_names
  end

  define_method(:save) do
    @@all_names.push(self)
  end

  define_singleton_method(:clear) do
    @@all_names = []
  end
  define_method(:id) do
    @id
  end
  define_singleton_method(:find) do |identification|
    found_name = nil
    @@all_names.each() do |name_find|
      if name_find.id().eql?(identification.to_i())
        found_name = name_find
      end
    end
    found_name
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="gold">#FFCD00</color>
    <color name="white_75">#BFFFFFFF</color>
    <color name="gray85">#D9252525</color>
    <color name="black85">#D9000000</color>
    <color name="white">#FFFFFF</color>
</resources>


text:
gui/extended-status
===================
Adds more subpages to the ``z`` status screen.

Usage::

    gui/extended-status enable|disable|help|subpage_names
    enable|disable gui/extended-status

]====]

gui = require 'gui'
dialogs = require 'gui.dialogs'
gps = df.global.gps
world = df.global.world

if enabled == nil then
    enabled = false
end

subpages = {
    {key = 'CUSTOM_B', desc = 'Bedrooms', screen = 'bedroom_list'},
}

function derror(msg)
    dialogs.showMessage('Error', msg, COLOR_LIGHTRED)
    qerror(msg)
end

subpage_classes = {}
subpage_names = {}
function defsubpage(name)
    if subpage_classes[name] then
        error('Duplicate definition of subpage ' .. name)
    end
    local class = defclass(_ENV[name], gui.FramedScreen)
    class.ATTRS = {
        focus_path = 'extended_status/' .. name,
        frame_inset = 1,
    }
    subpage_classes[name] = class
    table.insert(subpage_names, name)
    _ENV[name] = class
end

function has_manager()
    return #df.historical_entity.find(df.global.ui.group_id).assignments_by_type.MANAGE_PRODUCTION > 0
end

function queue_beds(amount)
    amount = math.floor(tonumber(amount) or derror('Invalid number of beds: ' .. tostring(amount)))
    if amount == 0 then return end
    if amount < 0 then
        derror('Cannot queue a negative number of beds')
    end

    order = df.manager_order:new()
    order.id = df.global.world.manager_order_next_id
    df.global.world.manager_order_next_id = df.global.world.manager_order_next_id + 1
    order.job_type = df.job_type.ConstructBed
    order.material_category.wood = true
    order.amount_left = amount
    order.amount_total = amount
    df.global.world.manager_orders:insert('#', order)
end

status_overlay = defclass(status_overlay, gui.Screen)
status_overlay.ATTRS = {
    focus_path = 'status_overlay'
}

function status_overlay:init()
    self.show_menu = false
end

function status_overlay:onRender()
    local parent = self._native.parent
    parent:render()
    if self.show_menu then
        dfhack.screen.paintString({fg=COLOR_BLACK, bg=COLOR_DARKGREY},
            gps.dimx - 8, gps.dimy - 1, "DFHack")
        local p = gui.Painter.new_xy(2, 2, gps.dimx - 3, gps.dimy - 3)
        p:key_pen(COLOR_LIGHTRED)
        dfhack.screen.fillRect({}, 1, 1, gps.dimx - 2, gps.dimy - 2)
        for i, opt in pairs(subpages) do
            p:key(opt.key):string(': ' .. opt.desc):newline()
        end
        p:seek(0, p.height - 1):key('LEAVESCREEN'):string(': Back')
    else
        local p = gui.Painter.new_xy(1, 1, gps.dimx - 2, 3)
        p:key_pen(COLOR_LIGHTRED)
        p:seek(3, 2):key('CUSTOM_X'):string(': Additional options (DFHack)')
    end
end

function status_overlay:onInput(keys)
    local parent = self._native.parent
    if self.show_menu then
        if keys.LEAVESCREEN then
            self.show_menu = false
        end
        for _, opt in pairs(subpages) do
            if keys[opt.key] then
                local class = _ENV[opt.screen]
                if class then
                    class():show()
                else
                    derror('Undefined screen: ' .. opt.screen)
                end
                break
            end
        end
    else
        if keys.CUSTOM_X then
            self.show_menu = true
            return
        end
        if keys.LEAVESCREEN then
            self:dismiss()
        end
        gui.simulateInput(parent, keys)
    end
end

defsubpage('bedroom_list')
bedroom_list.ATTRS.frame_title = 'Bedroom status'

function bedroom_list:init()
    self.dirty = false
    self:refresh()
end

function bedroom_list:refresh()
    self.data = {
        {'Beds', 'beds'},
        {'Built beds', 'bbeds'},
        {'Unbuilt beds', 'ubeds'},
        {'Bedrooms', 'brooms'},
        {'Owned Bedrooms', 'obrooms'},
        {'Unowned Bedrooms', 'ubrooms'},
        {'Units', 'units'},
        {'Units with bedrooms', 'uwith'},
        {'Units without bedrooms', 'uwithout'}
    }
    self.data.raw = {}
    for _, d in pairs(self.data) do d.list = {} end
    local function add(key, item)
        for _, d in pairs(self.data) do
            if d[2] == key then
                table.insert(d.list, item)
                self.data.raw[key] = (self.data.raw[key] or 0) + 1
            end
        end
    end
    for _, u in pairs(world.units.active) do
        if dfhack.units.isCitizen(u) then
            add('units', u)
            local has_bed = false
            for _, b in pairs(u.owned_buildings) do
                if df.building_bedst:is_instance(b) then
                    has_bed = true
                end
            end
            if has_bed then
                add('uwith', u)
            else
                add('uwithout', u)
            end
        end
    end
    for _, bed in pairs(world.items.other.BED) do
        add('beds', bed)
        add(bed.flags.in_building and 'bbeds' or 'ubeds', bed)
    end
    for _, building in pairs(world.buildings.other.BED) do
        if building.is_room then
            add('brooms', building)
            add(building.owner and 'obrooms' or 'ubrooms', building)
        end
    end
    self.queued_beds = 0
    for _, order in pairs(df.global.world.manager_orders) do
        if order.job_type == df.job_type.ConstructBed then
            self.queued_beds = self.queued_beds + order.amount_left
        end
    end
end

function bedroom_list:onRenderBody(p)
    if self.dirty then
        self:refresh()
        self.dirty = false
    end

    p:key_pen(COLOR_LIGHTRED)
    for _, item in ipairs(self.data) do
        p:string(item[1]):string(': '):string(tostring(#item.list)):newline()
    end

    p:seek(40, 0)
    p:key_string('MANAGER_NEW_ORDER', 'Order more beds')

    p:newline(40):advance(3)
    p:string(tostring(self.queued_beds), self.queued_beds > 0 and COLOR_LIGHTGREEN or nil)
    p:string(' queued')
    if not has_manager() then
        p:string(' - '):string('needs manager', COLOR_LIGHTRED)
    end

    p:newline(40)
    p:key_string('UNITJOB_MANAGER', 'Open manager')
end

function bedroom_list:onInput(keys)
    if keys.LEAVESCREEN then
        self:dismiss()
    elseif keys.MANAGER_NEW_ORDER then
        dialogs.showInputPrompt(
            'Queue beds',
            'Number of beds to queue:',
            nil,
            tostring(math.max(0, self.data.raw.units - self.data.raw.beds - self.queued_beds)),
            function(amount)
                queue_beds(amount)
                self:refresh()
            end
        )
    elseif keys.UNITJOB_MANAGER then
        dfhack.screen.show(df.viewscreen_jobmanagementst:new())
        self.dirty = true
    end
end

screen_history = screen_history or {'', ''}
dfhack.onStateChange['gui/extended-status'] = function(e)
    table.insert(screen_history, dfhack.gui.getCurFocus())
    table.remove(screen_history, 1)
    if enabled and screen_history[2] == 'overallstatus' and screen_history[1]:sub(1, 6) ~= 'dfhack' then
        status_overlay():show()
    end
end

args = {...}
if dfhack_flags and dfhack_flags.enable then
    args = {dfhack_flags.enable_state and 'enable' or 'disable'}
end
if args[1] == 'enable' then
    enabled = true
elseif args[1] == 'disable' then
    enabled = false
elseif subpage_classes[args[1]] then
    subpage_classes[args[1]]():show()
else
    print((([[Usage:
    gui/extended-status enable|disable|help|subpage_names
    enable|disable gui/extended-status
    ]]):gsub('subpage_names', table.concat(subpage_names, '|'))))
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>amaascore.assets.currency — amaas-core-sdk-python 0.1.11 documentation</title>

    <link rel="stylesheet" href="../../../_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />

  <link rel="stylesheet" href="../../../_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Source code for amaascore.assets.currency

from __future__ import absolute_import, division, print_function, unicode_literals

from amaascore.assets.asset import Asset

[docs]class Currency(Asset):

    def __init__(self, asset_id, deliverable, asset_status='Active', minor_unit_places=2, description='',
                 country_id=None, *args, **kwargs):
        self.asset_class = 'Currency'
        self.deliverable = deliverable
        self.minor_unit_places = minor_unit_places
        super(Currency, self).__init__(asset_manager_id=0, asset_id=asset_id, fungible=True,
                                       asset_class=self.asset_class, asset_status=asset_status, description=description,
                                       country_id=country_id, venue_id=None, maturity_date=None,
                                       *args, **kwargs)

Related Topics

Documentation overview

Module code

Quick search

    <form class="search" action="../../../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2017, AMaaS.

      |
      Powered by Sphinx 1.5.5
      & Alabaster 0.7.10