text:
    1 {-# LANGUAGE FlexibleInstances #-}
    2 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
    3 {-# LANGUAGE MultiParamTypeClasses #-}
    4 {-# LANGUAGE PackageImports #-}
    5 {-# LANGUAGE ScopedTypeVariables #-}
    6 {-# LANGUAGE UndecidableInstances #-}
    7
    8 {-|
    9
   10 This module contains the core Heist data types.  TemplateMonad intentionally
   11 does not expose any of its functionality via MonadState or MonadReader
   12 functions.  We define passthrough instances for the most common types of
   13 monads.  These instances allow the user to use TemplateMonad in a monad stack
   14 without needing calls to `lift`.
   15
   16 Edward Kmett wrote most of the TemplateMonad code and associated instances,
   17 liberating us from the unused writer portion of RWST.
   18
   19 -}
   20
   21 module Text.Templating.Heist.Types where
   22
   23 ------------------------------------------------------------------------------
   24 import             Control.Applicative
   25 import             Control.Arrow
   26 import             Control.Monad.Cont
   27 import             Control.Monad.Error
   28 import             Control.Monad.Reader
   29 import             Control.Monad.State
   30 import             Data.ByteString.Char8 (ByteString)
   31 import qualified   Data.Map as Map
   32 import             Data.Map (Map)
   33 import             Data.Monoid
   34 import             Data.Text (Text)
   35 import             Data.Typeable
   36 import             Prelude hiding (catch)
   37 import qualified   Text.XmlHtml as X
   38
   39
   40 ------------------------------------------------------------------------------
   41 -- | A 'Template' is a forest of XML nodes.  Here we deviate from the "single
   42 -- root node" constraint of well-formed XML because we want to allow templates
   43 -- to contain fragments of a document that may not have a single root.
   44 type Template = [X.Node]
   45
   46
   47 ------------------------------------------------------------------------------
   48 -- | MIME Type.  The type alias is here to make the API clearer.
   49 type MIMEType = ByteString
   50
   51
   52 ------------------------------------------------------------------------------
   53 -- | Reversed list of directories.  This holds the path to the template
   54 -- currently being processed.
   55 type TPath = [ByteString]
   56
   57
   58 data DocumentFile = DocumentFile
   59     { dfDoc  :: X.Document
   60     , dfFile :: Maybe FilePath
   61     } deriving (Eq)
   62
   63 ------------------------------------------------------------------------------
   64 -- | All documents representing templates are stored in a map.
   65 type TemplateMap = Map TPath DocumentFile
   66
   67
   68 ------------------------------------------------------------------------------
   69 -- | A Splice is a TemplateMonad computation that returns a 'Template'.
   70 type Splice m = TemplateMonad m Template
   71
   72
   73 ------------------------------------------------------------------------------
   74 -- | SpliceMap associates a name and a Splice.
   75 type SpliceMap m = Map Text (Splice m)
   76
   77
   78 ------------------------------------------------------------------------------
   79 -- | Holds all the state information needed for template processing.  You will
   80 -- build a @TemplateState@ using any of Heist's @TemplateState m ->
   81 -- TemplateState m@ \"filter\" functions.  Then you use the resulting
   82 -- @TemplateState@ in calls to @renderTemplate@.
   83 data TemplateState m = TemplateState {
   84     -- | A mapping of splice names to splice actions
   85       _spliceMap       :: SpliceMap m
   86     -- | A mapping of template names to templates
   87     , _templateMap     :: TemplateMap
   88     -- | A flag to control splice recursion
   89     , _recurse         :: Bool
   90     -- | The path to the template currently being processed.
   91     , _curContext      :: TPath
   92     -- | A counter keeping track of the current recursion depth to prevent
   93     -- infinite loops.
   94     , _recursionDepth  :: Int
   95     -- | A hook run on all templates at load time.
   96     , _onLoadHook      :: Template -> IO Template
   97     -- | A hook run on all templates just before they are rendered.
   98     , _preRunHook      :: Template -> m Template
   99     -- | A hook run on all templates just after they are rendered.
  100     , _postRunHook     :: Template -> m Template
  101     -- | The doctypes encountered during template processing.
  102     , _doctypes        :: [X.DocType]
  103     -- | The full path to the current template's file on disk.
  104     , _curTemplateFile :: Maybe FilePath
  105 }
  106
  107
  108 ------------------------------------------------------------------------------
  109 instance (Monad m) => Monoid (TemplateState m) where
  110     mempty = TemplateState Map.empty Map.empty True [] 0
  111                            return return return [] Nothing
  112
  113     (TemplateState s1 t1 r1 _ d1 o1 b1 a1 dt1 ctf1) `mappend`
  114         (TemplateState s2 t2 r2 c2 d2 o2 b2 a2 dt2 ctf2) =
  115         TemplateState s t r c2 d (o1 >=> o2) (b1 >=> b2) (a1 >=> a2)
  116             (dt1 `mappend` dt2) ctf
  117       where
  118         s = s1 `mappend` s2
  119         t = t1 `mappend` t2
  120         r = r1 && r2
  121         d = max d1 d2
  122         ctf = getLast $ Last ctf1 `mappend` Last ctf2
  123
  124
  125 ------------------------------------------------------------------------------
  126 instance Eq (TemplateState m) where
  127     a == b = (_recurse a == _recurse b) &&
  128              (_templateMap a == _templateMap b) &&
  129              (_curContext a == _curContext b)
  130
  131
  132 ------------------------------------------------------------------------------
  133 -- | The Typeable instance is here so Heist can be dynamically executed with
  134 -- Hint.
  135 templateStateTyCon :: TyCon
  136 templateStateTyCon = mkTyCon "Text.Templating.Heist.TemplateState"
  137 {-# NOINLINE templateStateTyCon #-}
  138
  139 instance (Typeable1 m) => Typeable (TemplateState m) where
  140     typeOf _ = mkTyConApp templateStateTyCon [typeOf1 (undefined :: m ())]
  141
  142
  143 {-# DEPRECATED TemplateMonad "NOTICE: The name TemplateMonad is being phased out in favor of the more appropriate HeistT.  Change your code now to prevent breakage in the future!" #-}
  144 ------------------------------------------------------------------------------
  145 -- | TemplateMonad is the monad used for 'Splice' processing.  TemplateMonad
  146 -- provides \"passthrough\" instances for many of the monads you might use in
  147 -- the inner monad.
  148 newtype TemplateMonad m a = TemplateMonad {
  149     runTemplateMonad :: X.Node
  150                      -> TemplateState m
  151                      -> m (a, TemplateState m)
  152 }
  153 type HeistT = TemplateMonad
  154
  155
  156 ------------------------------------------------------------------------------
  157 -- | Evaluates a template monad as a computation in the underlying monad.
  158 evalTemplateMonad :: Monad m
  159                   => TemplateMonad m a
  160                   -> X.Node
  161                   -> TemplateState m
  162                   -> m a
  163 evalTemplateMonad m r s = do
  164     (a, _) <- runTemplateMonad m r s
  165     return a
  166
  167
  168 ------------------------------------------------------------------------------
  169 -- | Functor instance
  170 instance Functor m => Functor (TemplateMonad m) where
  171     fmap f (TemplateMonad m) = TemplateMonad $ \r s -> first f <$> m r s
  172
  173
  174 ------------------------------------------------------------------------------
  175 -- | Applicative instance
  176 instance (Monad m, Functor m) => Applicative (TemplateMonad m) where
  177     pure = return
  178     (<*>) = ap
  179
  180
  181 ------------------------------------------------------------------------------
  182 -- | Monad instance
  183 instance Monad m => Monad (TemplateMonad m) where
  184     return a = TemplateMonad (\_ s -> return (a, s))
  185     TemplateMonad m >>= k = TemplateMonad $ \r s -> do
  186         (a, s') <- m r s
  187         runTemplateMonad (k a) r s'
  188
  189
  190 ------------------------------------------------------------------------------
  191 -- | MonadIO instance
  192 instance MonadIO m => MonadIO (TemplateMonad m) where
  193     liftIO = lift . liftIO
  194
  195
  196 ------------------------------------------------------------------------------
  197 -- | MonadTrans instance
  198 instance MonadTrans TemplateMonad where
  199     lift m = TemplateMonad $ \_ s -> do
  200         a <- m
  201         return (a, s)
  202
  203
  204 ------------------------------------------------------------------------------
  205 -- | MonadFix passthrough instance
  206 instance MonadFix m => MonadFix (TemplateMonad m) where
  207     mfix f = TemplateMonad $ \r s ->
  208         mfix $ \ (a, _) -> runTemplateMonad (f a) r s
  209
  210
  211 ------------------------------------------------------------------------------
  212 -- | Alternative passthrough instance
  213 instance (Functor m, MonadPlus m) => Alternative (TemplateMonad m) where
  214     empty = mzero
  215     (<|>) = mplus
  216
  217
  218 ------------------------------------------------------------------------------
  219 -- | MonadPlus passthrough instance
  220 instance MonadPlus m => MonadPlus (TemplateMonad m) where
  221     mzero = lift mzero
  222     m `mplus` n = TemplateMonad $ \r s ->
  223         runTemplateMonad m r s `mplus` runTemplateMonad n r s
  224
  225
  226 ------------------------------------------------------------------------------
  227 -- | MonadState passthrough instance
  228 instance MonadState s m => MonadState s (TemplateMonad m) where
  229     get = lift get
  230     put = lift . put
  231
  232
  233 ------------------------------------------------------------------------------
  234 -- | MonadReader passthrough instance
  235 instance MonadReader r m => MonadReader r (TemplateMonad m) where
  236     ask = TemplateMonad $ \_ s -> do
  237             r <- ask
  238             return (r,s)
  239     local f (TemplateMonad m) =
  240         TemplateMonad $ \r s -> local f (m r s)
  241
  242
  243 ------------------------------------------------------------------------------
  244 -- | Helper for MonadError instance.
  245 liftCatch :: (m (a,TemplateState m)
  246               -> (e -> m (a,TemplateState m))
  247               -> m (a,TemplateState m))
  248           -> TemplateMonad m a
  249           -> (e -> TemplateMonad m a)
  250           -> TemplateMonad m a
  251 liftCatch ce m h =
  252     TemplateMonad $ \r s ->
  253         (runTemplateMonad m r s `ce`
  254         (\e -> runTemplateMonad (h e) r s))
  255
  256
  257 ------------------------------------------------------------------------------
  258 -- | MonadError passthrough instance
  259 instance (MonadError e m) => MonadError e (TemplateMonad m) where
  260     throwError = lift . throwError
  261     catchError = liftCatch catchError
  262
  263
  264 ------------------------------------------------------------------------------
  265 -- | Helper for MonadCont instance.
  266 liftCallCC :: ((((a,TemplateState m) -> m (b, TemplateState m))
  267                   -> m (a, TemplateState m))
  268                 -> m (a, TemplateState m))
  269            -> ((a -> TemplateMonad m b) -> TemplateMonad m a)
  270            -> TemplateMonad m a
  271 liftCallCC ccc f = TemplateMonad $ \r s ->
  272     ccc $ \c ->
  273     runTemplateMonad (f (\a -> TemplateMonad $ \_ _ -> c (a, s))) r s
  274
  275
  276 ------------------------------------------------------------------------------
  277 -- | MonadCont passthrough instance
  278 instance (MonadCont m) => MonadCont (TemplateMonad m) where
  279     callCC = liftCallCC callCC
  280
  281
  282 ------------------------------------------------------------------------------
  283 -- | The Typeable instance is here so Heist can be dynamically executed with
  284 -- Hint.
  285 templateMonadTyCon :: TyCon
  286 templateMonadTyCon = mkTyCon "Text.Templating.Heist.TemplateMonad"
  287 {-# NOINLINE templateMonadTyCon #-}
  288
  289 instance (Typeable1 m) => Typeable1 (TemplateMonad m) where
  290     typeOf1 _ = mkTyConApp templateMonadTyCon [typeOf1 (undefined :: m ())]
  291
  292
  293 ------------------------------------------------------------------------------
  294 -- Functions for our monad.
  295 ------------------------------------------------------------------------------
  296
  297
  298 ------------------------------------------------------------------------------
  299 -- | Gets the node currently being processed.
  300 --
  301 --   > <speech author="Shakespeare">
  302 --   >   To sleep, perchance to dream.
  303 --   > </speech>
  304 --
  305 -- When you call @getParamNode@ inside the code for the @speech@ splice, it
  306 -- returns the Node for the @speech@ tag and its children.  @getParamNode >>=
  307 -- childNodes@ returns a list containing one 'TextNode' containing part of
  308 -- Hamlet's speech.  @liftM (getAttribute \"author\") getParamNode@ would
  309 -- return @Just "Shakespeare"@.
  310 getParamNode :: Monad m => TemplateMonad m X.Node
  311 getParamNode = TemplateMonad $ \r s -> return (r,s)
  312
  313
  314 ------------------------------------------------------------------------------
  315 -- | TemplateMonad's 'local'.
  316 localParamNode :: Monad m
  317                => (X.Node -> X.Node)
  318                -> TemplateMonad m a
  319                -> TemplateMonad m a
  320 localParamNode f m = TemplateMonad $ \r s -> runTemplateMonad m (f r) s
  321
  322
  323 ------------------------------------------------------------------------------
  324 -- | TemplateMonad's 'gets'.
  325 getsTS :: Monad m => (TemplateState m -> r) -> TemplateMonad m r
  326 getsTS f = TemplateMonad $ \_ s -> return (f s, s)
  327
  328
  329 ------------------------------------------------------------------------------
  330 -- | TemplateMonad's 'get'.
  331 getTS :: Monad m => TemplateMonad m (TemplateState m)
  332 getTS = TemplateMonad $ \_ s -> return (s, s)
  333
  334
  335 ------------------------------------------------------------------------------
  336 -- | TemplateMonad's 'put'.
  337 putTS :: Monad m => TemplateState m -> TemplateMonad m ()
  338 putTS s = TemplateMonad $ \_ _ -> return ((), s)
  339
  340
  341 ------------------------------------------------------------------------------
  342 -- | TemplateMonad's 'modify'.
  343 modifyTS :: Monad m
  344                     => (TemplateState m -> TemplateState m)
  345                     -> TemplateMonad m ()
  346 modifyTS f = TemplateMonad $ \_ s -> return ((), f s)
  347
  348
  349 ------------------------------------------------------------------------------
  350 -- | Restores the TemplateState.  This function is almost like putTS except it
  351 -- preserves the current doctypes.  You should use this function instead of
  352 -- @putTS@ to restore an old state.  This was needed because doctypes needs to
  353 -- be in a "global scope" as opposed to the template call "local scope" of
  354 -- state items such as recursionDepth, curContext, and spliceMap.
  355 restoreTS :: Monad m => TemplateState m -> TemplateMonad m ()
  356 restoreTS old = modifyTS (\cur -> old { _doctypes = _doctypes cur })
  357
  358
  359 ------------------------------------------------------------------------------
  360 -- | Abstracts the common pattern of running a TemplateMonad computation with
  361 -- a modified template state.
  362 localTS :: Monad m
  363         => (TemplateState m -> TemplateState m)
  364         -> TemplateMonad m a
  365         -> TemplateMonad m a
  366 localTS f k = do
  367     ts <- getTS
  368     putTS $ f ts
  369     res <- k
  370     restoreTS ts
  371     return res
  372


text:
Renderer of Angular application on Node

**caution**
`angular2-universal-render` only work when using Angular 2.1.0.
Because angular-universal is not yet correspond to Angular Core 2.1.1.

# Motivation
I wanted to run the server-side rendering of [angular-universal](https://github.com/angular/universal), without having to depend on the request of the web server.
Without using the Express, for example, even on AWS Lambda, it is possible to perform rendering as a function call.

# Reference
I created this library to reference [angular2-express-engine](https://github.com/angular/universal/tree/master/modules/express-engine).
I was re-implemented `createEngine()`, so that it can be run independently.

# Usage
## Install
```
$ npm install angular2-universal-render
```

## Basic
First to define the app modules for node.
Use modules of `angular2-universal/node`.

```
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UniversalModule, isBrowser, isNode } from 'angular2-universal/node';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { Page1Component } from './page1/page1.component';
import { Page2Component } from './page2/page2.component';
import { TestDataService } from './services/test-data.service';
import { Cache } from '../../src';

@NgModule({
  declarations: [
    AppComponent,
    Page1Component,
    Page2Component
  ],
  imports: [
    FormsModule,
    UniversalModule,
    AppRoutingModule
  ],
  providers: [
    { provide: 'isBrowser', useValue: isBrowser },
    { provide: 'isNode', useValue: isNode },
    TestDataService,
    Cache
  ],
  bootstrap: [AppComponent]
})
export class AppModule {

  constructor(public cache: Cache) {}

  // we need to use the arrow function here to bind the context as this is a gotcha in Universal for now until it's fixed
  universalDoDehydrate = (universalCache) => {
    universalCache['Cache'] = JSON.stringify(this.cache.dehydrate());
  }

  universalAfterDehydrate = () => {
    this.cache.clear();
  }

}
```

Next, create render function by `angular2-universal-render`.
Do not forget to import `angular2-universal-polyfills/node`.

```
import 'angular2-universal-polyfills/node';

import * as path from 'path';
import * as fs from 'fs';

import { AppModule } from './app/app.module.node';
import { createRender } from 'angular2-universal-render';

const document = fs.readFileSync(path.resolve(process.cwd(), './example/index.html'), 'utf-8');
const render = createRender({
  document: document,
  ngModule: AppModule
});
```

Finally, call the rendering function with request url.
This function return Promise<string> object.

```
render({
  requestUrl: '/page2'
})
.then(html => {
  console.log(html);
});
```

## Cache
When you want to share the data between the server and the browser, use `universal-cache`.
Data de-serialized in the browser, to use seamlessly.

```
import { Component, OnInit } from '@angular/core';

import { TestDataService } from '../services/test-data.service';
import { Cache } from 'angular2-universal-render';

@Component({
  selector: 'app-page2',
  templateUrl: './page2.component.html',
  styleUrls: ['./page2.component.css']
})
export class Page2Component implements OnInit {

  testData: string;

  constructor(private testDataSerivce: TestDataService, private cache: Cache) { }

  ngOnInit() {
    this.fetchTestData();
  }

  fetchTestData() {
    this.testDataSerivce
    .fetch()
    .then(data => {
      this.cache.set('testData', data);
      this.testData = JSON.stringify(data)
    });
  }

  clickButtonDidClick() {
    alert(JSON.stringify(this.cache.get('testData')));
  }

}
```

redpajama_set_name: RedPajamaGithub


text:
REGISTER_ENTITY(CInstructorEntity);

NETVAR_TABLE_BEGIN(CInstructorEntity);
NETVAR_TABLE_END();

SAVEDATA_TABLE_BEGIN(CInstructorEntity);
SAVEDATA_TABLE_END();

INPUTS_TABLE_BEGIN(CInstructorEntity);
	INPUT_DEFINE(DisplayLesson);
INPUTS_TABLE_END();

void CInstructorEntity::Spawn()
{
	BaseClass::Spawn();

	SetName("instructor");
}

void CInstructorEntity::DisplayLesson(const tvector<tstring>& sArgs)
{
	if (sArgs.size() == 0)
	{
		TMsg("DisplayLesson called without a lesson name argument.\n");
		return;
	}

	DigitanksWindow()->GetInstructor()->DisplayLesson(convertstring<tchar, char>(sArgs[0]));
}


text:
from cml_associations_unidirectional_vehicles_cmlc import *

print("Unidirectional Associations (cmlc_py)\n")

employee = Employee.create_employee("John")
organization = Organization.create_organization("Acme", [employee])
vehicle = Vehicle.create_vehicle("ABC12345", employee, organization)

print("Employee: %s" % employee)
print("Organization: %s" % organization)
print("Organization's Employees: %s" % ','.join(map(str, organization.employees)))
print("Vehicle: %s" % vehicle)


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model frontend\models\PenyelidikanKomposisiPasukanSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'penyelidikan_komposisi_pasukan_id') ?>

    <?= $form->field($model, 'permohonana_penyelidikan_id') ?>

    <?= $form->field($model, 'nama') ?>

    <?= $form->field($model, 'pasukan') ?>

    <?= $form->field($model, 'jawatan') ?>

    <?php // echo $form->field($model, 'telefon_no') ?>

    <?php // echo $form->field($model, 'emel') ?>

    <?php // echo $form->field($model, 'alamat_1') ?>

    <?php // echo $form->field($model, 'alamat_2') ?>

    <?php // echo $form->field($model, 'alamat_3') ?>

    <?php // echo $form->field($model, 'alamat_negeri') ?>

    <?php // echo $form->field($model, 'alamat_bandar') ?>

    <?php // echo $form->field($model, 'alamat_poskod') ?>

    <?php // echo $form->field($model, 'institusi_universiti_syarikat') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
/**
** To compile the file:
** javac CountingSynchronized.java
**
** To run:
** java CountingSynchronized
**
** After compiling/executing this code three times this is the output:
** 20000
** 20000
** 20000
**
**/
public class CountingSynchronized {

  public static void main(String ...args) throws InterruptedException {

      class Counter {

        private int count = 0;
        public synchronized void increment() { ++count; }
        public int getCount() { return count; }

      }

      final Counter counter = new Counter();

      class CountingThread extends Thread {

        public void run(){
            for (int x = 0; x < 10000; ++x) {
              counter.increment();
            }
        }
      }

      CountingThread t1 = new CountingThread();
      CountingThread t2 = new CountingThread();

      t1.start(); t2.start();
      t1.join(); t2.join();

      System.out.println(counter.getCount());
  }

}


text:
/* $Id: amqp.c 327551 2012-09-09 03:49:34Z pdezwart $ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "zend_ini.h"
#include "zend_exceptions.h"

#ifdef PHP_WIN32
# include "win32/php_stdint.h"
# include "win32/signal.h"
#else
# include <stdint.h>
# include <signal.h>
#endif
#include <amqp.h>
#include <amqp_framing.h>

#include "php_amqp.h"
#include "amqp_connection.h"
#include "amqp_channel.h"
#include "amqp_queue.h"
#include "amqp_exchange.h"
#include "amqp_envelope.h"
#include "amqp_basic_properties.h"
#include "amqp_connection_resource.h"

#ifdef PHP_WIN32
# include "win32/unistd.h"
#else
# include <unistd.h>
#endif

#include "amqp_connection.h"
#include "amqp_connection_resource.h"
#include "amqp_channel.h"
#include "amqp_envelope.h"
#include "amqp_exchange.h"
#include "amqp_queue.h"

/* True global resources - no need for thread safety here */

zend_class_entry *amqp_exception_class_entry,
				 *amqp_connection_exception_class_entry,
				 *amqp_channel_exception_class_entry,
				 *amqp_queue_exception_class_entry,
				 *amqp_exchange_exception_class_entry;

/* {{{ amqp_functions[]
*
*Every user visible function must have an entry in amqp_functions[].
*/
zend_function_entry amqp_functions[] = {
	{NULL, NULL, NULL}
};
/* }}} */

PHP_INI_BEGIN()
	PHP_INI_ENTRY("amqp.host",				DEFAULT_HOST,				PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.vhost",				DEFAULT_VHOST,				PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.port",				DEFAULT_PORT,				PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.timeout",			DEFAULT_TIMEOUT,			PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.read_timeout",		DEFAULT_READ_TIMEOUT,		PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.write_timeout",		DEFAULT_WRITE_TIMEOUT,		PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.connect_timeout",	DEFAULT_CONNECT_TIMEOUT,		PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.login",				DEFAULT_LOGIN,				PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.password",			DEFAULT_PASSWORD,			PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.auto_ack",			DEFAULT_AUTOACK,			PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.prefetch_count",	DEFAULT_PREFETCH_COUNT,		PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.channel_max",		DEFAULT_CHANNEL_MAX,		PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.frame_max",			DEFAULT_FRAME_MAX,			PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.heartbeat",			DEFAULT_HEARTBEAT,			PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.cacert",			DEFAULT_CACERT,				PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.cert",				DEFAULT_CERT,				PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.key",				DEFAULT_KEY,				PHP_INI_ALL, NULL)
	PHP_INI_ENTRY("amqp.verify",			DEFAULT_VERIFY,				PHP_INI_ALL, NULL)
PHP_INI_END()

ZEND_DECLARE_MODULE_GLOBALS(amqp);

static PHP_GINIT_FUNCTION(amqp) /* {{{ */
{
	amqp_globals->error_message = NULL;
	amqp_globals->error_code = 0;
} /* }}} */

static PHP_MINIT_FUNCTION(amqp) /* {{{ */
{
	zend_class_entry ce;

	/* Set up the connection resource */
	le_amqp_connection_resource = zend_register_list_destructors_ex(amqp_connection_resource_dtor, NULL, PHP_AMQP_CONNECTION_RES_NAME, module_number);
	le_amqp_connection_resource_persistent = zend_register_list_destructors_ex(NULL, amqp_connection_resource_dtor_persistent, PHP_AMQP_CONNECTION_RES_NAME, module_number);

	PHP_MINIT(amqp_connection)(INIT_FUNC_ARGS_PASSTHRU);
	PHP_MINIT(amqp_channel)(INIT_FUNC_ARGS_PASSTHRU);
	PHP_MINIT(amqp_queue)(INIT_FUNC_ARGS_PASSTHRU);
	PHP_MINIT(amqp_exchange)(INIT_FUNC_ARGS_PASSTHRU);
	PHP_MINIT(amqp_basic_properties)(INIT_FUNC_ARGS_PASSTHRU);
	PHP_MINIT(amqp_envelope)(INIT_FUNC_ARGS_PASSTHRU);

	/* Class Exceptions */
	INIT_CLASS_ENTRY(ce, "AMQPException", NULL);
	amqp_exception_class_entry = PHP5to7_zend_register_internal_class_ex(&ce, zend_exception_get_default(TSRMLS_C));

	INIT_CLASS_ENTRY(ce, "AMQPConnectionException", NULL);
	amqp_connection_exception_class_entry = PHP5to7_zend_register_internal_class_ex(&ce, amqp_exception_class_entry);

	INIT_CLASS_ENTRY(ce, "AMQPChannelException", NULL);
	amqp_channel_exception_class_entry = PHP5to7_zend_register_internal_class_ex(&ce, amqp_exception_class_entry);

	INIT_CLASS_ENTRY(ce, "AMQPQueueException", NULL);
	amqp_queue_exception_class_entry = PHP5to7_zend_register_internal_class_ex(&ce, amqp_exception_class_entry);

	INIT_CLASS_ENTRY(ce, "AMQPExchangeException", NULL);
	amqp_exchange_exception_class_entry = PHP5to7_zend_register_internal_class_ex(&ce, amqp_exception_class_entry);

	REGISTER_INI_ENTRIES();

	REGISTER_LONG_CONSTANT("AMQP_NOPARAM",			AMQP_NOPARAM,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_JUST_CONSUME",		AMQP_JUST_CONSUME,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_DURABLE",			AMQP_DURABLE,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_PASSIVE",			AMQP_PASSIVE,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_EXCLUSIVE",		AMQP_EXCLUSIVE,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_AUTODELETE",		AMQP_AUTODELETE,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_INTERNAL",			AMQP_INTERNAL,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_NOLOCAL",			AMQP_NOLOCAL,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_AUTOACK",			AMQP_AUTOACK,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_IFEMPTY",			AMQP_IFEMPTY,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_IFUNUSED",			AMQP_IFUNUSED,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_MANDATORY",		AMQP_MANDATORY,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_IMMEDIATE",		AMQP_IMMEDIATE,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_MULTIPLE",			AMQP_MULTIPLE,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_NOWAIT",			AMQP_NOWAIT,		CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("AMQP_REQUEUE",			AMQP_REQUEUE,		CONST_CS | CONST_PERSISTENT);

	REGISTER_STRING_CONSTANT("AMQP_EX_TYPE_DIRECT",	AMQP_EX_TYPE_DIRECT,	CONST_CS | CONST_PERSISTENT);
	REGISTER_STRING_CONSTANT("AMQP_EX_TYPE_FANOUT",	AMQP_EX_TYPE_FANOUT,	CONST_CS | CONST_PERSISTENT);
	REGISTER_STRING_CONSTANT("AMQP_EX_TYPE_TOPIC",	AMQP_EX_TYPE_TOPIC,		CONST_CS | CONST_PERSISTENT);
	REGISTER_STRING_CONSTANT("AMQP_EX_TYPE_HEADERS",AMQP_EX_TYPE_HEADERS,	CONST_CS | CONST_PERSISTENT);

	REGISTER_LONG_CONSTANT("AMQP_OS_SOCKET_TIMEOUT_ERRNO",	AMQP_OS_SOCKET_TIMEOUT_ERRNO,	CONST_CS | CONST_PERSISTENT);
	REGISTER_LONG_CONSTANT("PHP_AMQP_MAX_CHANNELS",			PHP_AMQP_MAX_CHANNELS,			CONST_CS | CONST_PERSISTENT);

	return SUCCESS;
} /* }}} */

static PHP_MSHUTDOWN_FUNCTION(amqp) /* {{{ */
{
	UNREGISTER_INI_ENTRIES();

	return SUCCESS;
} /* }}} */

static PHP_RSHUTDOWN_FUNCTION(amqp) /* {{{ */
{
    if (NULL != PHP_AMQP_G(error_message)) {
		efree(PHP_AMQP_G(error_message));
		PHP_AMQP_G(error_message) = NULL;
    }

    PHP_AMQP_G(error_code) = 0;

    return SUCCESS;
} /* }}} */

static PHP_MINFO_FUNCTION(amqp) /* {{{ */
{
	php_info_print_table_start();
	php_info_print_table_header(2, "Version",					PHP_AMQP_VERSION);
	php_info_print_table_header(2, "Revision",					PHP_AMQP_REVISION);
	php_info_print_table_header(2, "Compiled",					__DATE__ " @ "  __TIME__);
	php_info_print_table_header(2, "AMQP protocol version", 	"0-9-1");
	php_info_print_table_header(2, "librabbitmq version", amqp_version());
	php_info_print_table_header(2, "Default max channels per connection",	DEFAULT_CHANNEL_MAX);
	php_info_print_table_header(2, "Default max frame size",	DEFAULT_FRAME_MAX);
	php_info_print_table_header(2, "Default heartbeats interval",	DEFAULT_HEARTBEAT);
	DISPLAY_INI_ENTRIES();
} /* }}} */

/* {{{ amqp_module_entry
*/
zend_module_entry amqp_module_entry = {
	STANDARD_MODULE_HEADER,
	"amqp",
	amqp_functions,
	PHP_MINIT(amqp),
	PHP_MSHUTDOWN(amqp),
	NULL,
	PHP_RSHUTDOWN(amqp),
	PHP_MINFO(amqp),
	PHP_AMQP_VERSION,
	PHP_MODULE_GLOBALS(amqp),
	PHP_GINIT(amqp),
	NULL,
	NULL,
	STANDARD_MODULE_PROPERTIES_EX
};
/* }}} */

#ifdef COMPILE_DL_AMQP
	ZEND_GET_MODULE(amqp)
#endif

int php_amqp_error(amqp_rpc_reply_t reply, char **message, amqp_connection_resource *connection_resource, amqp_channel_resource *channel_resource TSRMLS_DC)
{
	return php_amqp_error_advanced(reply, message, connection_resource, channel_resource, 1 TSRMLS_CC);
}

int php_amqp_error_advanced(amqp_rpc_reply_t reply, char **message, amqp_connection_resource *connection_resource, amqp_channel_resource *channel_resource, int fail_on_errors TSRMLS_DC)
{
	assert(connection_resource != NULL);

	PHP_AMQP_G(error_code) = 0;
	if (*message != NULL) {
		efree(*message);
	}

	int res = php_amqp_connection_resource_error(reply, message, connection_resource, (amqp_channel_t)(channel_resource ? channel_resource->channel_id : 0) TSRMLS_CC);

	switch (res) {
		case PHP_AMQP_RESOURCE_RESPONSE_OK:
			break;
		case PHP_AMQP_RESOURCE_RESPONSE_ERROR:
			if (!fail_on_errors) {
				break;
			}
			/* Library or other non-protocol or even protocol related errors may be here. */
			/* In most cases it designate some underlying hard errors. Fail fast. */
		case PHP_AMQP_RESOURCE_RESPONSE_ERROR_CONNECTION_CLOSED:
			/* Mark connection resource as closed to prevent sending any further requests */
			connection_resource->is_connected = '\0';

			/* Close connection with all its channels */
			php_amqp_disconnect_force(connection_resource TSRMLS_CC);

			break;
		case PHP_AMQP_RESOURCE_RESPONSE_ERROR_CHANNEL_CLOSED:
			/* Mark channel as closed to prevent sending channel.close request */
			assert(channel_resource != NULL);
			if (channel_resource) {
				channel_resource->is_connected = '\0';

				/* Close channel */
				php_amqp_close_channel(channel_resource TSRMLS_CC);
			}
			/* No more error handling necessary, returning. */
			break;
		default:
			spprintf(message, 0, "Unknown server error, method id 0x%08X (not handled by extension)", reply.reply.id);
			break;
	}

	return res;
}

void php_amqp_zend_throw_exception_short(amqp_rpc_reply_t reply, zend_class_entry *exception_ce TSRMLS_DC) {
	php_amqp_zend_throw_exception(reply, exception_ce, PHP_AMQP_G(error_message), PHP_AMQP_G(error_code) TSRMLS_CC);
}

void php_amqp_zend_throw_exception(amqp_rpc_reply_t reply, zend_class_entry *exception_ce, const char *message, PHP5to7_param_long_type_t code TSRMLS_DC)
{
	switch (reply.reply_type) {
		case AMQP_RESPONSE_NORMAL:
			break;
		case AMQP_RESPONSE_NONE:
			exception_ce = amqp_exception_class_entry;
			break;
		case AMQP_RESPONSE_LIBRARY_EXCEPTION:
			exception_ce = amqp_exception_class_entry;
			break;
		case AMQP_RESPONSE_SERVER_EXCEPTION:
			switch (reply.reply.id) {
				case AMQP_CONNECTION_CLOSE_METHOD:
					/* Fatal errors - pass them to connection level */
					exception_ce = amqp_connection_exception_class_entry;
					break;
				case AMQP_CHANNEL_CLOSE_METHOD:
					/* Most channel-level errors occurs due to previously known action and thus their kind can be predicted. */
					/* exception_ce = amqp_channel_exception_class_entry; */
					break;
			}
			break;
		/* Default for the above switch should be handled by the below default. */
		default:
			exception_ce = amqp_exception_class_entry;
			break;
	}

	zend_throw_exception(exception_ce, message, code TSRMLS_CC);
}

void php_amqp_maybe_release_buffers_on_channel(amqp_connection_resource *connection_resource, amqp_channel_resource *channel_resource)
{
	assert(channel_resource != NULL);
	assert(channel_resource->channel_id > 0);

	if (connection_resource) {
		amqp_maybe_release_buffers_on_channel(connection_resource->connection_state, channel_resource->channel_id);
	}
}

amqp_bytes_t php_amqp_long_string(char const *cstr, PHP5to7_param_str_len_type_t len)
{
	if (len < 1) {
		return amqp_empty_bytes;
	}

	amqp_bytes_t result;
	result.len   = (size_t)len;
	result.bytes = (void *) cstr;

	return result;
}

char *stringify_bytes(amqp_bytes_t bytes)
{
/* We will need up to 4 chars per byte, plus the terminating 0 */
	char *res = emalloc(bytes.len * 4 + 1);
	uint8_t *data = bytes.bytes;
	char *p = res;
	size_t i;

	for (i = 0; i < bytes.len; i++) {
		if (data[i] >= 32 && data[i] != 127) {
			*p++ = data[i];
		} else {
			*p++ = '\\';
			*p++ = '0' + (data[i] >> 6);
			*p++ = '0' + (data[i] >> 3 & 0x7);
			*p++ = '0' + (data[i] & 0x7);
		}
	}

	*p = 0;
	return res;
}

void internal_convert_zval_to_amqp_table(zval *zvalArguments, amqp_table_t *arguments, char allow_int_keys TSRMLS_DC)
{
	HashTable *ht;
	HashPosition pos;

	zval *value;
	zval **data;

	PHP5to7_ZEND_REAL_HASH_KEY_T *real_key;

	char *key;
	uint key_len;

	ulong index;

	char type[16];
	amqp_table_t *inner_table;

	ht = Z_ARRVAL_P(zvalArguments);

	/* Allocate all the memory necessary for storing the arguments */
	arguments->entries = (amqp_table_entry_t *)ecalloc((size_t)zend_hash_num_elements(ht), sizeof(amqp_table_entry_t));
	arguments->num_entries = 0;

	PHP5to7_ZEND_HASH_FOREACH_KEY_VAL(ht, index, real_key, key, key_len, data, value, pos) {
		char *strKey;
		char *strValue;
		amqp_table_entry_t *table;
		amqp_field_value_t *field;

		/* Now pull the key */

		if (!PHP5to7_ZEND_HASH_KEY_IS_STRING(ht, real_key, key, key_len, index, pos)) {
			if (allow_int_keys) {
				/* Convert to strings non-string keys */
				char str[32];

				key_len = sprintf(str, "%lu", index);
				key     = str;
			} else {
				/* Skip things that are not strings */
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Ignoring non-string header field '%lu'", index);

				PHP5to7_ZEND_HASH_FOREACH_CONTINUE;
			}
		} else {
			PHP5to7_ZEND_HASH_KEY_MAYBE_UNPACK(real_key, key, key_len);
		}

		/* Build the value */
		table = &arguments->entries[arguments->num_entries++];
		field = &table->value;

		switch (Z_TYPE_P(value)) {
			PHP5to7_CASE_IS_BOOL:
				field->kind          = AMQP_FIELD_KIND_BOOLEAN;
				field->value.boolean = (amqp_boolean_t)Z_LVAL_P(value);
				break;
			case IS_DOUBLE:
				field->kind      = AMQP_FIELD_KIND_F64;
				field->value.f64 = Z_DVAL_P(value);
				break;
			case IS_LONG:
				field->kind      = AMQP_FIELD_KIND_I64;
				field->value.i64 = Z_LVAL_P(value);
				break;
			case IS_STRING:
				field->kind        = AMQP_FIELD_KIND_UTF8;

				if (Z_STRLEN_P(value)) {
					amqp_bytes_t bytes;
					bytes.len = (size_t) Z_STRLEN_P(value);
					bytes.bytes = estrndup(Z_STRVAL_P(value), (uint)Z_STRLEN_P(value));

					field->value.bytes = bytes;
				} else {
					field->value.bytes = amqp_empty_bytes;
				}

				break;
			case IS_ARRAY:
				field->kind = AMQP_FIELD_KIND_TABLE;
				internal_convert_zval_to_amqp_table(value, &field->value.table, 1 TSRMLS_CC);

				break;
			default:
				switch(Z_TYPE_P(value)) {
					case IS_NULL:     strcpy(type, "null"); break;
					case IS_OBJECT:   strcpy(type, "object"); break;
					case IS_RESOURCE: strcpy(type, "resource"); break;
					default:          strcpy(type, "unknown");
				}

				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Ignoring field '%s' due to unsupported value type (%s)", key, type);

				/* Reset entries counter back */
				arguments->num_entries --;

				PHP5to7_ZEND_HASH_FOREACH_CONTINUE;
		}

		strKey     = estrndup(key, key_len);
		table->key = amqp_cstring_bytes(strKey);

	} PHP5to7_ZEND_HASH_FOREACH_END();
};

amqp_table_t *convert_zval_to_amqp_table(zval *zvalArguments TSRMLS_DC)
{
	amqp_table_t *arguments;
	/* In setArguments, we are overwriting all the existing values */
	arguments = (amqp_table_t *)emalloc(sizeof(amqp_table_t));

	internal_convert_zval_to_amqp_table(zvalArguments, arguments, 0 TSRMLS_CC);

	return arguments;
}

void internal_php_amqp_free_amqp_table(amqp_table_t *object, char clear_root)
{
	if (!object) {
		return;
	}

	if (object->entries) {
		int macroEntryCounter;
		for (macroEntryCounter = 0; macroEntryCounter < object->num_entries; macroEntryCounter++) {

			amqp_table_entry_t *entry = &object->entries[macroEntryCounter];
			efree(entry->key.bytes);

			switch (entry->value.kind) {
				case AMQP_FIELD_KIND_TABLE:
					internal_php_amqp_free_amqp_table(&entry->value.value.table, 0);
					break;
				case AMQP_FIELD_KIND_UTF8:
					if (entry->value.value.bytes.bytes) {
						efree(entry->value.value.bytes.bytes);
					}
					break;
				default:
					break;
			}
		}
		efree(object->entries);
	}

	if (clear_root) {
		efree(object);
	}
}

void php_amqp_free_amqp_table(amqp_table_t *object)
{
	internal_php_amqp_free_amqp_table(object, 1);
}

/*
*Local variables:
*tab-width: 4
*c-basic-offset: 4
*End:
*vim600: noet sw=4 ts=4 fdm=marker
*vim<600: noet sw=4 ts=4
*/


text:
// https://github.com/dmtrKovalenko/cypress-real-events
import 'cypress-real-events/support';

// https://github.com/testing-library/cypress-testing-library
import '@testing-library/cypress/add-commands';

// https://github.com/percy/percy-cypress
import '@percy/cypress';


text:
// 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.

#include "arrow/testing/gtest_util.h"

#include "arrow/testing/extension_type.h"

#ifdef _WIN32
#include <crtdbg.h>
#include <io.h>
#else
#include <fcntl.h>     // IWYU pragma: keep
#include <sys/stat.h>  // IWYU pragma: keep
#include <sys/wait.h>  // IWYU pragma: keep
#include <unistd.h>    // IWYU pragma: keep
#endif

#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <locale>
#include <memory>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/datum.h"
#include "arrow/ipc/json_simple.h"
#include "arrow/pretty_print.h"
#include "arrow/status.h"
#include "arrow/table.h"
#include "arrow/type.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/future.h"
#include "arrow/util/io_util.h"
#include "arrow/util/logging.h"
#include "arrow/util/thread_pool.h"
#include "arrow/util/windows_compatibility.h"

namespace arrow {

using internal::checked_cast;
using internal::checked_pointer_cast;
using internal::ThreadPool;

std::vector<Type::type> AllTypeIds() {
  return {Type::NA,
          Type::BOOL,
          Type::INT8,
          Type::INT16,
          Type::INT32,
          Type::INT64,
          Type::UINT8,
          Type::UINT16,
          Type::UINT32,
          Type::UINT64,
          Type::HALF_FLOAT,
          Type::FLOAT,
          Type::DOUBLE,
          Type::DECIMAL128,
          Type::DECIMAL256,
          Type::DATE32,
          Type::DATE64,
          Type::TIME32,
          Type::TIME64,
          Type::TIMESTAMP,
          Type::INTERVAL_DAY_TIME,
          Type::INTERVAL_MONTHS,
          Type::DURATION,
          Type::STRING,
          Type::BINARY,
          Type::LARGE_STRING,
          Type::LARGE_BINARY,
          Type::FIXED_SIZE_BINARY,
          Type::STRUCT,
          Type::LIST,
          Type::LARGE_LIST,
          Type::FIXED_SIZE_LIST,
          Type::MAP,
          Type::DENSE_UNION,
          Type::SPARSE_UNION,
          Type::DICTIONARY,
          Type::EXTENSION,
          Type::INTERVAL_MONTH_DAY_NANO};
}

template <typename T, typename CompareFunctor>
void AssertTsSame(const T& expected, const T& actual, CompareFunctor&& compare) {
  if (!compare(actual, expected)) {
    std::stringstream pp_expected;
    std::stringstream pp_actual;
    ::arrow::PrettyPrintOptions options(/*indent=*/2);
    options.window = 50;
    ARROW_EXPECT_OK(PrettyPrint(expected, options, &pp_expected));
    ARROW_EXPECT_OK(PrettyPrint(actual, options, &pp_actual));
    FAIL() << "Got: \n" << pp_actual.str() << "\nExpected: \n" << pp_expected.str();
  }
}

template <typename CompareFunctor>
void AssertArraysEqualWith(const Array& expected, const Array& actual, bool verbose,
                           CompareFunctor&& compare) {
  std::stringstream diff;
  if (!compare(expected, actual, &diff)) {
    if (expected.data()->null_count != actual.data()->null_count) {
      diff << "Null counts differ. Expected " << expected.data()->null_count
           << " but was " << actual.data()->null_count << "\n";
    }
    if (verbose) {
      ::arrow::PrettyPrintOptions options(/*indent=*/2);
      options.window = 50;
      diff << "Expected:\n";
      ARROW_EXPECT_OK(PrettyPrint(expected, options, &diff));
      diff << "\nActual:\n";
      ARROW_EXPECT_OK(PrettyPrint(actual, options, &diff));
    }
    FAIL() << diff.str();
  }
}

void AssertArraysEqual(const Array& expected, const Array& actual, bool verbose,
                       const EqualOptions& options) {
  return AssertArraysEqualWith(
      expected, actual, verbose,
      [&](const Array& expected, const Array& actual, std::stringstream* diff) {
        return expected.Equals(actual, options.diff_sink(diff));
      });
}

void AssertArraysApproxEqual(const Array& expected, const Array& actual, bool verbose,
                             const EqualOptions& options) {
  return AssertArraysEqualWith(
      expected, actual, verbose,
      [&](const Array& expected, const Array& actual, std::stringstream* diff) {
        return expected.ApproxEquals(actual, options.diff_sink(diff));
      });
}

void AssertScalarsEqual(const Scalar& expected, const Scalar& actual, bool verbose,
                        const EqualOptions& options) {
  if (!expected.Equals(actual, options)) {
    std::stringstream diff;
    if (verbose) {
      diff << "Expected:\n" << expected.ToString();
      diff << "\nActual:\n" << actual.ToString();
    }
    FAIL() << diff.str();
  }
}

void AssertScalarsApproxEqual(const Scalar& expected, const Scalar& actual, bool verbose,
                              const EqualOptions& options) {
  if (!expected.ApproxEquals(actual, options)) {
    std::stringstream diff;
    if (verbose) {
      diff << "Expected:\n" << expected.ToString();
      diff << "\nActual:\n" << actual.ToString();
    }
    FAIL() << diff.str();
  }
}

void AssertBatchesEqual(const RecordBatch& expected, const RecordBatch& actual,
                        bool check_metadata) {
  AssertTsSame(expected, actual,
               [&](const RecordBatch& expected, const RecordBatch& actual) {
                 return expected.Equals(actual, check_metadata);
               });
}

void AssertBatchesApproxEqual(const RecordBatch& expected, const RecordBatch& actual) {
  AssertTsSame(expected, actual,
               [&](const RecordBatch& expected, const RecordBatch& actual) {
                 return expected.ApproxEquals(actual);
               });
}

void AssertChunkedEqual(const ChunkedArray& expected, const ChunkedArray& actual) {
  ASSERT_EQ(expected.num_chunks(), actual.num_chunks()) << "# chunks unequal";
  if (!actual.Equals(expected)) {
    std::stringstream diff;
    for (int i = 0; i < actual.num_chunks(); ++i) {
      auto c1 = actual.chunk(i);
      auto c2 = expected.chunk(i);
      diff << "# chunk " << i << std::endl;
      ARROW_IGNORE_EXPR(c1->Equals(c2, EqualOptions().diff_sink(&diff)));
    }
    FAIL() << diff.str();
  }
}

void AssertChunkedEqual(const ChunkedArray& actual, const ArrayVector& expected) {
  AssertChunkedEqual(ChunkedArray(expected, actual.type()), actual);
}

void AssertChunkedEquivalent(const ChunkedArray& expected, const ChunkedArray& actual) {
  // XXX: AssertChunkedEqual in gtest_util.h does not permit the chunk layouts
  // to be different
  if (!actual.Equals(expected)) {
    std::stringstream pp_expected;
    std::stringstream pp_actual;
    ::arrow::PrettyPrintOptions options(/*indent=*/2);
    options.window = 50;
    ARROW_EXPECT_OK(PrettyPrint(expected, options, &pp_expected));
    ARROW_EXPECT_OK(PrettyPrint(actual, options, &pp_actual));
    FAIL() << "Got: \n" << pp_actual.str() << "\nExpected: \n" << pp_expected.str();
  }
}

void AssertChunkedApproxEquivalent(const ChunkedArray& expected,
                                   const ChunkedArray& actual,
                                   const EqualOptions& equal_options) {
  if (!actual.ApproxEquals(expected, equal_options)) {
    std::stringstream pp_expected;
    std::stringstream pp_actual;
    ::arrow::PrettyPrintOptions options(/*indent=*/2);
    options.window = 50;
    ARROW_EXPECT_OK(PrettyPrint(expected, options, &pp_expected));
    ARROW_EXPECT_OK(PrettyPrint(actual, options, &pp_actual));
    FAIL() << "Got: \n" << pp_actual.str() << "\nExpected: \n" << pp_expected.str();
  }
}

void AssertBufferEqual(const Buffer& buffer, const std::vector<uint8_t>& expected) {
  ASSERT_EQ(static_cast<size_t>(buffer.size()), expected.size())
      << "Mismatching buffer size";
  const uint8_t* buffer_data = buffer.data();
  for (size_t i = 0; i < expected.size(); ++i) {
    ASSERT_EQ(buffer_data[i], expected[i]);
  }
}

void AssertBufferEqual(const Buffer& buffer, const std::string& expected) {
  ASSERT_EQ(static_cast<size_t>(buffer.size()), expected.length())
      << "Mismatching buffer size";
  const uint8_t* buffer_data = buffer.data();
  for (size_t i = 0; i < expected.size(); ++i) {
    ASSERT_EQ(buffer_data[i], expected[i]);
  }
}

void AssertBufferEqual(const Buffer& buffer, const Buffer& expected) {
  ASSERT_EQ(buffer.size(), expected.size()) << "Mismatching buffer size";
  ASSERT_TRUE(buffer.Equals(expected));
}

template <typename T>
std::string ToStringWithMetadata(const T& t, bool show_metadata) {
  return t.ToString(show_metadata);
}

std::string ToStringWithMetadata(const DataType& t, bool show_metadata) {
  return t.ToString();
}

template <typename T>
void AssertFingerprintablesEqual(const T& left, const T& right, bool check_metadata,
                                 const char* types_plural) {
  ASSERT_TRUE(left.Equals(right, check_metadata))
      << types_plural << " '" << ToStringWithMetadata(left, check_metadata) << "' and '"
      << ToStringWithMetadata(right, check_metadata) << "' should have compared equal";
  auto lfp = left.fingerprint();
  auto rfp = right.fingerprint();
  // Note: all types tested in this file should implement fingerprinting,
  // except extension types.
  if (check_metadata) {
    lfp += left.metadata_fingerprint();
    rfp += right.metadata_fingerprint();
  }
  ASSERT_EQ(lfp, rfp) << "Fingerprints for " << types_plural << " '"
                      << ToStringWithMetadata(left, check_metadata) << "' and '"
                      << ToStringWithMetadata(right, check_metadata)
                      << "' should have compared equal";
}

template <typename T>
void AssertFingerprintablesEqual(const std::shared_ptr<T>& left,
                                 const std::shared_ptr<T>& right, bool check_metadata,
                                 const char* types_plural) {
  ASSERT_NE(left, nullptr);
  ASSERT_NE(right, nullptr);
  AssertFingerprintablesEqual(*left, *right, check_metadata, types_plural);
}

template <typename T>
void AssertFingerprintablesNotEqual(const T& left, const T& right, bool check_metadata,
                                    const char* types_plural) {
  ASSERT_FALSE(left.Equals(right, check_metadata))
      << types_plural << " '" << ToStringWithMetadata(left, check_metadata) << "' and '"
      << ToStringWithMetadata(right, check_metadata) << "' should have compared unequal";
  auto lfp = left.fingerprint();
  auto rfp = right.fingerprint();
  // Note: all types tested in this file should implement fingerprinting,
  // except extension types.
  if (lfp != "" && rfp != "") {
    if (check_metadata) {
      lfp += left.metadata_fingerprint();
      rfp += right.metadata_fingerprint();
    }
    ASSERT_NE(lfp, rfp) << "Fingerprints for " << types_plural << " '"
                        << ToStringWithMetadata(left, check_metadata) << "' and '"
                        << ToStringWithMetadata(right, check_metadata)
                        << "' should have compared unequal";
  }
}

template <typename T>
void AssertFingerprintablesNotEqual(const std::shared_ptr<T>& left,
                                    const std::shared_ptr<T>& right, bool check_metadata,
                                    const char* types_plural) {
  ASSERT_NE(left, nullptr);
  ASSERT_NE(right, nullptr);
  AssertFingerprintablesNotEqual(*left, *right, check_metadata, types_plural);
}

#define ASSERT_EQUAL_IMPL(NAME, TYPE, PLURAL)                                            \
  void Assert##NAME##Equal(const TYPE& left, const TYPE& right, bool check_metadata) {   \
    AssertFingerprintablesEqual(left, right, check_metadata, PLURAL);                    \
  }                                                                                \
                                                                                \
  void Assert##NAME##Equal(const std::shared_ptr<TYPE>& left,                            \
                           const std::shared_ptr<TYPE>& right, bool check_metadata) {    \
    AssertFingerprintablesEqual(left, right, check_metadata, PLURAL);                    \
  }                                                                                \
                                                                                \
  void Assert##NAME##NotEqual(const TYPE& left, const TYPE& right,                       \
                              bool check_metadata) {                                     \
    AssertFingerprintablesNotEqual(left, right, check_metadata, PLURAL);                 \
  }                                                                                \
  void Assert##NAME##NotEqual(const std::shared_ptr<TYPE>& left,                         \
                              const std::shared_ptr<TYPE>& right, bool check_metadata) { \
    AssertFingerprintablesNotEqual(left, right, check_metadata, PLURAL);                 \
  }

ASSERT_EQUAL_IMPL(Type, DataType, "types")
ASSERT_EQUAL_IMPL(Field, Field, "fields")
ASSERT_EQUAL_IMPL(Schema, Schema, "schemas")
#undef ASSERT_EQUAL_IMPL

void AssertDatumsEqual(const Datum& expected, const Datum& actual, bool verbose) {
  ASSERT_EQ(expected.kind(), actual.kind())
      << "expected:" << expected.ToString() << " got:" << actual.ToString();

  switch (expected.kind()) {
    case Datum::SCALAR:
      AssertScalarsEqual(*expected.scalar(), *actual.scalar(), verbose);
      break;
    case Datum::ARRAY: {
      auto expected_array = expected.make_array();
      auto actual_array = actual.make_array();
      AssertArraysEqual(*expected_array, *actual_array, verbose);
    } break;
    case Datum::CHUNKED_ARRAY:
      AssertChunkedEquivalent(*expected.chunked_array(), *actual.chunked_array());
      break;
    default:
      // TODO: Implement better print
      ASSERT_TRUE(actual.Equals(expected));
      break;
  }
}

void AssertDatumsApproxEqual(const Datum& expected, const Datum& actual, bool verbose,
                             const EqualOptions& options) {
  ASSERT_EQ(expected.kind(), actual.kind())
      << "expected:" << expected.ToString() << " got:" << actual.ToString();

  switch (expected.kind()) {
    case Datum::SCALAR:
      AssertScalarsApproxEqual(*expected.scalar(), *actual.scalar(), verbose, options);
      break;
    case Datum::ARRAY: {
      auto expected_array = expected.make_array();
      auto actual_array = actual.make_array();
      AssertArraysApproxEqual(*expected_array, *actual_array, verbose, options);
      break;
    }
    case Datum::CHUNKED_ARRAY: {
      auto expected_array = expected.chunked_array();
      auto actual_array = actual.chunked_array();
      AssertChunkedApproxEquivalent(*expected_array, *actual_array, options);
      break;
    }
    default:
      // TODO: Implement better print
      ASSERT_TRUE(actual.Equals(expected));
      break;
  }
}

std::shared_ptr<Array> ArrayFromJSON(const std::shared_ptr<DataType>& type,
                                     std::string_view json) {
  EXPECT_OK_AND_ASSIGN(auto out, ipc::internal::json::ArrayFromJSON(type, json));
  return out;
}

std::shared_ptr<Array> DictArrayFromJSON(const std::shared_ptr<DataType>& type,
                                         std::string_view indices_json,
                                         std::string_view dictionary_json) {
  std::shared_ptr<Array> out;
  ABORT_NOT_OK(
      ipc::internal::json::DictArrayFromJSON(type, indices_json, dictionary_json, &out));
  return out;
}

std::shared_ptr<ChunkedArray> ChunkedArrayFromJSON(const std::shared_ptr<DataType>& type,
                                                   const std::vector<std::string>& json) {
  std::shared_ptr<ChunkedArray> out;
  ABORT_NOT_OK(ipc::internal::json::ChunkedArrayFromJSON(type, json, &out));
  return out;
}

std::shared_ptr<RecordBatch> RecordBatchFromJSON(const std::shared_ptr<Schema>& schema,
                                                 std::string_view json) {
  // Parse as a StructArray
  auto struct_type = struct_(schema->fields());
  std::shared_ptr<Array> struct_array = ArrayFromJSON(struct_type, json);

  // Convert StructArray to RecordBatch
  return *RecordBatch::FromStructArray(struct_array);
}

std::shared_ptr<Scalar> ScalarFromJSON(const std::shared_ptr<DataType>& type,
                                       std::string_view json) {
  std::shared_ptr<Scalar> out;
  ABORT_NOT_OK(ipc::internal::json::ScalarFromJSON(type, json, &out));
  return out;
}

std::shared_ptr<Scalar> DictScalarFromJSON(const std::shared_ptr<DataType>& type,
                                           std::string_view index_json,
                                           std::string_view dictionary_json) {
  std::shared_ptr<Scalar> out;
  ABORT_NOT_OK(
      ipc::internal::json::DictScalarFromJSON(type, index_json, dictionary_json, &out));
  return out;
}

std::shared_ptr<Table> TableFromJSON(const std::shared_ptr<Schema>& schema,
                                     const std::vector<std::string>& json) {
  std::vector<std::shared_ptr<RecordBatch>> batches;
  for (const std::string& batch_json : json) {
    batches.push_back(RecordBatchFromJSON(schema, batch_json));
  }
  return *Table::FromRecordBatches(schema, std::move(batches));
}

Result<std::optional<std::string>> PrintArrayDiff(const ChunkedArray& expected,
                                                  const ChunkedArray& actual) {
  if (actual.Equals(expected)) {
    return std::nullopt;
  }

  std::stringstream ss;
  if (expected.length() != actual.length()) {
    ss << "Expected length " << expected.length() << " but was actually "
       << actual.length();
    return ss.str();
  }

  PrettyPrintOptions options(/*indent=*/2);
  options.window = 50;
  RETURN_NOT_OK(internal::ApplyBinaryChunked(
      actual, expected,
      [&](const Array& left_piece, const Array& right_piece, int64_t position) {
        std::stringstream diff;
        if (!left_piece.Equals(right_piece, EqualOptions().diff_sink(&diff))) {
          ss << "Unequal at absolute position " << position << "\n" << diff.str();
          ss << "Expected:\n";
          ARROW_EXPECT_OK(PrettyPrint(right_piece, options, &ss));
          ss << "\nActual:\n";
          ARROW_EXPECT_OK(PrettyPrint(left_piece, options, &ss));
        }
        return Status::OK();
      }));
  return ss.str();
}

void AssertTablesEqual(const Table& expected, const Table& actual, bool same_chunk_layout,
                       bool combine_chunks) {
  ASSERT_EQ(expected.num_columns(), actual.num_columns());

  if (combine_chunks) {
    auto pool = default_memory_pool();
    ASSERT_OK_AND_ASSIGN(auto new_expected, expected.CombineChunks(pool));
    ASSERT_OK_AND_ASSIGN(auto new_actual, actual.CombineChunks(pool));

    AssertTablesEqual(*new_expected, *new_actual, false, false);
    return;
  }

  if (same_chunk_layout) {
    for (int i = 0; i < actual.num_columns(); ++i) {
      AssertChunkedEqual(*expected.column(i), *actual.column(i));
    }
  } else {
    std::stringstream ss;
    for (int i = 0; i < actual.num_columns(); ++i) {
      auto actual_col = actual.column(i);
      auto expected_col = expected.column(i);

      ASSERT_OK_AND_ASSIGN(auto diff, PrintArrayDiff(*expected_col, *actual_col));
      if (diff.has_value()) {
        FAIL() << *diff;
      }
    }
  }
}

template <typename CompareFunctor>
void CompareBatchWith(const RecordBatch& left, const RecordBatch& right,
                      bool compare_metadata, CompareFunctor&& compare) {
  if (!left.schema()->Equals(*right.schema(), compare_metadata)) {
    FAIL() << "Left schema: " << left.schema()->ToString(compare_metadata)
           << "\nRight schema: " << right.schema()->ToString(compare_metadata);
  }
  ASSERT_EQ(left.num_columns(), right.num_columns())
      << left.schema()->ToString() << " result: " << right.schema()->ToString();
  ASSERT_EQ(left.num_rows(), right.num_rows());
  for (int i = 0; i < left.num_columns(); ++i) {
    if (!compare(*left.column(i), *right.column(i))) {
      std::stringstream ss;
      ss << "Idx: " << i << " Name: " << left.column_name(i);
      ss << std::endl << "Left: ";
      ASSERT_OK(PrettyPrint(*left.column(i), 0, &ss));
      ss << std::endl << "Right: ";
      ASSERT_OK(PrettyPrint(*right.column(i), 0, &ss));
      FAIL() << ss.str();
    }
  }
}

void CompareBatch(const RecordBatch& left, const RecordBatch& right,
                  bool compare_metadata) {
  return CompareBatchWith(
      left, right, compare_metadata,
      [](const Array& left, const Array& right) { return left.Equals(right); });
}

void ApproxCompareBatch(const RecordBatch& left, const RecordBatch& right,
                        bool compare_metadata) {
  return CompareBatchWith(
      left, right, compare_metadata,
      [](const Array& left, const Array& right) { return left.ApproxEquals(right); });
}

std::shared_ptr<Array> TweakValidityBit(const std::shared_ptr<Array>& array,
                                        int64_t index, bool validity) {
  auto data = array->data()->Copy();
  if (data->buffers[0] == nullptr) {
    data->buffers[0] = *AllocateBitmap(data->length);
    bit_util::SetBitsTo(data->buffers[0]->mutable_data(), 0, data->length, true);
  }
  bit_util::SetBitTo(data->buffers[0]->mutable_data(), index, validity);
  data->null_count = kUnknownNullCount;
  // Need to return a new array, because Array caches the null bitmap pointer
  return MakeArray(data);
}

// XXX create a testing/io.{h,cc}?

#if defined(_WIN32)
static void InvalidParamHandler(const wchar_t* expr, const wchar_t* func,
                                const wchar_t* source_file, unsigned int source_line,
                                uintptr_t reserved) {
  wprintf(L"Invalid parameter in function '%s'. Source: '%s' line %d expression '%s'\n",
          func, source_file, source_line, expr);
}
#endif

bool FileIsClosed(int fd) {
#if defined(_WIN32)
  // Disables default behavior on wrong params which causes the application to crash
  // https://msdn.microsoft.com/en-us/library/ksazx244.aspx
  _set_invalid_parameter_handler(InvalidParamHandler);

  // Disables possible assertion alert box on invalid input arguments
  _CrtSetReportMode(_CRT_ASSERT, 0);

  int new_fd = _dup(fd);
  if (new_fd == -1) {
    return errno == EBADF;
  }
  _close(new_fd);
  return false;
#else
  if (-1 != fcntl(fd, F_GETFD)) {
    return false;
  }
  return errno == EBADF;
#endif
}

bool LocaleExists(const char* locale) {
  try {
    std::locale loc(locale);
    return true;
  } catch (std::runtime_error&) {
    return false;
  }
}

class LocaleGuard::Impl {
 public:
  explicit Impl(const char* new_locale) : global_locale_(std::locale()) {
    try {
      std::locale::global(std::locale(new_locale));
    } catch (std::runtime_error&) {
      ARROW_LOG(WARNING) << "Locale unavailable (ignored): '" << new_locale << "'";
    }
  }

  ~Impl() { std::locale::global(global_locale_); }

 protected:
  std::locale global_locale_;
};

LocaleGuard::LocaleGuard(const char* new_locale) : impl_(new Impl(new_locale)) {}

LocaleGuard::~LocaleGuard() {}

EnvVarGuard::EnvVarGuard(const std::string& name, const std::string& value)
    : name_(name) {
  auto maybe_value = arrow::internal::GetEnvVar(name);
  if (maybe_value.ok()) {
    was_set_ = true;
    old_value_ = *std::move(maybe_value);
  } else {
    was_set_ = false;
  }
  ARROW_CHECK_OK(arrow::internal::SetEnvVar(name, value));
}

EnvVarGuard::~EnvVarGuard() {
  if (was_set_) {
    ARROW_CHECK_OK(arrow::internal::SetEnvVar(name_, old_value_));
  } else {
    ARROW_CHECK_OK(arrow::internal::DelEnvVar(name_));
  }
}

struct SignalHandlerGuard::Impl {
  int signum_;
  internal::SignalHandler old_handler_;

  Impl(int signum, const internal::SignalHandler& handler)
      : signum_(signum), old_handler_(*internal::SetSignalHandler(signum, handler)) {}

  ~Impl() { ARROW_EXPECT_OK(internal::SetSignalHandler(signum_, old_handler_)); }
};

SignalHandlerGuard::SignalHandlerGuard(int signum, Callback cb)
    : SignalHandlerGuard(signum, internal::SignalHandler(cb)) {}

SignalHandlerGuard::SignalHandlerGuard(int signum, const internal::SignalHandler& handler)
    : impl_(new Impl{signum, handler}) {}

SignalHandlerGuard::~SignalHandlerGuard() = default;

namespace {

// Used to prevent compiler optimizing away side-effect-less statements
volatile int throw_away = 0;

}  // namespace

void AssertZeroPadded(const Array& array) {
  for (const auto& buffer : array.data()->buffers) {
    if (buffer) {
      const int64_t padding = buffer->capacity() - buffer->size();
      if (padding > 0) {
        std::vector<uint8_t> zeros(padding);
        ASSERT_EQ(0, memcmp(buffer->data() + buffer->size(), zeros.data(), padding));
      }
    }
  }
}

void TestInitialized(const Array& array) { TestInitialized(*array.data()); }

void TestInitialized(const ArrayData& array) {
  uint8_t total = 0;
  for (const auto& buffer : array.buffers) {
    if (buffer && buffer->capacity() > 0) {
      auto data = buffer->data();
      for (int64_t i = 0; i < buffer->size(); ++i) {
        total ^= data[i];
      }
    }
  }
  uint8_t total_bit = 0;
  for (uint32_t mask = 1; mask < 256; mask <<= 1) {
    total_bit ^= (total & mask) != 0;
  }
  // This is a dummy condition on all the bits of `total` (which depend on the
  // entire buffer data).  If not all bits are well-defined, Valgrind will
  // error with "Conditional jump or move depends on uninitialised value(s)".
  if (total_bit == 0) {
    ++throw_away;
  }
  for (const auto& child : array.child_data) {
    TestInitialized(*child);
  }
  if (array.dictionary) {
    TestInitialized(*array.dictionary);
  }
}

void SleepFor(double seconds) {
  std::this_thread::sleep_for(
      std::chrono::nanoseconds(static_cast<int64_t>(seconds * 1e9)));
}

#ifdef _WIN32
void SleepABit() {
  LARGE_INTEGER freq, start, now;
  QueryPerformanceFrequency(&freq);
  // 1 ms
  auto desired = freq.QuadPart / 1000;
  if (desired <= 0) {
    // Fallback to STL sleep if high resolution clock not available, tests may fail,
    // shouldn't really happen
    SleepFor(1e-3);
    return;
  }
  QueryPerformanceCounter(&start);
  while (true) {
    std::this_thread::yield();
    QueryPerformanceCounter(&now);
    auto elapsed = now.QuadPart - start.QuadPart;
    if (elapsed > desired) {
      break;
    }
  }
}
#else
// std::this_thread::sleep_for should be high enough resolution on non-Windows systems
void SleepABit() { SleepFor(1e-3); }
#endif

void BusyWait(double seconds, std::function<bool()> predicate) {
  const double period = 0.001;
  for (int i = 0; !predicate() && i * period < seconds; ++i) {
    SleepFor(period);
  }
}

namespace {

// These threads will spend most of their time sleeping so there
// is no need to base this on the # of cores.  Instead it should be
// high enough to ensure good concurrency when there is concurrent hardware.
//
// Note using a thread pool prevents potentially hitting thread count limits
// in stress tests (ARROW-17927).
constexpr int kNumSleepThreads = 32;

std::shared_ptr<ThreadPool> CreateSleepThreadPool() {
  Result<std::shared_ptr<ThreadPool>> thread_pool =
      ThreadPool::MakeEternal(kNumSleepThreads);
  return thread_pool.ValueOrDie();
}

}  // namespace

Future<> SleepABitAsync() {
  static std::shared_ptr<ThreadPool> sleep_tp = CreateSleepThreadPool();
  return DeferNotOk(sleep_tp->Submit([] { SleepABit(); }));
}

///////////////////////////////////////////////////////////////////////////
// Extension types

bool UuidType::ExtensionEquals(const ExtensionType& other) const {
  return (other.extension_name() == this->extension_name());
}

std::shared_ptr<Array> UuidType::MakeArray(std::shared_ptr<ArrayData> data) const {
  DCHECK_EQ(data->type->id(), Type::EXTENSION);
  DCHECK_EQ("uuid", static_cast<const ExtensionType&>(*data->type).extension_name());
  return std::make_shared<UuidArray>(data);
}

Result<std::shared_ptr<DataType>> UuidType::Deserialize(
    std::shared_ptr<DataType> storage_type, const std::string& serialized) const {
  if (serialized != "uuid-serialized") {
    return Status::Invalid("Type identifier did not match: '", serialized, "'");
  }
  if (!storage_type->Equals(*fixed_size_binary(16))) {
    return Status::Invalid("Invalid storage type for UuidType: ",
                           storage_type->ToString());
  }
  return std::make_shared<UuidType>();
}

bool SmallintType::ExtensionEquals(const ExtensionType& other) const {
  return (other.extension_name() == this->extension_name());
}

std::shared_ptr<Array> SmallintType::MakeArray(std::shared_ptr<ArrayData> data) const {
  DCHECK_EQ(data->type->id(), Type::EXTENSION);
  DCHECK_EQ("smallint", static_cast<const ExtensionType&>(*data->type).extension_name());
  return std::make_shared<SmallintArray>(data);
}

Result<std::shared_ptr<DataType>> SmallintType::Deserialize(
    std::shared_ptr<DataType> storage_type, const std::string& serialized) const {
  if (serialized != "smallint") {
    return Status::Invalid("Type identifier did not match: '", serialized, "'");
  }
  if (!storage_type->Equals(*int16())) {
    return Status::Invalid("Invalid storage type for SmallintType: ",
                           storage_type->ToString());
  }
  return std::make_shared<SmallintType>();
}

bool ListExtensionType::ExtensionEquals(const ExtensionType& other) const {
  return (other.extension_name() == this->extension_name());
}

std::shared_ptr<Array> ListExtensionType::MakeArray(
    std::shared_ptr<ArrayData> data) const {
  DCHECK_EQ(data->type->id(), Type::EXTENSION);
  DCHECK_EQ("list-ext", static_cast<const ExtensionType&>(*data->type).extension_name());
  return std::make_shared<ListExtensionArray>(data);
}

Result<std::shared_ptr<DataType>> ListExtensionType::Deserialize(
    std::shared_ptr<DataType> storage_type, const std::string& serialized) const {
  if (serialized != "list-ext") {
    return Status::Invalid("Type identifier did not match: '", serialized, "'");
  }
  if (!storage_type->Equals(*list(int32()))) {
    return Status::Invalid("Invalid storage type for ListExtensionType: ",
                           storage_type->ToString());
  }
  return std::make_shared<ListExtensionType>();
}

bool DictExtensionType::ExtensionEquals(const ExtensionType& other) const {
  return (other.extension_name() == this->extension_name());
}

std::shared_ptr<Array> DictExtensionType::MakeArray(
    std::shared_ptr<ArrayData> data) const {
  DCHECK_EQ(data->type->id(), Type::EXTENSION);
  DCHECK(ExtensionEquals(checked_cast<const ExtensionType&>(*data->type)));
  // No need for a specific ExtensionArray derived class
  return std::make_shared<ExtensionArray>(data);
}

Result<std::shared_ptr<DataType>> DictExtensionType::Deserialize(
    std::shared_ptr<DataType> storage_type, const std::string& serialized) const {
  if (serialized != "dict-extension-serialized") {
    return Status::Invalid("Type identifier did not match: '", serialized, "'");
  }
  if (!storage_type->Equals(*storage_type_)) {
    return Status::Invalid("Invalid storage type for DictExtensionType: ",
                           storage_type->ToString());
  }
  return std::make_shared<DictExtensionType>();
}

bool Complex128Type::ExtensionEquals(const ExtensionType& other) const {
  return (other.extension_name() == this->extension_name());
}

std::shared_ptr<Array> Complex128Type::MakeArray(std::shared_ptr<ArrayData> data) const {
  DCHECK_EQ(data->type->id(), Type::EXTENSION);
  DCHECK(ExtensionEquals(checked_cast<const ExtensionType&>(*data->type)));
  return std::make_shared<Complex128Array>(data);
}

Result<std::shared_ptr<DataType>> Complex128Type::Deserialize(
    std::shared_ptr<DataType> storage_type, const std::string& serialized) const {
  if (serialized != "complex128-serialized") {
    return Status::Invalid("Type identifier did not match: '", serialized, "'");
  }
  if (!storage_type->Equals(*storage_type_)) {
    return Status::Invalid("Invalid storage type for Complex128Type: ",
                           storage_type->ToString());
  }
  return std::make_shared<Complex128Type>();
}

std::shared_ptr<DataType> uuid() { return std::make_shared<UuidType>(); }

std::shared_ptr<DataType> smallint() { return std::make_shared<SmallintType>(); }

std::shared_ptr<DataType> list_extension_type() {
  return std::make_shared<ListExtensionType>();
}

std::shared_ptr<DataType> dict_extension_type() {
  return std::make_shared<DictExtensionType>();
}

std::shared_ptr<DataType> complex128() { return std::make_shared<Complex128Type>(); }

std::shared_ptr<Array> MakeComplex128(const std::shared_ptr<Array>& real,
                                      const std::shared_ptr<Array>& imag) {
  auto type = complex128();
  std::shared_ptr<Array> storage(
      new StructArray(checked_cast<const ExtensionType&>(*type).storage_type(),
                      real->length(), {real, imag}));
  return ExtensionType::WrapArray(type, storage);
}

std::shared_ptr<Array> ExampleUuid() {
  auto arr = ArrayFromJSON(
      fixed_size_binary(16),
      "[null, \"abcdefghijklmno0\", \"abcdefghijklmno1\", \"abcdefghijklmno2\"]");
  return ExtensionType::WrapArray(uuid(), arr);
}

std::shared_ptr<Array> ExampleSmallint() {
  auto arr = ArrayFromJSON(int16(), "[-32768, null, 1, 2, 3, 4, 32767]");
  return ExtensionType::WrapArray(smallint(), arr);
}

std::shared_ptr<Array> ExampleDictExtension() {
  auto arr = DictArrayFromJSON(dictionary(int8(), utf8()), "[0, 1, null, 1]",
                               R"(["foo", "bar"])");
  return ExtensionType::WrapArray(dict_extension_type(), arr);
}

std::shared_ptr<Array> ExampleComplex128() {
  auto arr = ArrayFromJSON(struct_({field("", float64()), field("", float64())}),
                           "[[1.0, -2.5], null, [3.0, -4.5]]");
  return ExtensionType::WrapArray(complex128(), arr);
}

ExtensionTypeGuard::ExtensionTypeGuard(const std::shared_ptr<DataType>& type)
    : ExtensionTypeGuard(DataTypeVector{type}) {}

ExtensionTypeGuard::ExtensionTypeGuard(const DataTypeVector& types) {
  for (const auto& type : types) {
    ARROW_CHECK_EQ(type->id(), Type::EXTENSION);
    auto ext_type = checked_pointer_cast<ExtensionType>(type);

    ARROW_CHECK_OK(RegisterExtensionType(ext_type));
    extension_names_.push_back(ext_type->extension_name());
    DCHECK(!extension_names_.back().empty());
  }
}

ExtensionTypeGuard::~ExtensionTypeGuard() {
  for (const auto& name : extension_names_) {
    ARROW_CHECK_OK(UnregisterExtensionType(name));
  }
}

class GatingTask::Impl : public std::enable_shared_from_this<GatingTask::Impl> {
 public:
  explicit Impl(double timeout_seconds)
      : timeout_seconds_(timeout_seconds), status_(), unlocked_(false) {
    unlocked_future_ = Future<>::Make();
  }

  ~Impl() {
    if (num_running_ != num_launched_) {
      ADD_FAILURE()
          << "A GatingTask instance was destroyed but some underlying tasks did not "
             "start running"
          << std::endl;
    } else if (num_finished_ != num_launched_) {
      ADD_FAILURE()
          << "A GatingTask instance was destroyed but some underlying tasks did not "
             "finish running"
          << std::endl;
    }
  }

  std::function<void()> Task() {
    num_launched_++;
    auto self = shared_from_this();
    return [self] { self->RunTask(); };
  }

  Future<> AsyncTask() {
    std::lock_guard<std::mutex> lk(mx_);
    num_launched_++;
    num_running_++;
    running_cv_.notify_all();
    /// TODO(ARROW-13004) Could maybe implement this check with future chains
    /// if we check to see if the future has been "consumed" or not
    num_finished_++;
    return unlocked_future_;
  }

  void RunTask() {
    std::unique_lock<std::mutex> lk(mx_);
    num_running_++;
    running_cv_.notify_all();
    if (!unlocked_cv_.wait_for(
            lk, std::chrono::nanoseconds(static_cast<int64_t>(timeout_seconds_ * 1e9)),
            [this] { return unlocked_; })) {
      status_ &= Status::Invalid("Timed out (" + std::to_string(timeout_seconds_) + "," +
                                 std::to_string(unlocked_) +
                                 " seconds) waiting for the gating task to be unlocked");
    }
    num_finished_++;
  }

  Status WaitForRunning(int count) {
    std::unique_lock<std::mutex> lk(mx_);
    if (running_cv_.wait_for(
            lk, std::chrono::nanoseconds(static_cast<int64_t>(timeout_seconds_ * 1e9)),
            [this, count] { return num_running_ >= count; })) {
      return Status::OK();
    }
    return Status::Invalid("Timed out waiting for tasks to launch");
  }

  Status Unlock() {
    {
      std::lock_guard<std::mutex> lk(mx_);
      unlocked_ = true;
      unlocked_cv_.notify_all();
    }
    unlocked_future_.MarkFinished();
    return status_;
  }

 private:
  double timeout_seconds_;
  Status status_;
  bool unlocked_;
  std::atomic<int> num_launched_{0};
  int num_running_ = 0;
  int num_finished_ = 0;
  std::mutex mx_;
  std::condition_variable running_cv_;
  std::condition_variable unlocked_cv_;
  Future<> unlocked_future_;
};

GatingTask::GatingTask(double timeout_seconds) : impl_(new Impl(timeout_seconds)) {}

GatingTask::~GatingTask() {}

std::function<void()> GatingTask::Task() { return impl_->Task(); }

Future<> GatingTask::AsyncTask() { return impl_->AsyncTask(); }

Status GatingTask::Unlock() { return impl_->Unlock(); }

Status GatingTask::WaitForRunning(int count) { return impl_->WaitForRunning(count); }

std::shared_ptr<GatingTask> GatingTask::Make(double timeout_seconds) {
  return std::make_shared<GatingTask>(timeout_seconds);
}

}  // namespace arrow


text:
#include "lineDetector.h"

using namespace iotik::blocks::details;

LineDetectorBlock::LineDetectorBlock()
{
}

void LineDetectorBlock::run()
{
	//evalCode(stringProperty("Variable") + " = lineSensor[0]");
	emit done(mNextBlockId);
}


text:
package com.google.gerrit.server.mail;

public class Address {
  public static Address parse(final String in) {
    final int lt = in.indexOf('<');
    final int gt = in.indexOf('>');
    final int at = in.indexOf("@");
    if (0 <= lt && lt < gt && lt + 1 < at && at + 1 < gt) {
      final String email = in.substring(lt + 1, gt).trim();
      final String name = in.substring(0, lt).trim();
      return new Address(name.length() > 0 ? name : null, email);
    }

    if (lt < 0 && gt < 0 && 0 < at && at < in.length() - 1) {
      return new Address(in);
    }

    throw new IllegalArgumentException("Invalid email address: " + in);
  }

  final String name;
  final String email;

  public Address(String email) {
    this(null, email);
  }

  public Address(String name, String email) {
    this.name = name;
    this.email = email;
  }

  public String getName() {
    return name;
  }

  public String getEmail() {
    return email;
  }

  @Override
  public int hashCode() {
    return email.hashCode();
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof Address) {
      return email.equals(((Address) other).email);
    }
    return false;
  }

  @Override
  public String toString() {
    return toHeaderString();
  }

  public String toHeaderString() {
    if (name != null) {
      return quotedPhrase(name) + " <" + email + ">";
    } else if (isSimple()) {
      return email;
    }
    return "<" + email + ">";
  }

  private static final String MUST_QUOTE_EMAIL = "()<>,;:\\\"[]";
  private static final String MUST_QUOTE_NAME = MUST_QUOTE_EMAIL + "@.";

  private boolean isSimple() {
    for (int i = 0; i < email.length(); i++) {
      final char c = email.charAt(i);
      if (c <= ' ' || 0x7F <= c || MUST_QUOTE_EMAIL.indexOf(c) != -1) {
        return false;
      }
    }
    return true;
  }

  private static String quotedPhrase(final String name) {
    if (EmailHeader.needsQuotedPrintable(name)) {
      return EmailHeader.quotedPrintable(name);
    }
    for (int i = 0; i < name.length(); i++) {
      final char c = name.charAt(i);
      if (MUST_QUOTE_NAME.indexOf(c) != -1) {
        return wrapInQuotes(name);
      }
    }
    return name;
  }

  private static String wrapInQuotes(final String name) {
    final StringBuilder r = new StringBuilder(2 + name.length());
    r.append('"');
    for (int i = 0; i < name.length(); i++) {
      char c = name.charAt(i);
      if (c == '"' || c == '\\') {
        r.append('\\');
      }
      r.append(c);
    }
    r.append('"');
    return r.toString();
  }
}


text:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Obsidian.Application.Cryptography;
using Obsidian.Domain;
using Obsidian.Foundation.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;

namespace Obsidian.Application.OAuth20
{
    [Service(ServiceLifetime.Scoped)]
    public class OAuth20Service
    {
        private readonly AsymmetricSecurityKey _signingKey;
        private readonly OAuth20Configuration _config;
        private readonly RsaSigningService _rsaService;

        public OAuth20Service(IOptions<OAuth20Configuration> options, RsaSigningService signingService)
        {
            _config = options.Value;
            _rsaService = signingService;
            _signingKey = new RsaSecurityKey(_rsaService.GetPrivateKey());
        }

        public string GenerateAccessToken(User user, IEnumerable<PermissionScope> scopes)
        {
            var signingCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha512Signature);
            var claims = user.GetClaims(scopes);
            var jwt = new JwtSecurityToken(
                issuer: _config.TokenIssuer,
                audience: _config.TokenAudience,
                claims: claims,
                signingCredentials: signingCredentials,
                expires: DateTime.Now.AddMinutes(5)
                );
            var token = new JwtSecurityTokenHandler().WriteToken(jwt);
            return token;
        }

        public bool VerifyToken(string token)
        {
            var handler = new JwtSecurityTokenHandler();
            var param = new TokenValidationParameters
            {
                AuthenticationType = AuthenticationSchemes.Bearer,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _signingKey,
                ValidateIssuer = true,
                ValidIssuer = _config.TokenIssuer,
                ValidAudience = _config.TokenAudience
            };
            var principal = handler.ValidateToken(token, param, out var vt);
            return principal != null;
        }
    }
}


text:
package csi

import (
	"fmt"

	gofig "github.com/akutz/gofig/types"

	apitypes "github.com/thecodeteam/rexray/libstorage/api/types"
	apiutils "github.com/thecodeteam/rexray/libstorage/api/utils"
	dvol "github.com/docker/go-plugins-helpers/volume"
)

type dockerLegacy struct {
	ctx    apitypes.Context
	config gofig.Config
	lsc    apitypes.Client
}

func newDockerLegacy(
	ctx apitypes.Context,
	config gofig.Config,
	lsc apitypes.Client) (*dockerLegacy, error) {

	endpoint := &dockerLegacy{
		ctx:    ctx,
		config: config,
		lsc:    lsc,
	}

	ctx.Info("docker-legacy: created Docker legacy endpoint")
	return endpoint, nil
}

func (d *dockerLegacy) Create(req *dvol.CreateRequest) error {

	store := apiutils.NewStoreWithVars(req.Options)
	volType := store.GetStringPtr("type")
	if volType == nil {
		volType = store.GetStringPtr("volumetype")
	}

	_, err := d.lsc.Integration().Create(
		d.ctx,
		req.Name,
		&apitypes.VolumeCreateOpts{
			AvailabilityZone: store.GetStringPtr("availabilityZone"),
			IOPS:             store.GetInt64Ptr("iops"),
			Size:             store.GetInt64Ptr("size"),
			Type:             volType,
			Encrypted:        store.GetBoolPtr("encrypted"),
			Opts:             store,
		})

	if err != nil {
		err = fmt.Errorf(
			"docker-legacy: Create: %s: failed: %v",
			req.Name, err)
		d.ctx.Error(err)
		return err
	}

	return nil
}

func (d *dockerLegacy) List() (*dvol.ListResponse, error) {

	vols, err := d.lsc.Integration().List(d.ctx, apiutils.NewStore())

	if err != nil {
		err = fmt.Errorf("docker-legacy: List: failed: %v", err)
		d.ctx.Error(err)
		return nil, err
	}

	res := &dvol.ListResponse{Volumes: make([]*dvol.Volume, len(vols))}
	for i, v := range vols {
		res.Volumes[i] = d.toDockerVolume(v)
	}

	return res, nil
}

func (d *dockerLegacy) Get(req *dvol.GetRequest) (*dvol.GetResponse, error) {

	vol, err := d.lsc.Integration().Inspect(
		d.ctx,
		req.Name,
		apiutils.NewStore())

	if err != nil {
		err = fmt.Errorf(
			"docker-legacy: Get: %s: failed: %v",
			req.Name, err)
		d.ctx.Error(err)
		return nil, err
	}

	return &dvol.GetResponse{Volume: d.toDockerVolume(vol)}, nil
}

func (d *dockerLegacy) Remove(req *dvol.RemoveRequest) error {

	err := d.lsc.Integration().Remove(
		d.ctx,
		req.Name,
		&apitypes.VolumeRemoveOpts{Opts: apiutils.NewStore()})

	if err != nil {
		err = fmt.Errorf(
			"docker-legacy: Remove: %s: failed: %v",
			req.Name, err)
		d.ctx.Error(err)
		return err
	}

	return nil
}

func (d *dockerLegacy) Path(req *dvol.PathRequest) (*dvol.PathResponse, error) {

	mountPath, err := d.lsc.Integration().Path(
		d.ctx,
		"",
		req.Name,
		apiutils.NewStore())

	if err != nil {
		err = fmt.Errorf(
			"docker-legacy: Path: %s: failed: %v",
			req.Name, err)
		d.ctx.Error(err)
		return nil, err
	}

	return &dvol.PathResponse{Mountpoint: mountPath}, nil
}

func (d *dockerLegacy) Mount(
	req *dvol.MountRequest) (*dvol.MountResponse, error) {

	mountPath, _, err := d.lsc.Integration().Mount(
		d.ctx,
		"",
		req.Name,
		&apitypes.VolumeMountOpts{})

	if err != nil {
		err = fmt.Errorf(
			"docker-legacy: Mount: %s: failed: %v",
			req.Name, err)
		d.ctx.Error(err)
		return nil, err
	}

	return &dvol.MountResponse{Mountpoint: mountPath}, nil
}

func (d *dockerLegacy) Unmount(req *dvol.UnmountRequest) error {

	_, err := d.lsc.Integration().Unmount(
		d.ctx,
		"",
		req.Name,
		apiutils.NewStore())

	if err != nil {
		err = fmt.Errorf(
			"docker-legacy: Unmount: %s: failed: %v",
			req.Name, err)
		d.ctx.Error(err)
		return err
	}

	return nil
}

func (d *dockerLegacy) Capabilities() *dvol.CapabilitiesResponse {
	res := &dvol.CapabilitiesResponse{}
	res.Capabilities.Scope = "global"
	return res
}

func (d *dockerLegacy) toDockerVolume(v apitypes.VolumeMapping) *dvol.Volume {
	return &dvol.Volume{
		Name:       v.VolumeName(),
		Mountpoint: v.MountPoint(),
		Status:     v.Status(),
	}
}


text: This repository [has moved](https://github.com/paychex/tracking)!


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Plugins
{
    using System.Collections.Immutable;
    using System.IO;

    public interface IPostProcessorHost
    {
        /// <summary>
        /// Source file information
        /// </summary>
        IImmutableList<SourceFileInfo> SourceFileInfos { get; }

        /// <summary>
        /// Whether the post processor should trace incremental information.
        /// </summary>
        bool ShouldTraceIncrementalInfo { get; }

        /// <summary>
        /// Whether the post processor can be incremental.
        /// </summary>
        bool IsIncremental { get; }

        /// <summary>
        /// Load context info from last post processing.
        /// </summary>
        /// <returns>Stream to be read, return null when there is no last info.</returns>
        Stream LoadContextInfo();

        /// <summary>
        /// Save context information to current post processing.
        /// </summary>
        /// <returns>Stream to be written, return null when should not trace incremental information.</returns>
        Stream SaveContextInfo();
    }
}


text:
package org.spongepowered.asm.mixin.transformer;

import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.transformer.MixinConfig.IListener;

/**
 * Coprocessors are parts of the mixin pipeline which aren't involved in
 * applying mixins but handle other transformation tasks required by
 * mixins.
 *
 *
Such tasks as {@link MixinCoprocessorAccessor making accessor mixins
 * loadable (and transforming the accessors therein)}, {@link
 * MixinCoprocessorSyntheticInner exposing synthetic inner classes to all
 * consumers} and {@link MixinCoprocessorNestHost applying nest member
 * attributes to nest hosts which may themselves not be mixin targets} are
 * handled by different coprocessors.

 *
 *
These classes were previously encapsulated in a single companion class
 * called <tt>MixinPostProcessor</tt>, but the mixture of responsibilities of
 * that class made its role unclear and slightly schizophrenic.

 */
abstract class MixinCoprocessor implements IListener {

    /**
     * The result of a specific coprocessor's action on a supplied class,
     * effectively a tuple of <tt>transformed</tt> and <tt>passthrough</tt>
     * which combines the normal <tt>transformed</tt> flag (which is returned to
     * the service so it knows whether the supplied class was altered or not)
     * and a second flag which indicates whether the class is eligible for
     * processing by the mixin pipeline: Results with <tt>passthrough</tt> set
     * will not be processed further by the mixin processor.
     */
    enum ProcessResult {

        /**
         * This coprocessor does not take any action for the specified class
         */
        NONE(false, false),

        /**
         * This coprocessor acted on the supplied bytecode, but does not change
         * the flow of the main mixin processor pipeline
         */
        TRANSFORMED(false, true),

        /**
         * This coprocessor did not transform the supplied bytecode, and mixins
         * should not be applied to this class
         */
        PASSTHROUGH_NONE(true, false),

        /**
         * This coprocessor acted on the supplied bytecode, and mixins should
         * not be applied to this class
         */
        PASSTHROUGH_TRANSFORMED(true, true);

        private boolean passthrough;

        private boolean transformed;

        private ProcessResult(boolean passthrough, boolean transformed) {
            this.passthrough = passthrough;
            this.transformed = transformed;
        }

        boolean isPassthrough() {
            return this.passthrough;
        }

        boolean isTransformed() {
            return this.transformed;
        }

        /**
         * Combine this result with the supplied result
         */
        ProcessResult with(ProcessResult other) {
            if (other == this) {
                return this;
            }
            return ProcessResult.of(this.passthrough || other.passthrough, this.transformed || other.transformed);
        }

        /**
         * Return a result which represents the supplied tuple of attributes
         */
        static ProcessResult of(boolean passthrough, boolean transformed) {
            if (passthrough) {
                return transformed ? ProcessResult.PASSTHROUGH_TRANSFORMED : ProcessResult.PASSTHROUGH_NONE;
            }
            return transformed ? ProcessResult.TRANSFORMED : ProcessResult.NONE;
        }

    }

    /**
     * Coprocessor name, for debugging only
     */
    abstract String getName();

    /* (non-Javadoc)
     * @see org.spongepowered.asm.mixin.transformer.MixinConfig.IListener
     *      #onPrepare(org.spongepowered.asm.mixin.transformer.MixinInfo)
     */
    @Override
    public void onPrepare(MixinInfo mixin) {
    }

    /* (non-Javadoc)
     * @see org.spongepowered.asm.mixin.transformer.MixinConfig.IListener
     *      #onInit(org.spongepowered.asm.mixin.transformer.MixinInfo)
     */
    @Override
    public void onInit(MixinInfo mixin) {
    }

    /**
     * Process the supplied class. If the class is transformed, or should be
     * passed through (rather than treated as a mixin target) then this is
     * indicated by the return value
     *
     * @param className Name of the target class
     * @param classNode Classnode of the target class
     * @return result indicating whether the class was transformed, and whether
     *      or not to passthrough instead of apply mixins
     */
    ProcessResult process(String className, ClassNode classNode) {
        return ProcessResult.NONE;
    }

    /**
     * Perform postprocessing actions on the supplied class. This is called for
     * all classes. For passthrough classes and classes which are not mixin
     * targets this is called immediately after {@link process} is completed for
     * all coprocessors. For mixin targets this is called after mixins are
     * applied.
     *
     * @param className Name of the target class
     * @param classNode Classnode of the target class
     * @return true if the coprocessor applied any transformations
     */
    boolean postProcess(String className, ClassNode classNode) {
        return false;
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.kymjs.aframe.http</title>
<meta name="date" content="2014-10-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.kymjs.aframe.http

接口

I_HttpParams

I_HttpRespond

类

FileCallBack

HttpCallBack

HttpConfig

KJFileParams

KJHttp

KJStringParams

RetryHandler

StringCallBack