text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="layout_margin">10dp</dimen>
    <dimen name="layout_margin_x2">20dp</dimen>
    <dimen name="path_width">130dp</dimen>
    <dimen name="big_button_width">230dp</dimen>
    <dimen name="label_margin">5dp</dimen>
    <dimen name="icon_size">40dp</dimen>
    <dimen name="edit_text_number">70dp</dimen>
</resources>


text:
It's possible to write modular regexes by using subroutines. First things first:
```php
$regex1 = '/(\d+),\1/';     // Backreference
$regex2 = '/(\d+),(?1)/';   // Subroutine
```

In the first regex we used a backreference `\1`, it will match what was matched in group 1. So the first regex will match `123,123` but won't match `123,156`.

In the second regex we used a subroutine (or recursion) `(?1)`, it will repeat the pattern that was used in group 1. You might say it's the same as writing `/(\d+),\d+/`. It will match `123,123` and `123,156`.

We can also use named groups instead:
```php
$regex = '/(?<number>\d+),(?&number)/';   // Named subroutine
```

Let's use this to our advantage
```php

$regex = <<<'regex'
~
(?(DEFINE)
   (?<id>\d+)
   (?<username>user(?&id))
   (?<protocol>https?|ftp)
   (?<domain>example[.]com)
   (?<url>(?&protocol)://(?&domain)/users/(?&id)/(?&username)/?)
)

^(?&url)$   # Anchor our match
~x
regex;
```

We first have a bunch of definitions and then we use one of those definitions in our pattern. For some reason you must change the regex so that an id must be alphanumeric instead of digits, support other protocols or change the domain. You name it. You would only need to change that specific definition instead of rewriting a complete regex.

If you want to read about the DEFINE construct. Check out this [StackOverflow answer](https://stackoverflow.com/a/18151617)

### [<< previous](06%20Escaping%20a%20backslash%20hell.md)

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once STEAM_CONDENSER_PATH . 'steam/packets/SteamPacket.php';

/**
 * This packet class represent a M2S_REQUESTRESTART response replied from a
 * master server
 *
 * It is used to request a game server restart, e.g. when the server is
 * outdated.
 *
 * @author Sebastian Staudt
 * @package steam-condenser
 * @subpackage packets
 * @see MasterServer::sendHeartbeat
 */
class M2S_REQUESTRESTART_Packet extends SteamPacket {

    /**
     * @var int
     */
    private $challenge;

    /**
     * Creates a new M2S_REQUESTRESTART object based on the given data
     *
     * @param string $data The raw packet data replied from the server
     */
    public function __construct($data) {
        parent::__construct(SteamPacket::C2M_CHECKMD5_HEADER, $data);

        $this->challenge = $this->contentData->getUnsignedLong();
    }

    /**
     * Returns the challenge number used for master server communication
     *
     * @return int The challenge number
     */
    public function getChallenge() {
        return $this->challenge;
    }

}


text:
package com.rodrigodev.xgen4j.test.integration.common.appliance;

import com.rodrigodev.xgen4j.test.integration.common.CommonException;
import com.rodrigodev.xgen4j.test.integration.HouseException;
import com.rodrigodev.xgen4j.test.integration.ErrorCode;

/**
 * Autogenerated by XGen4J on January 1, 0001.
 */
public class ApplianceException extends CommonException {

    protected ApplianceException(ErrorCode errorCode, String message) {
        super(errorCode, message);
    }

    protected ApplianceException(ErrorCode errorCode, String message, Throwable cause) {
        super(errorCode, message, cause);
    }
}


text:
layout: post
title: Lazily Check the Body of an HttpServletRequest
tags: [java, programming]
keywords: [httpservletrequest, spring, servlet]
---

Recently I was helping a junior developer analyze the incoming parameters of an HTTP request in a Spring/Java Servlet application.

The issue came down to reading the body of the request: the way an [HttpServletRequest](https://docs.oracle.com/javaee/6/api/index.html?javax/servlet/http/HttpServletRequest.html) is designed, once the body is read, then the body is consumed. It's gone. Any attempt to read the body again will result in reading an empty body.

Of course, that's no good.

After a [few attempts](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) at [caching the body](http://www.javabyexamples.com/read-request-body-multiple-times-using-spring-mvc) to [read it twice](https://stackoverflow.com/questions/32763922/spring-reading-request-body-twice) (either using custom wrappers or Spring's [ContentCachingRequestWrapper](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/ContentCachingRequestWrapper.html)) I decided it might be better to lazily read the body. That is, only read the body when  it's requested, and then pass the body onto the requesting method.

I did this by creating a custom HttpServletRequest class (that extends [HttpServletRequestWrapper](https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequestWrapper.html)).

And then, in a filter class, wrap the request and send in on down the chain

Finally, you'll need to add the filter to your web.xml file:

<script src="https://gist.github.com/hendrixjoseph/1c737841fdc1aa92743fb1140069caf5.js"></script>

There are two caveats, though:

1. If the body never happens to be read (i.e. neither the `getInputStream` or `getReader` methods get called) then it will never be examined.
2. If the request gets unwrapped (via the [`getRequest`](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequestWrapper.html#getRequest()) method of `ServletRequestWrapper` inherited by my custom HttpServletRequest class) then my overrided method will not be called.


text:
module AccountSubGroupsHelper
end


text:
var beersCount = 0;

var updateBar = function (minutes) {
    var bar = document.getElementById('bar');
    bar.innerHTML = '';

    for (var i = minutes; i--;) {
      var b = document.createElement('span')
      b.style.backgroundImage = "url('" + chrome.extension.getURL('icon.png') + "')";
      b.style.height = b.style.width = b.style.backgroundSize = '16px';
      b.style.display = 'inline-block';
      bar.appendChild(b);
    }
};

document.addEventListener('DOMContentLoaded', function () {
  var d = new Date();
  beersCount = Math.floor(18 * 60 - (d.getMinutes() + d.getHours() * 60 + d.getSeconds() / 60));
  updateBar(beersCount);
});

chrome.runtime.onMessage.addListener(function(minutes) {
  updateBar(minutes);
});


text:
/*
 * XSEC
 *
 * DSIGObject := Defines the container class used by dsig to hold objects
 *				 inside a signture
 *
 * $Id$
 *
 */

#ifndef DSIGOBJECT_INCLUDE
#define DSIGOBJECT_INCLUDE

// XSEC Includes

#include <xsec/framework/XSECDefs.hpp>

XSEC_DECLARE_XERCES_CLASS(DOMElement);
XSEC_DECLARE_XERCES_CLASS(DOMNode);

class XSECEnv;

/**
 * @ingroup pubsig
 */

/**
 * @brief Base class for \<Object\> nodes in a \<Signature\> element.
 *
 * The DSIG spec allows for enveloping signatures, in which the signature holds
 * the information it is signing.  For these types of signatures, the data being
 * signed can be held in an \<Object\> container.
 *
 * This class allows callers to and manipulate Object containers.
 *
 */

class XSEC_EXPORT DSIGObject {

public:

	/** @name Constructors and Destructors */
	//@{

	/**
	 * \brief Construct from an owning signature
	 *
	 * Called by the library when an Object needs to be created from an Object
	 * in a DOM tree.
	 *
	 * @param env The environment that the Object is operating within
	 * @param dom The DOM node that will be loaded
	 */

	DSIGObject(const XSECEnv * env, XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *dom);

	/**
	 * \brief Construct a new object
	 *
	 * Called by the library to create an Object from scratch
	 *
	 * @param env The environment the Object is operating within
	 */

	DSIGObject(const XSECEnv * env);

	/**
	 * \brief Destructor
	 */

	~DSIGObject();

	//@}

	/** @name Library functions */
	//@{

	/**
	 * \brief Load the object from DOM
	 *
	 * Called by the library to load a constructed object
	 */

	void load(void);

	/**
	 * \brief Create a new Object
	 *
	 * Create a new Object from scratch (will generate the DOM)
	 */

	XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *
		createBlankObject(void);

	//@}

	/** @name Get functions */
	//@{

	/**
	 * \brief Get the Id for this object
	 *
	 * @returns the URI attribute string for this object
	 */

	const XMLCh * getId(void) const;

	/**
	 * \brief Returns the MimeType string of this object
	 *
	 * @returns a pointer to the buffer containing the Mime Type string
	 */

	const XMLCh * getMimeType(void) const;

	/**
	 * \brief Returns the Encoding string of this object
	 *
	 * @returns a pointer to the buffer containing the Encoding string
	 */

	const XMLCh * getEncoding(void) const;

	/**
	 * \brief Returns the Element node for this object
	 *
	 * @returns the Element node at the head of this object
	 */

	const XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * getElement(void) const;

	//@}

	/** @name Setter functions */
	//@{

	/**
	 * \brief Set the Id attribute for this Object
	 *
	 * @param id String to use for the Id attribute
	 */

	void setId(const XMLCh * id);

	/**
	 * \brief Set the Id attribute for this Object
	 *
	 * @param type String to use for the MimeType attribute
	 */

	void setMimeType(const XMLCh * type);

	/**
	 * \brief Set the Encoding attribute for this Object
	 *
	 * @param encoding String to use for the Encoding attribute
	 */

	void setEncoding(const XMLCh * encoding);

	/**
	 * \brief Add a child node to the Object
	 *
	 * This is a "ease of use" function to allow users to add a DOM structure
	 * that has been built previously into the Object element
	 */

	void appendChild(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode * child);

	//@}

private:

	const XSECEnv		* mp_env;
	XERCES_CPP_NAMESPACE_QUALIFIER DOMNode
						* mp_objectNode;
	XERCES_CPP_NAMESPACE_QUALIFIER DOMNode
						* mp_idAttr;
	XERCES_CPP_NAMESPACE_QUALIFIER DOMNode
						* mp_mimeTypeAttr;
	XERCES_CPP_NAMESPACE_QUALIFIER DOMNode
						* mp_encodingAttr;

};

#endif /* DSIGOBJECT_INCLUDE */


text:
/*
    This file is part of Repetier-Firmware.

    Repetier-Firmware is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Repetier-Firmware is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Repetier-Firmware.  If not, see <http://www.gnu.org/licenses/>.

    This firmware is a nearly complete rewrite of the sprinter firmware
    by kliment (https://github.com/kliment/Sprinter)
    which based on Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware.
*/

#ifndef _REPETIER_H
#define _REPETIER_H

#include <math.h>
#include <stdint.h>
#define REPETIER_VERSION "0.92.9"

// ##########################################################################################
// ##                                  Debug configuration                                 ##
// ##########################################################################################
// These are run time switchable debug flags
enum debugFlags {DEB_ECHO = 0x1, DEB_INFO = 0x2, DEB_ERROR = 0x4,DEB_DRYRUN = 0x8,
                 DEB_COMMUNICATION = 0x10, DEB_NOMOVES = 0x20, DEB_DEBUG = 0x40
                };

/** Uncomment, to see detailed data for every move. Only for debugging purposes! */
//#define DEBUG_QUEUE_MOVE
/** write infos about path planner changes */
//#define DEBUG_PLANNER
/** Allows M111 to set bit 5 (16) which disables all commands except M111. This can be used
to test your data throughput or search for communication problems. */
#define INCLUDE_DEBUG_COMMUNICATION 1
/** Allows M111 so set bit 6 (32) which disables moves, at the first tried step. In combination
with a dry run, you can test the speed of path computations, which are still performed. */
#define INCLUDE_DEBUG_NO_MOVE 1
/** Writes the free RAM to output, if it is less then at the last test. Should always return
values >500 for safety, since it doesn't catch every function call. Nice to tweak cache
usage or for searching for memory induced errors. Switch it off for production, it costs execution time. */
//#define DEBUG_FREE_MEMORY
//#define DEBUG_ADVANCE
/** If enabled, writes the created generic table to serial port at startup. */
//#define DEBUG_GENERIC
/** If enabled, steps to move and moved steps are compared. */
//#define DEBUG_STEPCOUNT
/** This enables code to make M666 drop an ok, so you get problems with communication. It is to test host robustness. */
//#define DEBUG_COM_ERRORS
/** Adds a menu point in quick settings to write debug informations to the host in case of hangs where the ui still works. */
//#define DEBUG_PRINT
//#define DEBUG_DELTA_OVERFLOW
//#define DEBUG_DELTA_REALPOS
//#define DEBUG_SPLIT
//#define DEBUG_JAM
// Find the longest segment length during a print
//#define DEBUG_SEGMENT_LENGTH
// Find the maximum real jerk during a print
//#define DEBUG_REAL_JERK
// Debug reason for not mounting a sd card
//#define DEBUG_SD_ERROR
// Uncomment the following line to enable debugging. You can better control debugging below the following line
//#define DEBUG

#define CARTESIAN 0
#define XY_GANTRY 1
#define YX_GANTRY 2
#define DELTA 3
#define TUGA 4
#define BIPOD 5
#define XZ_GANTRY 8
#define ZX_GANTRY 9
#define GANTRY_FAKE 10

#define WIZARD_STACK_SIZE 8
#define IGNORE_COORDINATE 999999

// Uncomment if no analyzer is connected
//#define ANALYZER
// Channel->pin assignments
#define ANALYZER_CH0 63 // New move
#define ANALYZER_CH1 40 // Step loop
#define ANALYZER_CH2 53 // X Step
#define ANALYZER_CH3 65 // Y Step
#define ANALYZER_CH4 59 // X Direction
#define ANALYZER_CH5 64 // Y Direction
#define ANALYZER_CH6 58 // xsig
#define ANALYZER_CH7 57 // ysig

#ifdef ANALYZER
#define ANALYZER_ON(a) {WRITE(a,HIGH);}
#define ANALYZER_OFF(a) {WRITE(a,LOW);}
#else
#define ANALYZER_ON(a)
#define ANALYZER_OFF(a)
#endif

#define X_AXIS 0
#define Y_AXIS 1
#define Z_AXIS 2
#define E_AXIS 3
#define VIRTUAL_AXIS 4
// How big an array to hold X_AXIS..<MAX_AXIS>
#define Z_AXIS_ARRAY 3
#define E_AXIS_ARRAY 4
#define VIRTUAL_AXIS_ARRAY 5

#define A_TOWER 0
#define B_TOWER 1
#define C_TOWER 2
#define TOWER_ARRAY 3
#define E_TOWER_ARRAY 4

#define ANALOG_REF_AREF 0
#define ANALOG_REF_AVCC _BV(REFS0)
#define ANALOG_REF_INT_1_1 _BV(REFS1)
#define ANALOG_REF_INT_2_56 _BV(REFS0) | _BV(REFS1)
#define ANALOG_REF ANALOG_REF_AVCC

#define HOME_ORDER_XYZ 1
#define HOME_ORDER_XZY 2
#define HOME_ORDER_YXZ 3
#define HOME_ORDER_YZX 4
#define HOME_ORDER_ZXY 5
#define HOME_ORDER_ZYX 6
#define HOME_ORDER_ZXYTZ 7 // Needs hot hotend for correct homing
#define HOME_ORDER_XYTZ 8 // Needs hot hotend for correct homing

#define NO_CONTROLLER 0
#define UICONFIG_CONTROLLER 1
#define CONTROLLER_SMARTRAMPS 2
#define CONTROLLER_ADAFRUIT 3
#define CONTROLLER_FOLTYN 4
#define CONTROLLER_VIKI 5
#define CONTROLLER_MEGATRONIC 6
#define CONTROLLER_RADDS 7
#define CONTROLLER_PIBOT20X4 8
#define CONTROLLER_PIBOT16X2 9
#define CONTROLLER_GADGETS3D_SHIELD 10
#define CONTROLLER_REPRAPDISCOUNT_GLCD 11
#define CONTROLLER_FELIX 12
#define CONTROLLER_RAMBO 13
#define CONTROLLER_OPENHARDWARE_LCD2004 14
#define CONTROLLER_SANGUINOLOLU_PANELOLU2 15
#define CONTROLLER_GAMEDUINO2 16
#define CONTROLLER_MIREGLI 17
#define CONTROLLER_GATE_3NOVATICA 18
#define CONTROLLER_SPARKLCD 19
#define CONTROLLER_BAM_DICE_DUE 20
#define CONTROLLER_VIKI2 21
#define CONTROLLER_LCD_MP_PHARAOH_DUE 22
#define CONTROLLER_SPARKLCD_ADAPTER 23
#define CONTROLLER_ZONESTAR 24
#define CONTROLLER_FELIX_DUE 405

//direction flags
#define X_DIRPOS 1
#define Y_DIRPOS 2
#define Z_DIRPOS 4
#define E_DIRPOS 8
#define XYZ_DIRPOS 7
//step flags
#define XSTEP 16
#define YSTEP 32
#define ZSTEP 64
#define ESTEP 128
//combo's
#define XYZ_STEP 112
#define XY_STEP 48
#define XYZE_STEP 240
#define E_STEP_DIRPOS 136
#define Y_STEP_DIRPOS 34
#define X_STEP_DIRPOS 17
#define Z_STEP_DIRPOS 68

// add pid control
#define TEMP_PID 1

#define PRINTER_MODE_FFF 0
#define PRINTER_MODE_LASER 1
#define PRINTER_MODE_CNC 2

#define ILLEGAL_Z_PROBE -888

// we can not prevent this as some configurations need a parameter and others not
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-variable"

#include "Configuration.h"

#ifndef SHARED_EXTRUDER_HEATER
#define SHARED_EXTRUDER_HEATER 0
#endif

#ifndef DUAL_X_AXIS
#define DUAL_X_AXIS 0
#endif

#if SHARED_EXTRUDER_HEATER || MIXING_EXTRUDER
#undef EXT1_HEATER_PIN
#undef EXT2_HEATER_PIN
#undef EXT3_HEATER_PIN
#undef EXT4_HEATER_PIN
#undef EXT5_HEATER_PIN
#define EXT1_HEATER_PIN -1
#define EXT2_HEATER_PIN -1
#define EXT3_HEATER_PIN -1
#define EXT4_HEATER_PIN -1
#define EXT5_HEATER_PIN -1
#endif

#ifndef BOARD_FAN_SPEED
#define BOARD_FAN_SPEED
#endif

#ifndef MAX_JERK_DISTANCE
#define MAX_JERK_DISTANCE 0.6
#endif
#define XY_GANTRY 1
#define YX_GANTRY 2
#define DELTA 3
#define TUGA 4
#define BIPOD 5
#define XZ_GANTRY 8
#define ZX_GANTRY 9
#if defined(FAST_COREXYZ) && !(DRIVE_SYSTEM==XY_GANTRY || DRIVE_SYSTEM==YX_GANTRY || DRIVE_SYSTEM==XZ_GANTRY || DRIVE_SYSTEM==ZX_GANTRY || DRIVE_SYSTEM==GANTRY_FAKE)
#undef FAST_COREXYZ
#endif
#ifdef FAST_COREXYZ
#if DELTA_SEGMENTS_PER_SECOND_PRINT < 30
#undef DELTA_SEGMENTS_PER_SECOND_PRINT
#define DELTA_SEGMENTS_PER_SECOND_PRINT 30 // core is linear, no subsegments needed
#endif
#if DELTA_SEGMENTS_PER_SECOND_MOVE < 30
#undef DELTA_SEGMENTS_PER_SECOND_MOVE
#define DELTA_SEGMENTS_PER_SECOND_MOVE 30
#endif
#endif

inline void memcopy2(void *dest,void *source) {
	*((int16_t*)dest) = *((int16_t*)source);
}
inline void memcopy4(void *dest,void *source) {
	*((int32_t*)dest) = *((int32_t*)source);
}

#ifndef JSON_OUTPUT
#define JSON_OUTPUT 0
#endif

#if !defined(ZPROBE_MIN_TEMPERATURE) && defined(ZHOME_MIN_TEMPERATURE)
#define ZPROBE_MIN_TEMPERATURE ZHOME_MIN_TEMPERATURE
#endif

#if FEATURE_Z_PROBE && Z_PROBE_PIN < 0
#error You need to define Z_PROBE_PIN to use z probe!
#endif

#if DISTORTION_CORRECTION
#if !FEATURE_Z_PROBE
#error Distortion correction requires the z probe feature to be enabled and configured!
#endif
#endif

#ifndef MAX_ROOM_TEMPERATURE
#define MAX_ROOM_TEMPERATURE 40
#endif
#ifndef ZHOME_X_POS
#define ZHOME_X_POS IGNORE_COORDINATE
#endif
#ifndef ZHOME_Y_POS
#define ZHOME_Y_POS IGNORE_COORDINATE
#endif

// MS1 MS2 Stepper Driver Micro stepping mode table
#define MICROSTEP1 LOW,LOW
#define MICROSTEP2 HIGH,LOW
#define MICROSTEP4 LOW,HIGH
#define MICROSTEP8 HIGH,HIGH
#if (MOTHERBOARD == 501)
#define MICROSTEP16 LOW,LOW
#else
#define MICROSTEP16 HIGH,HIGH
#endif
#define MICROSTEP32 HIGH,HIGH

#define GCODE_BUFFER_SIZE 1

#ifndef FEATURE_BABYSTEPPING
#define FEATURE_BABYSTEPPING 0
#define BABYSTEP_MULTIPLICATOR 1
#endif

#if !defined(Z_PROBE_REPETITIONS) || Z_PROBE_REPETITIONS < 1
#define Z_PROBE_SWITCHING_DISTANCE 0.5 // Distance to safely untrigger probe
#define Z_PROBE_REPETITIONS 1
#endif

#ifndef MINMAX_HARDWARE_ENDSTOP_Z2
#define MINMAX_HARDWARE_ENDSTOP_Z2 0
#define Z2_MINMAX_PIN -1
#endif

#define SPEED_MIN_MILLIS 400
#define SPEED_MAX_MILLIS 60
#define SPEED_MAGNIFICATION 100.0f

#define SOFTWARE_LEVELING (defined(FEATURE_SOFTWARE_LEVELING) && (DRIVE_SYSTEM==DELTA))
/**  \brief Horizontal distance bridged by the diagonal push rod when the end effector is in the center. It is pretty close to 50% of the push rod length (250 mm).
*/
#if !defined(ROD_RADIUS) && DRIVE_SYSTEM == DELTA
#define ROD_RADIUS (PRINTER_RADIUS-END_EFFECTOR_HORIZONTAL_OFFSET-CARRIAGE_HORIZONTAL_OFFSET)
#endif

#ifndef UI_SPEEDDEPENDENT_POSITIONING
#define UI_SPEEDDEPENDENT_POSITIONING true
#endif

#if DRIVE_SYSTEM==DELTA || DRIVE_SYSTEM==TUGA || DRIVE_SYSTEM==BIPOD || defined(FAST_COREXYZ)
#define NONLINEAR_SYSTEM 1
#else
#define NONLINEAR_SYSTEM 0
#endif

#ifdef FEATURE_Z_PROBE
#define MANUAL_CONTROL 1
#endif

#define GANTRY ( DRIVE_SYSTEM==XY_GANTRY || DRIVE_SYSTEM==YX_GANTRY || DRIVE_SYSTEM==XZ_GANTRY || DRIVE_SYSTEM==ZX_GANTRY || DRIVE_SYSTEM==GANTRY_FAKE)

//Step to split a circle in small Lines
#ifndef MM_PER_ARC_SEGMENT
#define MM_PER_ARC_SEGMENT 1
#define MM_PER_ARC_SEGMENT_BIG 3
#else
#define MM_PER_ARC_SEGMENT_BIG MM_PER_ARC_SEGMENT
#endif
//After this count of steps a new SIN / COS calculation is started to correct the circle interpolation
#define N_ARC_CORRECTION 25

// Test for shared cooler
#if NUM_EXTRUDER == 6 && EXT0_EXTRUDER_COOLER_PIN > -1 && EXT0_EXTRUDER_COOLER_PIN == EXT1_EXTRUDER_COOLER_PIN && EXT2_EXTRUDER_COOLER_PIN == EXT3_EXTRUDER_COOLER_PIN && EXT4_EXTRUDER_COOLER_PIN == EXT5_EXTRUDER_COOLER_PIN && EXT0_EXTRUDER_COOLER_PIN == EXT2_EXTRUDER_COOLER_PIN && EXT0_EXTRUDER_COOLER_PIN == EXT4_EXTRUDER_COOLER_PIN
#define SHARED_COOLER 1
#elif NUM_EXTRUDER == 5 && EXT0_EXTRUDER_COOLER_PIN > -1 && EXT0_EXTRUDER_COOLER_PIN == EXT1_EXTRUDER_COOLER_PIN && EXT2_EXTRUDER_COOLER_PIN == EXT3_EXTRUDER_COOLER_PIN && EXT3_EXTRUDER_COOLER_PIN == EXT5_EXTRUDER_COOLER_PIN && EXT0_EXTRUDER_COOLER_PIN == EXT2_EXTRUDER_COOLER_PIN
#define SHARED_COOLER 1
#elif NUM_EXTRUDER == 4 && EXT0_EXTRUDER_COOLER_PIN > -1 && EXT0_EXTRUDER_COOLER_PIN == EXT1_EXTRUDER_COOLER_PIN && EXT2_EXTRUDER_COOLER_PIN == EXT3_EXTRUDER_COOLER_PIN && EXT0_EXTRUDER_COOLER_PIN == EXT2_EXTRUDER_COOLER_PIN
#define SHARED_COOLER 1
#elif NUM_EXTRUDER == 3 && EXT0_EXTRUDER_COOLER_PIN > -1 && EXT0_EXTRUDER_COOLER_PIN == EXT1_EXTRUDER_COOLER_PIN && EXT2_EXTRUDER_COOLER_PIN == EXT0_EXTRUDER_COOLER_PIN
#define SHARED_COOLER 1
#elif NUM_EXTRUDER == 2 && EXT0_EXTRUDER_COOLER_PIN > -1 && EXT0_EXTRUDER_COOLER_PIN == EXT1_EXTRUDER_COOLER_PIN
#define SHARED_COOLER 1
#else
#define SHARED_COOLER 0
#endif

#ifndef START_STEP_WITH_HIGH
#define START_STEP_WITH_HIGH 1
#endif

#if NUM_EXTRUDER > 0 && EXT0_TEMPSENSOR_TYPE == 101
#define SUPPORT_MAX6675
#endif

#if NUM_EXTRUDER > 0 && EXT0_TEMPSENSOR_TYPE == 102
#define SUPPORT_MAX31855
#endif

// Test for shared coolers between extruders and mainboard
#if EXT0_EXTRUDER_COOLER_PIN > -1 && EXT0_EXTRUDER_COOLER_PIN == FAN_BOARD_PIN
#define SHARED_COOLER_BOARD_EXT 1
#else
#define SHARED_COOLER_BOARD_EXT 0
#endif

#if defined(UI_SERVO_CONTROL) && UI_SERVO_CONTROL > FEATURE_SERVO
#undef UI_SERVO_CONTROL
#define UI_SERVO_CONTROL FEATURE_SERVO
#endif

#if (defined(EXT0_JAM_PIN) && EXT0_JAM_PIN > -1) || (defined(EXT1_JAM_PIN) && EXT1_JAM_PIN > -1) || (defined(EXT2_JAM_PIN) && EXT2_JAM_PIN > -1) || (defined(EXT3_JAM_PIN) && EXT3_JAM_PIN > -1) || (defined(EXT4_JAM_PIN) && EXT4_JAM_PIN > -1) || (defined(EXT5_JAM_PIN) && EXT5_JAM_PIN > -1)
#define EXTRUDER_JAM_CONTROL 1
#else
#define EXTRUDER_JAM_CONTROL 0
#endif
#ifndef JAM_METHOD
#define JAM_METHOD 1
#endif

#if NUM_EXTRUDER > 0 && EXT0_TEMPSENSOR_TYPE < 101
#define EXT0_ANALOG_INPUTS 1
#define EXT0_SENSOR_INDEX 0
#define EXT0_ANALOG_CHANNEL EXT0_TEMPSENSOR_PIN
#define ACCOMMA0 ,
#else
#define ACCOMMA0
#define EXT0_ANALOG_INPUTS 0
#define EXT0_SENSOR_INDEX EXT0_TEMPSENSOR_PIN
#define EXT0_ANALOG_CHANNEL
#endif

#if NUM_EXTRUDER > 1 && EXT1_TEMPSENSOR_TYPE < 101
#define EXT1_ANALOG_INPUTS 1
#define EXT1_SENSOR_INDEX EXT0_ANALOG_INPUTS
#define EXT1_ANALOG_CHANNEL ACCOMMA0 EXT1_TEMPSENSOR_PIN
#define ACCOMMA1 ,
#else
#define ACCOMMA1 ACCOMMA0
#define EXT1_ANALOG_INPUTS 0
#define EXT1_SENSOR_INDEX EXT1_TEMPSENSOR_PIN
#define EXT1_ANALOG_CHANNEL
#endif

#if NUM_EXTRUDER > 2 && EXT2_TEMPSENSOR_TYPE < 101
#define EXT2_ANALOG_INPUTS 1
#define EXT2_SENSOR_INDEX EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS
#define EXT2_ANALOG_CHANNEL ACCOMMA1 EXT2_TEMPSENSOR_PIN
#define ACCOMMA2 ,
#else
#define ACCOMMA2 ACCOMMA1
#define EXT2_ANALOG_INPUTS 0
#define EXT2_SENSOR_INDEX EXT2_TEMPSENSOR_PIN
#define EXT2_ANALOG_CHANNEL
#endif

#if NUM_EXTRUDER > 3 && EXT3_TEMPSENSOR_TYPE < 101
#define EXT3_ANALOG_INPUTS 1
#define EXT3_SENSOR_INDEX EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS+EXT2_ANALOG_INPUTS
#define EXT3_ANALOG_CHANNEL ACCOMMA2 EXT3_TEMPSENSOR_PIN
#define ACCOMMA3 ,
#else
#define ACCOMMA3 ACCOMMA2
#define EXT3_ANALOG_INPUTS 0
#define EXT3_SENSOR_INDEX EXT3_TEMPSENSOR_PIN
#define EXT3_ANALOG_CHANNEL
#endif

#if NUM_EXTRUDER > 4 && EXT4_TEMPSENSOR_TYPE < 101
#define EXT4_ANALOG_INPUTS 1
#define EXT4_SENSOR_INDEX EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS+EXT2_ANALOG_INPUTS+EXT3_ANALOG_INPUTS
#define EXT4_ANALOG_CHANNEL ACCOMMA3 EXT4_TEMPSENSOR_PIN
#define ACCOMMA4 ,
#else
#define ACCOMMA4 ACCOMMA3
#define EXT4_ANALOG_INPUTS 0
#define EXT4_SENSOR_INDEX EXT4_TEMPSENSOR_PIN
#define EXT4_ANALOG_CHANNEL
#endif

#if NUM_EXTRUDER > 5 && EXT5_TEMPSENSOR_TYPE < 101
#define EXT5_ANALOG_INPUTS 1
#define EXT5_SENSOR_INDEX EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS+EXT2_ANALOG_INPUTS+EXT3_ANALOG_INPUTS+EXT4_ANALOG_INPUTS
#define EXT5_ANALOG_CHANNEL ACCOMMA4 EXT5_TEMPSENSOR_PIN
#define ACCOMMA5 ,
#else
#define ACCOMMA5 ACCOMMA4
#define EXT5_ANALOG_INPUTS 0
#define EXT5_SENSOR_INDEX EXT5_TEMPSENSOR_PIN
#define EXT5_ANALOG_CHANNEL
#endif

#if HAVE_HEATED_BED && HEATED_BED_SENSOR_TYPE < 101
#define BED_ANALOG_INPUTS 1
#define BED_SENSOR_INDEX EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS+EXT2_ANALOG_INPUTS+EXT3_ANALOG_INPUTS+EXT4_ANALOG_INPUTS+EXT5_ANALOG_INPUTS
#define BED_ANALOG_CHANNEL ACCOMMA5 HEATED_BED_SENSOR_PIN
#define BED_KOMMA ,
#else
#define BED_ANALOG_INPUTS 0
#define BED_SENSOR_INDEX HEATED_BED_SENSOR_PIN
#define BED_ANALOG_CHANNEL
#define BED_KOMMA ACCOMMA5
#endif

#if FAN_THERMO_THERMISTOR_PIN > -1 && FAN_THERMO_PIN > -1
#define THERMO_ANALOG_INPUTS 1
#define THERMO_ANALOG_INDEX EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS+EXT2_ANALOG_INPUTS+EXT3_ANALOG_INPUTS+EXT4_ANALOG_INPUTS+EXT5_ANALOG_INPUTS+BED_ANALOG_INPUTS
#define THERMO_ANALOG_CHANNEL BED_KOMMA FAN_THERMO_THERMISTOR_PIN
#define THERMO_COMMA ,
#else
#define THERMO_ANALOG_INPUTS 0
#define THERMO_ANALOG_CHANNEL
#define THERMO_COMMA BED_KOMMA
#endif

#if defined(ADC_KEYPAD_PIN) && (ADC_KEYPAD_PIN > -1)
#define KEYPAD_ANALOG_INPUTS 1
#define KEYPAD_ANALOG_INDEX EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS+EXT2_ANALOG_INPUTS+EXT3_ANALOG_INPUTS+EXT4_ANALOG_INPUTS+EXT5_ANALOG_INPUTS+BED_ANALOG_INPUTS+THERMO_ANALOG_INPUTS
#define KEYPAD_ANALOG_CHANNEL THERMO_COMMA ADC_KEYPAD_PIN
#else
#define KEYPAD_ANALOG_INPUTS 0
#define KEYPAD_ANALOG_CHANNEL
#endif

#ifndef DEBUG_FREE_MEMORY
#define DEBUG_MEMORY
#else
#define DEBUG_MEMORY Commands::checkFreeMemory();
#endif

/** \brief number of analog input signals. Normally 1 for each temperature sensor */
#define ANALOG_INPUTS (EXT0_ANALOG_INPUTS+EXT1_ANALOG_INPUTS+EXT2_ANALOG_INPUTS+EXT3_ANALOG_INPUTS+EXT4_ANALOG_INPUTS+EXT5_ANALOG_INPUTS+BED_ANALOG_INPUTS+THERMO_ANALOG_INPUTS+KEYPAD_ANALOG_INPUTS)
#if ANALOG_INPUTS > 0
/** Channels are the MUX-part of ADMUX register */
#define  ANALOG_INPUT_CHANNELS {EXT0_ANALOG_CHANNEL EXT1_ANALOG_CHANNEL EXT2_ANALOG_CHANNEL EXT3_ANALOG_CHANNEL EXT4_ANALOG_CHANNEL EXT5_ANALOG_CHANNEL BED_ANALOG_CHANNEL THERMO_ANALOG_CHANNEL KEYPAD_ANALOG_CHANNEL}
#endif

#define MENU_MODE_SD_MOUNTED 1
#define MENU_MODE_SD_PRINTING 2
#define MENU_MODE_SD_PAUSED 4
#define MENU_MODE_FAN_RUNNING 8
#define MENU_MODE_PRINTING 16
#define MENU_MODE_FULL_PID 32
#define MENU_MODE_DEADTIME 64

#ifndef BENDING_CORRECTION_A
#define BENDING_CORRECTION_A 0
#endif

#ifndef BENDING_CORRECTION_B
#define BENDING_CORRECTION_B 0
#endif

#ifndef BENDING_CORRECTION_C
#define BENDING_CORRECTION_C 0
#endif

#ifndef Z_ACCELERATION_TOP
#define Z_ACCELERATION_TOP 0
#endif

#include "HAL.h"
#include "gcode.h"
#define MAX_VFAT_ENTRIES (2)
/** Total size of the buffer used to store the long filenames */
#define LONG_FILENAME_LENGTH (13*MAX_VFAT_ENTRIES+1)
#define SD_MAX_FOLDER_DEPTH 2

#include "ui.h"
#include "Communication.h"

#if UI_DISPLAY_TYPE != DISPLAY_U8G
#if (defined(USER_KEY1_PIN) && (USER_KEY1_PIN==UI_DISPLAY_D5_PIN || USER_KEY1_PIN==UI_DISPLAY_D6_PIN || USER_KEY1_PIN==UI_DISPLAY_D7_PIN)) || (defined(USER_KEY2_PIN) && (USER_KEY2_PIN==UI_DISPLAY_D5_PIN || USER_KEY2_PIN==UI_DISPLAY_D6_PIN || USER_KEY2_PIN==UI_DISPLAY_D7_PIN)) || (defined(USER_KEY3_PIN) && (USER_KEY3_PIN==UI_DISPLAY_D5_PIN || USER_KEY3_PIN==UI_DISPLAY_D6_PIN || USER_KEY3_PIN==UI_DISPLAY_D7_PIN)) || (defined(USER_KEY4_PIN) && (USER_KEY4_PIN==UI_DISPLAY_D5_PIN || USER_KEY4_PIN==UI_DISPLAY_D6_PIN || USER_KEY4_PIN==UI_DISPLAY_D7_PIN))
#error You cannot use DISPLAY_D5_PIN, DISPLAY_D6_PIN or DISPLAY_D7_PIN for "User Keys" with character LCD display
#endif
#endif

#ifndef SDCARDDETECT
#define SDCARDDETECT       -1
#endif
#ifndef SDSUPPORT
#define SDSUPPORT 0
#endif
#if SDSUPPORT
#include "SdFat.h"
#endif

#if ENABLE_BACKLASH_COMPENSATION && DRIVE_SYSTEM != CARTESIAN
#undef ENABLE_BACKLASH_COMPENSATION
#define ENABLE_BACKLASH_COMPENSATION false
#endif

#define uint uint16_t
#define uint8 uint8_t
#define int8 int8_t
#define uint32 uint32_t
#define int32 int32_t

#undef min
#undef max

class RMath
{
public:
    static inline float min(float a,float b)
    {
        if(a < b) return a;
        return b;
    }
    static inline float max(float a,float b)
    {
        if(a < b) return b;
        return a;
    }
    static inline int32_t min(int32_t a,int32_t b)
    {
        if(a < b) return a;
        return b;
    }
    static inline int32_t min(int32_t a,int32_t b, int32_t c)
    {
        if(a < b) return a < c ? a : c;
        return b<c ? b : c;
    }
    static inline float min(float a,float b, float c)
    {
        if(a < b) return a < c ? a : c;
        return b < c ? b : c;
    }
    static inline int32_t max(int32_t a,int32_t b)
    {
        if(a < b) return b;
        return a;
    }
    static inline int min(int a,int b)
    {
        if(a < b) return a;
        return b;
    }
    static inline uint16_t min(uint16_t a,uint16_t b)
    {
        if(a < b) return a;
        return b;
    }
    static inline int16_t max(int16_t a,int16_t b)
    {
        if(a < b) return b;
        return a;
    }
    static inline uint16_t max(uint16_t a,uint16_t b)
    {
        if(a < b) return b;
        return a;
    }
    static inline unsigned long absLong(long a)
    {
        return a >= 0 ? a : -a;
    }
    static inline int32_t sqr(int32_t a)
    {
        return a*a;
    }
    static inline uint32_t sqr(uint32_t a)
    {
        return a*a;
    }
#ifdef SUPPORT_64_BIT_MATH
    static inline int64_t sqr(int64_t a)
    {
        return a*a;
    }
    static inline uint64_t sqr(uint64_t a)
    {
        return a*a;
    }
#endif

    static inline float sqr(float a)
    {
        return a*a;
    }
};

class RVector3
{
public:
    float x, y, z;
    RVector3(float _x = 0,float _y = 0,float _z = 0):x(_x),y(_y),z(_z) {};
    RVector3(const RVector3 &a):x(a.x),y(a.y),z(a.z) {};

/*    const float &operator[](std::size_t idx) const
    {
        if(idx == 0) return x;
        if(idx == 1) return y;
        return z;
    };

    float &operator[](std::size_t idx)
    {
        switch(idx) {
        case 0: return x;
        case 1: return y;
        case 2: return z;
        }
        return 0;
    };*/

    inline bool operator==(const RVector3 &rhs)
    {
        return x==rhs.x && y==rhs.y && z==rhs.z;
    }
    inline bool operator!=(const RVector3 &rhs)
    {
        return !(*this==rhs);
    }
    inline RVector3& operator=(const RVector3 &rhs)
    {
        if(this!=&rhs)
        {
            x = rhs.x;
            y = rhs.y;
            z = rhs.z;
        }
        return *this;
    }

    inline RVector3& operator+=(const RVector3 &rhs)
    {
        x += rhs.x;
        y += rhs.y;
        z += rhs.z;
        return *this;
    }

    inline RVector3& operator-=(const RVector3 &rhs)
    {
        x -= rhs.x;
        y -= rhs.y;
        z -= rhs.z;
        return *this;
    }
    inline RVector3 operator-() const
    {
        return RVector3(-x,-y,-z);
    }

    inline float length() const
    {
        return sqrt(x * x + y * y + z * z);
    }

    inline float lengthSquared() const
    {
        return (x*x+y*y+z*z);
    }

    inline RVector3 cross(const RVector3 &b) const
    {
        return RVector3(y*b.z-z*b.y,z*b.x-x*b.z,x*b.y-y*b.x);
    }
    inline float scalar(const RVector3 &b) const
    {
        return (x*b.x+y*b.y+z*b.z);
    }
    inline RVector3 scale(float factor) const
    {
        return RVector3(x*factor,y*factor,z*factor);
    }
    inline void scaleIntern(float factor)
    {
        x*=factor;
        y*=factor;
        z*=factor;
    }
    inline void setMinimum(const RVector3 &b)
    {
        x = RMath::min(x,b.x);
        y = RMath::min(y,b.y);
        z = RMath::min(z,b.z);
    }
    inline void setMaximum(const RVector3 &b)
    {
        x = RMath::max(x,b.x);
        y = RMath::max(y,b.y);
        z = RMath::max(z,b.z);
    }
    inline float distance(const RVector3 &b) const
    {
        float dx = b.x-x,dy = b.y-y, dz = b.z-z;
        return (sqrt(dx*dx+dy*dy+dz*dz));
    }
    inline float angle(RVector3 &direction)
    {
        return static_cast<float>(acos(scalar(direction)/(length()*direction.length())));
    }

    inline RVector3 normalize() const
    {
        float len = length();
        if(len != 0) len = static_cast<float>(1.0/len);
        return RVector3(x*len,y*len,z*len);
    }

    inline RVector3 interpolatePosition(const RVector3 &b, float pos) const
    {
        float pos2 = 1.0f - pos;
        return RVector3(x * pos2 + b.x * pos, y * pos2 + b.y * pos, z * pos2 + b.z * pos);
    }

    inline RVector3 interpolateDirection(const RVector3 &b,float pos) const
    {
        //float pos2 = 1.0f - pos;

        float dot = scalar(b);
        if (dot > 0.9995 || dot < -0.9995)
            return interpolatePosition(b,pos); // cases cause trouble, use linear interpolation here

        float theta = acos(dot) * pos; // interpolated position
        float st = sin(theta);
        RVector3 t(b);
        t -= scale(dot);
        float lengthSq = t.lengthSquared();
        float dl = st * ((lengthSq < 0.0001f) ? 1.0f : 1.0f / sqrt(lengthSq));
        t.scaleIntern(dl);
        t += scale(cos(theta));
        return t.normalize();
    }
};
	inline RVector3 operator+(RVector3 lhs, const RVector3& rhs) // first arg by value, second by const ref
	{
		lhs.x += rhs.x;
		lhs.y += rhs.y;
		lhs.z += rhs.z;
		return lhs;
	}

	inline RVector3 operator-(RVector3 lhs, const RVector3& rhs) // first arg by value, second by const ref
	{
		lhs.x -= rhs.x;
		lhs.y -= rhs.y;
		lhs.z -= rhs.z;
		return lhs;
	}

    inline RVector3 operator*(const RVector3 &lhs,float rhs) {
        return lhs.scale(rhs);
    }

    inline RVector3 operator*(float lhs,const RVector3 &rhs) {
        return rhs.scale(lhs);
    }
extern const uint8 osAnalogInputChannels[] PROGMEM;
//extern uint8 osAnalogInputCounter[ANALOG_INPUTS];
//extern uint osAnalogInputBuildup[ANALOG_INPUTS];
//extern uint8 osAnalogInputPos; // Current sampling position
#if ANALOG_INPUTS > 0
extern volatile uint osAnalogInputValues[ANALOG_INPUTS];
#endif
#define PWM_HEATED_BED NUM_EXTRUDER
#define PWM_BOARD_FAN PWM_HEATED_BED+1
#define PWM_FAN1 PWM_BOARD_FAN+1
#define PWM_FAN2 PWM_FAN1+1
#define PWM_FAN_THERMO PWM_FAN2+1
#define NUM_PWM PWM_FAN_THERMO+1
extern uint8_t pwm_pos[NUM_PWM]; // 0-NUM_EXTRUDER = Heater 0-NUM_EXTRUDER of extruder, NUM_EXTRUDER = Heated bed, NUM_EXTRUDER+1 Board fan, NUM_EXTRUDER+2 = Fan
#if USE_ADVANCE
#if ENABLE_QUADRATIC_ADVANCE
extern int maxadv;
#endif
extern int maxadv2;
extern float maxadvspeed;
#endif

#include "Extruder.h"

void manage_inactivity(uint8_t debug);

extern void finishNextSegment();
#if NONLINEAR_SYSTEM
extern uint8_t transformCartesianStepsToDeltaSteps(long cartesianPosSteps[], long deltaPosSteps[]);
#if SOFTWARE_LEVELING
extern void calculatePlane(long factors[], long p1[], long p2[], long p3[]);
extern float calcZOffset(long factors[], long pointX, long pointY);
#endif
#endif
extern void linear_move(long steps_remaining[]);
#ifndef FEATURE_DITTO_PRINTING
#define FEATURE_DITTO_PRINTING false
#endif
#if FEATURE_DITTO_PRINTING && (NUM_EXTRUDER > 4 || NUM_EXTRUDER < 2)
#error Ditto printing requires 2 - 4 extruder.
#endif

extern millis_t previousMillisCmd;
extern millis_t maxInactiveTime;
extern millis_t stepperInactiveTime;

extern void setupTimerInterrupt();
extern void motorCurrentControlInit();
extern void microstepInit();

#include "Printer.h"
#include "motion.h"
extern long baudrate;

#include "HAL.h"

extern unsigned int counterPeriodical;
extern volatile uint8_t executePeriodical;
extern uint8_t counter250ms;
extern void writeMonitor();
#if FEATURE_FAN_CONTROL
extern uint8_t fanKickstart;
#endif
#if FEATURE_FAN2_CONTROL
extern uint8_t fan2Kickstart;
#endif

#if SDSUPPORT
extern char tempLongFilename[LONG_FILENAME_LENGTH+1];
extern char fullName[LONG_FILENAME_LENGTH*SD_MAX_FOLDER_DEPTH+SD_MAX_FOLDER_DEPTH+1];
#define SHORT_FILENAME_LENGTH 14
#include "SdFat.h"

enum LsAction {LS_SerialPrint,LS_Count,LS_GetFilename};
class SDCard
{
public:
    SdFat fat;
    //Sd2Card card; // ~14 Byte
    //SdVolume volume;
    //SdFile root;
    //SdFile dir[SD_MAX_FOLDER_DEPTH+1];
    SdFile file;
#if JSON_OUTPUT
    GCodeFileInfo fileInfo;
#endif
    uint32_t filesize;
    uint32_t sdpos;
    //char fullName[13*SD_MAX_FOLDER_DEPTH+13]; // Fill name
    char *shortname; // Pointer to start of filename itself
    char *pathend; // File to char where pathname in fullname ends
    uint8_t sdmode;  // true if we are printing from sd card, 2 = stop accepting new commands
    bool sdactive;
    //int16_t n;
    bool savetosd;
    SdBaseFile parentFound;

    SDCard();
    void initsd();
    void writeCommand(GCode *code);
    bool selectFile(const char *filename,bool silent=false);
    void mount();
    void unmount();
    void startPrint();
    void pausePrint(bool intern = false);
    void continuePrint(bool intern = false);
    void stopPrint();
    inline void setIndex(uint32_t  newpos)
    {
        if(!sdactive) return;
        sdpos = newpos;
        file.seekSet(sdpos);
    }
    void printStatus();
    void ls();
#if JSON_OUTPUT
    void lsJSON(const char *filename);
    void JSONFileInfo(const char *filename);
    static void printEscapeChars(const char *s);
#endif
    void startWrite(char *filename);
    void deleteFile(char *filename);
    void finishWrite();
    char *createFilename(char *buffer,const dir_t &p);
    void makeDirectory(char *filename);
    bool showFilename(const uint8_t *name);
    void automount();
#ifdef GLENN_DEBUG
    void writeToFile();
#endif
private:
    uint8_t lsRecursive(SdBaseFile *parent,uint8_t level,char *findFilename);
// SdFile *getDirectory(char* name);
};

extern SDCard sd;
#endif

extern volatile int waitRelax; // Delay filament relax at the end of print, could be a simple timeout
extern void updateStepsParameter(PrintLine *p/*,uint8_t caller*/);

#ifdef DEBUG_PRINT
extern int debugWaitLoop;
#endif

#if NONLINEAR_SYSTEM
#define NUM_AXIS 4
#endif

#define STR(s) #s
#define XSTR(s) STR(s)
#include "Commands.h"
#include "Eeprom.h"

#if CPU_ARCH == ARCH_AVR
#define DELAY1MICROSECOND        __asm__("nop\n\t""nop\n\t""nop\n\t""nop\n\t""nop\n\t""nop\n\t")
#define DELAY2MICROSECOND        __asm__("nop\n\t""nop\n\t""nop\n\t""nop\n\t""nop\n\t""nop\n\tnop\n\t""nop\n\t""nop\n\t""nop\n\t""nop\n\t""nop\n\t")
#else
#define DELAY1MICROSECOND     HAL::delayMicroseconds(1);
#define DELAY2MICROSECOND     HAL::delayMicroseconds(2);
#endif

#ifdef FAST_INTEGER_SQRT
#define SQRT(x) ( HAL::integerSqrt(x) )
#else
#define SQRT(x) sqrt(x)
#endif

#include "Drivers.h"

#include "Events.h"
#if defined(CUSTOM_EVENTS)
#include "CustomEvents.h"
#endif

#endif


text:
'use strict';

var utils = require('radiodan-client').utils,
    state = require('../../state'),
    boundVolume = require('../../../../utils/bound-volume');

module.exports = function(radio, opts) {
  var logger;

  opts   = opts        || {};
  logger = opts.logger || utils.logger(__filename);
  state  = opts.state  || state;

  var command = opts,
      commandPromise = utils.promise.reject(new Error("Volume Command not found")),
      absoluteVol;

  if(command.hasOwnProperty('value')) {
    absoluteVol = command.value;

    commandPromise = radio.sendCommands([
      ['setvol', boundVolume(absoluteVol)]
    ]);
  } else if(command.diff) {
    commandPromise = state.invoke(radio, 'player')
                          .then(function(status) {
                            var currentVol = parseInt(status.volume, 10);
                            return radio.sendCommands([['setvol', boundVolume(currentVol, command.diff)]]);
                          }, utils.failedPromiseHandler());
  }

  return commandPromise;
};


text:
@interface STManager : NSObject

+ (instancetype)sharedInstance;
- (void)stringtomizeKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName;
- (void)uploadBaseLanguageStrings;
- (void)uploadTranslationStrings;
- (void)uploadTranslationStringsOverwriting:(BOOL)overwrite;

@property (nonatomic) NSString *endpoint;
@property (nonatomic) BOOL verbose;
@property (nonatomic) NSString *token;
@end


text:
/* tab styles */
div.sheet-tab-content { display: none; }

input.sheet-tab-character:checked ~ div.sheet-tab-character,
input.sheet-tab-ship:checked ~ div.sheet-tab-ship,
{
  display: block;
}

input.sheet-tab
{
  width: 150px;
  height: 20px;
  position: relative;
  left: 6px;
  margin: -1.5px;
  cursor: pointer;
  z-index: 1;
}

input.sheet-tab::before
{
  content: attr(title);

  border: solid 1px #a8a8a8;
  border-bottom-color: black;
  text-align: center;
  display: inline-block;

  background: #bbb;

  width: 150px;
  height: 20px;
  font-size: 18px;
}

input.sheet-tab:checked::before
{
  background: #fff;
  border-bottom-color: #fff;
}

input.sheet-tab:not(:first-child)::before
{
  border-left: none;
}

input.sheet-tab-input:checked::before
{
  background: #dcdcdc;
  background: -moz-linear-gradient(to top, #fcecec, #f8c8c8, #fcecec);
  background: -webkit-linear-gradient(to top, #fcecec, #f8c8c8, #fcecec);
  background: -ms-linear-gradient(to top, #fcecec, #f8c8c8, #fcecec);
  background: -o-linear-gradient(to top, #fcecec, #f8c8c8, #fcecec);
  background: linear-gradient(to top, #fcecec, #f8c8c8, #fcecec);
  border-bottom-color: #fcecec;
}

div.sheet-tab-content
{
  border: 1px solid #a8a8a8;
  border-top-color: #000;
  margin: 2px 0 0 5px;
  padding: 5px;
}

div.sheet-tab-input
{
  background-color: #fcecec;
}

/* character sheet styles */
.charsheet {
  background-color: white;
}
.charsheet .sheet-wrapper h1, .charsheet .sheet-wrapper h3 {
  margin: 0 auto;
  border: 2px solid #000000;
  background-color: #848482;
  text-align: center;
  color: #ffffff;
  font-size: 15pt;
}
.charsheet .sheet-wrapper .sheet-logo {
  width: 100%;
}
.charsheet .sheet-wrapper .sheet-logo img {
  display: block;
  margin: auto;
}
.charsheet .sheet-wrapper .sheet-swn-min {
  font-size: 10px;
}
.charsheet .sheet-wrapper h3 {
  margin-top: 10px;
  margin-bottom: 10px;
  text-align: left;
  font-size: 15px;
}

/* Rows */
.charsheet .sheet-wrapper .sheet-skills .sheet-row,
.charsheet .sheet-wrapper div.sheet-gear-cyberware,
.charsheet .sheet-wrapper .sheet-stats div,
.charsheet .sheet-wrapper .sheet-gear div {
  min-height: 30px;
}
.charsheet .sheet-wrapper .sheet-skills {
  padding-top: 5px;
  padding-bottom: 5px;
  margin-bottom: 5px;
  border: 1px solid #000;
}

.charsheet .sheet-wrapper .sheet-stat-bonus {
  width: 40px;
}

.charsheet .sheet-wrapper .sheet-skills:nth-child(odd) {
  background-color: #d3d3d3;
}

/* Cols */
.sheet-col-whitespace {
  width: 30px;
}
.charsheet .sheet-wrapper .sheet-stats div.sheet-stats-label {
  width: 90px;
}
.charsheet .sheet-wrapper .sheet-stats div.sheet-attribute-label {
  width: 50px;
}
.charsheet .sheet-wrapper .sheet-stats div.sheet-attribute-ext-label {
  width: 100px;
}
.charsheet .sheet-wrapper .sheet-saves .sheet-col {
  width: 150px;
}
.charsheet .sheet-wrapper .sheet-gear div.sheet-gear-name {
  width: 180px;
}
.charsheet .sheet-wrapper .sheet-gear div.sheet-gear-readied {
  width: 55px;
  text-align: center;
}
.charsheet .sheet-wrapper .sheet-gear div.sheet-gear-encumbrance {
  width: 100px;
}
.charsheet .sheet-wrapper div.sheet-psionics-level {
  width: 300px;
}
.charsheet .sheet-wrapper div.sheet-psionics-pp {
  width: 380px;
}
.charsheet .sheet-wrapper div.sheet-psionics-pp .sheet-col {
  width: 50px;
}
.charsheet .sheet-wrapper div.sheet-misc-goal,
.charsheet .sheet-wrapper div.sheet-misc-goal-xp {
  width: 100px;
}

/* Labels */
.charsheet .sheet-wrapper label {
  font-weight: bold;
}
.charsheet .sheet-wrapper .sheet-skills label {
  display: inline;
  width: 175px;
  white-space: nowrap;
}
.charsheet .sheet-wrapper .sheet-skills label.sheet-skill-points-unspent {
  background: #000000;
  color: #ffffff;
}
.sheet-weapons-wrapper label {
    display: inline-block;
    width: 140px;
    padding: 0;
    margin: 0;
    font-weight: bold;
}
.sheet-weapons-wrapper label.sheet-weapons-short {
    width: 95px;
}
.sheet-languages {
  margin-top: 15px;
}

/* Input fields */
.charsheet .sheet-wrapper textarea {
  resize: none;
}
.charsheet .sheet-wrapper .sheet-stats input {
  width: 243px;
}
.charsheet .sheet-wrapper .sheet-stats input.sheet-stats-half {
  width: 75px;
}
.charsheet .sheet-wrapper .sheet-skills input {
  width: 50px;
}
.charsheet .sheet-wrapper input.sheet-skills-custom {
  display: inline;
  width: 150px;
}
.charsheet .sheet-wrapper input.sheet-gear-credits {
  width: 100px;
}
.charsheet .sheet-wrapper .sheet-gear-cyberware input {
  width: 340px;
}
.charsheet .sheet-wrapper .sheet-gear-other textarea {
  width: 330px;
  min-height: 164px;
}
.charsheet .sheet-wrapper .sheet-psionics-discipline input {
  width: 340px;
}
.charsheet .sheet-wrapper .sheet-psionics-discipline-level input {
  width: 50px;
}
.charsheet .sheet-wrapper .sheet-psionics-power input,
.charsheet .sheet-wrapper .sheet-psionics-mastered input {
  width: 340px;
}
.charsheet .sheet-wrapper .sheet-psionics-pp input {
  width: 50px;
}
.charsheet .sheet-wrapper .sheet-misc-goal input {
  width: 400px;
}
.charsheet .sheet-wrapper .sheet-misc-goal-xp input {
  width: 100px;
}
.sheet-weapons-wrapper input {
    width: 140px;
    padding: 0;
    margin: 0;
}
.sheet-textarea-wide {
  width: 97%;
}

/* ship sheet styles */

.sheet-tab-ship .sheet-stats .sheet-col .sheet-stats-ship-min-max .sheet-stats-ship-value {
  width: 50px;
  margin: 0;
}

.sheet-tab-ship .sheet-stats .sheet-col .sheet-stats-ship-min-max .sheet-stats-ship-value input {
  width: 50px;
  margin: 0;
}

.sheet-tab-ship .sheet-stats .sheet-col .sheet-stats-ship-min-max .sheet-stats-label-separator {
  width: 5px;
  margin: 1px;
  padding: 0;
}

.sheet-tab-ship .sheet-ship-repeating-headers {
  width: 100%;
}

.sheet-tab-ship .sheet-ship-weapons .sheet-6colrow {
  width: 100%;
}

.sheet-tab-ship .sheet-ship-repeating-headers .sheet-3colrow div {
  width: 27%;
  margin: 0;
}

.sheet-tab-ship .sheet-ship-repeating-headers .sheet-6colrow div {
  width: 15%;
  margin: 0;
}

.sheet-tab-ship .sheet-ship-repeating-headers .sheet-6colrow input {
  width: 100%;
}

.sheet-tab-ship .sheet-ship-other-notes {
  width: 98%;
}

/* roll templates */

.sheet-rolltemplate-skill .sheet-swn-template-container,
.sheet-rolltemplate-attack .sheet-swn-template-container,
.sheet-rolltemplate-save .sheet-swn-template-container,
.sheet-rolltemplate-morale .sheet-swn-template-container {
    width:100%;
    height: 100px;
    background: url(http://i.imgur.com/YRwSfnk.jpg) top left;
    background-size: 296px 217px;
    color: white;

    -webkit-box-shadow: 10px 10px 25px 0px rgba(0,0,0,0.5);
    -moz-box-shadow: 10px 10px 25px 0px rgba(0,0,0,0.5);
    box-shadow: 10px 10px 25px 0px rgba(0,0,0,0.5);

    border-radius: 5px 5px 5px 5px;
    -moz-border-radius: 5px 5px 5px 5px;
    -webkit-border-radius: 5px 5px 5px 5px;

    border: 0px solid #000000;
}

.sheet-rolltemplate-skill .sheet-swn-template-container .sheet-swn-template-title,
.sheet-rolltemplate-save .sheet-swn-template-container .sheet-swn-template-title,
.sheet-rolltemplate-morale .sheet-swn-template-container .sheet-swn-template-title {
    text-align: center;
    height: 25%;
    font-size: 1.0em;
    vertical-align: middle;
    font-weight: bold;
    padding-top:15px;
}

.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-title {
    text-align: center;
    height: 25%;
    font-size: 1.0em;
    vertical-align: middle;
    font-weight: bold;
    padding-top:5px;
}

.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-title-character {
  font-size: 1.5em;
}

.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-title-action {
  font-size: 0.8em;
}

.sheet-rolltemplate-skill .sheet-swn-template-container .sheet-swn-template-results-row,
.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-results-row,
.sheet-rolltemplate-save .sheet-swn-template-container .sheet-swn-template-results-row,
.sheet-rolltemplate-morale .sheet-swn-template-container .sheet-swn-template-results-row {
    width: 100%;
    height: 75%;
}

.sheet-rolltemplate-skill .sheet-swn,
.sheet-rolltemplate-attack .sheet-swn,
.sheet-rolltemplate-save .sheet-swn,
.sheet-rolltemplate-morale .sheet-swn {
    opacity: 0.9;
    vertical-align: middle;
    padding-top: 10px;
}

.sheet-rolltemplate-skill .sheet-swn-template-container .sheet-swn-template-results-row .sheet-results-element,
.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-results-row .sheet-results-element,
.sheet-rolltemplate-save .sheet-swn-template-container .sheet-swn-template-results-row .sheet-results-element,
.sheet-rolltemplate-morale .sheet-swn-template-container .sheet-swn-template-results-row .sheet-results-element {
    width: 50%;
    font-size: 0.9em;
    text-align: center;
    vertical-align: middle;
    height: 30px;
}

.sheet-rolltemplate-skill .sheet-swn-template-container .sheet-swn-template-results-row .sheet-success,
.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-results-row .sheet-success,
.sheet-rolltemplate-save .sheet-swn-template-container .sheet-swn-template-results-row .sheet-success,
.sheet-rolltemplate-morale .sheet-swn-template-container .sheet-swn-template-results-row .sheet-success {
    background-color: green;
    color: white;
    float: left;
}

.sheet-rolltemplate-skill .sheet-swn-template-container .sheet-swn-template-results-row .sheet-fail,
.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-results-row .sheet-fail,
.sheet-rolltemplate-save .sheet-swn-template-container .sheet-swn-template-results-row .sheet-fail,
.sheet-rolltemplate-morale .sheet-swn-template-container .sheet-swn-template-results-row .sheet-fail {
    background-color: red;
    color: white;
    float: left;
}

.sheet-rolltemplate-attack .sheet-black-text {
    color: black;
}

.sheet-rolltemplate-skill .sheet-swn-template-container .sheet-swn-template-results-row .sheet-roll-output,
.sheet-rolltemplate-attack .sheet-swn-template-container .sheet-swn-template-results-row .sheet-roll-output,
.sheet-rolltemplate-save .sheet-swn-template-container .sheet-swn-template-results-row .sheet-roll-output,
.sheet-rolltemplate-morale .sheet-swn-template-container .sheet-swn-template-results-row .sheet-roll-output {
    background-color: #dcdcdc;
    color: black;
    float: right;
}

.sheet-rolltemplate-skill .sheet-swn-template-container .sheet-swn-template-results-row .sheet-roll-neutral {
    background-color: #dcdcdc;
    color: black;
    float: left;
}


text:
from django.conf.urls import patterns, url
from .views import block_view, unblock_ip_view, unblock_username_view

urlpatterns = patterns(
    '',
    url(r'^blocks/$', block_view,
        name="defender_blocks_view"),
    url(r'^blocks/ip/(?P<ip_address>[a-z0-9-._]+)/unblock$', unblock_ip_view,
        name="defender_unblock_ip_view"),
    url(r'^blocks/username/(?P<username>[a-z0-9-._@]+)/unblock$',
        unblock_username_view,
        name="defender_unblock_username_view"),
)


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>

        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />

            <corners
                android:topLeftRadius="10dp"
                android:topRightRadius="10dp"
                android:bottomLeftRadius="0dp"
                android:bottomRightRadius="0dp"
                />
        </shape>

    </item>
</layer-list>


text:
package org.springframework.transaction.config;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Rob Harrop
 */
@Transactional
public class TransactionalService implements BeanNameAware {

	public void setBeanName(String name) {
		// just for testing :)
	}

}


text:
//
//  MainVC.m
//  XHTabBar-Demo
//
//  Created by xiaohui on 16/2/26.
//  Copyright © 2016年 qiantou. All rights reserved.
//

#import "MainVC.h"
#import "MsgVC.h"
@interface MainVC ()

@end

@implementation MainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"首页";
     self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

    [self initUI];

    // Do any additional setup after loading the view.
}
-(void)initUI
{
    UIButton *pushBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    pushBtn.backgroundColor = [UIColor orangeColor];
    [pushBtn setTitle:@"Push" forState:UIControlStateNormal];
    pushBtn.frame = CGRectMake(self.view.frame.size.width/2.0-40.0, self.view.frame.size.height/2.0-20.0, 80.0, 40.0);
    [pushBtn addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pushBtn];
}
-(void)push
{
    MsgVC *VC = [[MsgVC alloc] init];
    VC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
from __future__ import absolute_import

import six

from base64 import b64encode
from django.core.urlresolvers import reverse
from django.core import mail
from mock import patch
from exam import fixture
from pprint import pprint

from sentry.constants import RESERVED_ORGANIZATION_SLUGS
from sentry.models import (
    AuditLogEntry,
    Authenticator,
    DeletedOrganization,
    Organization,
    OrganizationAvatar,
    OrganizationOption,
    OrganizationStatus,
    TotpInterface)
from sentry.signals import project_created
from sentry.testutils import APITestCase, TwoFactorAPITestCase

class OrganizationDetailsTest(APITestCase):
    def test_simple(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.get(url, format='json')
        assert response.data['onboardingTasks'] == []
        assert response.status_code == 200, response.content
        assert response.data['id'] == six.text_type(org.id)

        for i in range(5):
            self.create_project(organization=org)

        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        # TODO(dcramer): we need to pare this down -- lots of duplicate queries
        # for membership data
        with self.assertNumQueries(28, using='default'):
            from django.db import connections
            response = self.client.get(url, format='json')
            pprint(connections['default'].queries)
        assert len(response.data['projects']) == 5

    def test_onboarding_tasks(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.get(url, format='json')
        assert response.data['onboardingTasks'] == []
        assert response.status_code == 200, response.content
        assert response.data['id'] == six.text_type(org.id)

        project = self.create_project(organization=org)
        project_created.send(project=project, user=self.user, sender=type(project))

        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.get(url, format='json')
        assert len(response.data['onboardingTasks']) == 1
        assert response.data['onboardingTasks'][0]['task'] == 1

class OrganizationUpdateTest(APITestCase):
    def test_simple(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'name': 'hello world',
                'slug': 'foobar',
            }
        )
        assert response.status_code == 200, response.content
        org = Organization.objects.get(id=org.id)
        assert org.name == 'hello world'
        assert org.slug == 'foobar'

    def test_dupe_slug(self):
        org = self.create_organization(owner=self.user)
        org2 = self.create_organization(owner=self.user, slug='baz')
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'slug': org2.slug,
            }
        )
        assert response.status_code == 400, response.content

    def test_short_slug(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'slug': 'a',
            }
        )
        assert response.status_code == 400, response.content

    def test_reserved_slug(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'slug': list(RESERVED_ORGANIZATION_SLUGS)[0],
            }
        )
        assert response.status_code == 400, response.content

    def test_upload_avatar(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url,
            data={
                'avatarType': 'upload',
                'avatar': b64encode(self.load_fixture('avatar.jpg')),
            },
            format='json'
        )

        avatar = OrganizationAvatar.objects.get(
            organization=org,
        )
        assert response.status_code == 200, response.content
        assert avatar.get_avatar_type_display() == 'upload'
        assert avatar.file

    def test_various_options(self):
        org = self.create_organization(owner=self.user)
        initial = org.get_audit_log_data()

        # clear logs
        for log in AuditLogEntry.objects.filter(organization=org):
            log.delete()

        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )

        data = {
            'openMembership': False,
            'isEarlyAdopter': True,
            'allowSharedIssues': False,
            'enhancedPrivacy': True,
            'dataScrubber': True,
            'dataScrubberDefaults': True,
            'sensitiveFields': [u'password'],
            'safeFields': [u'email'],
            'storeCrashReports': True,
            'scrubIPAddresses': True,
            'scrapeJavaScript': False,
            'defaultRole': 'owner',
            'require2FA': True
        }

        # needed to set require2FA
        interface = TotpInterface()
        interface.enroll(self.user)
        assert Authenticator.objects.user_has_2fa(self.user)

        response = self.client.put(url, data=data)
        assert response.status_code == 200, response.content
        org = Organization.objects.get(id=org.id)
        assert initial != org.get_audit_log_data()

        assert org.flags.early_adopter
        assert not org.flags.allow_joinleave
        assert org.flags.disable_shared_issues
        assert org.flags.enhanced_privacy
        assert org.flags.require_2fa
        assert org.default_role == 'owner'

        options = {o.key: o.value for o in OrganizationOption.objects.filter(
            organization=org,
        )}

        assert options.get('sentry:require_scrub_defaults')
        assert options.get('sentry:require_scrub_data')
        assert options.get('sentry:require_scrub_ip_address')
        assert options.get('sentry:sensitive_fields') == ['password']
        assert options.get('sentry:safe_fields') == ['email']
        assert options.get('sentry:store_crash_reports') is True
        assert options.get('sentry:scrape_javascript') is False

        # log created
        log = AuditLogEntry.objects.get(organization=org)
        assert log.get_event_display() == 'org.edit'
        # org fields & flags
        assert 'to {}'.format(data['defaultRole']) in log.data['default_role']
        assert 'to {}'.format(data['openMembership']) in log.data['allow_joinleave']
        assert 'to {}'.format(data['isEarlyAdopter']) in log.data['early_adopter']
        assert 'to {}'.format(data['enhancedPrivacy']) in log.data['enhanced_privacy']
        assert 'to {}'.format(not data['allowSharedIssues']) in log.data['disable_shared_issues']
        assert 'to {}'.format(data['require2FA']) in log.data['require_2fa']
        # org options
        assert 'to {}'.format(data['dataScrubber']) in log.data['dataScrubber']
        assert 'to {}'.format(data['dataScrubberDefaults']) in log.data['dataScrubberDefaults']
        assert 'to {}'.format(data['sensitiveFields']) in log.data['sensitiveFields']
        assert 'to {}'.format(data['safeFields']) in log.data['safeFields']
        assert 'to {}'.format(data['scrubIPAddresses']) in log.data['scrubIPAddresses']

    def test_setting_legacy_rate_limits(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url,
            data={
                'accountRateLimit': 1000,
            }
        )
        assert response.status_code == 400, response.content

        response = self.client.put(
            url,
            data={
                'projectRateLimit': 1000,
            }
        )
        assert response.status_code == 400, response.content

        OrganizationOption.objects.set_value(org, 'sentry:project-rate-limit', 1)

        response = self.client.put(
            url,
            data={
                'projectRateLimit': 100,
            }
        )
        assert response.status_code == 200, response.content

        assert OrganizationOption.objects.get_value(org, 'sentry:project-rate-limit') == 100

        response = self.client.put(
            url,
            data={
                'accountRateLimit': 50,
            }
        )
        assert response.status_code == 200, response.content

        assert OrganizationOption.objects.get_value(org, 'sentry:account-rate-limit') == 50

    def test_safe_fields_as_string_regression(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'safeFields': 'email',
            }
        )
        assert response.status_code == 400, (response.status_code, response.content)
        org = Organization.objects.get(id=org.id)

        options = {o.key: o.value for o in OrganizationOption.objects.filter(
            organization=org,
        )}

        assert not options.get('sentry:safe_fields')

    def test_manager_cannot_set_default_role(self):
        org = self.create_organization(owner=self.user)
        user = self.create_user('baz@example.com')
        self.create_member(organization=org, user=user, role='manager')
        self.login_as(user=user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'defaultRole': 'owner',
            }
        )
        assert response.status_code == 200, response.content
        org = Organization.objects.get(id=org.id)

        assert org.default_role == 'member'

    def test_empty_string_in_array_safe_fields(self):
        org = self.create_organization(owner=self.user)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'safeFields': [''],
            }
        )
        assert response.status_code == 400, (response.status_code, response.content)
        org = Organization.objects.get(id=org.id)

        options = {o.key: o.value for o in OrganizationOption.objects.filter(
            organization=org,
        )}

        assert not options.get('sentry:safe_fields')

    def test_empty_string_in_array_sensitive_fields(self):
        org = self.create_organization(owner=self.user)
        OrganizationOption.objects.set_value(
            org,
            'sentry:sensitive_fields',
            ['foobar'],
        )
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'sensitiveFields': [''],
            }
        )
        assert response.status_code == 400, (response.status_code, response.content)
        org = Organization.objects.get(id=org.id)

        options = {o.key: o.value for o in OrganizationOption.objects.filter(
            organization=org,
        )}

        assert options.get('sentry:sensitive_fields') == ['foobar']

    def test_empty_sensitive_fields(self):
        org = self.create_organization(owner=self.user)
        OrganizationOption.objects.set_value(
            org,
            'sentry:sensitive_fields',
            ['foobar'],
        )
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'sensitiveFields': [],
            }
        )
        assert response.status_code == 200, (response.status_code, response.content)
        org = Organization.objects.get(id=org.id)

        options = {o.key: o.value for o in OrganizationOption.objects.filter(
            organization=org,
        )}

        assert not options.get('sentry:sensitive_fields')

    def test_cancel_delete(self):
        org = self.create_organization(owner=self.user, status=OrganizationStatus.PENDING_DELETION)
        self.login_as(user=self.user)
        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.put(
            url, data={
                'cancelDeletion': True,
            }
        )
        assert response.status_code == 200, (response.status_code, response.content)
        org = Organization.objects.get(id=org.id)
        assert org.status == OrganizationStatus.VISIBLE

class OrganizationDeleteTest(APITestCase):
    @patch('sentry.api.endpoints.organization_details.uuid4')
    @patch('sentry.api.endpoints.organization_details.delete_organization')
    def test_can_remove_as_owner(self, mock_delete_organization, mock_uuid4):
        class uuid(object):
            hex = 'abc123'

        mock_uuid4.return_value = uuid

        org = self.create_organization()

        user = self.create_user(email='foo@example.com', is_superuser=False)

        self.create_member(
            organization=org,
            user=user,
            role='owner',
        )

        self.login_as(user)

        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )

        owners = org.get_owners()
        assert len(owners) > 0

        with self.tasks():
            response = self.client.delete(url)

        org = Organization.objects.get(id=org.id)

        assert response.status_code == 202, response.data

        assert org.status == OrganizationStatus.PENDING_DELETION

        deleted_org = DeletedOrganization.objects.get(slug=org.slug)
        self.assert_valid_deleted_log(deleted_org, org)

        mock_delete_organization.apply_async.assert_called_once_with(
            kwargs={
                'object_id': org.id,
                'transaction_id': 'abc123',
                'actor_id': user.id,
            },
            countdown=86400,
        )

        # Make sure we've emailed all owners
        assert len(mail.outbox) == len(owners)
        owner_emails = set(o.email for o in owners)
        for msg in mail.outbox:
            assert 'Deletion' in msg.subject
            assert len(msg.to) == 1
            owner_emails.remove(msg.to[0])
        # No owners should be remaining
        assert len(owner_emails) == 0

    def test_cannot_remove_as_admin(self):
        org = self.create_organization(owner=self.user)

        user = self.create_user(email='foo@example.com', is_superuser=False)

        self.create_member(
            organization=org,
            user=user,
            role='admin',
        )

        self.login_as(user=user)

        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )
        response = self.client.delete(url)

        assert response.status_code == 403

    def test_cannot_remove_default(self):
        Organization.objects.all().delete()

        org = self.create_organization(owner=self.user)

        self.login_as(self.user)

        url = reverse(
            'sentry-api-0-organization-details', kwargs={
                'organization_slug': org.slug,
            }
        )

        with self.settings(SENTRY_SINGLE_ORGANIZATION=True):
            response = self.client.delete(url)

        assert response.status_code == 400, response.data

class OrganizationSettings2FATest(TwoFactorAPITestCase):
    def setUp(self):
        self.org_2fa = self.create_organization(owner=self.create_user())
        self.enable_org_2fa(self.org_2fa)
        self.no_2fa_user = self.create_user()
        self.create_member(organization=self.org_2fa, user=self.no_2fa_user, role="member")

        # 2FA not enforced org and members
        self.owner = self.create_user()
        self.organization = self.create_organization(owner=self.owner)
        self.manager = self.create_user()
        self.create_member(organization=self.organization, user=self.manager, role="manager")
        self.org_user = self.create_user()
        self.create_member(organization=self.organization, user=self.org_user, role="member")

    @fixture
    def path(self):
        return reverse('sentry-api-0-organization-details', kwargs={
            'organization_slug': self.org_2fa.slug,
        })

    def assert_2fa_email_equal(self, outbox, expected):
        assert len(outbox) == len(expected)
        assert sorted([email.to[0] for email in outbox]) == sorted(expected)

    def assert_can_access_org_details(self, url):
        response = self.client.get(url)
        assert response.status_code == 200

    def assert_cannot_access_org_details(self, url):
        response = self.client.get(url)
        assert response.status_code == 401

    def test_cannot_enforce_2fa_without_2fa_enabled(self):
        assert not Authenticator.objects.user_has_2fa(self.owner)
        self.assert_cannot_enable_org_2fa(self.organization, self.owner, 400)

    def test_owner_can_set_2fa_single_member(self):
        org = self.create_organization(owner=self.owner)
        TotpInterface().enroll(self.owner)
        with self.options({'system.url-prefix': 'http://example.com'}), self.tasks():
            self.assert_can_enable_org_2fa(org, self.owner)
        assert len(mail.outbox) == 0

    def test_manager_can_set_2fa(self):
        org = self.create_organization(owner=self.owner)
        self.create_member(organization=org, user=self.manager, role="manager")

        self.assert_cannot_enable_org_2fa(org, self.manager, 400)
        TotpInterface().enroll(self.manager)
        with self.options({'system.url-prefix': 'http://example.com'}), self.tasks():
            self.assert_can_enable_org_2fa(org, self.manager)
        self.assert_2fa_email_equal(mail.outbox, [self.owner.email])

    def test_members_cannot_set_2fa(self):
        self.assert_cannot_enable_org_2fa(self.organization, self.org_user, 403)
        TotpInterface().enroll(self.org_user)
        self.assert_cannot_enable_org_2fa(self.organization, self.org_user, 403)

    def test_owner_can_set_org_2fa(self):
        org = self.create_organization(owner=self.owner)
        TotpInterface().enroll(self.owner)
        user_emails_without_2fa = self.add_2fa_users_to_org(org)

        with self.options({'system.url-prefix': 'http://example.com'}), self.tasks():
            self.assert_can_enable_org_2fa(org, self.owner)
        self.assert_2fa_email_equal(mail.outbox, user_emails_without_2fa)

        mail.outbox = []
        with self.options({'system.url-prefix': 'http://example.com'}), self.tasks():
            response = self.api_disable_org_2fa(org, self.owner)

        assert response.status_code == 200
        assert not Organization.objects.get(id=org.id).flags.require_2fa
        assert len(mail.outbox) == 0

    def test_preexisting_members_must_enable_2fa(self):
        self.login_as(self.no_2fa_user)
        self.assert_cannot_access_org_details(self.path)

        TotpInterface().enroll(self.no_2fa_user)
        self.assert_can_access_org_details(self.path)

    def test_new_member_must_enable_2fa(self):
        new_user = self.create_user()
        self.create_member(organization=self.org_2fa, user=new_user, role="member")
        self.login_as(new_user)
        self.assert_cannot_access_org_details(self.path)

        TotpInterface().enroll(new_user)
        self.assert_can_access_org_details(self.path)

    def test_member_disable_all_2fa_blocked(self):
        TotpInterface().enroll(self.no_2fa_user)
        self.login_as(self.no_2fa_user)

        self.assert_can_access_org_details(self.path)

        Authenticator.objects.get(user=self.no_2fa_user).delete()
        self.assert_cannot_access_org_details(self.path)


text:
var internals = {};

// Plugin registration

exports.register = function (plugin, options, next) {

    if (options.route) {
        plugin.register(require('../../--test1'), options, next);
    }
    else {
        plugin.register(require('../../--test1'), next);
    }
};

exports.register.attributes = {
    pkg: require('../package.json')
};


text:
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="app.news.controller.api.post" class="AppBundle\Controller\Api\PostController">
            <argument type="service" id="sonata.news.manager.post" />
            <argument type="service" id="sonata.news.manager.comment" />
            <argument type="service" id="sonata.news.mailer" />
            <argument type="service" id="form.factory" />
            <argument type="service" id="sonata.formatter.pool" />

            <argument type="service" id="sonata.classification.manager.collection" />
        </service>

         <service id="app.page.controller.api.page" class="AppBundle\Controller\Api\PageController">
            <argument type="service" id="sonata.page.manager.site" />
            <argument type="service" id="sonata.page.manager.page" />
            <argument type="service" id="sonata.page.manager.block" />
            <argument type="service" id="form.factory" />
            <argument type="service" id="sonata.notification.backend" />
        </service>
    </services>

</container>


text:
import static org.junit.Assert.assertNotNull;

import java.io.IOException;
import java.security.GeneralSecurityException;
import org.junit.Test;

public class TestCreateFolder {
  @Test
  public void createFolder() throws IOException, GeneralSecurityException {
    String id = CreateFolder.createFolder();
    assertNotNull(id);
  }
}


text:
namespace MonoUI.Core.Views
{
    public struct ExpansionOptions
    {
        public short Value { get; private set; }
        public static ExpansionOptions Fixed = new ExpansionOptions(0);
        public static ExpansionOptions Expand = new ExpansionOptions(1);
        public static ExpansionOptions WithLevel(byte level) { return new ExpansionOptions((short)(level + 1)); }

        private ExpansionOptions(short value)
            : this()
        {
            Value = value;
        }

        public override string ToString()
        {
            if (Equals(this, Fixed)) return "fixed";
            if (Equals(this, Expand)) return "expand";
            return Value.ToString();
        }

        public bool Equals(ExpansionOptions other)
        {
            return Value == other.Value;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            return obj is ExpansionOptions && Equals((ExpansionOptions)obj);
        }

        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }

        public static bool operator ==(ExpansionOptions p1,ExpansionOptions p2)
        {
            return p1.Value == p2.Value;
        }

        public static bool operator !=(ExpansionOptions p1, ExpansionOptions p2)
        {
            return !(p1 == p2);
        }
    }
}


text:
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/pagemap.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/inet.h>
#include <linux/namei.h>
#include <linux/idr.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <net/9p/9p.h>
#include <net/9p/client.h>

#include "v9fs.h"
#include "v9fs_vfs.h"
#include "fid.h"

/**
 * v9fs_dentry_delete - called when dentry refcount equals 0
 * @dentry:  dentry in question
 *
 * By returning 1 here we should remove cacheing of unused
 * dentry components.
 *
 */

static int v9fs_dentry_delete(const struct dentry *dentry)
{
	p9_debug(P9_DEBUG_VFS, " dentry: %s (%p)\n",
		 dentry->d_name.name, dentry);

	return 1;
}

/**
 * v9fs_cached_dentry_delete - called when dentry refcount equals 0
 * @dentry:  dentry in question
 *
 */
static int v9fs_cached_dentry_delete(const struct dentry *dentry)
{
	p9_debug(P9_DEBUG_VFS, " dentry: %s (%p)\n",
		 dentry->d_name.name, dentry);

	/* Don't cache negative dentries */
	if (!dentry->d_inode)
		return 1;
	return 0;
}

/**
 * v9fs_dentry_release - called when dentry is going to be freed
 * @dentry:  dentry that is being release
 *
 */

static void v9fs_dentry_release(struct dentry *dentry)
{
	struct v9fs_dentry *dent;
	struct p9_fid *temp, *current_fid;

	p9_debug(P9_DEBUG_VFS, " dentry: %s (%p)\n",
		 dentry->d_name.name, dentry);
	dent = dentry->d_fsdata;
	if (dent) {
		list_for_each_entry_safe(current_fid, temp, &dent->fidlist,
									dlist) {
			p9_client_clunk(current_fid);
		}

		kfree(dent);
		dentry->d_fsdata = NULL;
	}
}

static int v9fs_lookup_revalidate(struct dentry *dentry, struct nameidata *nd)
{
	struct p9_fid *fid;
	struct inode *inode;
	struct v9fs_inode *v9inode;

	if (nd->flags & LOOKUP_RCU)
		return -ECHILD;

	inode = dentry->d_inode;
	if (!inode)
		goto out_valid;

	v9inode = V9FS_I(inode);
	if (v9inode->cache_validity & V9FS_INO_INVALID_ATTR) {
		int retval;
		struct v9fs_session_info *v9ses;
		fid = v9fs_fid_lookup(dentry);
		if (IS_ERR(fid))
			return PTR_ERR(fid);

		v9ses = v9fs_inode2v9ses(inode);
		if (v9fs_proto_dotl(v9ses))
			retval = v9fs_refresh_inode_dotl(fid, inode);
		else
			retval = v9fs_refresh_inode(fid, inode);
		if (retval == -ENOENT)
			return 0;
		if (retval < 0)
			return retval;
	}
out_valid:
	return 1;
}

const struct dentry_operations v9fs_cached_dentry_operations = {
	.d_revalidate = v9fs_lookup_revalidate,
	.d_delete = v9fs_cached_dentry_delete,
	.d_release = v9fs_dentry_release,
};

const struct dentry_operations v9fs_dentry_operations = {
	.d_delete = v9fs_dentry_delete,
	.d_release = v9fs_dentry_release,
};


text:
namespace {

template<typename T>
int VectorToBitArray(const std::vector<T>& vec) {
  int bits = 0;
  for (const T& item : vec)
    bits |= item;
  return bits;
}

}  // namespace

namespace mate {

template<>
struct Converter<base::char16> {
  static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val,
                     base::char16* out) {
    base::string16 code = base::UTF8ToUTF16(V8ToString(val));
    if (code.length() != 1)
      return false;
    *out = code[0];
    return true;
  }
};

template<>
struct Converter<blink::WebInputEvent::Type> {
  static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val,
                     blink::WebInputEvent::Type* out) {
    std::string type = base::ToLowerASCII(V8ToString(val));
    if (type == "mousedown")
      *out = blink::WebInputEvent::kMouseDown;
    else if (type == "mouseup")
      *out = blink::WebInputEvent::kMouseUp;
    else if (type == "mousemove")
      *out = blink::WebInputEvent::kMouseMove;
    else if (type == "mouseenter")
      *out = blink::WebInputEvent::kMouseEnter;
    else if (type == "mouseleave")
      *out = blink::WebInputEvent::kMouseLeave;
    else if (type == "contextmenu")
      *out = blink::WebInputEvent::kContextMenu;
    else if (type == "mousewheel")
      *out = blink::WebInputEvent::kMouseWheel;
    else if (type == "keydown")
      *out = blink::WebInputEvent::kRawKeyDown;
    else if (type == "keyup")
      *out = blink::WebInputEvent::kKeyUp;
    else if (type == "char")
      *out = blink::WebInputEvent::kChar;
    else if (type == "touchstart")
      *out = blink::WebInputEvent::kTouchStart;
    else if (type == "touchmove")
      *out = blink::WebInputEvent::kTouchMove;
    else if (type == "touchend")
      *out = blink::WebInputEvent::kTouchEnd;
    else if (type == "touchcancel")
      *out = blink::WebInputEvent::kTouchCancel;
    return true;
  }
};

template<>
struct Converter<blink::WebMouseEvent::Button> {
  static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val,
                     blink::WebMouseEvent::Button* out) {
    std::string button = base::ToLowerASCII(V8ToString(val));
    if (button == "left")
      *out = blink::WebMouseEvent::Button::kLeft;
    else if (button == "middle")
      *out = blink::WebMouseEvent::Button::kMiddle;
    else if (button == "right")
      *out = blink::WebMouseEvent::Button::kRight;
    else
      return false;
    return true;
  }
};

template<>
struct Converter<blink::WebInputEvent::Modifiers> {
  static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val,
                     blink::WebInputEvent::Modifiers* out) {
    std::string modifier = base::ToLowerASCII(V8ToString(val));
    if (modifier == "shift")
      *out = blink::WebInputEvent::kShiftKey;
    else if (modifier == "control" || modifier == "ctrl")
      *out = blink::WebInputEvent::kControlKey;
    else if (modifier == "alt")
      *out = blink::WebInputEvent::kAltKey;
    else if (modifier == "meta" || modifier == "command" || modifier == "cmd")
      *out = blink::WebInputEvent::kMetaKey;
    else if (modifier == "iskeypad")
      *out = blink::WebInputEvent::kIsKeyPad;
    else if (modifier == "isautorepeat")
      *out = blink::WebInputEvent::kIsAutoRepeat;
    else if (modifier == "leftbuttondown")
      *out = blink::WebInputEvent::kLeftButtonDown;
    else if (modifier == "middlebuttondown")
      *out = blink::WebInputEvent::kMiddleButtonDown;
    else if (modifier == "rightbuttondown")
      *out = blink::WebInputEvent::kRightButtonDown;
    else if (modifier == "capslock")
      *out = blink::WebInputEvent::kCapsLockOn;
    else if (modifier == "numlock")
      *out = blink::WebInputEvent::kNumLockOn;
    else if (modifier == "left")
      *out = blink::WebInputEvent::kIsLeft;
    else if (modifier == "right")
      *out = blink::WebInputEvent::kIsRight;
    return true;
  }
};

blink::WebInputEvent::Type GetWebInputEventType(v8::Isolate* isolate,
    v8::Local<v8::Value> val) {
  blink::WebInputEvent::Type type = blink::WebInputEvent::kUndefined;
  mate::Dictionary dict;
  ConvertFromV8(isolate, val, &dict) && dict.Get("type", &type);
  return type;
}

bool Converter<blink::WebInputEvent>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val,
    blink::WebInputEvent* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  blink::WebInputEvent::Type type;
  if (!dict.Get("type", &type))
    return false;
  out->SetType(type);
  std::vector<blink::WebInputEvent::Modifiers> modifiers;
  if (dict.Get("modifiers", &modifiers))
    out->SetModifiers(VectorToBitArray(modifiers));
  out->SetTimeStampSeconds(base::Time::Now().ToDoubleT());
  return true;
}

bool Converter<blink::WebKeyboardEvent>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val,
    blink::WebKeyboardEvent* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  if (!ConvertFromV8(isolate, val, static_cast<blink::WebInputEvent*>(out)))
    return false;

  std::string str;
  if (!dict.Get("keyCode", &str))
    return false;

  bool shifted = false;
  ui::KeyboardCode keyCode = atom::KeyboardCodeFromStr(str, &shifted);
  out->windows_key_code = keyCode;
  if (shifted)
    out->SetModifiers(out->GetModifiers() | blink::WebInputEvent::kShiftKey);

  ui::DomCode domCode = ui::UsLayoutKeyboardCodeToDomCode(keyCode);
  out->dom_code = static_cast<int>(domCode);

  ui::DomKey domKey;
  ui::KeyboardCode dummy_code;
  int flags = atom::WebEventModifiersToEventFlags(out->GetModifiers());
  if (ui::DomCodeToUsLayoutDomKey(domCode, flags, &domKey, &dummy_code))
    out->dom_key = static_cast<int>(domKey);

  if ((out->GetType() == blink::WebInputEvent::kChar ||
       out->GetType() == blink::WebInputEvent::kRawKeyDown)) {
    // Make sure to not read beyond the buffer in case some bad code doesn't
    // NULL-terminate it (this is called from plugins).
    size_t text_length_cap = blink::WebKeyboardEvent::kTextLengthCap;
    base::string16 text16 = base::UTF8ToUTF16(str);

    memset(out->text, 0, text_length_cap);
    memset(out->unmodified_text, 0, text_length_cap);
    for (size_t i = 0; i < std::min(text_length_cap, text16.size()); ++i) {
      out->text[i] = text16[i];
      out->unmodified_text[i] = text16[i];
    }
  }
  return true;
}

bool Converter<content::NativeWebKeyboardEvent>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val,
    content::NativeWebKeyboardEvent* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  if (!ConvertFromV8(isolate, val, static_cast<blink::WebKeyboardEvent*>(out)))
    return false;
  dict.Get("skipInBrowser", &out->skip_in_browser);
  return true;
}

v8::Local<v8::Value> Converter<content::NativeWebKeyboardEvent>::ToV8(
    v8::Isolate* isolate, const content::NativeWebKeyboardEvent& in) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);

  if (in.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
    dict.Set("type", "keyDown");
  else if (in.GetType() == blink::WebInputEvent::Type::kKeyUp)
    dict.Set("type", "keyUp");
  dict.Set("key", ui::KeycodeConverter::DomKeyToKeyString(in.dom_key));
  dict.Set("code", ui::KeycodeConverter::DomCodeToCodeString(
    static_cast<ui::DomCode>(in.dom_code)));

  using Modifiers = blink::WebInputEvent::Modifiers;
  dict.Set("isAutoRepeat", (in.GetModifiers() & Modifiers::kIsAutoRepeat) != 0);
  dict.Set("shift", (in.GetModifiers() & Modifiers::kShiftKey) != 0);
  dict.Set("control", (in.GetModifiers() & Modifiers::kControlKey) != 0);
  dict.Set("alt", (in.GetModifiers() & Modifiers::kAltKey) != 0);
  dict.Set("meta", (in.GetModifiers() & Modifiers::kMetaKey) != 0);

  return dict.GetHandle();
}

bool Converter<blink::WebMouseEvent>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val, blink::WebMouseEvent* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  if (!ConvertFromV8(isolate, val, static_cast<blink::WebInputEvent*>(out)))
    return false;

  float x = 0.f;
  float y = 0.f;
  if (!dict.Get("x", &x) || !dict.Get("y", &y))
    return false;
  out->SetPositionInWidget(x, y);

  if (!dict.Get("button", &out->button))
    out->button = blink::WebMouseEvent::Button::kLeft;

  float global_x = 0.f;
  float global_y = 0.f;
  dict.Get("globalX", &global_x);
  dict.Get("globalY", &global_y);
  out->SetPositionInScreen(global_x, global_y);

  dict.Get("movementX", &out->movement_x);
  dict.Get("movementY", &out->movement_y);
  dict.Get("clickCount", &out->click_count);
  return true;
}

bool Converter<blink::WebMouseWheelEvent>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val,
    blink::WebMouseWheelEvent* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  if (!ConvertFromV8(isolate, val, static_cast<blink::WebMouseEvent*>(out)))
    return false;
  dict.Get("deltaX", &out->delta_x);
  dict.Get("deltaY", &out->delta_y);
  dict.Get("wheelTicksX", &out->wheel_ticks_x);
  dict.Get("wheelTicksY", &out->wheel_ticks_y);
  dict.Get("accelerationRatioX", &out->acceleration_ratio_x);
  dict.Get("accelerationRatioY", &out->acceleration_ratio_y);
  dict.Get("hasPreciseScrollingDeltas", &out->has_precise_scrolling_deltas);

#if defined(USE_AURA)
  // Matches the behavior of ui/events/blink/web_input_event_traits.cc:
  bool can_scroll = true;
  if (dict.Get("canScroll", &can_scroll) && !can_scroll) {
    out->has_precise_scrolling_deltas = false;
    out->SetModifiers(out->GetModifiers() & ~blink::WebInputEvent::kControlKey);
  }
#endif
  return true;
}

bool Converter<blink::WebFloatPoint>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val, blink::WebFloatPoint* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  return dict.Get("x", &out->x) && dict.Get("y", &out->y);
}

bool Converter<blink::WebPoint>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val, blink::WebPoint* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  return dict.Get("x", &out->x) && dict.Get("y", &out->y);
}

bool Converter<blink::WebSize>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val, blink::WebSize* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  return dict.Get("width", &out->width) && dict.Get("height", &out->height);
}

bool Converter<blink::WebDeviceEmulationParams>::FromV8(
    v8::Isolate* isolate, v8::Local<v8::Value> val,
    blink::WebDeviceEmulationParams* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;

  std::string screen_position;
  if (dict.Get("screenPosition", &screen_position)) {
    screen_position = base::ToLowerASCII(screen_position);
    if (screen_position == "mobile")
      out->screen_position = blink::WebDeviceEmulationParams::kMobile;
    else if (screen_position == "desktop")
      out->screen_position = blink::WebDeviceEmulationParams::kDesktop;
    else
      return false;
  }

  dict.Get("screenSize", &out->screen_size);
  dict.Get("viewPosition", &out->view_position);
  dict.Get("deviceScaleFactor", &out->device_scale_factor);
  dict.Get("viewSize", &out->view_size);
  dict.Get("scale", &out->scale);
  return true;
}

bool Converter<blink::WebFindOptions>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    blink::WebFindOptions* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;

  dict.Get("forward", &out->forward);
  dict.Get("matchCase", &out->match_case);
  dict.Get("findNext", &out->find_next);
  dict.Get("wordStart", &out->word_start);
  dict.Get("medialCapitalAsWordStart", &out->medial_capital_as_word_start);
  return true;
}

// static
v8::Local<v8::Value> Converter<blink::WebContextMenuData::MediaType>::ToV8(
      v8::Isolate* isolate, const blink::WebContextMenuData::MediaType& in) {
  switch (in) {
    case blink::WebContextMenuData::kMediaTypeImage:
      return mate::StringToV8(isolate, "image");
    case blink::WebContextMenuData::kMediaTypeVideo:
      return mate::StringToV8(isolate, "video");
    case blink::WebContextMenuData::kMediaTypeAudio:
      return mate::StringToV8(isolate, "audio");
    case blink::WebContextMenuData::kMediaTypeCanvas:
      return mate::StringToV8(isolate, "canvas");
    case blink::WebContextMenuData::kMediaTypeFile:
      return mate::StringToV8(isolate, "file");
    case blink::WebContextMenuData::kMediaTypePlugin:
      return mate::StringToV8(isolate, "plugin");
    default:
      return mate::StringToV8(isolate, "none");
  }
}

// static
v8::Local<v8::Value> Converter<blink::WebContextMenuData::InputFieldType>::ToV8(
      v8::Isolate* isolate,
      const blink::WebContextMenuData::InputFieldType& in) {
  switch (in) {
    case blink::WebContextMenuData::kInputFieldTypePlainText:
      return mate::StringToV8(isolate, "plainText");
    case blink::WebContextMenuData::kInputFieldTypePassword:
      return mate::StringToV8(isolate, "password");
    case blink::WebContextMenuData::kInputFieldTypeOther:
      return mate::StringToV8(isolate, "other");
    default:
      return mate::StringToV8(isolate, "none");
  }
}

v8::Local<v8::Value> EditFlagsToV8(v8::Isolate* isolate, int editFlags) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("canUndo",
      !!(editFlags & blink::WebContextMenuData::kCanUndo));
  dict.Set("canRedo",
      !!(editFlags & blink::WebContextMenuData::kCanRedo));
  dict.Set("canCut",
      !!(editFlags & blink::WebContextMenuData::kCanCut));
  dict.Set("canCopy",
      !!(editFlags & blink::WebContextMenuData::kCanCopy));

  bool pasteFlag = false;
  if (editFlags & blink::WebContextMenuData::kCanPaste) {
    std::vector<base::string16> types;
    bool ignore;
    ui::Clipboard::GetForCurrentThread()->ReadAvailableTypes(
        ui::CLIPBOARD_TYPE_COPY_PASTE, &types, &ignore);
    pasteFlag = !types.empty();
  }
  dict.Set("canPaste", pasteFlag);

  dict.Set("canDelete",
      !!(editFlags & blink::WebContextMenuData::kCanDelete));
  dict.Set("canSelectAll",
      !!(editFlags & blink::WebContextMenuData::kCanSelectAll));

  return mate::ConvertToV8(isolate, dict);
}

v8::Local<v8::Value> MediaFlagsToV8(v8::Isolate* isolate, int mediaFlags) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("inError",
      !!(mediaFlags & blink::WebContextMenuData::kMediaInError));
  dict.Set("isPaused",
      !!(mediaFlags & blink::WebContextMenuData::kMediaPaused));
  dict.Set("isMuted",
      !!(mediaFlags & blink::WebContextMenuData::kMediaMuted));
  dict.Set("hasAudio",
      !!(mediaFlags & blink::WebContextMenuData::kMediaHasAudio));
  dict.Set("isLooping",
      (mediaFlags & blink::WebContextMenuData::kMediaLoop) != 0);
  dict.Set("isControlsVisible",
      (mediaFlags & blink::WebContextMenuData::kMediaControls) != 0);
  dict.Set("canToggleControls",
      !!(mediaFlags & blink::WebContextMenuData::kMediaCanToggleControls));
  dict.Set("canRotate",
      !!(mediaFlags & blink::WebContextMenuData::kMediaCanRotate));
  return mate::ConvertToV8(isolate, dict);
}

v8::Local<v8::Value> Converter<blink::WebCache::ResourceTypeStat>::ToV8(
    v8::Isolate* isolate,
    const blink::WebCache::ResourceTypeStat& stat) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("count", static_cast<uint32_t>(stat.count));
  dict.Set("size", static_cast<double>(stat.size));
  dict.Set("liveSize", static_cast<double>(stat.decoded_size));
  return dict.GetHandle();
}

v8::Local<v8::Value> Converter<blink::WebCache::ResourceTypeStats>::ToV8(
    v8::Isolate* isolate,
    const blink::WebCache::ResourceTypeStats& stats) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("images", stats.images);
  dict.Set("scripts", stats.scripts);
  dict.Set("cssStyleSheets", stats.css_style_sheets);
  dict.Set("xslStyleSheets", stats.xsl_style_sheets);
  dict.Set("fonts", stats.fonts);
  dict.Set("other", stats.other);
  return dict.GetHandle();
}

}  // namespace mate


text:
package deref

// DO NOT MODIFY. Generated by nullable-generate.

// Bool returns the value pointed to by bp.
// If bp is nil, then this function returns false.
func Bool(bp *bool) bool {
	if bp == nil {
		return false
	}
	return *bp
}