[fs-uae-controller]
name = Logitech Rumblepad 2 USB
platform = windows

[device]
make = Logitech
model = F510
type = gamepad

[sdl]
guid = 6d0418c2000000000000504944564944
buttons = 12
hats = 1
axes = 4
balls = 0

[default]
include = universal_gamepad
axis_0_neg = lstick_left
axis_0_pos = lstick_right
axis_1_neg = lstick_up
axis_1_pos = lstick_down
axis_2_neg = rstick_left
axis_2_pos = rstick_right
axis_3_neg = rstick_up
axis_3_pos = rstick_down
button_0 = west_button
button_1 = south_button
button_10 = lstick_button
button_11 = rstick_button
button_2 = east_button
button_3 = north_button
button_4 = left_shoulder
button_5 = right_shoulder
button_6 = left_trigger
button_7 = right_trigger
button_8 = select_button
button_9 = start_button
hat_0_down = dpad_down
hat_0_left = dpad_left
hat_0_right = dpad_right
hat_0_up = dpad_up

{'repo_name': 'FrodeSolheim/fs-uae', 'stars': '278', 'repo_language': 'C++', 'file_name': 'format', 'mime_type': 'text/plain', 'hash': 2908297305485336083, 'source_dataset': 'data'}


## DESCRIPTION
## Calculus: Areas between Curves
## ENDDESCRIPTION

## Tagged by XW

## DBsubject(Calculus - single variable)
## DBchapter(Applications of integration)
## DBsection(Areas between curves)
## Date(6/5/2005)
## Institution(UVA)
## Author(Jeff Holt)
## Level(4)
## TitleText1('Calculus: Early Transcendentals')
## AuthorText1('Stewart')
## EditionText1('5')
## Section1('6.1')
## Problem1('23')
## TitleText2('Calculus: Early Transcendentals')
## AuthorText2('Stewart')
## EditionText2('6')
## Section2('6.1')
## Problem2('')
## TitleText3('Calculus: Early Transcendentals')
## AuthorText3('Rogawski')
## EditionText3('1')
## Section3('6.1')
## Problem3('31')
## KEYWORDS('calculus', 'integration', 'integrals', 'areas between curves')

DOCUMENT();        # This should be the first executable line in the problem.

loadMacros(
  "PGstandard.pl",
  "PGchoicemacros.pl",
  "PGcourse.pl"
);

TEXT(beginproblem());
$showPartialCorrectAnswers = 1;

$a=random(2, 9);
$b=2*$a;
$soln = $a*(2-$PI/2);

TEXT(EV2(<<EOT));
Sketch the region enclosed by the curves given below.
Decide whether to integrate with respect to \(x\) or \(y\).
Then find the area of the region.
\[ y = $a \cos x, \quad y = $a-\frac{$b x}{ \pi}.   \]
$BR
Area = \{ans_rule(30) \}
EOT
ANS(num_cmp($soln));

ENDDOCUMENT();        # This should be the last executable line in the problem.

{'repo_name': 'openwebwork/webwork-open-problem-library', 'stars': '146', 'repo_language': 'PostScript', 'file_name': 'p8.pg', 'mime_type': 'text/plain', 'hash': 5656291793885410592, 'source_dataset': 'data'}


require 'spec_helper'

describe 'Accessing server resources using the API' do
  let(:api_client) {Postmark::ApiClient.new(ENV['POSTMARK_API_KEY'], :http_open_timeout => 15)}
  let(:recipient) {ENV['POSTMARK_CI_RECIPIENT']}
  let(:message) {
    {
        :from => ENV['POSTMARK_CI_SENDER'],
        :to => recipient,
        :subject => "Mail::Message object",
        :text_body => "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " \
                    "sed do eiusmod tempor incididunt ut labore et dolore " \
                    "magna aliqua."
    }
  }

  context 'Messages API' do
    def with_retries(max_retries = 20, wait_seconds = 3)
      yield
    rescue => e
      retries = retries ? retries + 1 : 1
      if retries < max_retries
        sleep wait_seconds
        retry
      else
        raise e
      end
    end

    it 'is possible to send a message and access its details via the Messages API' do
      response = api_client.deliver(message)
      message = with_retries {api_client.get_message(response[:message_id])}
      expect(message[:recipients]).to include(recipient)
    end

    it 'is possible to send a message and dump it via the Messages API' do
      response = api_client.deliver(message)
      dump = with_retries {api_client.dump_message(response[:message_id])}
      expect(dump[:body]).to include('Mail::Message object')
    end

    it 'is possible to send a message and find it via the Messages API' do
      response = api_client.deliver(message)
      expect {
        with_retries {
          messages = api_client.get_messages(:recipient => recipient,
                                             :fromemail => message[:from],
                                             :subject => message[:subject])
          unless messages.map {|m| m[:message_id]}.include?(response[:message_id])
            raise 'Message not found'
          end
        }
      }.not_to raise_error
    end
  end
end

{'repo_name': 'wildbit/postmark-gem', 'stars': '159', 'repo_language': 'Ruby', 'file_name': 'mail.rb', 'mime_type': 'text/x-ruby', 'hash': -3467960161265197268, 'source_dataset': 'data'}


<?php

/*
 * This file is part of SwiftMailer.
 * (c) 2004-2009 Chris Corbyn
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * The minimum interface for an Event.
 *
 * @package Swift
 * @subpackage Events
 * @author Chris Corbyn
 */
interface Swift_Events_Event
{

  /**
   * Get the source object of this event.
   * @return object
   */
  public function getSource();

  /**
   * Prevent this Event from bubbling any further up the stack.
   * @param boolean $cancel, optional
   */
  public function cancelBubble($cancel = true);

  /**
   * Returns true if this Event will not bubble any further up the stack.
   * @return boolean
   */
  public function bubbleCancelled();

}

{'repo_name': 'appleseedproj/appleseed', 'stars': '117', 'repo_language': 'PHP', 'file_name': 'Command.php', 'mime_type': 'text/x-php', 'hash': 8973441284647927117, 'source_dataset': 'data'}


/*************************************************************************
 *
 * This file is part of the SAMRAI distribution.  For full copyright
 * information, see COPYRIGHT and LICENSE.
 *
 * Copyright:     (c) 1997-2020 Lawrence Livermore National Security, LLC
 * Description:   Abstract base class for patch data objects
 *
 ************************************************************************/

#ifndef included_hier_PatchData
#define included_hier_PatchData

#include "SAMRAI/SAMRAI_config.h"
#include "SAMRAI/tbox/MessageStream.h"
#include "SAMRAI/hier/Box.h"
#include "SAMRAI/hier/BoxOverlap.h"
#include "SAMRAI/hier/IntVector.h"
#include "SAMRAI/tbox/Database.h"
#include "SAMRAI/tbox/Utilities.h"

namespace SAMRAI {
namespace hier {

/**
 * Class PatchData is a pure virtual base class for the data storage
 * defined over a box.  Patch data objects are generally contained within
 * a patch.  Patch data defines the abstract virtual functions for data
 * management and communication that must be supplied by the subclasses.
 * Subclasses implement the virtual functions as appropriate for the derived
 * type; for example, cell centered objects will copy data differently than
 * face centered objects.
 *
 * Patch data objects are created by patch data factories and associated
 * subclasses.  This separation into abstract factory and concrete
 * implementation subclasses facilitates the creation of new patch data
 * subtypes.  See the Design Patterns book for more details about the
 * Abstract Factory pattern.
 *
 * The copy and pack/unpack functions in the patch data object take
 * box overlap descriptions that describe the index space over which
 * data is to be copied or packed/unpacked.  Box overlaps are computed
 * by the box geometry classes, which are accessed through the patch
 * data factories.  Box geometry classes are created by the patch data
 * factories instead of the patch data objects because patch data objects
 * are distributed across memory with patches and therefore may not exist
 * on a particular processor.  Patch data factories are guaranteed to
 * exist on all processors independent of the patch-to-processor mapping.
 *
 * @see BoxOverlap
 * @see BoxGeometry
 * @see Patch
 * @see PatchDataFactory
 * @see PatchDescriptor
 */

class PatchData
{
public:
   /**
    * The constructor for a patch data object.  Patch data objects will
    * manage the interior box over which they are defined and the associated
    * ghost cell width.
    *
    * @pre domain.getDim() == ghosts.getDim()
    */
   PatchData(
      const Box& domain,
      const IntVector& ghosts);

   /**
    * The virtual destructor for a patch data object.
    */
   virtual ~PatchData();

   /**
    * Return the box over which this patch data object is defined.  All
    * objects in the same patch are defined over the same box, although
    * the patch data objects may interpret how to allocate storage for
    * that box in different ways.
    */
   const Box&
   getBox() const
   {
      return d_box;
   }

   /**
    * Return the ghost cell box.  The ghost cell box is defined to be
    * the interior box grown by the ghost cell width.
    */
   const Box&
   getGhostBox() const
   {
      return d_ghost_box;
   }

   /**
    * Get the ghost cell width associated with this patch data object.
    */
   const IntVector&
   getGhostCellWidth() const
   {
      return d_ghosts;
   }

   /**
    * Set the simulation time stamp for the patch data type.  The simulation
    * time is initialized to zero when the patch data type is created.
    */
   void
   setTime(
      const double timestamp)
   {
      d_timestamp = timestamp;
   }

   /**
    * Get the simulation time stamp for the patch data type.
    */
   double
   getTime() const
   {
      return d_timestamp;
   }

   /**
    * A fast copy between the source and destination.  Data is copied from
    * the source into the destination where there is overlap in the underlying
    * index space.  The copy is performed on the interior plus the ghost cell
    * width (for both the source and destination).  If this copy does not
    * understand how to copy data from the argument, then copy2() is called
    * on the source object.
    */
   virtual void
   copy(
      const PatchData& src) = 0;

   /**
    * A fast copy between the source and destination.  Data is copied from
    * the source into the destination where there is overlap in the underlying
    * index space.  The copy is performed on the interior plus the ghost cell
    * width (for both the source and destination).  If this copy does not
    * understand how to copy data from the destination, then it may throw
    * an assertion (aka dump core in a failed assertion).
    */
   virtual void
   copy2(
      PatchData& dst) const = 0;

   /**
    * Copy data from the source into the destination using the designated
    * overlap descriptor.  The overlap description will have been computed
    * using the appropriate box geometry objects.  If this member function
    * cannot complete the copy from source (e.g., if it doesn't understand
    * the type of source), then copy2() is called on the source object.
    */
   virtual void
   copy(
      const PatchData& src,
      const BoxOverlap& overlap) = 0;

   /**
    * Copy data from the source into the destination using the designated
    * overlap descriptor.  The overlap description will have been computed
    * using the appropriate box geometry objects If this member function
    * cannot complete the copy from the destination, then it may throw an
    * assertion (aka dump core in a failed assertion).
    */
   virtual void
   copy2(
      PatchData& dst,
      const BoxOverlap& overlap) const = 0;

   /**
    * Determines whether the patch data subclass can estimate the necessary
    * stream size using only index space information.  The return value will
    * most likely be true for data types that are fixed size (such as doubles)
    * but will be false for complex data types that allocate their own storage
    * (such as lists of particles).  This routine is used to estimate whether
    * a processor can estimate space for incoming messages or whether it needs
    * to receive a message size from the sending processor.
    */
   virtual bool
   canEstimateStreamSizeFromBox() const = 0;

   /**
    * Calculate the number of bytes needed to stream the data lying
    * in the specified box domain.  This estimate must be an upper
    * bound on the size of the data in the actual message stream.
    * The upper bound should be close, however, since buffer space
    * will be allocated according to these values, and excess buffer
    * space will waste memory resources.
    */
   virtual size_t
   getDataStreamSize(
      const BoxOverlap& overlap) const = 0;

   /**
    * Pack data lying on the specified index set into the output stream.
    * See the abstract stream virtual base class for more information about
    * the packing operators defined for streams.
    */
   virtual void
   packStream(
      tbox::MessageStream& stream,
      const BoxOverlap& overlap) const = 0;

   /**
    * Unpack data from the message stream into the specified index set.
    * See the abstract stream virtual base class for more information about
    * the packing operators defined for streams.
    */
   virtual void
   unpackStream(
      tbox::MessageStream& stream,
      const BoxOverlap& overlap) = 0;

   /**
    * Checks that class version and restart file version are equal.  If so,
    * reads in the data members common to all patch data types from restart
    * database.
    *
    * @pre restart_db
    */
   virtual void
   getFromRestart(
      const std::shared_ptr<tbox::Database>& restart_db);

   /**
    * Writes out the class version number to the restart database.  Then,
    * writes the data members common to all patch data types to database.
    *
    * @pre restart_db
    */
   virtual void
   putToRestart(
      const std::shared_ptr<tbox::Database>& restart_db) const;

   /**
    * @brief Return the dimension of this object.
    */
   const tbox::Dimension&
   getDim() const
   {
      return d_box.getDim();
   }

protected:
   /**
    * This protected method is used by concrete patch data subclasses
    * to set the ghost box over which the patch data will be allocated.
    * Note that this allows the ghost box to be inconsistant with its
    * standard interpretation as the patch domain box grown by the ghost
    * cell width (as set in the constructor).
    *
    * This function is included to treat some special cases for concrete
    * patch data types and should be used with caution.
    *
    * @pre getDim() == ghost_box.getDim()
    * @pre (ghost_box * getBox()).isSpatiallyEqual(getBox())
    */
   void
   setGhostBox(
      const Box& ghost_box)
   {
      TBOX_ASSERT_OBJDIM_EQUALITY2(d_box, ghost_box);
      TBOX_ASSERT((ghost_box * d_box).isSpatiallyEqual(d_box));
      d_ghost_box = ghost_box;
   }

private:
   /*
    * Static integer constant describing class's version number.
    */
   static const int HIER_PATCH_DATA_VERSION;

   PatchData(
      const PatchData&);        // not implemented
   PatchData&
   operator = (
      const PatchData&);                // not implemented

   Box d_box;                           // interior box description
   Box d_ghost_box;                     // interior box plus ghosts
   IntVector d_ghosts;                  // ghost cell width
   double d_timestamp;                          // timestamp for the data

};

}
}

#endif

{'repo_name': 'LLNL/SAMRAI', 'stars': '139', 'repo_language': 'C', 'file_name': 'FindHYPRE.cmake', 'mime_type': 'text/plain', 'hash': 6473732581467294302, 'source_dataset': 'data'}


/////////////////////////////////////////////////////////////////
/*
MIT License

Copyright (c) 2019 lewis he

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

axp20x.h - Arduino library for X-Power AXP202 chip.
Created by Lewis he on April 1, 2019.
github:https://github.com/lewisxhe/AXP202X_Libraries
*/
/////////////////////////////////////////////////////////////////
#pragma once

#include <Arduino.h>
#include <Wire.h>

// #define AXP_DEBUG_PORT  Serial
#ifdef AXP_DEBUG_PORT
#define AXP_DEBUG(fmt, ...) AXP_DEBUG_PORT.printf_P((PGM_P)PSTR(fmt), ##__VA_ARGS__)
#else
#define AXP_DEBUG(...)
#endif

#ifndef RISING
#define RISING 0x01
#endif

#ifndef FALLING
#define FALLING 0x02
#endif

#ifdef _BV
#undef _BV
#endif
#define _BV(b) (1ULL << (b))

//! Error Code
#define AXP_PASS            (0)
#define AXP_FAIL            (-1)
#define AXP_INVALID         (-2)
#define AXP_NOT_INIT        (-3)
#define AXP_NOT_SUPPORT     (-4)
#define AXP_ARG_INVALID     (-5)

//! Chip Address
#define AXP202_SLAVE_ADDRESS (0x35)
#define AXP192_SLAVE_ADDRESS (0x34)
#define AXP173_SLAVE_ADDRESS (0x34)

//! Chip ID
#define AXP202_CHIP_ID 0x41
#define AXP192_CHIP_ID 0x03
#define AXP173_CHIP_ID 0xAD     //!Axp173 does not have a chip ID, given a custom ID

//! Logic states
#define AXP202_ON 1
#define AXP202_OFF 0

//! REG MAP
#define AXP202_STATUS (0x00)
#define AXP202_MODE_CHGSTATUS (0x01)
#define AXP202_OTG_STATUS (0x02)
#define AXP202_IC_TYPE (0x03)
#define AXP202_DATA_BUFFER1 (0x04)
#define AXP202_DATA_BUFFER2 (0x05)
#define AXP202_DATA_BUFFER3 (0x06)
#define AXP202_DATA_BUFFER4 (0x07)
#define AXP202_DATA_BUFFER5 (0x08)
#define AXP202_DATA_BUFFER6 (0x09)
#define AXP202_DATA_BUFFER7 (0x0A)
#define AXP202_DATA_BUFFER8 (0x0B)
#define AXP202_DATA_BUFFER9 (0x0C)
#define AXP202_DATA_BUFFERA (0x0D)
#define AXP202_DATA_BUFFERB (0x0E)
#define AXP202_DATA_BUFFERC (0x0F)
#define AXP202_LDO234_DC23_CTL (0x12)
#define AXP202_DC2OUT_VOL (0x23)
#define AXP202_LDO3_DC2_DVM (0x25)
#define AXP202_DC3OUT_VOL (0x27)
#define AXP202_LDO24OUT_VOL (0x28)
#define AXP202_LDO3OUT_VOL (0x29)
#define AXP202_IPS_SET (0x30)
#define AXP202_VOFF_SET (0x31)
#define AXP202_OFF_CTL (0x32)
#define AXP202_CHARGE1 (0x33)
#define AXP202_CHARGE2 (0x34)
#define AXP202_BACKUP_CHG (0x35)
#define AXP202_POK_SET (0x36)
#define AXP202_DCDC_FREQSET (0x37)
#define AXP202_VLTF_CHGSET (0x38)
#define AXP202_VHTF_CHGSET (0x39)
#define AXP202_APS_WARNING1 (0x3A)
#define AXP202_APS_WARNING2 (0x3B)
#define AXP202_TLTF_DISCHGSET (0x3C)
#define AXP202_THTF_DISCHGSET (0x3D)
#define AXP202_DCDC_MODESET (0x80)
#define AXP202_ADC_EN1 (0x82)
#define AXP202_ADC_EN2 (0x83)
#define AXP202_ADC_SPEED (0x84)
#define AXP202_ADC_INPUTRANGE (0x85)
#define AXP202_ADC_IRQ_RETFSET (0x86)
#define AXP202_ADC_IRQ_FETFSET (0x87)
#define AXP202_TIMER_CTL (0x8A)
#define AXP202_VBUS_DET_SRP (0x8B)
#define AXP202_HOTOVER_CTL (0x8F)
#define AXP202_GPIO0_CTL (0x90)
#define AXP202_GPIO0_VOL (0x91)
#define AXP202_GPIO1_CTL (0x92)
#define AXP202_GPIO2_CTL (0x93)
#define AXP202_GPIO012_SIGNAL (0x94)
#define AXP202_GPIO3_CTL (0x95)
#define AXP202_INTEN1 (0x40)
#define AXP202_INTEN2 (0x41)
#define AXP202_INTEN3 (0x42)
#define AXP202_INTEN4 (0x43)
#define AXP202_INTEN5 (0x44)
#define AXP202_INTSTS1 (0x48)
#define AXP202_INTSTS2 (0x49)
#define AXP202_INTSTS3 (0x4A)
#define AXP202_INTSTS4 (0x4B)
#define AXP202_INTSTS5 (0x4C)

//Irq control register
#define AXP192_INTEN1 (0x40)
#define AXP192_INTEN2 (0x41)
#define AXP192_INTEN3 (0x42)
#define AXP192_INTEN4 (0x43)
#define AXP192_INTEN5 (0x4A)
//Irq status register
#define AXP192_INTSTS1 (0x44)
#define AXP192_INTSTS2 (0x45)
#define AXP192_INTSTS3 (0x46)
#define AXP192_INTSTS4 (0x47)
#define AXP192_INTSTS5 (0x4D)

#define AXP192_DC1_VLOTAGE (0x26)
#define AXP192_LDO23OUT_VOL (0x28)
#define AXP192_GPIO0_CTL (0x90)
#define AXP192_GPIO0_VOL (0x91)
#define AXP192_GPIO1_CTL (0X92)
#define AXP192_GPIO2_CTL (0x93)
#define AXP192_GPIO012_SIGNAL (0x94)
#define AXP192_GPIO34_CTL (0x95)

/* axp 192/202 adc data register */
#define AXP202_BAT_AVERVOL_H8 (0x78)
#define AXP202_BAT_AVERVOL_L4 (0x79)
#define AXP202_BAT_AVERCHGCUR_H8 (0x7A)
#define AXP202_BAT_AVERCHGCUR_L4 (0x7B)
#define AXP202_BAT_AVERCHGCUR_L5 (0x7B)
#define AXP202_ACIN_VOL_H8 (0x56)
#define AXP202_ACIN_VOL_L4 (0x57)
#define AXP202_ACIN_CUR_H8 (0x58)
#define AXP202_ACIN_CUR_L4 (0x59)
#define AXP202_VBUS_VOL_H8 (0x5A)
#define AXP202_VBUS_VOL_L4 (0x5B)
#define AXP202_VBUS_CUR_H8 (0x5C)
#define AXP202_VBUS_CUR_L4 (0x5D)
#define AXP202_INTERNAL_TEMP_H8 (0x5E)
#define AXP202_INTERNAL_TEMP_L4 (0x5F)
#define AXP202_TS_IN_H8 (0x62)
#define AXP202_TS_IN_L4 (0x63)
#define AXP202_GPIO0_VOL_ADC_H8 (0x64)
#define AXP202_GPIO0_VOL_ADC_L4 (0x65)
#define AXP202_GPIO1_VOL_ADC_H8 (0x66)
#define AXP202_GPIO1_VOL_ADC_L4 (0x67)

#define AXP202_BAT_AVERDISCHGCUR_H8 (0x7C)
#define AXP202_BAT_AVERDISCHGCUR_L5 (0x7D)
#define AXP202_APS_AVERVOL_H8 (0x7E)
#define AXP202_APS_AVERVOL_L4 (0x7F)
#define AXP202_INT_BAT_CHGCUR_H8 (0xA0)
#define AXP202_INT_BAT_CHGCUR_L4 (0xA1)
#define AXP202_EXT_BAT_CHGCUR_H8 (0xA2)
#define AXP202_EXT_BAT_CHGCUR_L4 (0xA3)
#define AXP202_INT_BAT_DISCHGCUR_H8 (0xA4)
#define AXP202_INT_BAT_DISCHGCUR_L4 (0xA5)
#define AXP202_EXT_BAT_DISCHGCUR_H8 (0xA6)
#define AXP202_EXT_BAT_DISCHGCUR_L4 (0xA7)
#define AXP202_BAT_CHGCOULOMB3 (0xB0)
#define AXP202_BAT_CHGCOULOMB2 (0xB1)
#define AXP202_BAT_CHGCOULOMB1 (0xB2)
#define AXP202_BAT_CHGCOULOMB0 (0xB3)
#define AXP202_BAT_DISCHGCOULOMB3 (0xB4)
#define AXP202_BAT_DISCHGCOULOMB2 (0xB5)
#define AXP202_BAT_DISCHGCOULOMB1 (0xB6)
#define AXP202_BAT_DISCHGCOULOMB0 (0xB7)
#define AXP202_COULOMB_CTL (0xB8)
#define AXP202_BAT_POWERH8 (0x70)
#define AXP202_BAT_POWERM8 (0x71)
#define AXP202_BAT_POWERL8 (0x72)

#define AXP202_VREF_TEM_CTRL (0xF3)
#define AXP202_BATT_PERCENTAGE (0xB9)

/* bit definitions for AXP events, irq event */
/*  AXP202  */
#define AXP202_IRQ_USBLO (1)
#define AXP202_IRQ_USBRE (2)
#define AXP202_IRQ_USBIN (3)
#define AXP202_IRQ_USBOV (4)
#define AXP202_IRQ_ACRE (5)
#define AXP202_IRQ_ACIN (6)
#define AXP202_IRQ_ACOV (7)

#define AXP202_IRQ_TEMLO (8)
#define AXP202_IRQ_TEMOV (9)
#define AXP202_IRQ_CHAOV (10)
#define AXP202_IRQ_CHAST (11)
#define AXP202_IRQ_BATATOU (12)
#define AXP202_IRQ_BATATIN (13)
#define AXP202_IRQ_BATRE (14)
#define AXP202_IRQ_BATIN (15)

#define AXP202_IRQ_POKLO (16)
#define AXP202_IRQ_POKSH (17)
#define AXP202_IRQ_LDO3LO (18)
#define AXP202_IRQ_DCDC3LO (19)
#define AXP202_IRQ_DCDC2LO (20)
#define AXP202_IRQ_CHACURLO (22)
#define AXP202_IRQ_ICTEMOV (23)

#define AXP202_IRQ_EXTLOWARN2 (24)
#define AXP202_IRQ_EXTLOWARN1 (25)
#define AXP202_IRQ_SESSION_END (26)
#define AXP202_IRQ_SESS_AB_VALID (27)
#define AXP202_IRQ_VBUS_UN_VALID (28)
#define AXP202_IRQ_VBUS_VALID (29)
#define AXP202_IRQ_PDOWN_BY_NOE (30)
#define AXP202_IRQ_PUP_BY_NOE (31)

#define AXP202_IRQ_GPIO0TG (32)
#define AXP202_IRQ_GPIO1TG (33)
#define AXP202_IRQ_GPIO2TG (34)
#define AXP202_IRQ_GPIO3TG (35)
#define AXP202_IRQ_PEKFE (37)
#define AXP202_IRQ_PEKRE (38)
#define AXP202_IRQ_TIMER (39)

//Signal Capture
#define AXP202_BATT_VOLTAGE_STEP (1.1F)
#define AXP202_BATT_DISCHARGE_CUR_STEP (0.5F)
#define AXP202_BATT_CHARGE_CUR_STEP (0.5F)
#define AXP202_ACIN_VOLTAGE_STEP (1.7F)
#define AXP202_ACIN_CUR_STEP (0.625F)
#define AXP202_VBUS_VOLTAGE_STEP (1.7F)
#define AXP202_VBUS_CUR_STEP (0.375F)
#define AXP202_INTERNAL_TEMP_STEP (0.1F)
#define AXP202_APS_VOLTAGE_STEP (1.4F)
#define AXP202_TS_PIN_OUT_STEP (0.8F)
#define AXP202_GPIO0_STEP (0.5F)
#define AXP202_GPIO1_STEP (0.5F)
// AXP192 only
#define AXP202_GPIO2_STEP (0.5F)
#define AXP202_GPIO3_STEP (0.5F)

// AXP173
#define AXP173_EXTEN_DC2_CTL   (0x10)
#define AXP173_CTL_DC2_BIT      (0)
#define AXP173_CTL_EXTEN_BIT    (2)
#define AXP173_DC1_VLOTAGE      (0x26)
#define AXP173_LDO4_VLOTAGE     (0x27)

#define FORCED_OPEN_DCDC3(x) (x |= (AXP202_ON << AXP202_DCDC3))
#define BIT_MASK(x) (1 << x)
#define IS_OPEN(reg, channel) (bool)(reg & BIT_MASK(channel))

enum {
    AXP202_EXTEN = 0,
    AXP202_DCDC3 = 1,
    AXP202_LDO2 = 2,
    AXP202_LDO4 = 3,
    AXP202_DCDC2 = 4,
    AXP202_LDO3 = 6,
    AXP202_OUTPUT_MAX,
};

enum {
    AXP192_DCDC1 = 0,
    AXP192_DCDC3 = 1,
    AXP192_LDO2 = 2,
    AXP192_LDO3 = 3,
    AXP192_DCDC2 = 4,
    AXP192_EXTEN = 6,
    AXP192_OUTPUT_MAX,
};

enum {
    AXP173_DCDC1 = 0,
    AXP173_LDO4 = 1,
    AXP173_LDO2 = 2,
    AXP173_LDO3 = 3,
    AXP173_DCDC2 = 4,
    AXP173_EXTEN = 6,
    AXP173_OUTPUT_MAX,
};

typedef enum {
    AXP202_STARTUP_TIME_128MS,
    AXP202_STARTUP_TIME_3S,
    AXP202_STARTUP_TIME_1S,
    AXP202_STARTUP_TIME_2S,
} axp202_startup_time_t;

typedef enum {
    AXP192_STARTUP_TIME_128MS,
    AXP192_STARTUP_TIME_512MS,
    AXP192_STARTUP_TIME_1S,
    AXP192_STARTUP_TIME_2S,
} axp192_startup_time_t;

typedef enum {
    AXP_LONGPRESS_TIME_1S,
    AXP_LONGPRESS_TIME_1S5,
    AXP_LONGPRESS_TIME_2S,
    AXP_LONGPRESS_TIME_2S5,
} axp_loonPress_time_t;

typedef enum {
    AXP_POWER_OFF_TIME_4S,
    AXP_POWER_OFF_TIME_65,
    AXP_POWER_OFF_TIME_8S,
    AXP_POWER_OFF_TIME_16S,
} axp_poweroff_time_t;

//REG 33H: Charging control 1 Charging target-voltage setting
typedef enum {
    AXP202_TARGET_VOL_4_1V,
    AXP202_TARGET_VOL_4_15V,
    AXP202_TARGET_VOL_4_2V,
    AXP202_TARGET_VOL_4_36V
} axp_chargeing_vol_t;

//REG 82H: ADC Enable 1 register Parameter
typedef enum {
    AXP202_BATT_VOL_ADC1 = 1 << 7,
    AXP202_BATT_CUR_ADC1 = 1 << 6,
    AXP202_ACIN_VOL_ADC1 = 1 << 5,
    AXP202_ACIN_CUR_ADC1 = 1 << 4,
    AXP202_VBUS_VOL_ADC1 = 1 << 3,
    AXP202_VBUS_CUR_ADC1 = 1 << 2,
    AXP202_APS_VOL_ADC1 = 1 << 1,
    AXP202_TS_PIN_ADC1 = 1 << 0
} axp_adc1_func_t;

// REG 83H: ADC Enable 2 register Parameter
typedef enum {
    AXP202_TEMP_MONITORING_ADC2 = 1 << 7,
    AXP202_GPIO1_FUNC_ADC2 = 1 << 3,
    AXP202_GPIO0_FUNC_ADC2 = 1 << 2
} axp_adc2_func_t;

typedef enum {
    AXP202_LDO3_MODE_LDO,
    AXP202_LDO3_MODE_DCIN
} axp202_ldo3_mode_t;

typedef enum {
    //! IRQ1 REG 40H
    AXP202_VBUS_VHOLD_LOW_IRQ       = _BV(1),   //VBUS is available, but lower than V HOLD, IRQ enable
    AXP202_VBUS_REMOVED_IRQ         = _BV(2),   //VBUS removed, IRQ enable
    AXP202_VBUS_CONNECT_IRQ         = _BV(3),   //VBUS connected, IRQ enable
    AXP202_VBUS_OVER_VOL_IRQ        = _BV(4),   //VBUS over-voltage, IRQ enable
    AXP202_ACIN_REMOVED_IRQ         = _BV(5),   //ACIN removed, IRQ enable
    AXP202_ACIN_CONNECT_IRQ         = _BV(6),   //ACIN connected, IRQ enable
    AXP202_ACIN_OVER_VOL_IRQ        = _BV(7),   //ACIN over-voltage, IRQ enable

    //! IRQ2 REG 41H
    AXP202_BATT_LOW_TEMP_IRQ        = _BV(8),   //Battery low-temperature, IRQ enable
    AXP202_BATT_OVER_TEMP_IRQ       = _BV(9),   //Battery over-temperature, IRQ enable
    AXP202_CHARGING_FINISHED_IRQ    = _BV(10),  //Charge finished, IRQ enable
    AXP202_CHARGING_IRQ             = _BV(11),  //Be charging, IRQ enable
    AXP202_BATT_EXIT_ACTIVATE_IRQ   = _BV(12),  //Exit battery activate mode, IRQ enable
    AXP202_BATT_ACTIVATE_IRQ        = _BV(13),  //Battery activate mode, IRQ enable
    AXP202_BATT_REMOVED_IRQ         = _BV(14),  //Battery removed, IRQ enable
    AXP202_BATT_CONNECT_IRQ         = _BV(15),  //Battery connected, IRQ enable

    //! IRQ3 REG 42H
    AXP202_PEK_LONGPRESS_IRQ        = _BV(16),  //PEK long press, IRQ enable
    AXP202_PEK_SHORTPRESS_IRQ       = _BV(17),  //PEK short press, IRQ enable
    AXP202_LDO3_LOW_VOL_IRQ         = _BV(18),  //LDO3output voltage is lower than the set value, IRQ enable
    AXP202_DC3_LOW_VOL_IRQ          = _BV(19),  //DC-DC3output voltage is lower than the set value, IRQ enable
    AXP202_DC2_LOW_VOL_IRQ          = _BV(20),  //DC-DC2 output voltage is lower than the set value, IRQ enable
    //**Reserved and unchangeable BIT 5
    AXP202_CHARGE_LOW_CUR_IRQ       = _BV(22),  //Charge current is lower than the set current, IRQ enable
    AXP202_CHIP_TEMP_HIGH_IRQ       = _BV(23),  //AXP202 internal over-temperature, IRQ enable

    //! IRQ4 REG 43H
    AXP202_APS_LOW_VOL_LEVEL2_IRQ   = _BV(24),  //APS low-voltage, IRQ enable（LEVEL2）
    APX202_APS_LOW_VOL_LEVEL1_IRQ   = _BV(25),  //APS low-voltage, IRQ enable（LEVEL1）
    AXP202_VBUS_SESSION_END_IRQ     = _BV(26),  //VBUS Session End IRQ enable
    AXP202_VBUS_SESSION_AB_IRQ      = _BV(27),  //VBUS Session A/B IRQ enable
    AXP202_VBUS_INVALID_IRQ         = _BV(28),  //VBUS invalid, IRQ enable
    AXP202_VBUS_VAILD_IRQ           = _BV(29),  //VBUS valid, IRQ enable
    AXP202_NOE_OFF_IRQ              = _BV(30),  //N_OE shutdown, IRQ enable
    AXP202_NOE_ON_IRQ               = _BV(31),  //N_OE startup, IRQ enable

    //! IRQ5 REG 44H
    AXP202_GPIO0_EDGE_TRIGGER_IRQ   = _BV(32),  //GPIO0 input edge trigger, IRQ enable
    AXP202_GPIO1_EDGE_TRIGGER_IRQ   = _BV(33),  //GPIO1input edge trigger or ADC input, IRQ enable
    AXP202_GPIO2_EDGE_TRIGGER_IRQ   = _BV(34),  //GPIO2input edge trigger, IRQ enable
    AXP202_GPIO3_EDGE_TRIGGER_IRQ   = _BV(35),  //GPIO3 input edge trigger, IRQ enable
    //**Reserved and unchangeable BIT 4
    AXP202_PEK_FALLING_EDGE_IRQ     = _BV(37),  //PEK press falling edge, IRQ enable
    AXP202_PEK_RISING_EDGE_IRQ      = _BV(38),  //PEK press rising edge, IRQ enable
    AXP202_TIMER_TIMEOUT_IRQ        = _BV(39),  //Timer timeout, IRQ enable

    AXP202_ALL_IRQ                  = (0xFFFFFFFFFFULL)
} axp_irq_t;

typedef enum {
    AXP202_LDO4_1250MV,
    AXP202_LDO4_1300MV,
    AXP202_LDO4_1400MV,
    AXP202_LDO4_1500MV,
    AXP202_LDO4_1600MV,
    AXP202_LDO4_1700MV,
    AXP202_LDO4_1800MV,
    AXP202_LDO4_1900MV,
    AXP202_LDO4_2000MV,
    AXP202_LDO4_2500MV,
    AXP202_LDO4_2700MV,
    AXP202_LDO4_2800MV,
    AXP202_LDO4_3000MV,
    AXP202_LDO4_3100MV,
    AXP202_LDO4_3200MV,
    AXP202_LDO4_3300MV,
    AXP202_LDO4_MAX,
} axp_ldo4_table_t;

typedef enum {
    AXP202_LDO5_1800MV,
    AXP202_LDO5_2500MV,
    AXP202_LDO5_2800MV,
    AXP202_LDO5_3000MV,
    AXP202_LDO5_3100MV,
    AXP202_LDO5_3300MV,
    AXP202_LDO5_3400MV,
    AXP202_LDO5_3500MV,
} axp_ldo5_table_t;

typedef enum {
    AXP20X_LED_OFF,
    AXP20X_LED_BLINK_1HZ,
    AXP20X_LED_BLINK_4HZ,
    AXP20X_LED_LOW_LEVEL,
} axp_chgled_mode_t;

typedef enum {
    AXP_ADC_SAMPLING_RATE_25HZ = 0,
    AXP_ADC_SAMPLING_RATE_50HZ = 1,
    AXP_ADC_SAMPLING_RATE_100HZ = 2,
    AXP_ADC_SAMPLING_RATE_200HZ = 3,
} axp_adc_sampling_rate_t;

typedef enum {
    AXP_TS_PIN_CURRENT_20UA = 0,
    AXP_TS_PIN_CURRENT_40UA = 1,
    AXP_TS_PIN_CURRENT_60UA = 2,
    AXP_TS_PIN_CURRENT_80UA = 3,
} axp_ts_pin_current_t;

typedef enum {
    AXP_TS_PIN_FUNCTION_BATT = 0,
    AXP_TS_PIN_FUNCTION_ADC = 1,
} axp_ts_pin_function_t;

typedef enum {
    AXP_TS_PIN_MODE_DISABLE = 0,
    AXP_TS_PIN_MODE_CHARGING = 1,
    AXP_TS_PIN_MODE_SAMPLING = 2,
    AXP_TS_PIN_MODE_ENABLE = 3,
} axp_ts_pin_mode_t;

//! Only AXP192 and AXP202 have gpio function
typedef enum {
    AXP_GPIO_0,
    AXP_GPIO_1,
    AXP_GPIO_2,
    AXP_GPIO_3,
    AXP_GPIO_4,
} axp_gpio_t;

typedef enum {
    AXP_IO_OUTPUT_LOW_MODE,
    AXP_IO_OUTPUT_HIGH_MODE,
    AXP_IO_INPUT_MODE,
    AXP_IO_LDO_MODE,
    AXP_IO_ADC_MODE,
    AXP_IO_FLOATING_MODE,
    AXP_IO_OPEN_DRAIN_OUTPUT_MODE,
    AXP_IO_PWM_OUTPUT_MODE,
    AXP_IO_EXTERN_CHARGING_CTRL_MODE,
} axp_gpio_mode_t;

typedef enum {
    AXP_IRQ_NONE,
    AXP_IRQ_RISING,
    AXP_IRQ_FALLING,
    AXP_IRQ_DOUBLE_EDGE,
} axp_gpio_irq_t;

typedef enum {
    AXP192_GPIO_1V8,
    AXP192_GPIO_1V9,
    AXP192_GPIO_2V0,
    AXP192_GPIO_2V1,
    AXP192_GPIO_2V2,
    AXP192_GPIO_2V3,
    AXP192_GPIO_2V4,
    AXP192_GPIO_2V5,
    AXP192_GPIO_2V6,
    AXP192_GPIO_2V7,
    AXP192_GPIO_2V8,
    AXP192_GPIO_2V9,
    AXP192_GPIO_3V0,
    AXP192_GPIO_3V1,
    AXP192_GPIO_3V2,
    AXP192_GPIO_3V3,
} axp192_gpio_voltage_t;

typedef enum {
    AXP1XX_CHARGE_CUR_100MA,
    AXP1XX_CHARGE_CUR_190MA,
    AXP1XX_CHARGE_CUR_280MA,
    AXP1XX_CHARGE_CUR_360MA,
    AXP1XX_CHARGE_CUR_450MA,
    AXP1XX_CHARGE_CUR_550MA,
    AXP1XX_CHARGE_CUR_630MA,
    AXP1XX_CHARGE_CUR_700MA,
    AXP1XX_CHARGE_CUR_780MA,
    AXP1XX_CHARGE_CUR_880MA,
    AXP1XX_CHARGE_CUR_960MA,
    AXP1XX_CHARGE_CUR_1000MA,
    AXP1XX_CHARGE_CUR_1080MA,
    AXP1XX_CHARGE_CUR_1160MA,
    AXP1XX_CHARGE_CUR_1240MA,
    AXP1XX_CHARGE_CUR_1320MA,
} axp1xx_charge_current_t;

typedef uint8_t (*axp_com_fptr_t)(uint8_t dev_addr, uint8_t reg_addr, uint8_t *data, uint8_t len);

class AXP20X_Class
{
public:
    int begin(TwoWire &port = Wire, uint8_t addr = AXP202_SLAVE_ADDRESS, bool isAxp173 = false);
    int begin(axp_com_fptr_t read_cb, axp_com_fptr_t write_cb, uint8_t addr = AXP202_SLAVE_ADDRESS, bool isAxp173 = false);

    // Power Output Control
    int setPowerOutPut(uint8_t ch, bool en);

    bool isBatteryConnect();
    bool isChargeing();
    bool isLDO2Enable();
    bool isLDO3Enable();
    bool isLDO4Enable();
    bool isDCDC3Enable();
    bool isDCDC2Enable();
    bool isChargeingEnable();
    bool isVBUSPlug();
    bool isExtenEnable();

    //Only axp192 chip
    bool isDCDC1Enable();

    //IRQ Status
    bool isAcinOverVoltageIRQ();
    bool isAcinPlugInIRQ();
    bool isAcinRemoveIRQ();
    bool isVbusOverVoltageIRQ();
    bool isVbusPlugInIRQ();
    bool isVbusRemoveIRQ();
    bool isVbusLowVHOLDIRQ();

    bool isBattPlugInIRQ();
    bool isBattRemoveIRQ();
    bool isBattEnterActivateIRQ();
    bool isBattExitActivateIRQ();
    bool isChargingIRQ();
    bool isChargingDoneIRQ();
    bool isBattTempLowIRQ();
    bool isBattTempHighIRQ();

    bool isPEKShortPressIRQ();
    bool isPEKLongtPressIRQ();
    bool isTimerTimeoutIRQ();

    //! Group4 ADC data
    float getAcinVoltage();
    float getAcinCurrent();
    float getVbusVoltage();
    float getVbusCurrent();
    float getTemp();
    float getTSTemp();
    float getGPIO0Voltage();
    float getGPIO1Voltage();
    float getBattInpower();
    float getBattVoltage();
    float getBattChargeCurrent();
    float getBattDischargeCurrent();
    float getSysIPSOUTVoltage();
    uint32_t getBattChargeCoulomb();
    uint32_t getBattDischargeCoulomb();
    float getSettingChargeCurrent();

    int setChargingTargetVoltage(axp_chargeing_vol_t param);
    int enableChargeing(bool en);

    int adc1Enable(uint16_t params, bool en);
    int adc2Enable(uint16_t params, bool en);

    int setTScurrent(axp_ts_pin_current_t current);
    int setTSfunction(axp_ts_pin_function_t func);
    int setTSmode(axp_ts_pin_mode_t mode);

    int setTimer(uint8_t minutes);
    int offTimer();
    int clearTimerStatus();
    /**
     * param:   axp202_startup_time_t or axp192_startup_time_t
     */
    int setStartupTime(uint8_t param);

    /**
     * param: axp_loonPress_time_t
     */
    int setlongPressTime(uint8_t param);

    /**
     * @param  param: axp_poweroff_time_t
     */
    int setShutdownTime(uint8_t param);

    int setTimeOutShutdown(bool en);

    int shutdown();

    /**
     * params: axp_irq_t
     */
    int enableIRQ(uint64_t params, bool en);
    int readIRQ();
    void clearIRQ();

    int setDCDC1Voltage(uint16_t mv); //! Only AXP192 support and AXP173
    // return mv
    uint16_t getDCDC1Voltage(); //! Only AXP192 support and AXP173

    // -----------------

    /*
    !! Chip resource table
    | CHIP     | AXP173           | AXP192           | AXP202           |
    | -------- | ---------------- | ---------------- | ---------------- |
    | DC1      | 0v7~3v5  /1200mA | 0v7~3v5  /1200mA | X                |
    | DC2      | 0v7~2v275/1600mA | 0v7~2v275/1600mA | 0v7~2v275/1600mA |
    | DC3      | X                | 0v7~3v5  /700mA  | 0v7~3v5  /1200mA |
    | LDO1     | 3v3      /30mA   | 3v3      /30mA   | 3v3      /30mA   |
    | LDO2     | 1v8~3v3  /200mA  | 1v8~3v3  /200mA  | 1v8~3v3  /200mA  |
    | LDO3     | 1v8~3v3  /200mA  | 1v8~3v3  /200mA  | 0v7~3v3  /200mA  |
    | LDO4     | 0v7~3v5  /500mA  | X                | 1v8~3v3  /200mA  |
    | LDO5/IO0 | X                | 1v8~3v3  /50mA   | 1v8~3v3  /50mA   |
    */
    int setDCDC2Voltage(uint16_t mv);
    uint16_t getDCDC2Voltage();

    int setDCDC3Voltage(uint16_t mv);
    uint16_t getDCDC3Voltage();

    int setLDO2Voltage(uint16_t mv);
    uint16_t getLDO2Voltage();

    int setLDO3Voltage(uint16_t mv);
    uint16_t getLDO3Voltage();

    int setLDO4Voltage(axp_ldo4_table_t param); //! Only axp202 support
    int setLDO4Voltage(uint16_t mv);            //! Only axp173 support

    // return mv
    uint16_t getLDO4Voltage();                  //! Only axp173/axp202 support

    /**
     * @param  mode: axp_chgled_mode_t
     */
    int setChgLEDMode(axp_chgled_mode_t mode);

    /**
     * @param  mode: axp202_ldo3_mode_t
     */
    int setLDO3Mode(uint8_t mode); //! Only AXP202 support

    int getBattPercentage();

    int debugCharging();
    int debugStatus();
    int limitingOff();

    int setAdcSamplingRate(axp_adc_sampling_rate_t rate);
    uint8_t getAdcSamplingRate();
    float getCoulombData();
    uint8_t getCoulombRegister();
    int setCoulombRegister(uint8_t val);
    int EnableCoulombcounter(void);
    int DisableCoulombcounter(void);
    int StopCoulombcounter(void);
    int ClearCoulombcounter(void);

    int setGPIOMode(axp_gpio_t gpio, axp_gpio_mode_t mode);
    int setGPIOIrq(axp_gpio_t gpio, axp_gpio_irq_t irq);
    int setLDO5Voltage(axp_ldo5_table_t vol);

    int gpioWrite(axp_gpio_t gpio, uint8_t vol);
    int gpioRead(axp_gpio_t gpio);

    // When the chip is axp192 / 173, the allowed values are 0 ~ 15, corresponding to the axp1xx_charge_current_t enumeration
    // When the chip is axp202 allows maximum charging current of 1800mA, minimum 300mA
    int getChargeControlCur();
    int setChargeControlCur(uint16_t mA);

private:
    uint16_t _getRegistH8L5(uint8_t regh8, uint8_t regl5)
    {
        uint8_t hv, lv;
        _readByte(regh8, 1, &hv);
        _readByte(regl5, 1, &lv);
        return (hv << 5) | (lv & 0x1F);
    }

    uint16_t _getRegistResult(uint8_t regh8, uint8_t regl4)
    {
        uint8_t hv, lv;
        _readByte(regh8, 1, &hv);
        _readByte(regl4, 1, &lv);
        return (hv << 4) | (lv & 0x0F);
    }

    int _readByte(uint8_t reg, uint8_t nbytes, uint8_t *data)
    {
        if (_read_cb != nullptr) {
            return _read_cb(_address, reg, data, nbytes);
        }
        if (nbytes == 0 || !data)
            return -1;
        _i2cPort->beginTransmission(_address);
        _i2cPort->write(reg);
        _i2cPort->endTransmission();
        _i2cPort->requestFrom(_address, nbytes);
        uint8_t index = 0;
        while (_i2cPort->available())
            data[index++] = _i2cPort->read();
        return 0;
    }

    int _writeByte(uint8_t reg, uint8_t nbytes, uint8_t *data)
    {
        if (_write_cb != nullptr) {
            return _write_cb(_address, reg, data, nbytes);
        }
        if (nbytes == 0 || !data)
            return -1;
        _i2cPort->beginTransmission(_address);
        _i2cPort->write(reg);
        for (uint8_t i = 0; i < nbytes; i++) {
            _i2cPort->write(data[i]);
        }
        _i2cPort->endTransmission();
        return 0;
    }

    int _setGpioInterrupt(uint8_t *val, int mode, bool en);
    int _axp_probe();
    int _axp_irq_mask(axp_gpio_irq_t irq);

    int _axp192_gpio_set(axp_gpio_t gpio, axp_gpio_mode_t mode);
    int _axp192_gpio_0_select( axp_gpio_mode_t mode);
    int _axp192_gpio_1_select( axp_gpio_mode_t mode);
    int _axp192_gpio_3_select( axp_gpio_mode_t mode);
    int _axp192_gpio_4_select( axp_gpio_mode_t mode);

    int _axp202_gpio_set(axp_gpio_t gpio, axp_gpio_mode_t mode);
    int _axp202_gpio_0_select( axp_gpio_mode_t mode);
    int _axp202_gpio_1_select( axp_gpio_mode_t mode);
    int _axp202_gpio_2_select( axp_gpio_mode_t mode);
    int _axp202_gpio_3_select( axp_gpio_mode_t mode);
    int _axp202_gpio_irq_set(axp_gpio_t gpio, axp_gpio_irq_t irq);
    int _axp202_gpio_write(axp_gpio_t gpio, uint8_t val);
    int _axp202_gpio_read(axp_gpio_t gpio);

    static const uint8_t startupParams[], longPressParams[], shutdownParams[], targetVolParams[];
    static uint8_t _outputReg;
    uint8_t _address, _irq[5], _chip_id, _gpio[4];
    bool _init = false;
    axp_com_fptr_t _read_cb = nullptr;
    axp_com_fptr_t _write_cb = nullptr;
    TwoWire *_i2cPort;
    bool _isAxp173;
};

{'repo_name': 'arendst/Tasmota', 'stars': '11421', 'repo_language': 'HTML', 'file_name': 'spi_flash.h', 'mime_type': 'text/plain', 'hash': -82095582977303489, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: e921390140af1f44ebe7acff87499029
timeCreated: 1438309902
licenseType: Free
MonoImporter:
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'SnpM/LockstepFramework', 'stars': '917', 'repo_language': 'C#', 'file_name': 'LSScenePropertyDrawer.cs', 'mime_type': 'text/x-c++', 'hash': -8928750544904511456, 'source_dataset': 'data'}


/*
 * Copyright (c) 2012-2018 Red Hat, Inc.
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.workspace.infrastructure.kubernetes.server;

import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
import io.fabric8.kubernetes.api.model.ServicePortBuilder;
import io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath;
import io.fabric8.kubernetes.api.model.extensions.HTTPIngressRuleValue;
import io.fabric8.kubernetes.api.model.extensions.Ingress;
import io.fabric8.kubernetes.api.model.extensions.IngressBackend;
import io.fabric8.kubernetes.api.model.extensions.IngressBuilder;
import io.fabric8.kubernetes.api.model.extensions.IngressRule;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.che.api.core.model.workspace.config.ServerConfig;
import org.eclipse.che.api.core.model.workspace.runtime.ServerStatus;
import org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl;
import org.eclipse.che.api.workspace.server.model.impl.ServerImpl;
import org.eclipse.che.api.workspace.shared.Constants;
import org.eclipse.che.commons.lang.Pair;
import org.eclipse.che.workspace.infrastructure.kubernetes.Annotations;
import org.eclipse.che.workspace.infrastructure.kubernetes.Annotations.Serializer;
import org.eclipse.che.workspace.infrastructure.kubernetes.server.external.IngressPathTransformInverter;
import org.eclipse.che.workspace.infrastructure.kubernetes.server.resolver.IngressServerResolver;
import org.eclipse.che.workspace.infrastructure.kubernetes.server.resolver.ServerResolver;
import org.testng.annotations.Test;

/**
 * Test for {@link IngressServerResolver}.
 *
 * @author Sergii Leshchenko
 */
public class IngressServerResolverTest {

  private static final Map<String, String> ATTRIBUTES_MAP = singletonMap("key", "value");
  private static final int CONTAINER_PORT = 3054;
  private static final String INGRESS_IP = "127.0.0.1";
  private static final String INGRESS_RULE_PATH_PREFIX = "/server-8080";
  private static final String INGRESS_PATH_PREFIX = "server-8080";

  @Test
  public void
      testResolvingServersWhenThereIsNoTheCorrespondingServiceAndIngressForTheSpecifiedMachine() {
    // given
    Service nonMatchedByPodService =
        createService("nonMatched", "foreignMachine", CONTAINER_PORT, null);
    Ingress ingress =
        createIngress(
            "nonMatched",
            "foreignMachine",
            Pair.of("http-server", new ServerConfigImpl("3054", "http", "/api", ATTRIBUTES_MAP)));

    ServerResolver serverResolver =
        new IngressServerResolver(
            new NoopPathTransformInverter(),
            singletonList(nonMatchedByPodService),
            singletonList(ingress));

    // when
    Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

    // then
    assertTrue(resolved.isEmpty());
  }

  @Test
  public void testResolvingServersWhenThereIsMatchedIngressForTheSpecifiedMachine() {
    Ingress ingress =
        createIngress(
            "matched",
            "machine",
            Pair.of("http-server", new ServerConfigImpl("3054", "http", "/api/", ATTRIBUTES_MAP)));

    ServerResolver serverResolver =
        new IngressServerResolver(
            new NoopPathTransformInverter(), emptyList(), singletonList(ingress));

    Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

    assertEquals(resolved.size(), 1);
    assertEquals(
        resolved.get("http-server"),
        new ServerImpl()
            .withUrl("http://" + INGRESS_IP + INGRESS_RULE_PATH_PREFIX + "/api/")
            .withStatus(ServerStatus.UNKNOWN)
            .withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054")));
  }

  @Test
  public void testResolvingServersWhenThereIsMatchedIngressForMachineAndServerPathIsNull() {
    Ingress ingress =
        createIngress(
            "matched",
            "machine",
            Pair.of("http-server", new ServerConfigImpl("3054", "http", null, ATTRIBUTES_MAP)));

    ServerResolver serverResolver =
        new IngressServerResolver(
            new NoopPathTransformInverter(), emptyList(), singletonList(ingress));

    Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

    assertEquals(resolved.size(), 1);
    assertEquals(
        resolved.get("http-server"),
        new ServerImpl()
            .withUrl("http://" + INGRESS_IP + INGRESS_RULE_PATH_PREFIX + "/")
            .withStatus(ServerStatus.UNKNOWN)
            .withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054")));
  }

  @Test
  public void testResolvingServersWhenThereIsMatchedIngressForMachineAndServerPathIsEmpty() {
    Ingress ingress =
        createIngress(
            "matched",
            "machine",
            Pair.of("http-server", new ServerConfigImpl("3054", "http", "", ATTRIBUTES_MAP)));

    ServerResolver serverResolver =
        new IngressServerResolver(
            new NoopPathTransformInverter(), emptyList(), singletonList(ingress));

    Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

    assertEquals(resolved.size(), 1);
    assertEquals(
        resolved.get("http-server"),
        new ServerImpl()
            .withUrl("http://" + INGRESS_IP + INGRESS_RULE_PATH_PREFIX + "/")
            .withStatus(ServerStatus.UNKNOWN)
            .withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054")));
  }

  @Test
  public void testResolvingServersWhenThereIsMatchedIngressForMachineAndServerPathIsRelative() {
    Ingress ingress =
        createIngress(
            "matched",
            "machine",
            Pair.of("http-server", new ServerConfigImpl("3054", "http", "api", ATTRIBUTES_MAP)));

    ServerResolver serverResolver =
        new IngressServerResolver(
            new NoopPathTransformInverter(), emptyList(), singletonList(ingress));

    Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

    assertEquals(resolved.size(), 1);
    assertEquals(
        resolved.get("http-server"),
        new ServerImpl()
            .withUrl("http://" + INGRESS_IP + INGRESS_RULE_PATH_PREFIX + "/api/")
            .withStatus(ServerStatus.UNKNOWN)
            .withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054")));
  }

  @Test
  public void testResolvingInternalServers() {
    Service service =
        createService(
            "service11",
            "machine",
            CONTAINER_PORT,
            singletonMap(
                "http-server", new ServerConfigImpl("3054", "http", "api", ATTRIBUTES_MAP)));

    ServerResolver serverResolver =
        new IngressServerResolver(
            new NoopPathTransformInverter(), singletonList(service), emptyList());

    Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

    assertEquals(resolved.size(), 1);
    assertEquals(
        resolved.get("http-server"),
        new ServerImpl()
            .withUrl("http://service11:3054/api")
            .withStatus(ServerStatus.UNKNOWN)
            .withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054")));
  }

  @Test
  public void testResolvingInternalServersWithPortWithTransportProtocol() {
    Service service =
        createService(
            "service11",
            "machine",
            CONTAINER_PORT,
            singletonMap(
                "http-server", new ServerConfigImpl("3054/udp", "xxx", "api", ATTRIBUTES_MAP)));

    ServerResolver serverResolver =
        new IngressServerResolver(
            new NoopPathTransformInverter(), singletonList(service), emptyList());

    Map<String, ServerImpl> resolved = serverResolver.resolve("machine");

    assertEquals(resolved.size(), 1);
    assertEquals(
        resolved.get("http-server"),
        new ServerImpl()
            .withUrl("xxx://service11:3054/api")
            .withStatus(ServerStatus.UNKNOWN)
            .withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054")));
  }

  private Service createService(
      String name, String machineName, Integer port, Map<String, ServerConfigImpl> servers) {
    Serializer serializer = Annotations.newSerializer();
    serializer.machineName(machineName);
    if (servers != null) {
      serializer.servers(servers);
    }

    return new ServiceBuilder()
        .withNewMetadata()
        .withName(name)
        .withAnnotations(serializer.annotations())
        .endMetadata()
        .withNewSpec()
        .withPorts(
            new ServicePortBuilder()
                .withPort(port)
                .withNewTargetPort()
                .withIntVal(port)
                .endTargetPort()
                .build())
        .endSpec()
        .build();
  }

  private Ingress createIngress(
      String name, String machineName, Pair<String, ServerConfig> server) {
    Serializer serializer = Annotations.newSerializer();
    serializer.machineName(machineName);
    serializer.server(server.first, server.second);

    return new IngressBuilder()
        .withNewMetadata()
        .withName(name)
        .withAnnotations(serializer.annotations())
        .endMetadata()
        .withNewSpec()
        .withRules(
            new IngressRule(
                null,
                new HTTPIngressRuleValue(
                    singletonList(
                        new HTTPIngressPath(
                            new IngressBackend(name, new IntOrString("8080")),
                            INGRESS_PATH_PREFIX)))))
        .endSpec()
        .withNewStatus()
        .withNewLoadBalancer()
        .addNewIngress()
        .withIp("127.0.0.1")
        .endIngress()
        .endLoadBalancer()
        .endStatus()
        .build();
  }

  private Map<String, String> defaultAttributeAnd(String key, String value) {
    HashMap<String, String> attributes = new HashMap<>(ATTRIBUTES_MAP);
    attributes.put(key, value);
    return attributes;
  }

  private static final class NoopPathTransformInverter extends IngressPathTransformInverter {
    NoopPathTransformInverter() {
      super("%s");
    }
  }
}

{'repo_name': 'eclipse/che', 'stars': '6171', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -755525689813484442, 'source_dataset': 'data'}


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

	<meta charset="UTF-8" />
	<title>Infragistics jQuery Client Editors - Date Picker </title>
	<link type="text/css" href="../../../../src/css/themes/infragistics/infragistics.theme.css" rel="stylesheet" />
	<link type="text/css" href="../../../../src/css/structure/modules/infragistics.ui.popover.css" rel="stylesheet" />
	<link type="text/css" href="../../../../src/css/structure/modules/infragistics.ui.notifier.css" rel="stylesheet" />
	<link type="text/css" href="../../../../src/css/structure/modules/infragistics.ui.editors.css" rel="stylesheet" />

	<link type="text/css" href="../../../../node_modules/qunitjs/qunit/qunit.css" rel="stylesheet" media="screen" />

Test results

{'repo_name': 'IgniteUI/ignite-ui', 'stars': '464', 'repo_language': 'JavaScript', 'file_name': 'basic-usage.html', 'mime_type': 'text/html', 'hash': -9187543058592424912, 'source_dataset': 'data'}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.example.transaction.base.seata.raw.jdbc;

import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.apache.shardingsphere.transaction.core.TransactionTypeHolder;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Order service.
 *
 */
class SeataATOrderService {

    private final DataSource dataSource;

    SeataATOrderService(final String yamlConfigFile) throws IOException, SQLException {
        dataSource = YamlShardingSphereDataSourceFactory.createDataSource(getFile(yamlConfigFile));
    }

    private File getFile(final String fileName) {
        return new File(SeataATOrderService.class.getResource(fileName).getFile());
    }

    /**
     * Init.
     */
    void init() throws SQLException {
        try (Connection connection = dataSource.getConnection()) {
            Statement statement = connection.createStatement();
            statement.execute("DROP TABLE IF EXISTS t_order");
            statement.execute("CREATE TABLE t_order (order_id BIGINT AUTO_INCREMENT, user_id INT NOT NULL, status VARCHAR(50), PRIMARY KEY (order_id))");
        }
    }

    /**
     * Clean up.
     */
    void cleanup() throws SQLException {
        try (Connection connection = dataSource.getConnection()) {
            Statement statement = connection.createStatement();
            statement.execute("DROP TABLE IF EXISTS t_order");
        }
    }

    /**
     * Execute XA.
     *
     * @throws SQLException SQL exception
     */
    void insert() throws SQLException {
        TransactionTypeHolder.set(TransactionType.BASE);
        try (Connection connection = dataSource.getConnection()) {
            connection.setAutoCommit(false);
            PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO t_order (user_id, status) VALUES (?, ?)");
            doInsert(preparedStatement);
            connection.commit();
        } finally {
            TransactionTypeHolder.clear();
        }
    }

    /**
     * Execute XA with exception.
     *
     * @throws SQLException SQL exception
     */
    void insertFailed() throws SQLException {
        TransactionTypeHolder.set(TransactionType.BASE);
        try (Connection connection = dataSource.getConnection()) {
            connection.setAutoCommit(false);
            PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO t_order (user_id, status) VALUES (?, ?)");
            doInsert(preparedStatement);
            connection.rollback();
        } finally {
            TransactionTypeHolder.clear();
        }
    }

    private void doInsert(final PreparedStatement preparedStatement) throws SQLException {
        for (int i = 0; i < 10; i++) {
            preparedStatement.setObject(1, i);
            preparedStatement.setObject(2, "init");
            preparedStatement.executeUpdate();
        }
    }

    /**
     * Select all.
     *
     * @return record count
     */
    int selectAll() throws SQLException {
        int result = 0;
        try (Connection connection = dataSource.getConnection()) {
            Statement statement = connection.createStatement();
            statement.executeQuery("SELECT COUNT(1) AS count FROM t_order");
            ResultSet resultSet = statement.getResultSet();
            while (resultSet.next()) {
                result = resultSet.getInt(1);
            }
        }
        return result;
    }
}

{'repo_name': 'apache/shardingsphere', 'stars': '11625', 'repo_language': 'Java', 'file_name': 'MockedDataSource.java', 'mime_type': 'text/x-java', 'hash': 6141488950725383206, 'source_dataset': 'data'}


#ifndef _SHA_H
#define _SHA_H

typedef struct
{
    ULONG flag;
    UCHAR hash[20];
    ULONG state[5];
    ULONG count[2];
    UCHAR buffer[64];
} A_SHA_CTX;

VOID A_SHAInit(
    _Out_ A_SHA_CTX *Context
    );

VOID A_SHAUpdate(
    _Inout_ A_SHA_CTX *Context,
    _In_reads_bytes_(Length) UCHAR *Input,
    _In_ ULONG Length
    );

VOID A_SHAFinal(
    _Inout_ A_SHA_CTX *Context,
    _Out_writes_bytes_(20) UCHAR *Hash
    );

#endif

{'repo_name': 'processhacker/processhacker', 'stars': '3488', 'repo_language': 'C', 'file_name': 'growl.h', 'mime_type': 'text/x-c', 'hash': 5974927382071299737, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/ripple_material_light" />

{'repo_name': 'dtrung98/MusicPlayer', 'stars': '149', 'repo_language': 'Java', 'file_name': 'ExampleUnitTest.java', 'mime_type': 'text/html', 'hash': -7618265787110477828, 'source_dataset': 'data'}


using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VirtualRadar.WebServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VirtualRadar.WebServer")]
[assembly: AssemblyCopyright("Copyright ©  2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ec7e1bc3-41a1-4616-b527-56b0ebe47976")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

{'repo_name': 'vradarserver/vrs', 'stars': '147', 'repo_language': 'C#', 'file_name': 'OptionsView.cs', 'mime_type': 'text/plain', 'hash': 2094722416742933454, 'source_dataset': 'data'}


/*
 * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package org.jetbrains.kotlin.tools.projectWizard.wizard.service

import com.intellij.ide.util.PropertiesComponent
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.tools.projectWizard.core.service.SettingSavingWizardService

class IdeaSettingSavingWizardService : SettingSavingWizardService, IdeaWizardService {
    override fun saveSettingValue(settingPath: String, settingValue: String) = runWriteAction {
        PropertiesComponent.getInstance().setValue(PATH_PREFIX + settingPath, settingValue)
    }

    override fun getSettingValue(settingPath: String): String? = runReadAction {
        PropertiesComponent.getInstance().getValue(PATH_PREFIX + settingPath)
    }

    companion object {
        private const val PATH_PREFIX = "NewKotlinWizard."
    }
}

{'repo_name': 'JetBrains/kotlin', 'stars': '32558', 'repo_language': 'Kotlin', 'file_name': 'OptionalParameters1.kt', 'mime_type': 'text/plain', 'hash': 7775914045029383337, 'source_dataset': 'data'}


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

package org.jsonschema2pojo.rules;

import static com.sun.codemodel.JExpr.*;
import static com.sun.codemodel.JMod.*;

import java.util.Iterator;
import java.util.Map;

import org.jsonschema2pojo.Schema;
import org.jsonschema2pojo.util.LanguageFeatures;
import org.jsonschema2pojo.util.Models;

import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JConditional;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldRef;
import com.sun.codemodel.JInvocation;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JOp;
import com.sun.codemodel.JSwitch;
import com.sun.codemodel.JType;
import com.sun.codemodel.JTypeVar;
import com.sun.codemodel.JVar;

/**
 * Adds methods for dynamically getting, setting, and building properties.
 *
 * @author Christian Trimble
 *
 */
public class DynamicPropertiesRule implements Rule<JDefinedClass, JDefinedClass> {

    public static final String NOT_FOUND_VALUE_FIELD = "NOT_FOUND_VALUE";
    public static final String SETTER_NAME = "set";
    public static final String GETTER_NAME = "get";
    public static final String BUILDER_NAME = "with";
    public static final String DEFINED_SETTER_NAME = "declaredProperty";
    public static final String DEFINED_GETTER_NAME = "declaredPropertyOrNotFound";

    private RuleFactory ruleFactory;

    public DynamicPropertiesRule(RuleFactory ruleFactory) {
        this.ruleFactory = ruleFactory;
    }

    /**
     * This rule adds dynamic getter, setter and builder methods based on the properties and additional properties
     * defined in a schema.
     *

     * If accessors are being generated, then methods for getting and setting properties by name will be added.  These
     * methods first attempt to call the appropriate getter or setter for the property.  If the named property is not defined,
     * then the additional properties map is used.
     *

     * If builders are being generated, then a method for building properties by name will be added.  This method first
     * attempts to call the builder for the property.  If no property with the supplied name is defined, then the additional
     * properties map is used.
     *

     * The methods generated by this class throw an IllegalArgumentException, if the name specified for the property is unknown and
     * additional properties are not enabled.  A ClassCastException will be thrown, when the value being set is incompatible with the
     * type of the named property.
     *
     * @param nodeName
     *            the name of the node for which dynamic getters, setters, and builders are being added.
     * @param node
     *            the properties node, containing property names and their
     *            definition
     * @param parent
     *            the parent node
     * @param jclass
     *            the Java type which will have the given properties added
     * @param currentSchema
     *            the schema being implemented
     * @return the given jclass
     */
    @Override
    public JDefinedClass apply(String nodeName, JsonNode node, JsonNode parent, JDefinedClass jclass, Schema currentSchema) {
        if (!ruleFactory.getGenerationConfig().isIncludeDynamicAccessors() ||
                (!ruleFactory.getGenerationConfig().isIncludeDynamicSetters() &&
                !ruleFactory.getGenerationConfig().isIncludeDynamicGetters() &&
                !ruleFactory.getGenerationConfig().isIncludeDynamicBuilders())) {
            return jclass;
        }

        boolean isIncludeGetters = ruleFactory.getGenerationConfig().isIncludeGetters();
        boolean isIncludeSetters = ruleFactory.getGenerationConfig().isIncludeSetters();
        boolean isGenerateBuilders = ruleFactory.getGenerationConfig().isGenerateBuilders();

        if (isIncludeGetters || isIncludeSetters || isGenerateBuilders) {
            if (LanguageFeatures.canUseJava7(ruleFactory.getGenerationConfig())) {
                if (isIncludeSetters) {
                    addInternalSetMethodJava7(jclass, node);
                }
                if (isIncludeGetters) {
                    addInternalGetMethodJava7(jclass, node);
                }
            } else {
                if (isIncludeSetters) {
                    addInternalSetMethodJava6(jclass, node);
                }
                if (isIncludeGetters) {
                    addInternalGetMethodJava6(jclass, node);
                }
            }
        }

        if (isIncludeGetters) {
            addGetMethods(jclass);
        }

        if (isIncludeSetters) {
            addSetMethods(jclass);
        }

        if (isGenerateBuilders) {
            addWithMethods(jclass);
        }

        return jclass;
    }

    void addGetMethods(JDefinedClass jclass) {
        JFieldRef notFoundVar = getOrAddNotFoundVar(jclass);
        JMethod internalGetMethod = this.getInternalGetMethod(jclass);
        addPublicGetMethod(jclass, internalGetMethod, notFoundVar);
    }

    JFieldRef getOrAddNotFoundVar(JDefinedClass jclass) {
        jclass.field(PROTECTED | STATIC | FINAL, Object.class, NOT_FOUND_VALUE_FIELD,
                _new(jclass.owner()._ref(Object.class)));
        return jclass.staticRef(NOT_FOUND_VALUE_FIELD);
    }

    private JMethod addPublicGetMethod(JDefinedClass jclass, JMethod internalGetMethod, JFieldRef notFoundValue) {
        JMethod method = jclass.method(PUBLIC, jclass.owner()._ref(Object.class), GETTER_NAME);
        JTypeVar returnType = method.generify("T");
        method.type(returnType);
        Models.suppressWarnings(method, "unchecked");
        JVar nameParam = method.param(String.class, "name");
        JBlock body = method.body();
        JVar valueVar = body.decl(jclass.owner()._ref(Object.class), "value",
                invoke(internalGetMethod).arg(nameParam).arg(notFoundValue));
        JConditional found = method.body()._if(notFoundValue.ne(valueVar));
        found._then()._return(cast(returnType, valueVar));
        JBlock notFound = found._else();

        JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
        if (getAdditionalProperties != null) {
            notFound._return(cast(returnType, invoke(getAdditionalProperties).invoke("get").arg(nameParam)));
        } else {
            notFound._throw(illegalArgumentInvocation(jclass, nameParam));
        }

        return method;
    }

    private JMethod addInternalGetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) {
        JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
        JVar nameParam = method.param(String.class, "name");
        JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
        JBlock body = method.body();
        JSwitch propertySwitch = body._switch(nameParam);
        if (propertiesNode != null) {
            for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
                Map.Entry<String, JsonNode> property = properties.next();
                String propertyName = property.getKey();
                JsonNode node = property.getValue();
                String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
                JType propertyType = jclass.fields().get(fieldName).type();

                addGetPropertyCase(jclass, propertySwitch, propertyName, propertyType, node);
            }
        }
        JClass extendsType = jclass._extends();
        if (extendsType != null && extendsType instanceof JDefinedClass) {
            JDefinedClass parentClass = (JDefinedClass) extendsType;
            JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
                    new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
            propertySwitch._default().body()
            ._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
        } else {
            propertySwitch._default().body()
            ._return(notFoundParam);
        }

        return method;
    }

    private JMethod addInternalGetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
        JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME);
        JVar nameParam = method.param(String.class, "name");
        JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue");
        JBlock body = method.body();
        JConditional propertyConditional = null;

        if (propertiesNode != null) {
            for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
                Map.Entry<String, JsonNode> property = properties.next();
                String propertyName = property.getKey();
                JsonNode node = property.getValue();
                String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
                JType propertyType = jclass.fields().get(fieldName).type();

                JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
                if (propertyConditional == null) {
                    propertyConditional = body._if(condition);
                } else {
                    propertyConditional = propertyConditional._elseif(condition);
                }
                JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {});
                propertyConditional._then()._return(invoke(propertyGetter));
            }
        }

        JClass extendsType = jclass._extends();
        JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();
        if (extendsType != null && extendsType instanceof JDefinedClass) {
            JDefinedClass parentClass = (JDefinedClass) extendsType;
            JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME,
                    new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
            lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam));
        } else {
            lastBlock._return(notFoundParam);
        }

        return method;
    }

    private void addGetPropertyCase(JDefinedClass jclass, JSwitch propertySwitch, String propertyName, JType propertyType, JsonNode node) {
        JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {});
        propertySwitch._case(lit(propertyName)).body()
        ._return(invoke(propertyGetter));
    }

    private void addSetMethods(JDefinedClass jclass) {
        JMethod internalSetMethod = getInternalSetMethod(jclass);
        addPublicSetMethod(jclass, internalSetMethod);
    }

    private JMethod addPublicSetMethod(JDefinedClass jclass, JMethod internalSetMethod) {
        JMethod method = jclass.method(PUBLIC, jclass.owner().VOID, SETTER_NAME);
        JVar nameParam = method.param(String.class, "name");
        JVar valueParam = method.param(Object.class, "value");
        JBlock body = method.body();
        JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

        // if we have additional properties, then put value.
        JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
        if (getAdditionalProperties != null) {
            JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
            notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                    .arg(cast(additionalPropertiesType, valueParam)));
        }
        // else throw exception.
        else {
            notFound._throw(illegalArgumentInvocation(jclass, nameParam));
        }

        return method;
    }

    private void addWithMethods(JDefinedClass jclass) {
        JMethod internalSetMethod = getInternalSetMethod(jclass);
        addPublicWithMethod(jclass, internalSetMethod);
    }

    private JMethod addPublicWithMethod(JDefinedClass jclass, JMethod internalSetMethod) {
        JMethod method = jclass.method(PUBLIC, jclass, BUILDER_NAME);
        JVar nameParam = method.param(String.class, "name");
        JVar valueParam = method.param(Object.class, "value");
        JBlock body = method.body();
        JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

        // if we have additional properties, then put value.
        JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
        if (getAdditionalProperties != null) {
            JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
            notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                    .arg(cast(additionalPropertiesType, valueParam)));
        }
        // else throw exception.
        else {
            notFound._throw(illegalArgumentInvocation(jclass, nameParam));
        }
        body._return(_this());

        return method;
    }

    private JMethod addInternalSetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) {
        JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
        JVar nameParam = method.param(String.class, "name");
        JVar valueParam = method.param(Object.class, "value");
        JBlock body = method.body();
        JSwitch propertySwitch = body._switch(nameParam);
        if (propertiesNode != null) {
            for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
                Map.Entry<String, JsonNode> property = properties.next();
                String propertyName = property.getKey();
                JsonNode node = property.getValue();
                String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
                JType propertyType = jclass.fields().get(fieldName).type();

                addSetPropertyCase(jclass, propertySwitch, propertyName, propertyType, valueParam, node);
            }
        }
        JBlock defaultBlock = propertySwitch._default().body();
        JClass extendsType = jclass._extends();
        if (extendsType != null && extendsType instanceof JDefinedClass) {
            JDefinedClass parentClass = (JDefinedClass) extendsType;
            JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
                    new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
            defaultBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
        } else {
            defaultBlock._return(FALSE);
        }
        return method;
    }

    private JMethod addInternalSetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) {
        JMethod method = jclass.method(PROTECTED, jclass.owner().BOOLEAN, DEFINED_SETTER_NAME);
        JVar nameParam = method.param(String.class, "name");
        JVar valueParam = method.param(Object.class, "value");
        JBlock body = method.body();
        JConditional propertyConditional = null;
        if (propertiesNode != null) {
            for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) {
                Map.Entry<String, JsonNode> property = properties.next();
                String propertyName = property.getKey();
                JsonNode node = property.getValue();
                String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node);
                JType propertyType = jclass.fields().get(fieldName).type();
                JExpression condition = lit(propertyName).invoke("equals").arg(nameParam);
                propertyConditional = propertyConditional == null ? propertyConditional = body._if(condition)
                        : propertyConditional._elseif(condition);

                JBlock callSite = propertyConditional._then();
                addSetProperty(jclass, callSite, propertyName, propertyType, valueParam, node);
                callSite._return(TRUE);
            }
        }
        JClass extendsType = jclass._extends();
        JBlock lastBlock = propertyConditional == null ? body : propertyConditional._else();

        if (extendsType != null && extendsType instanceof JDefinedClass) {
            JDefinedClass parentClass = (JDefinedClass) extendsType;
            JMethod parentMethod = parentClass.getMethod(DEFINED_SETTER_NAME,
                    new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) });
            lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(valueParam));
        } else {
            lastBlock._return(FALSE);
        }
        return method;
    }

    private JMethod getInternalSetMethod(JDefinedClass jclass) {
        return jclass.getMethod(DEFINED_SETTER_NAME,
                new JType[] { jclass.owner().ref(String.class), jclass.owner().ref(Object.class) });
    }

    private JMethod getInternalGetMethod(JDefinedClass jclass) {
        return jclass.getMethod(DEFINED_GETTER_NAME,
                new JType[] { jclass.owner().ref(String.class), jclass.owner().ref(Object.class) });
    }

    private void addSetPropertyCase(JDefinedClass jclass, JSwitch setterSwitch, String propertyName, JType propertyType, JVar valueVar, JsonNode node) {
        JBlock setterBody = setterSwitch._case(lit(propertyName)).body();
        addSetProperty(jclass, setterBody, propertyName, propertyType, valueVar, node);
        setterBody._return(TRUE);
    }

    private void addSetProperty(JDefinedClass jclass, JBlock callSite, String propertyName, JType propertyType, JVar valueVar, JsonNode node) {
        JMethod propertySetter = jclass.getMethod(getSetterName(propertyName, node), new JType[] { propertyType });
        JConditional isInstance = callSite._if(valueVar._instanceof(propertyType.boxify().erasure()));
        isInstance._then()
        .invoke(propertySetter).arg(cast(propertyType.boxify(), valueVar));
        isInstance._else()
        ._throw(illegalArgumentInvocation(jclass, propertyName, propertyType, valueVar));
    }

    private JInvocation illegalArgumentInvocation(JDefinedClass jclass, JVar propertyName) {
        return _new(jclass.owner()._ref(IllegalArgumentException.class))
                .arg(lit("property \"").plus(propertyName).plus(lit("\" is not defined")));
    }

    private JInvocation illegalArgumentInvocation(JDefinedClass jclass, String propertyName, JType propertyType, JVar valueVar) {
        return _new(jclass.owner()._ref(IllegalArgumentException.class))
                .arg(lit("property \"" + propertyName + "\" is of type \"" + propertyType.fullName() + "\", but got ")
                        .plus(valueVar.invoke("getClass").invoke("toString")));
    }

    private String getSetterName(String propertyName, JsonNode node) {
        return ruleFactory.getNameHelper().getSetterName(propertyName, node);
    }

    private String getGetterName(String propertyName, JType type, JsonNode node) {
        return ruleFactory.getNameHelper().getGetterName(propertyName, type, node);
    }
}

{'repo_name': 'joelittlejohn/jsonschema2pojo', 'stars': '5148', 'repo_language': 'Java', 'file_name': 'Example.java', 'mime_type': 'text/x-c', 'hash': -1918148341852885584, 'source_dataset': 'data'}


// SPDX-License-Identifier: GPL-2.0
/*
 * Firmware replacement code.
 *
 * Work around broken BIOSes that don't set an aperture, only set the
 * aperture in the AGP bridge, or set too small aperture.
 *
 * If all fails map the aperture over some low memory.  This is cheaper than
 * doing bounce buffering. The memory is lost. This is done at early boot
 * because only the bootmem allocator can allocate 32+MB.
 *
 * Copyright 2002 Andi Kleen, SuSE Labs.
 */
#define pr_fmt(fmt) "AGP: " fmt

#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/memblock.h>
#include <linux/mmzone.h>
#include <linux/pci_ids.h>
#include <linux/pci.h>
#include <linux/bitops.h>
#include <linux/suspend.h>
#include <asm/e820/api.h>
#include <asm/io.h>
#include <asm/iommu.h>
#include <asm/gart.h>
#include <asm/pci-direct.h>
#include <asm/dma.h>
#include <asm/amd_nb.h>
#include <asm/x86_init.h>

/*
 * Using 512M as goal, in case kexec will load kernel_big
 * that will do the on-position decompress, and could overlap with
 * with the gart aperture that is used.
 * Sequence:
 * kernel_small
 * ==> kexec (with kdump trigger path or gart still enabled)
 * ==> kernel_small (gart area become e820_reserved)
 * ==> kexec (with kdump trigger path or gart still enabled)
 * ==> kerne_big (uncompressed size will be big than 64M or 128M)
 * So don't use 512M below as gart iommu, leave the space for kernel
 * code for safe.
 */
#define GART_MIN_ADDR	(512ULL << 20)
#define GART_MAX_ADDR	(1ULL   << 32)

int gart_iommu_aperture;
int gart_iommu_aperture_disabled __initdata;
int gart_iommu_aperture_allowed __initdata;

int fallback_aper_order __initdata = 1; /* 64MB */
int fallback_aper_force __initdata;

int fix_aperture __initdata = 1;

/* This code runs before the PCI subsystem is initialized, so just
   access the northbridge directly. */

static u32 __init allocate_aperture(void)
{
	u32 aper_size;
	unsigned long addr;

	/* aper_size should <= 1G */
	if (fallback_aper_order > 5)
		fallback_aper_order = 5;
	aper_size = (32 * 1024 * 1024) << fallback_aper_order;

	/*
	 * Aperture has to be naturally aligned. This means a 2GB aperture
	 * won't have much chance of finding a place in the lower 4GB of
	 * memory. Unfortunately we cannot move it up because that would
	 * make the IOMMU useless.
	 */
	addr = memblock_find_in_range(GART_MIN_ADDR, GART_MAX_ADDR,
				      aper_size, aper_size);
	if (!addr) {
		pr_err("Cannot allocate aperture memory hole [mem %#010lx-%#010lx] (%uKB)\n",
		       addr, addr + aper_size - 1, aper_size >> 10);
		return 0;
	}
	memblock_reserve(addr, aper_size);
	pr_info("Mapping aperture over RAM [mem %#010lx-%#010lx] (%uKB)\n",
		addr, addr + aper_size - 1, aper_size >> 10);
	register_nosave_region(addr >> PAGE_SHIFT,
			       (addr+aper_size) >> PAGE_SHIFT);

	return (u32)addr;
}

/* Find a PCI capability */
static u32 __init find_cap(int bus, int slot, int func, int cap)
{
	int bytes;
	u8 pos;

	if (!(read_pci_config_16(bus, slot, func, PCI_STATUS) &
						PCI_STATUS_CAP_LIST))
		return 0;

	pos = read_pci_config_byte(bus, slot, func, PCI_CAPABILITY_LIST);
	for (bytes = 0; bytes < 48 && pos >= 0x40; bytes++) {
		u8 id;

		pos &= ~3;
		id = read_pci_config_byte(bus, slot, func, pos+PCI_CAP_LIST_ID);
		if (id == 0xff)
			break;
		if (id == cap)
			return pos;
		pos = read_pci_config_byte(bus, slot, func,
						pos+PCI_CAP_LIST_NEXT);
	}
	return 0;
}

/* Read a standard AGPv3 bridge header */
static u32 __init read_agp(int bus, int slot, int func, int cap, u32 *order)
{
	u32 apsize;
	u32 apsizereg;
	int nbits;
	u32 aper_low, aper_hi;
	u64 aper;
	u32 old_order;

	pr_info("pci 0000:%02x:%02x:%02x: AGP bridge\n", bus, slot, func);
	apsizereg = read_pci_config_16(bus, slot, func, cap + 0x14);
	if (apsizereg == 0xffffffff) {
		pr_err("pci 0000:%02x:%02x.%d: APSIZE unreadable\n",
		       bus, slot, func);
		return 0;
	}

	/* old_order could be the value from NB gart setting */
	old_order = *order;

	apsize = apsizereg & 0xfff;
	/* Some BIOS use weird encodings not in the AGPv3 table. */
	if (apsize & 0xff)
		apsize |= 0xf00;
	nbits = hweight16(apsize);
	*order = 7 - nbits;
	if ((int)*order < 0) /* < 32MB */
		*order = 0;

	aper_low = read_pci_config(bus, slot, func, 0x10);
	aper_hi = read_pci_config(bus, slot, func, 0x14);
	aper = (aper_low & ~((1<<22)-1)) | ((u64)aper_hi << 32);

	/*
	 * On some sick chips, APSIZE is 0. It means it wants 4G
	 * so let double check that order, and lets trust AMD NB settings:
	 */
	pr_info("pci 0000:%02x:%02x.%d: AGP aperture [bus addr %#010Lx-%#010Lx] (old size %uMB)\n",
		bus, slot, func, aper, aper + (32ULL << (old_order + 20)) - 1,
		32 << old_order);
	if (aper + (32ULL<<(20 + *order)) > 0x100000000ULL) {
		pr_info("pci 0000:%02x:%02x.%d: AGP aperture size %uMB (APSIZE %#x) is not right, using settings from NB\n",
			bus, slot, func, 32 << *order, apsizereg);
		*order = old_order;
	}

	pr_info("pci 0000:%02x:%02x.%d: AGP aperture [bus addr %#010Lx-%#010Lx] (%uMB, APSIZE %#x)\n",
		bus, slot, func, aper, aper + (32ULL << (*order + 20)) - 1,
		32 << *order, apsizereg);

	if (!aperture_valid(aper, (32*1024*1024) << *order, 32<<20))
		return 0;
	return (u32)aper;
}

/*
 * Look for an AGP bridge. Windows only expects the aperture in the
 * AGP bridge and some BIOS forget to initialize the Northbridge too.
 * Work around this here.
 *
 * Do an PCI bus scan by hand because we're running before the PCI
 * subsystem.
 *
 * All AMD AGP bridges are AGPv3 compliant, so we can do this scan
 * generically. It's probably overkill to always scan all slots because
 * the AGP bridges should be always an own bus on the HT hierarchy,
 * but do it here for future safety.
 */
static u32 __init search_agp_bridge(u32 *order, int *valid_agp)
{
	int bus, slot, func;

	/* Poor man's PCI discovery */
	for (bus = 0; bus < 256; bus++) {
		for (slot = 0; slot < 32; slot++) {
			for (func = 0; func < 8; func++) {
				u32 class, cap;
				u8 type;
				class = read_pci_config(bus, slot, func,
							PCI_CLASS_REVISION);
				if (class == 0xffffffff)
					break;

				switch (class >> 16) {
				case PCI_CLASS_BRIDGE_HOST:
				case PCI_CLASS_BRIDGE_OTHER: /* needed? */
					/* AGP bridge? */
					cap = find_cap(bus, slot, func,
							PCI_CAP_ID_AGP);
					if (!cap)
						break;
					*valid_agp = 1;
					return read_agp(bus, slot, func, cap,
							order);
				}

				/* No multi-function device? */
				type = read_pci_config_byte(bus, slot, func,
							       PCI_HEADER_TYPE);
				if (!(type & 0x80))
					break;
			}
		}
	}
	pr_info("No AGP bridge found\n");

	return 0;
}

static bool gart_fix_e820 __initdata = true;

static int __init parse_gart_mem(char *p)
{
	return kstrtobool(p, &gart_fix_e820);
}
early_param("gart_fix_e820", parse_gart_mem);

void __init early_gart_iommu_check(void)
{
	/*
	 * in case it is enabled before, esp for kexec/kdump,
	 * previous kernel already enable that. memset called
	 * by allocate_aperture/__alloc_bootmem_nopanic cause restart.
	 * or second kernel have different position for GART hole. and new
	 * kernel could use hole as RAM that is still used by GART set by
	 * first kernel
	 * or BIOS forget to put that in reserved.
	 * try to update e820 to make that region as reserved.
	 */
	u32 agp_aper_order = 0;
	int i, fix, slot, valid_agp = 0;
	u32 ctl;
	u32 aper_size = 0, aper_order = 0, last_aper_order = 0;
	u64 aper_base = 0, last_aper_base = 0;
	int aper_enabled = 0, last_aper_enabled = 0, last_valid = 0;

	if (!amd_gart_present())
		return;

	if (!early_pci_allowed())
		return;

	/* This is mostly duplicate of iommu_hole_init */
	search_agp_bridge(&agp_aper_order, &valid_agp);

	fix = 0;
	for (i = 0; amd_nb_bus_dev_ranges[i].dev_limit; i++) {
		int bus;
		int dev_base, dev_limit;

		bus = amd_nb_bus_dev_ranges[i].bus;
		dev_base = amd_nb_bus_dev_ranges[i].dev_base;
		dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;

		for (slot = dev_base; slot < dev_limit; slot++) {
			if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
				continue;

			ctl = read_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL);
			aper_enabled = ctl & GARTEN;
			aper_order = (ctl >> 1) & 7;
			aper_size = (32 * 1024 * 1024) << aper_order;
			aper_base = read_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE) & 0x7fff;
			aper_base <<= 25;

			if (last_valid) {
				if ((aper_order != last_aper_order) ||
				    (aper_base != last_aper_base) ||
				    (aper_enabled != last_aper_enabled)) {
					fix = 1;
					break;
				}
			}

			last_aper_order = aper_order;
			last_aper_base = aper_base;
			last_aper_enabled = aper_enabled;
			last_valid = 1;
		}
	}

	if (!fix && !aper_enabled)
		return;

	if (!aper_base || !aper_size || aper_base + aper_size > 0x100000000UL)
		fix = 1;

	if (gart_fix_e820 && !fix && aper_enabled) {
		if (e820__mapped_any(aper_base, aper_base + aper_size,
				    E820_TYPE_RAM)) {
			/* reserve it, so we can reuse it in second kernel */
			pr_info("e820: reserve [mem %#010Lx-%#010Lx] for GART\n",
				aper_base, aper_base + aper_size - 1);
			e820__range_add(aper_base, aper_size, E820_TYPE_RESERVED);
			e820__update_table_print();
		}
	}

	if (valid_agp)
		return;

	/* disable them all at first */
	for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) {
		int bus;
		int dev_base, dev_limit;

		bus = amd_nb_bus_dev_ranges[i].bus;
		dev_base = amd_nb_bus_dev_ranges[i].dev_base;
		dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;

		for (slot = dev_base; slot < dev_limit; slot++) {
			if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
				continue;

			ctl = read_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL);
			ctl &= ~GARTEN;
			write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl);
		}
	}

}

static int __initdata printed_gart_size_msg;

int __init gart_iommu_hole_init(void)
{
	u32 agp_aper_base = 0, agp_aper_order = 0;
	u32 aper_size, aper_alloc = 0, aper_order = 0, last_aper_order = 0;
	u64 aper_base, last_aper_base = 0;
	int fix, slot, valid_agp = 0;
	int i, node;

	if (!amd_gart_present())
		return -ENODEV;

	if (gart_iommu_aperture_disabled || !fix_aperture ||
	    !early_pci_allowed())
		return -ENODEV;

	pr_info("Checking aperture...\n");

	if (!fallback_aper_force)
		agp_aper_base = search_agp_bridge(&agp_aper_order, &valid_agp);

	fix = 0;
	node = 0;
	for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) {
		int bus;
		int dev_base, dev_limit;
		u32 ctl;

		bus = amd_nb_bus_dev_ranges[i].bus;
		dev_base = amd_nb_bus_dev_ranges[i].dev_base;
		dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;

		for (slot = dev_base; slot < dev_limit; slot++) {
			if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
				continue;

			iommu_detected = 1;
			gart_iommu_aperture = 1;
			x86_init.iommu.iommu_init = gart_iommu_init;

			ctl = read_pci_config(bus, slot, 3,
					      AMD64_GARTAPERTURECTL);

			/*
			 * Before we do anything else disable the GART. It may
			 * still be enabled if we boot into a crash-kernel here.
			 * Reconfiguring the GART while it is enabled could have
			 * unknown side-effects.
			 */
			ctl &= ~GARTEN;
			write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl);

			aper_order = (ctl >> 1) & 7;
			aper_size = (32 * 1024 * 1024) << aper_order;
			aper_base = read_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE) & 0x7fff;
			aper_base <<= 25;

			pr_info("Node %d: aperture [bus addr %#010Lx-%#010Lx] (%uMB)\n",
				node, aper_base, aper_base + aper_size - 1,
				aper_size >> 20);
			node++;

			if (!aperture_valid(aper_base, aper_size, 64<<20)) {
				if (valid_agp && agp_aper_base &&
				    agp_aper_base == aper_base &&
				    agp_aper_order == aper_order) {
					/* the same between two setting from NB and agp */
					if (!no_iommu &&
					    max_pfn > MAX_DMA32_PFN &&
					    !printed_gart_size_msg) {
						pr_err("you are using iommu with agp, but GART size is less than 64MB\n");
						pr_err("please increase GART size in your BIOS setup\n");
						pr_err("if BIOS doesn't have that option, contact your HW vendor!\n");
						printed_gart_size_msg = 1;
					}
				} else {
					fix = 1;
					goto out;
				}
			}

			if ((last_aper_order && aper_order != last_aper_order) ||
			    (last_aper_base && aper_base != last_aper_base)) {
				fix = 1;
				goto out;
			}
			last_aper_order = aper_order;
			last_aper_base = aper_base;
		}
	}

out:
	if (!fix && !fallback_aper_force) {
		if (last_aper_base)
			return 1;
		return 0;
	}

	if (!fallback_aper_force) {
		aper_alloc = agp_aper_base;
		aper_order = agp_aper_order;
	}

	if (aper_alloc) {
		/* Got the aperture from the AGP bridge */
	} else if ((!no_iommu && max_pfn > MAX_DMA32_PFN) ||
		   force_iommu ||
		   valid_agp ||
		   fallback_aper_force) {
		pr_info("Your BIOS doesn't leave an aperture memory hole\n");
		pr_info("Please enable the IOMMU option in the BIOS setup\n");
		pr_info("This costs you %dMB of RAM\n",
			32 << fallback_aper_order);

		aper_order = fallback_aper_order;
		aper_alloc = allocate_aperture();
		if (!aper_alloc) {
			/*
			 * Could disable AGP and IOMMU here, but it's
			 * probably not worth it. But the later users
			 * cannot deal with bad apertures and turning
			 * on the aperture over memory causes very
			 * strange problems, so it's better to panic
			 * early.
			 */
			panic("Not enough memory for aperture");
		}
	} else {
		return 0;
	}

	/* Fix up the north bridges */
	for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) {
		int bus, dev_base, dev_limit;

		/*
		 * Don't enable translation yet but enable GART IO and CPU
		 * accesses and set DISTLBWALKPRB since GART table memory is UC.
		 */
		u32 ctl = aper_order << 1;

		bus = amd_nb_bus_dev_ranges[i].bus;
		dev_base = amd_nb_bus_dev_ranges[i].dev_base;
		dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;
		for (slot = dev_base; slot < dev_limit; slot++) {
			if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
				continue;

			write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl);
			write_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE, aper_alloc >> 25);
		}
	}

	set_up_gart_resume(aper_order, aper_alloc);

	return 1;
}

{'repo_name': 'liva/minimal-linux', 'stars': '173', 'repo_language': 'C', 'file_name': 'rcu_segcblist.h', 'mime_type': 'text/x-c', 'hash': 8472804004441149296, 'source_dataset': 'data'}