text:
[![Build Status](https://travis-ci.org/otarsko/aem-seo-canonical-url.svg?branch=master)](https://travis-ci.org/otarsko/aem-seo-canonical-url)
[![Coverage Status](https://coveralls.io/repos/github/otarsko/aem-seo-canonical-url/badge.svg?branch=master)](https://coveralls.io/github/otarsko/aem-seo-canonical-url?branch=master)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

# Canonical Tagging Support for AEM
This is a library for inserting canonical tags into your pages.

## Why this library has been created
Many sites require content duplication. For example, there can be a sub-tree for each department in the company,
where they have their content. However, they may have content which is equal to content in the corporate section.

At the same time, content duplication can greatly affect your ranking.
Unfortunately, AEM does not provide flexible way of handling this.

## Features
This library provides next features:

* strict mapping, e.g. /path/page1 --(has canonical page)--> /anotherPath/page1
* mapping by the pattern with lookup path, e.g. /path/page[0-9] --(all pages under path have canonical pages)--> /anotherPath

Library has been tested on AEM 6.1 SP1, and JDK 7/8.

## Usage

#### Maven
Add maven dependency to your project:

        <dependency>
            <groupId>com.taradevko</groupId>
            <artifactId>com.taradevko.aem.seo</artifactId>
            <version>0.1.1</version>
        </dependency>

Embed bundle into the content package to be installed. It may look like this:

        <embedded>
             <groupId>com.taradevko</groupId>
             <artifactId>com.taradevko.aem.seo</artifactId>
             <filter>true</filter>
        </embedded>

#### Building from the sources
To build and install bundle to your AEM instance, use next command (host/port values should be adjusted to the values you have):

`mvn clean install -PautoInstallBundle -Daem.host=localhost -Daem.port=4502`

After bundle installed, next steps should be performed:

1. [Create system user](http://www.aemcq5tutorials.com/tutorials/create-system-user-in-aem/), grant required permissions to it and configure it for the bundle *com.taradevko.aem.seo*:

 ![Grant user permissions](doc/aem-grant-permisions.png)

 ![User mapping](doc/aem-user-mapping.png)

1. Configure service *Canonical Tagging Support* (pid com.taradevko.aem.seo.service.CanonicalTaggingImpl). Via Web Console/sling:OsgiConfig:

 ![AEM Canonical Configuration](doc/aem-canonical-configuration.png)

 Rule has next syntax:

 * for **strict** rules, where page is mapped to another page: `_PATH PAGE 1_=>_CANONICAL PAGE PATH_`
 * for rules which map pages by regex and provide lookup path: `_PATTERN FOR PAGE WHICH CHILD WILL BE MAPPED_>_LOOKUP PATH_`

1. Add canonical tag to your <head></head>. To do this: insert next code into the required place:
    ```
          <link
              data-sly-use.canonicalTagging="com.taradevko.aem.seo.CanonicalLinkModel"
              data-sly-test="${canonicalTagging.hasCanonicalPage}"
              rel="canonical"
              href="${canonicalTagging.canonicalUrl}.html" />
    ```
1. Make sure, that externalizer is configured. Also, you can additionally configure URL Mappings in Resource Resolver Factory, to omit some part of the path in URL.

 ![AEM Externalizer Configuration](doc/aem-externalizer-config.png)

 ![AEM Resource Resolver mapping](doc/aem-resource-resolver-mapping.png)

## Examples
Page structure:

 ![AEM SEO Example structue](doc/aem-seo-structure.png)

Having configuration and structure, how it is shown above, we will get next results:

* strict rule

 ![AEM SEO Canonical Strict rule](doc/aem-canonical-example-strict.png)

* pattern rule

 ![AEM SEO Canonical Pattern rule](doc/aem-canonical-example-pattern.png)

* pattern rule with url mapping

 ![AEM SEO Canonical Pattern rule with url mapping](doc/aem-canonical-example-pattern-with-url-mapping.png)

# LICENSE
The Apache License (Version 2.0, January 2004).


text:
namespace Tilde.LuaDebugger
{
	partial class TargetConnectionDialog
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			this.label1 = new System.Windows.Forms.Label();
			this.buttonCancel = new System.Windows.Forms.Button();
			this.buttonConnect = new System.Windows.Forms.Button();
			this.treeViewTargets = new System.Windows.Forms.TreeView();
			this.buttonRefresh = new System.Windows.Forms.Button();
			this.persistWindowComponent = new Tilde.Framework.View.PersistWindowComponent(this.components);
			this.SuspendLayout();
			//
			// label1
			//
			this.label1.AutoSize = true;
			this.label1.Location = new System.Drawing.Point(12, 9);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(92, 13);
			this.label1.TabIndex = 1;
			this.label1.Text = "Available Targets:";
			//
			// buttonCancel
			//
			this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.buttonCancel.Location = new System.Drawing.Point(216, 256);
			this.buttonCancel.Name = "buttonCancel";
			this.buttonCancel.Size = new System.Drawing.Size(75, 23);
			this.buttonCancel.TabIndex = 2;
			this.buttonCancel.Text = "Cancel";
			this.buttonCancel.UseVisualStyleBackColor = true;
			//
			// buttonConnect
			//
			this.buttonConnect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.buttonConnect.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.buttonConnect.Location = new System.Drawing.Point(135, 256);
			this.buttonConnect.Name = "buttonConnect";
			this.buttonConnect.Size = new System.Drawing.Size(75, 23);
			this.buttonConnect.TabIndex = 3;
			this.buttonConnect.Text = "Connect";
			this.buttonConnect.UseVisualStyleBackColor = true;
			//
			// treeViewTargets
			//
			this.treeViewTargets.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.treeViewTargets.Location = new System.Drawing.Point(15, 25);
			this.treeViewTargets.Name = "treeViewTargets";
			this.treeViewTargets.PathSeparator = "/";
			this.treeViewTargets.Size = new System.Drawing.Size(278, 225);
			this.treeViewTargets.TabIndex = 4;
			this.treeViewTargets.DoubleClick += new System.EventHandler(this.treeViewTargets_DoubleClick);
			this.treeViewTargets.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewTargets_AfterSelect);
			//
			// buttonRefresh
			//
			this.buttonRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.buttonRefresh.Location = new System.Drawing.Point(15, 256);
			this.buttonRefresh.Name = "buttonRefresh";
			this.buttonRefresh.Size = new System.Drawing.Size(75, 23);
			this.buttonRefresh.TabIndex = 5;
			this.buttonRefresh.Text = "Refresh";
			this.buttonRefresh.UseVisualStyleBackColor = true;
			this.buttonRefresh.Click += new System.EventHandler(this.buttonRefresh_Click);
			//
			// persistWindowComponent
			//
			this.persistWindowComponent.Form = this;
			this.persistWindowComponent.RegistryKey = "TargetConnectionDialog";
			//
			// TargetConnectionDialog
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(303, 291);
			this.Controls.Add(this.buttonRefresh);
			this.Controls.Add(this.treeViewTargets);
			this.Controls.Add(this.buttonConnect);
			this.Controls.Add(this.buttonCancel);
			this.Controls.Add(this.label1);
			this.Name = "TargetConnectionDialog";
			this.Text = "Choose Connection";
			this.Load += new System.EventHandler(this.TargetConnectionDialog_Load);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button buttonCancel;
		private System.Windows.Forms.Button buttonConnect;
		private System.Windows.Forms.TreeView treeViewTargets;
		private System.Windows.Forms.Button buttonRefresh;
		private Tilde.Framework.View.PersistWindowComponent persistWindowComponent;

	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Http\Controllers;

use App\Judite\Models\Course;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the dashboard.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        return Auth::user()->isAdmin()
            ? $this->adminDashboard()
            : $this->studentDashboard();
    }

    /**
     * Get the admin's dashboard.
     *
     * @return \Illuminate\View\View
     */
    protected function adminDashboard()
    {
        $courses = DB::transaction(function () {
            return Course::withCount('enrollments')
                ->orderedList()
                ->get();
        });

        $courses = $courses->groupBy(function ($course) {
            return $course->present()->getOrdinalYear();
        });

        return view('admin.dashboard', compact('courses'));
    }

    /**
     * Get the student's dashboard.
     *
     * @return \Illuminate\View\View
     */
    protected function studentDashboard()
    {
        $data = DB::transaction(function () {
            $proposedExchanges = Auth::student()->proposedExchanges()->get();
            $requestedExchanges = Auth::student()->requestedExchanges()->get();
            $enrollments = Auth::student()->enrollments()
                ->withCount('exchangesAsSource')
                ->orderByCourse()
                ->get();

            return compact('proposedExchanges', 'requestedExchanges', 'enrollments');
        });

        $data['enrollments'] = $data['enrollments']->groupBy(function ($enrollment) {
            return $enrollment->course->present()->getOrdinalYear();
        });

        return view('dashboard', $data);
    }
}


text:
namespace llvm {
  class AllocaInst;
  class CallSite;
  class Constant;
  class Function;
}

namespace swift {
  class ArchetypeType;
  class IRGenOptions;
  class SILDebugScope;
  class SILType;
  class SourceLoc;
  enum class MetadataState : size_t;

namespace Lowering {
  class TypeConverter;
}

namespace irgen {
  class DynamicMetadataRequest;
  class Explosion;
  class FunctionRef;
  class HeapLayout;
  class HeapNonFixedOffsets;
  class IRGenModule;
  class LinkEntity;
  class LocalTypeDataCache;
  class MetadataResponse;
  class Scope;
  class TypeInfo;
  enum class ValueWitness : unsigned;

/// IRGenFunction - Primary class for emitting LLVM instructions for a
/// specific function.
class IRGenFunction {
public:
  IRGenModule &IGM;
  IRBuilder Builder;

  /// If != OptimizationMode::NotSet, the optimization mode specified with an
  /// function attribute.
  OptimizationMode OptMode;

  llvm::Function *CurFn;
  ModuleDecl *getSwiftModule() const;
  SILModule &getSILModule() const;
  Lowering::TypeConverter &getSILTypes() const;
  const IRGenOptions &getOptions() const;

  IRGenFunction(IRGenModule &IGM, llvm::Function *fn,
                OptimizationMode Mode = OptimizationMode::NotSet,
                const SILDebugScope *DbgScope = nullptr,
                Optional<SILLocation> DbgLoc = None);
  ~IRGenFunction();

  void unimplemented(SourceLoc Loc, StringRef Message);

  friend class Scope;

  Address createErrorResultSlot(SILType errorType, bool isAsync);

  //--- Function prologue and epilogue
  //-------------------------------------------
public:
  Explosion collectParameters();
  void emitScalarReturn(SILType returnResultType, SILType funcResultType,
                        Explosion &scalars, bool isSwiftCCReturn,
                        bool isOutlined);
  void emitScalarReturn(llvm::Type *resultTy, Explosion &scalars);

  void emitBBForReturn();
  bool emitBranchToReturnBB();

  void emitAllExtractValues(llvm::Value *aggValue, llvm::StructType *type,
                            Explosion &out);

  /// Return the error result slot to be passed to the callee, given an error
  /// type.  There's always only one error type.
  ///
  /// For async functions, this is different from the caller result slot because
  /// that is a gep into the %swift.context.
  Address getCalleeErrorResultSlot(SILType errorType);
  Address getAsyncCalleeErrorResultSlot(SILType errorType);

  /// Return the error result slot provided by the caller.
  Address getCallerErrorResultSlot();

  /// Set the error result slot for the current function.
  void setCallerErrorResultSlot(Address address);

  /// Are we currently emitting a coroutine?
  bool isCoroutine() {
    return CoroutineHandle != nullptr;
  }
  llvm::Value *getCoroutineHandle() {
    assert(isCoroutine());
    return CoroutineHandle;
  }

  void setCoroutineHandle(llvm::Value *handle) {
    assert(CoroutineHandle == nullptr && "already set handle");
    assert(handle != nullptr && "setting a null handle");
    CoroutineHandle = handle;
  }

  llvm::Value *getAsyncTask();
  llvm::Value *getAsyncContext();
  void storeCurrentAsyncContext(llvm::Value *context);

  llvm::CallInst *emitSuspendAsyncCall(unsigned swiftAsyncContextIndex,
                                       llvm::StructType *resultTy,
                                       ArrayRef<llvm::Value *> args,
                                       bool restoreCurrentContext = true);

  llvm::Value *emitAsyncResumeProjectContext(llvm::Value *callerContextAddr);
  llvm::Function *getOrCreateResumePrjFn(bool forPrologue = false);
  llvm::Function *createAsyncDispatchFn(const FunctionPointer &fnPtr,
                                        ArrayRef<llvm::Value *> args);
  llvm::Function *createAsyncDispatchFn(const FunctionPointer &fnPtr,
                                        ArrayRef<llvm::Type *> argTypes);

  void emitGetAsyncContinuation(SILType resumeTy,
                                StackAddress optionalResultAddr,
                                Explosion &out,
                                bool canThrow);

  void emitAwaitAsyncContinuation(SILType resumeTy,
                                  bool isIndirectResult,
                                  Explosion &outDirectResult,
                                  llvm::BasicBlock *&normalBB,
                                  llvm::PHINode *&optionalErrorPhi,
                                  llvm::BasicBlock *&optionalErrorBB);

  void emitResumeAsyncContinuationReturning(llvm::Value *continuation,
                                            llvm::Value *srcPtr,
                                            SILType valueTy,
                                            bool throwing);

  void emitResumeAsyncContinuationThrowing(llvm::Value *continuation,
                                           llvm::Value *error);

  FunctionPointer
  getFunctionPointerForResumeIntrinsic(llvm::Value *resumeIntrinsic);

  void emitSuspensionPoint(Explosion &executor, llvm::Value *asyncResume);
  llvm::Function *getOrCreateResumeFromSuspensionFn();
  llvm::Function *createAsyncSuspendFn();

private:
  void emitPrologue();
  void emitEpilogue();

  Address ReturnSlot;
  llvm::BasicBlock *ReturnBB;
  Address CalleeErrorResultSlot;
  Address AsyncCalleeErrorResultSlot;
  Address CallerErrorResultSlot;
  llvm::Value *CoroutineHandle = nullptr;
  llvm::Value *AsyncCoroutineCurrentResume = nullptr;
  llvm::Value *AsyncCoroutineCurrentContinuationContext = nullptr;

  Address asyncContextLocation;

  /// The unique block that calls @llvm.coro.end.
  llvm::BasicBlock *CoroutineExitBlock = nullptr;

public:
  void emitCoroutineOrAsyncExit();

//--- Helper methods -----------------------------------------------------------
public:

  /// Returns the optimization mode for the function. If no mode is set for the
  /// function, returns the global mode, i.e. the mode in IRGenOptions.
  OptimizationMode getEffectiveOptimizationMode() const;

  /// Returns true if this function should be optimized for size.
  bool optimizeForSize() const {
    return getEffectiveOptimizationMode() == OptimizationMode::ForSize;
  }

  void setupAsync(unsigned asyncContextIndex);
  bool isAsync() const { return asyncContextLocation.isValid(); }

  Address createAlloca(llvm::Type *ty, Alignment align,
                       const llvm::Twine &name = "");
  Address createAlloca(llvm::Type *ty, llvm::Value *arraySize, Alignment align,
                       const llvm::Twine &name = "");
  Address createFixedSizeBufferAlloca(const llvm::Twine &name);

  StackAddress emitDynamicAlloca(SILType type, const llvm::Twine &name = "");
  StackAddress emitDynamicAlloca(llvm::Type *eltTy, llvm::Value *arraySize,
                                 Alignment align, bool allowTaskAlloc = true,
                                 const llvm::Twine &name = "");
  void emitDeallocateDynamicAlloca(StackAddress address,
                                   bool allowTaskDealloc = true);

  llvm::BasicBlock *createBasicBlock(const llvm::Twine &Name);
  const TypeInfo &getTypeInfoForUnlowered(Type subst);
  const TypeInfo &getTypeInfoForUnlowered(AbstractionPattern orig, Type subst);
  const TypeInfo &getTypeInfoForUnlowered(AbstractionPattern orig,
                                          CanType subst);
  const TypeInfo &getTypeInfoForLowered(CanType T);
  const TypeInfo &getTypeInfo(SILType T);
  void emitMemCpy(llvm::Value *dest, llvm::Value *src,
                  Size size, Alignment align);
  void emitMemCpy(llvm::Value *dest, llvm::Value *src,
                  llvm::Value *size, Alignment align);
  void emitMemCpy(Address dest, Address src, Size size);
  void emitMemCpy(Address dest, Address src, llvm::Value *size);

  llvm::Value *emitByteOffsetGEP(llvm::Value *base, llvm::Value *offset,
                                 llvm::Type *objectType,
                                 const llvm::Twine &name = "");
  Address emitByteOffsetGEP(llvm::Value *base, llvm::Value *offset,
                            const TypeInfo &type,
                            const llvm::Twine &name = "");
  Address emitAddressAtOffset(llvm::Value *base, Offset offset,
                              llvm::Type *objectType,
                              Alignment objectAlignment,
                              const llvm::Twine &name = "");

  llvm::Value *emitInvariantLoad(Address address,
                                 const llvm::Twine &name = "");

  void emitStoreOfRelativeIndirectablePointer(llvm::Value *value,
                                              Address addr,
                                              bool isFar);

  llvm::Value *emitLoadOfRelativePointer(Address addr, bool isFar,
                                         llvm::Type *expectedPointedToType,
                                         const llvm::Twine &name = "");
  llvm::Value *
  emitLoadOfCompactFunctionPointer(Address addr, bool isFar,
                                   llvm::Type *expectedPointedToType,
                                   const llvm::Twine &name = "");

  llvm::Value *emitAllocObjectCall(llvm::Value *metadata, llvm::Value *size,
                                   llvm::Value *alignMask,
                                   const llvm::Twine &name = "");
  llvm::Value *emitInitStackObjectCall(llvm::Value *metadata,
                                       llvm::Value *object,
                                       const llvm::Twine &name = "");
  llvm::Value *emitInitStaticObjectCall(llvm::Value *metadata,
                                        llvm::Value *object,
                                        const llvm::Twine &name = "");
  llvm::Value *emitVerifyEndOfLifetimeCall(llvm::Value *object,
                                           const llvm::Twine &name = "");
  llvm::Value *emitAllocRawCall(llvm::Value *size, llvm::Value *alignMask,
                                const llvm::Twine &name ="");
  void emitDeallocRawCall(llvm::Value *pointer, llvm::Value *size,
                          llvm::Value *alignMask);

  void emitAllocBoxCall(llvm::Value *typeMetadata,
                         llvm::Value *&box,
                         llvm::Value *&valueAddress);

  void emitMakeBoxUniqueCall(llvm::Value *box, llvm::Value *typeMetadata,
                             llvm::Value *alignMask, llvm::Value *&outBox,
                             llvm::Value *&outValueAddress);

  void emitDeallocBoxCall(llvm::Value *box, llvm::Value *typeMetadata);

  void emitTSanInoutAccessCall(llvm::Value *address);

  llvm::Value *emitTargetOSVersionAtLeastCall(llvm::Value *major,
                                              llvm::Value *minor,
                                              llvm::Value *patch);

  llvm::Value *emitProjectBoxCall(llvm::Value *box, llvm::Value *typeMetadata);

  llvm::Value *emitAllocEmptyBoxCall();

  // Emit a call to the given generic type metadata access function.
  MetadataResponse emitGenericTypeMetadataAccessFunctionCall(
                                          llvm::Function *accessFunction,
                                          ArrayRef<llvm::Value *> args,
                                          DynamicMetadataRequest request);

  // Emit a reference to the canonical type metadata record for the given AST
  // type. This can be used to identify the type at runtime. For types with
  // abstraction difference, the metadata contains the layout information for
  // values in the maximally-abstracted representation of the type; this is
  // correct for all uses of reabstractable values in opaque contexts.
  llvm::Value *emitTypeMetadataRef(CanType type);

  /// Emit a reference to the canonical type metadata record for the given
  /// formal type.  The metadata is only required to be abstract; that is,
  /// you cannot use the result for layout.
  llvm::Value *emitAbstractTypeMetadataRef(CanType type);

  MetadataResponse emitTypeMetadataRef(CanType type,
                                       DynamicMetadataRequest request);

  // Emit a reference to a metadata object that can be used for layout, but
  // cannot be used to identify a type. This will produce a layout appropriate
  // to the abstraction level of the given type. It may be able to avoid runtime
  // calls if there is a standard metadata object with the correct layout for
  // the type.
  //
  // TODO: It might be better to return just a value witness table reference
  // here, since for some types it's easier to get a shared reference to one
  // than a metadata reference, and it would be more type-safe.
  llvm::Value *emitTypeMetadataRefForLayout(SILType type);
  llvm::Value *emitTypeMetadataRefForLayout(SILType type,
                                            DynamicMetadataRequest request);

  llvm::Value *emitValueWitnessTableRef(SILType type,
                                        llvm::Value **metadataSlot = nullptr);
  llvm::Value *emitValueWitnessTableRef(SILType type,
                                        DynamicMetadataRequest request,
                                        llvm::Value **metadataSlot = nullptr);
  llvm::Value *emitValueWitnessTableRefForMetadata(llvm::Value *metadata);

  llvm::Value *emitValueWitnessValue(SILType type, ValueWitness index);
  FunctionPointer emitValueWitnessFunctionRef(SILType type,
                                              llvm::Value *&metadataSlot,
                                              ValueWitness index);

  /// Emit a load of a reference to the given Objective-C selector.
  llvm::Value *emitObjCSelectorRefLoad(StringRef selector);

  /// Return the SILDebugScope for this function.
  const SILDebugScope *getDebugScope() const { return DbgScope; }
  llvm::Value *coerceValue(llvm::Value *value, llvm::Type *toTy,
                           const llvm::DataLayout &);
  Explosion coerceValueTo(SILType fromTy, Explosion &from, SILType toTy);

  /// Mark a load as invariant.
  void setInvariantLoad(llvm::LoadInst *load);
  /// Mark a load as dereferenceable to `size` bytes.
  void setDereferenceableLoad(llvm::LoadInst *load, unsigned size);

  /// Emit a non-mergeable trap call, optionally followed by a terminator.
  void emitTrap(StringRef failureMessage, bool EmitUnreachable);

private:
  llvm::Instruction *AllocaIP;
  const SILDebugScope *DbgScope;
  /// The insertion point where we should but instructions we would normally put
  /// at the beginning of the function. LLVM's coroutine lowering really does
  /// not like it if we put instructions with side-effectrs before the
  /// coro.begin.
  llvm::Instruction *EarliestIP;

public:
  void setEarliestInsertionPoint(llvm::Instruction *inst) { EarliestIP = inst; }
  /// Returns the first insertion point before which we should insert
  /// instructions which have side-effects.
  llvm::Instruction *getEarliestInsertionPoint() const { return EarliestIP; }

  //--- Reference-counting methods
  //-----------------------------------------------
public:
  // Returns the default atomicity of the module.
  Atomicity getDefaultAtomicity();

  llvm::Value *emitUnmanagedAlloc(const HeapLayout &layout,
                                  const llvm::Twine &name,
                                  llvm::Constant *captureDescriptor,
                                  const HeapNonFixedOffsets *offsets = 0);

  // Functions that don't care about the reference-counting style.
  void emitFixLifetime(llvm::Value *value);

  // Routines that are generic over the reference-counting style:
  //   - strong references
  void emitStrongRetain(llvm::Value *value, ReferenceCounting refcounting,
                        Atomicity atomicity);
  void emitStrongRelease(llvm::Value *value, ReferenceCounting refcounting,
                         Atomicity atomicity);
  llvm::Value *emitLoadRefcountedPtr(Address addr, ReferenceCounting style);

  llvm::Value *getReferenceStorageExtraInhabitantIndex(Address src,
                                                   ReferenceOwnership ownership,
                                                   ReferenceCounting style);
  void storeReferenceStorageExtraInhabitant(llvm::Value *index,
                                            Address dest,
                                            ReferenceOwnership ownership,
                                            ReferenceCounting style);

#define NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Kind) \
  void emit##Kind##Name##Init(llvm::Value *val, Address dest); \
  void emit##Kind##Name##Assign(llvm::Value *value, Address dest); \
  void emit##Kind##Name##CopyInit(Address destAddr, Address srcAddr); \
  void emit##Kind##Name##TakeInit(Address destAddr, Address srcAddr); \
  void emit##Kind##Name##CopyAssign(Address destAddr, Address srcAddr); \
  void emit##Kind##Name##TakeAssign(Address destAddr, Address srcAddr); \
  llvm::Value *emit##Kind##Name##LoadStrong(Address src, \
                                            llvm::Type *resultType); \
  llvm::Value *emit##Kind##Name##TakeStrong(Address src, \
                                            llvm::Type *resultType); \
  void emit##Kind##Name##Destroy(Address addr);
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Kind) \
  void emit##Kind##Name##Retain(llvm::Value *value, Atomicity atomicity); \
  void emit##Kind##Name##Release(llvm::Value *value, Atomicity atomicity); \
  void emit##Kind##StrongRetain##Name(llvm::Value *value, Atomicity atomicity);\
  void emit##Kind##StrongRetainAnd##Name##Release(llvm::Value *value, \
                                                  Atomicity atomicity);
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Native) \
  NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Unknown) \
  void emit##Name##Init(llvm::Value *val, Address dest, ReferenceCounting style); \
  void emit##Name##Assign(llvm::Value *value, Address dest, \
                          ReferenceCounting style); \
  void emit##Name##CopyInit(Address destAddr, Address srcAddr, \
                            ReferenceCounting style); \
  void emit##Name##TakeInit(Address destAddr, Address srcAddr, \
                            ReferenceCounting style); \
  void emit##Name##CopyAssign(Address destAddr, Address srcAddr, \
                              ReferenceCounting style); \
  void emit##Name##TakeAssign(Address destAddr, Address srcAddr, \
                              ReferenceCounting style); \
  llvm::Value *emit##Name##LoadStrong(Address src, llvm::Type *resultType, \
                                      ReferenceCounting style); \
  llvm::Value *emit##Name##TakeStrong(Address src, llvm::Type *resultType, \
                                      ReferenceCounting style); \
  void emit##Name##Destroy(Address addr, ReferenceCounting style);
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, "...") \
  ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Native) \
  ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Unknown) \
  void emit##Name##Retain(llvm::Value *value, ReferenceCounting style, \
                         Atomicity atomicity); \
  void emit##Name##Release(llvm::Value *value, ReferenceCounting style, \
                          Atomicity atomicity); \
  void emitStrongRetain##Name(llvm::Value *value, ReferenceCounting style, \
                              Atomicity atomicity); \
  void emitStrongRetainAnd##Name##Release(llvm::Value *value, \
                                          ReferenceCounting style, \
                                          Atomicity atomicity);
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Native) \
  void emit##Name##Retain(llvm::Value *value, ReferenceCounting style, \
                         Atomicity atomicity) { \
    assert(style == ReferenceCounting::Native); \
    emitNative##Name##Retain(value, atomicity); \
  } \
  void emit##Name##Release(llvm::Value *value, ReferenceCounting style, \
                          Atomicity atomicity) { \
    assert(style == ReferenceCounting::Native); \
    emitNative##Name##Release(value, atomicity); \
  } \
  void emitStrongRetain##Name(llvm::Value *value, ReferenceCounting style, \
                              Atomicity atomicity) { \
    assert(style == ReferenceCounting::Native); \
    emitNativeStrongRetain##Name(value, atomicity); \
  } \
  void emitStrongRetainAnd##Name##Release(llvm::Value *value, \
                                          ReferenceCounting style, \
                                          Atomicity atomicity) { \
    assert(style == ReferenceCounting::Native); \
    emitNativeStrongRetainAnd##Name##Release(value, atomicity); \
  }
#include "swift/AST/ReferenceStorage.def"
#undef NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER
#undef ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER

  // Routines for the Swift native reference-counting style.
  //   - strong references
  void emitNativeStrongAssign(llvm::Value *value, Address addr);
  void emitNativeStrongInit(llvm::Value *value, Address addr);
  void emitNativeStrongRetain(llvm::Value *value, Atomicity atomicity);
  void emitNativeStrongRelease(llvm::Value *value, Atomicity atomicity);
  void emitNativeSetDeallocating(llvm::Value *value);

  // Routines for the ObjC reference-counting style.
  void emitObjCStrongRetain(llvm::Value *value);
  llvm::Value *emitObjCRetainCall(llvm::Value *value);
  llvm::Value *emitObjCAutoreleaseCall(llvm::Value *value);
  void emitObjCStrongRelease(llvm::Value *value);

  llvm::Value *emitBlockCopyCall(llvm::Value *value);
  void emitBlockRelease(llvm::Value *value);

  void emitForeignReferenceTypeLifetimeOperation(ValueDecl *fn,
                                                 llvm::Value *value);

  // Routines for an unknown reference-counting style (meaning,
  // dynamically something compatible with either the ObjC or Swift styles).
  //   - strong references
  void emitUnknownStrongRetain(llvm::Value *value, Atomicity atomicity);
  void emitUnknownStrongRelease(llvm::Value *value, Atomicity atomicity);

  // Routines for the Builtin.NativeObject reference-counting style.
  void emitBridgeStrongRetain(llvm::Value *value, Atomicity atomicity);
  void emitBridgeStrongRelease(llvm::Value *value, Atomicity atomicity);

  // Routines for the ErrorType reference-counting style.
  void emitErrorStrongRetain(llvm::Value *value);
  void emitErrorStrongRelease(llvm::Value *value);

  llvm::Value *emitIsUniqueCall(llvm::Value *value, ReferenceCounting style,
                                SourceLoc loc, bool isNonNull);

  llvm::Value *emitIsEscapingClosureCall(llvm::Value *value, SourceLoc loc,
                                         unsigned verificationType);

  Address emitTaskAlloc(llvm::Value *size,
                        Alignment alignment);
  void emitTaskDealloc(Address address);

  llvm::Value *alignUpToMaximumAlignment(llvm::Type *sizeTy, llvm::Value *val);

  //--- Expression emission
  //------------------------------------------------------
public:
  void emitFakeExplosion(const TypeInfo &type, Explosion &explosion);

//--- Declaration emission -----------------------------------------------------
public:

  void bindArchetype(ArchetypeType *type,
                     llvm::Value *metadata,
                     MetadataState metadataState,
                     ArrayRef<llvm::Value*> wtables);

//--- Type emission ------------------------------------------------------------
public:
  /// Look up a local type metadata reference, returning a null response
  /// if no entry was found which can satisfy the request.  This may need
  /// emit code to materialize the reference.
  ///
  /// This does a look up for a formal ("AST") type.  If you are looking for
  /// type metadata that will work for working with a representation
  /// ("lowered", "SIL") type, use getGetLocalTypeMetadataForLayout.
  MetadataResponse tryGetLocalTypeMetadata(CanType type,
                                           DynamicMetadataRequest request);

  /// Look up a local type data reference, returning null if no entry was
  /// found.  This may need to emit code to materialize the reference.
  ///
  /// The data kind cannot be for type metadata; use tryGetLocalTypeMetadata
  /// for that.
  llvm::Value *tryGetLocalTypeData(CanType type, LocalTypeDataKind kind);

  /// The same as tryGetLocalTypeMetadata, but for representation-compatible
  /// "layout" metadata.  The returned metadata may not be for a type that
  /// has anything to do with the formal type that was lowered to the given
  /// type; however, it is guaranteed to have equivalent characteristics
  /// in terms of layout, spare bits, POD-ness, and so on.
  ///
  /// We use a separate function name for this to clarify that you should
  /// only ever be looking for type metadata for a lowered SILType for the
  /// purposes of local manipulation, such as the layout of a type or
  /// emitting a value-copy.
  MetadataResponse tryGetLocalTypeMetadataForLayout(SILType type,
                                           DynamicMetadataRequest request);

  /// The same as tryGetForLocalTypeData, but for representation-compatible
  /// "layout" metadata.  See the comment on tryGetLocalTypeMetadataForLayout.
  ///
  /// The data kind cannot be for type metadata; use
  /// tryGetLocalTypeMetadataForLayout for that.
  llvm::Value *tryGetLocalTypeDataForLayout(SILType type,
                                            LocalTypeDataKind kind);

  /// Add a local type metadata reference at a point which definitely
  /// dominates all of its uses.
  void setUnscopedLocalTypeMetadata(CanType type,
                                    MetadataResponse response);

  /// Add a local type data reference at a point which definitely
  /// dominates all of its uses.
  ///
  /// The data kind cannot be for type metadata; use
  /// setUnscopedLocalTypeMetadata for that.
  void setUnscopedLocalTypeData(CanType type, LocalTypeDataKind kind,
                                llvm::Value *data);

  /// Add a local type metadata reference that is valid at the current
  /// insertion point.
  void setScopedLocalTypeMetadata(CanType type, MetadataResponse value);

  /// Add a local type data reference that is valid at the current
  /// insertion point.
  ///
  /// The data kind cannot be for type metadata; use setScopedLocalTypeMetadata
  /// for that.
  void setScopedLocalTypeData(CanType type, LocalTypeDataKind kind,
                              llvm::Value *data);

  /// The same as setScopedLocalTypeMetadata, but for representation-compatible
  /// "layout" metadata.  See the comment on tryGetLocalTypeMetadataForLayout.
  void setScopedLocalTypeMetadataForLayout(SILType type, MetadataResponse value);

  /// The same as setScopedLocalTypeData, but for representation-compatible
  /// "layout" metadata.  See the comment on tryGetLocalTypeMetadataForLayout.
  ///
  /// The data kind cannot be for type metadata; use
  /// setScopedLocalTypeMetadataForLayout for that.
  void setScopedLocalTypeDataForLayout(SILType type, LocalTypeDataKind kind,
                                       llvm::Value *data);

  // These are for the private use of the LocalTypeData subsystem.
  MetadataResponse tryGetLocalTypeMetadata(LocalTypeDataKey key,
                                           DynamicMetadataRequest request);
  llvm::Value *tryGetLocalTypeData(LocalTypeDataKey key);
  MetadataResponse tryGetConcreteLocalTypeData(LocalTypeDataKey key,
                                               DynamicMetadataRequest request);
  void setUnscopedLocalTypeData(LocalTypeDataKey key, MetadataResponse value);
  void setScopedLocalTypeData(LocalTypeDataKey key, MetadataResponse value);

  /// Given a concrete type metadata node, add all the local type data
  /// that we can reach from it.
  void bindLocalTypeDataFromTypeMetadata(CanType type, IsExact_t isExact,
                                         llvm::Value *metadata,
                                         MetadataState metadataState);

  /// Given the witness table parameter, bind local type data for
  /// the witness table itself and any conditional requirements.
  void bindLocalTypeDataFromSelfWitnessTable(
                const ProtocolConformance *conformance,
                llvm::Value *selfTable,
                llvm::function_ref<CanType (CanType)> mapTypeIntoContext);

  void setDominanceResolver(DominanceResolverFunction resolver) {
    assert(DominanceResolver == nullptr);
    DominanceResolver = resolver;
  }

  bool isActiveDominancePointDominatedBy(DominancePoint point) {
    // If the point is universal, it dominates.
    if (point.isUniversal()) return true;

    assert(!ActiveDominancePoint.isUniversal() &&
           "active dominance point is universal but there exists a"
           "non-universal point?");

    // If we don't have a resolver, we're emitting a simple helper
    // function; just assume dominance.
    if (!DominanceResolver) return true;

    // Otherwise, ask the resolver.
    return DominanceResolver(*this, ActiveDominancePoint, point);
  }

  /// Is the current dominance point conditional in some way not
  /// tracked by the active dominance point?
  ///
  /// This should only be used by the local type data cache code.
  bool isConditionalDominancePoint() const {
    return ConditionalDominance != nullptr;
  }

  void registerConditionalLocalTypeDataKey(LocalTypeDataKey key) {
    assert(ConditionalDominance != nullptr &&
           "not in a conditional dominance scope");
    ConditionalDominance->registerConditionalLocalTypeDataKey(key);
  }

  /// Return the currently-active dominance point.
  DominancePoint getActiveDominancePoint() const {
    return ActiveDominancePoint;
  }

  /// A RAII object for temporarily changing the dominance of the active
  /// definition point.
  class DominanceScope {
    IRGenFunction &IGF;
    DominancePoint OldDominancePoint;
  public:
    explicit DominanceScope(IRGenFunction &IGF, DominancePoint newPoint)
        : IGF(IGF), OldDominancePoint(IGF.ActiveDominancePoint) {
      IGF.ActiveDominancePoint = newPoint;
      assert(!newPoint.isOrdinary() || IGF.DominanceResolver);
    }

    DominanceScope(const DominanceScope &other) = delete;
    DominanceScope &operator=(const DominanceScope &other) = delete;

    ~DominanceScope() {
      IGF.ActiveDominancePoint = OldDominancePoint;
    }
  };

  /// A RAII object for temporarily suppressing type-data caching at the
  /// active definition point.  Do this if you're adding local control flow
  /// that isn't modeled by the dominance system.
  class ConditionalDominanceScope {
    IRGenFunction &IGF;
    ConditionalDominanceScope *OldScope;
    SmallVector<LocalTypeDataKey, 2> RegisteredKeys;

  public:
    explicit ConditionalDominanceScope(IRGenFunction &IGF)
        : IGF(IGF), OldScope(IGF.ConditionalDominance) {
      IGF.ConditionalDominance = this;
    }

    ConditionalDominanceScope(const ConditionalDominanceScope &other) = delete;
    ConditionalDominanceScope &operator=(const ConditionalDominanceScope &other)
      = delete;

    void registerConditionalLocalTypeDataKey(LocalTypeDataKey key) {
      RegisteredKeys.push_back(key);
    }

    ~ConditionalDominanceScope();
  };

  /// The kind of value DynamicSelf is.
  enum DynamicSelfKind {
    /// An object reference.
    ObjectReference,
    /// A Swift metatype.
    SwiftMetatype,
    /// An ObjC metatype.
    ObjCMetatype,
  };

  llvm::Value *getDynamicSelfMetadata();
  void setDynamicSelfMetadata(CanType selfBaseTy, bool selfIsExact,
                              llvm::Value *value, DynamicSelfKind kind);

private:
  LocalTypeDataCache &getOrCreateLocalTypeData();
  void destroyLocalTypeData();

  LocalTypeDataCache *LocalTypeData = nullptr;

  /// The dominance resolver.  This can be set at most once; when it's not
  /// set, this emission must never have a non-null active definition point.
  DominanceResolverFunction DominanceResolver = nullptr;
  DominancePoint ActiveDominancePoint = DominancePoint::universal();
  ConditionalDominanceScope *ConditionalDominance = nullptr;

  /// The value that satisfies metadata lookups for DynamicSelfType.
  llvm::Value *SelfValue = nullptr;
  /// If set, the dynamic Self type is assumed to be equivalent to this exact class.
  CanType SelfType;
  bool SelfTypeIsExact = false;
  DynamicSelfKind SelfKind;
};

using ConditionalDominanceScope = IRGenFunction::ConditionalDominanceScope;

} // end namespace irgen
} // end namespace swift

#endif


text:
#ifndef _PROC_EVENT_H_
#define _PROC_EVENT_H_

#include <sys/types.h>
#include <sys/user.h>
#define PROC_EVENT_LISTEN_SYSCALLS (1 << 0)

#define PROCEVENT_ACK 0

#define PROC_EVENT_SYSCALL_ENTER 0
#define PROC_EVENT_SYSCALL_EXIT  1

struct syscall_exit
{
    long retval;
    long syscall_nr;
};

struct proc_event
{
    int type;
    pid_t pid;
    pid_t thread;

    union {
        struct user_regs_struct syscall;
        struct syscall_exit syscall_exit;
    } e_un;
};

int proc_event_attach(pid_t pid, unsigned long flags);

#endif


text:
(function(µ,SMOD,GMOD,HMOD,SC){

	SC=SC({
		Promise:"Promise",
		register:"register",
    	ircManager:require.bind(null,"./IrcManager"),
		Download:"NIWA-Download.Download",
		File:"File",
		FileUtil:"File.util",
		eq:"equals"
	});
	let NET=require("net");
	let DownloadManager=GMOD("NIWA-Download.Manager");

	let config=require("../rest/config");
	let dccRegister=SC.register(2); //holds dcc offers (server user [ip:port]=offer)
	let xdccRegister=SC.register(1); //holds xdcc requests (server [user]={download,signal})

	let xdccManager=new DownloadManager({
		storagePath:false,
		filter:function(running,download)
		{
			if(download.dataSource.packnumber && !download.dataSource.ip)
			{//XDCC
				let found=running.find(SC.eq.test({
					dataSource:{
						network:download.dataSource.network,
						user:download.dataSource.user
					}
				}));
				if(found) return Promise.reject(download.dataSource.user+"@"+download.dataSource.network+" is busy");
			}
			return true;
		},
		accept:function(download)
		{
			return checkXdccDownload(this,download);
		},
		autoTrigger:true
	});

	xdccManager.parseMessage=function(message,network,user)
	{
		let match=message.text.match(dccExp)
		if(match)
		{
			let offer={
				command:match[1],
				argument:match[2]||match[3],
				ip:parseIp(match[4]),
				port:match[5],
				rest:match[6]
			};
			dccRegister[network][user][offer.ip+":"+offer.port]=offer;

			switch(offer.command)
			{
				case "SEND":
					offer.filename=offer.argument;
					offer.filesize=parseInt(offer.rest,10)||null;

					let xdccRequest=xdccRegister[network][user];
					if(xdccRequest)
					{
						clearTimeout(xdccRequest.timer);
						delete xdccRegister[network][user];
						let download=xdccRequest.download;
						if(checkName(xdccRequest.download,offer))
						{
							if(!xdccRequest.download.filename)xdccRequest.download.filename=offer.filename;
							if(offer.filesize)xdccRequest.download.filesize=offer.filesize;
							xdccRequest.download.dataSource.ip=offer.ip;
							xdccRequest.download.dataSource.port=offer.port;
							this.downloadDCC(xdccRequest.signal,xdccRequest.download);
						}
						else
						{
							//TODO notify other apps for open offer
							let catchOffer=null
							if(xdccRequest.download.context)
							{
								catchOffer=worker.ask(xdccRequest.download.context,"openIrcOffer",{
									offer:{
										network:network,
										user:user,
										filename:offer.filename,
										ip:offer.ip,
										port:offer.port,
									},
									originalDownloadName:xdccRequest.download.name
								});
							}
							else
							{
								catchOffer=Promise.reject();
							}
							catchOffer.then(result=>
							{
								µ.logger.info({result:result},"catched offer");
							},
							e=>
							{
								µ.logger.info({error:e},"could not catch offer");
								SC.ircManager.message(network,user,"XDCC CANCEL");
							});
							this.dbConnector.then(dbc=>
							{
								download.addMessage("wrong filename: "+offer.filename);
								download.state=SC.Download.states.FAILED;
								xdccRequest.signal.resolve();
							});
						}
					}
					break;
				case "ACCEPT":
					offer.filename=offer.argument;
					offer.startPos=parseInt(offer.rest,10)||null;

					let sendOffer=dccRegister[network][user][offer.ip+":"+offer.port];
					if(sendOffer&&sendOffer.command==="SEND"&&sendOffer.filename===offer.filename&&sendOffer.resume)
					{
						sendOffer.startPos=offer.startPos;
						sendOffer.resume();
					}
					return null;
			}
			return offer;
		}
		return null;
	};
	xdccManager.download=function(signal,download)
	{
		if(download.dataSource.packnumber&&!download.dataSource.ip) xdccManager.downloadXDCC(signal,download);
		else xdccManager.downloadDCC(signal,download);
	};
	xdccManager.downloadXDCC=function(signal,xdccDownload)
	{
		return checkXdccDownload(this,xdccDownload)
		.then(()=>config.ready)
		.then(function(config)
		{
			let data={download:xdccDownload,signal:signal};
			let removeFN=function()
			{
				delete xdccRegister[xdccDownload.dataSource.network][xdccDownload.dataSource.user];
				SC.ircManager.message(xdccDownload.dataSource.network,xdccDownload.dataSource.user,"XDCC CANCEL");
				SC.ircManager.message(xdccDownload.dataSource.network,xdccDownload.dataSource.user,"XDCC REMOVE #"+xdccDownload.dataSource.packnumber);
				signal.reject("XDCC request timeout");
			};
			signal.addAbort(function()
			{
				if(xdccRegister[xdccDownload.dataSource.network][xdccDownload.dataSource.user]) removeFN();
			});
			xdccRegister[xdccDownload.dataSource.network][xdccDownload.dataSource.user]=data;
			let messagePromise=SC.ircManager.connect(xdccDownload.dataSource.network);
			if(xdccDownload.dataSource.channel)
				messagePromise=messagePromise.then(()=>SC.ircManager.join(xdccDownload.dataSource.network,xdccDownload.dataSource.channel));
			return messagePromise.then(()=>
			{
				data.timer=setTimeout(removeFN,config.get(["DCC","XDCC request timeout"]).get());
				return SC.ircManager.message(xdccDownload.dataSource.network,xdccDownload.dataSource.user,"XDCC SEND #"+xdccDownload.dataSource.packnumber);
			});
		})
		.catch(signal.reject);
	};
	xdccManager.downloadDCC=function(signal,download)
	{
		let check=checkDccDownload(download);
		if (check.length!=0) signal.reject(check);

		let userRegister=dccRegister[download.dataSource.network][download.dataSource.user];
		let offerKey=download.dataSource.ip+":"+download.dataSource.port;
		let offer=userRegister[offerKey];

		if(!offer) return signal.reject( ["no offer"]);
		if(offer.command!=="SEND") return signal.reject( ["wrong offer: "+offer.command]);

		download.state=SC.Download.states.RUNNING;
		new SC.Promise([
			config.ready,
			new SC.File(download.filepath).exists().then(µ.constantFunctions.scope,function(){return signal.reject("filepath does not exist: "+this.getAbsolutePath())})
		])
		.then((config,folder)=>
		{
			let targetFile=folder.clone().changePath(download.filename);
			let suffix=getConfigValue(config,download.dataSource.suffix,["DCC","suffix"])
			let partFile=suffix?folder.clone().changePath(download.filename+suffix):targetFile;
			let openStream;
			if(getConfigValue(config,download.dataSource.resume,["DCC","resume"]))
			{
				openStream=partFile.exists()
				.then(()=>partFile.stat())
				.then(stats=>(stats.size>0?stats:Promise.reject("empty file")))
				.then(stats=>new Promise((resolve,reject)=>
				{
					let resumeTimer=setTimeout(()=>
					{
						delete offer.resume;

						download.addMessage("resume timeout");
						this.updateDownload(download);
						partFile.writeStream().then(resolve,reject);
					},getConfigValue(config,download.dataSource.resumeTimeout,["DCC","resume timeout"]));
					offer.resume=()=>
					{
						clearTimeout(resumeTimer);
						download.addMessage("resume");
						this.updateDownload(download);
						partFile.writeStream({flags:"a"}).then(resolve,reject);
					};

					download.addMessage("try to resume");
					this.updateDownload(download);
					SC.ircManager.message(download.dataSource.network,download.dataSource.user,`DCC RESUME ${offer.filename} ${offer.port} ${stats.size}`);
				}),
				()=>partFile.writeStream());
			}
			else openStream=openStream=partFile.writeStream();

			return openStream.then((fileStream)=>
			{
				delete userRegister[offerKey];
				let updateTimer=null;
				let completeCounter=0;
				let received=0;
				let sendBuffer = new Buffer(4);
				let connection = NET.connect(download.dataSource.port, download.dataSource.ip,()=>
				{
					download.addMessage("connected");
					download.startTime=Date.now(); //reset download time
					this.updateDownload(download);
					updateTimer=setInterval(()=>
					{
						download.setSize(received);
						if(download.size===download.filesize)
						{
							if(completeCounter++==10)// ~5sec complete
							{
								connection.end();
								download.addMessage("end stalled connection");
							}
						}
						this.updateDownload(download);
					},490);
				});
				connection.pipe(fileStream);

				//send acknowledgements
				connection.on('data', function(data)
				{
					received += data.length;

					/* TODO Large file support ???
					received += data.length;
					while (received > 0xFFFFFFFF)
					{
						received -= 0xFFFFFFFF;
					}
					*/
					sendBuffer.writeUInt32BE(received, 0);
					connection.write(sendBuffer);
                });

				let onError=(error)=>
				{
					clearInterval(updateTimer);
					fileStream.end();
					µ.logger.error({error:error});
					download.addMessage("error");
					download.state=SC.Download.states.FAILED;
					signal.reject(error);
				};
				fileStream.on("error",onError);
				connection.on("error",onError)
				.on("end",()=>
				{
					clearInterval(updateTimer);
					partFile.stat()
					.then((stats)=>
					{
						if(stats.size!=offer.filesize)
						{
							download.addMessage("Connection interrupted");
							download.state=SC.Download.states.FAILED;
							return Promise.reject("Connection interrupted");
						}
						download.addMessage("complete");
						download.state=SC.Download.states.DONE;
						if(targetFile!==partFile)
						{
							return SC.FileUtil.findUnusedName(targetFile)
							.then(()=>
							{
								return partFile.rename(targetFile.getName()).then(()=>
								{
									download.filename=partFile.getName();
								});
							});
						}
					})
					.then(signal.resolve,signal.reject);

					connection.destroy();
				});

				signal.addAbort(function()
				{
					SC.ircManager.message(download.dataSource.network,download.dataSource.user,"XDCC CANCEL");
					connection.removeAllListeners("error");
					setTimeout(()=>connection.end(),250);
				});
			},signal.reject);
		})
		.catch(signal.reject);
	};

    // matches: DCC {command} {argument} {ip} {port} {rest}
	let dccExp=/DCC (\w+) (?:['"](.+)["']|(\S+)) ([\d:a-fA-F]+) (\d+)\s*(.*)/;
	let parseIp=function(numberString)
	{
		if(numberString.indexOf(":")!=-1) return numberString // IPv6
		let number=parseInt(numberString,10);
		let ip=(number&255);
		ip=((number>>8)&255)+"."+ip;
		ip=((number>>16)&255)+"."+ip;
		ip=((number>>24)&255)+"."+ip;
		return ip;
	};
	let checkDccDownload=function(download)
	{
		let errors=[];

		if(!download.dataSource.network) errors.push("no network");
		if(!download.dataSource.user) errors.push("no user");
		if(!download.dataSource.ip) errors.push("no ip");
		if(!download.dataSource.port) errors.push("no port");
		if(!download.filepath) errors.push("no filepath");
		if(!download.filename) errors.push("no filename");

		return errors;
	};
	let checkXdccDownload=function(manager,download)
	{
		let errors=[];

		if(!download.dataSource.network) errors.push("no network");
		if(!download.dataSource.user) errors.push("no user");
		if(!download.dataSource.packnumber) errors.push("no ip");
		if(!download.filepath) errors.push("no filepath");

		if(errors.length>0) return Promise.reject(errors);
		return Promise.resolve(true);
	};
	let ignoreRegex=/[\s\._'"`´]+/g;
	let checkName=function(download,offer)
	{
		return !download.dataSource.checkName|| //no check
		download.dataSource.checkName==offer.filename|| //same
		download.dataSource.checkName.replace(ignoreRegex,"").toLowerCase()==offer.filename.replace(ignoreRegex,"").toLowerCase(); //similar
	};
	let getConfigValue=function(config,downloadValue,pathKeys)
	{
		let field=config.get(pathKeys);
		if(!field) return downloadValue;
		if(downloadValue==null||!field.isValid(downloadValue)) return field.get();
		return downloadValue;
	}

	module.exports=xdccManager;

})(Morgas,Morgas.setModule,Morgas.getModule,Morgas.hasModule,Morgas.shortcut);


text:
.PHONY: help

end = \033[0m
green = \033[92m

help:
	@echo "${green}start:${end} Up the project"

start:
	docker-compose up -d --build

stop:
	docker-compose down --remove-orphans

restart:
	$(MAKE) stop
	$(MAKE) start

shell-blog:
	docker exec -it blog sh

blog-init-db:
	docker-compose exec --env FLASK_APP=wsgi.py blog flask load_fixture

run-blog-dev:
	docker-compose exec blog flask run --host 0.0.0.0 --port 5000

reset:
	docker kill $(docker ps -q)
	docker rm $(docker ps -a -q)
	docker rmi $(docker images -q)
	docker volume rm $(docker volume ls -q --filter dangling=true)


text:
import React, { Component } from 'react'
import styled from 'styled-components/native'
import FollowButtonWithData from '../../../components/FollowButton'
import SmallButton from '../../../components/UI/Buttons/SmallButton'
import navigationService from '../../../utilities/navigationService'
import { Units } from '../../../constants/Style'
import gql from 'graphql-tag'

export const profileActionsFragment = gql`
  fragment ProfileActions on User {
    id
    can {
      follow
    }
  }
`

const Actions = styled.View`
  margin-vertical: ${Units.scale[2]};
  flex-direction: row;
  justify-content: center;
`

interface IFollowButtonsProps {
  id?: string
  type?: string
}

const FollowButton = styled(FollowButtonWithData)<IFollowButtonsProps>`
  margin-horizontal: ${Units.scale[1]};
`

const Action = styled(SmallButton)`
  margin-horizontal: ${Units.scale[1]};
`

interface IProfileActionsProps {
  user: any
  isTheCurrentUser: boolean
}

export default class ProfileActions extends Component<IProfileActionsProps, {}> {
  settings = () => navigationService.navigate('userSettings')

  render() {
    const {
      isTheCurrentUser,
      user: { id, can },
    } = this.props
    return (
      <Actions>
        {can.follow && <FollowButton id={id} type="USER" />}

        {isTheCurrentUser && <Action onPress={this.settings}>Settings</Action>}
      </Actions>
    )
  }
}


text:
module Fog
  module Parsers
    module Storage
      module AWS
        class ListParts < Fog::Parsers::Base
          def reset
            @part = {}
            @response = { 'Initiator' => {}, 'Part' => [] }
          end

          def end_element(name)
            case name
            when 'Bucket', 'Key', 'NextPartNumberMarker', 'PartNumberMarker', 'StorageClass', 'UploadId'
              @response[name] = value
            when 'DisplayName', 'ID'
              @response['Initiator'][name] = value
            when 'ETag'
              @part[name] = value
            when 'IsTruncated'
              @response[name] = value == 'true'
            when 'LastModified'
              @part[name] = Time.parse(value)
            when 'MaxParts'
              @response[name] = value.to_i
            when 'Part'
              @response['Part'] << @part
              @part = {}
            when 'PartNumber', 'Size'
              @part[name] = value.to_i
            end
          end
        end
      end
    end
  end
end


text:
package org.nd4j.linalg.api.ops.impl.accum.distances;

import org.apache.commons.math3.util.FastMath;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseAccumulation;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.util.ComplexUtil;

/**
 * Manhattan distance
 *
 * @author Adam Gibson
 */
public class ManhattanDistance extends BaseAccumulation {

    public ManhattanDistance() {
    }

    public ManhattanDistance(INDArray x, INDArray y, INDArray z, int n) {
        super(x, y, z, n);
    }

    public ManhattanDistance(INDArray x, INDArray y, int n) {
        super(x, y, n);
    }

    public ManhattanDistance(INDArray x) {
        super(x);
    }

    public ManhattanDistance(INDArray x, INDArray y) {
        super(x, y);
    }

    @Override
    public double update(double accum, double x){
        return accum;
    }

    @Override
    public double update(double accum, double x, double y){
        return accum + FastMath.abs(x-y);
    }

    @Override
    public float update(float accum, float x){
        return accum;
    }

    @Override
    public float update(float accum, float x, float y){
        return accum + FastMath.abs(x-y);
    }

    @Override
    public IComplexNumber update( IComplexNumber accum, double x){
        return accum;
    }

    @Override
    public IComplexNumber update( IComplexNumber accum, double x, double y){
        return accum.add(FastMath.abs(x-y));
    }

    @Override
    public IComplexNumber update( IComplexNumber accum, IComplexNumber x){
        return accum;
    }

    @Override
    public IComplexNumber update( IComplexNumber accum, IComplexNumber x, IComplexNumber y){
        return accum.add(x.sub(y).absoluteValue());
    }

    @Override
    public IComplexNumber update(IComplexNumber accum, IComplexNumber x, double y) {
        return accum.add(x.sub(y).absoluteValue());
    }

    @Override
    public double combineSubResults(double first, double second){
        return first + second;
    }

    @Override
    public float combineSubResults(float first, float second){
        return first + second;
    }

    @Override
    public IComplexNumber combineSubResults(IComplexNumber first, IComplexNumber second){
        return first.add(second);
    }

    @Override
    public String name() {
        return "manhattan";
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, double other) {
        numProcessed++;
        return origin.sub(other);
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, float other) {
        numProcessed++;
        return origin.sub(other);
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, IComplexNumber other) {
        numProcessed++;
        return origin.sub(other);
    }

    @Override
    public float op(float origin, float other) {
        return origin - other;
    }

    @Override
    public double op(double origin, double other) {
        numProcessed++;
        return origin - other;
    }

    @Override
    public double op(double origin) {
        numProcessed++;
        return origin;
    }

    @Override
    public float op(float origin) {
        numProcessed++;
        return origin;
    }

    @Override
    public IComplexNumber op(IComplexNumber origin) {
        numProcessed++;
        return origin;
    }

    @Override
    public Op opForDimension(int index, int dimension) {
        if (y() != null)
            return new ManhattanDistance(x.vectorAlongDimension(index, dimension), y.vectorAlongDimension(index, dimension), x.length());
        else
            return new ManhattanDistance(x.vectorAlongDimension(index, dimension));

    }

    @Override
    public Op opForDimension(int index, int... dimension) {
        if (y() != null)
            return new ManhattanDistance(x.tensorAlongDimension(index, dimension), y.tensorAlongDimension(index, dimension), x.length());
        else
            return new ManhattanDistance(x.tensorAlongDimension(index, dimension));
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Lecidea vinosa Eschw.

### Remarks
null


text:
/**
 * Created by pg9501 on 16.10.2017.
 */
(function () {
    'use strict';
    angular
        .module('myApp')
        .controller('QuestionnairePart1Question1314Controller', QuestionnairePart1Question1314Controller);

    /** @ngInject */
    function QuestionnairePart1Question1314Controller($location,$cookies,$timeout,$http) {

        //console.log($rootScope.globalsForTasks.currentUserForTasks);

        var amt = 12;

        var vm=this;

        vm.timeLimit=10;
        vm.numberOfTasks=24;
        vm.remainingTime=100;
        vm.isFinished=false;

        $timeout(function(){
            vm.progressValue = (100*amt)/vm.numberOfTasks;
        }, 200);

        vm.countTo = amt;
        vm.countFrom = 0;

        vm.username=($cookies.getObject('globalsForTasks') || {}).currentUserForTasks.username;

        vm.userSeq=vm.username.slice(vm.username.indexOf("_")+1);

        //console.log("vm.userSeq is "+vm.userSeq);

        vm.answer13="";
        vm.answer14="";
        vm.next=function () {

            $location.path('/questionnaire/part2/introduction');
        }
        function UpdateEvaluationQuestionnaire(question) {
            return $http.put('http://localhost:8087/bos/api/evaluationQuestionnaire/',question).then(handleSuccess, handleError('Error putting questionnaire info'));
        }
        function handleSuccess(res) {
            return res.data;
        }
        function handleError(error) {
            return function () {
                return { success: false, message: error };
            };
        }
    }

})();


text:
using System;

public class Int32IConvertibleToDateTime
{
    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Negative]");
        retVal = NegTest1() && retVal;
        retVal = NegTest2() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    #endregion

    #region Nagetive Test Cases
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: Convert an random int32 to DateTime ");

        try
        {
            Int32 i1 = TestLibrary.Generator.GetInt32(-55);
            IConvertible Icon1 = (IConvertible)i1;
            DateTime d1 = Icon1.ToDateTime(null);
            TestLibrary.TestFramework.LogError("101", "The InvalidCastException was not thrown as expected");
            retVal = false;

        }
        catch (System.InvalidCastException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }

    public bool NegTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest2: Convert zero to DateTime ");

        try
        {
            Int32 i1 = 0;
            DateTime d1 = (i1 as IConvertible).ToDateTime(null);
            TestLibrary.TestFramework.LogError("103", "The InvalidCastException was not thrown as expected");
            retVal = false;

        }
        catch (System.InvalidCastException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    #endregion
    #endregion

    public static int Main()
    {
        Int32IConvertibleToDateTime test = new Int32IConvertibleToDateTime();

        TestLibrary.TestFramework.BeginTestCase("Int32IConvertibleToDateTime");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
}


text:
import React, { PropTypes } from 'react';
import { Button } from 'react-bootstrap';

const getStatus = (step) => {
  switch (step) {
    case 1:
      return '申请任务';

    case 2:
      return '做任务';

    case 3:
      return '商家发货';

    case 4:
      return '签收好评';

    case 5:
      return '佣金提现';

    default:
      return '申请任务';
  }
};

const ActionButton = ({ step, nextStep }) => {
  return (
    <div className="action-button">
      当前状态:{step}-{getStatus(step)}
      {step > 1 && <Button onClick={nextStep}>完成</Button>}
    </div>
  );
};

ActionButton.propTypes = {
  step: PropTypes.number,
  nextStep: PropTypes.func
};

export default ActionButton;


text:
require.config({
    baseUrl: 'js/lib',
    paths: {
        app: '../app',
        text: 'text/text'
    }
});

/**
 * A test of source maps on a concatenated, but not minified file.
 */
require(['app/main']);


text:
<?php

namespace yii2mod\chosen;

use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;

/**
 * Chosen Select Widget based on Chosen jQuery plugin {@link http://harvesthq.github.io/chosen)
 * @package yii2mod\chosen
 *
 * @author Igor Chepurnoy
 */
class ChosenSelect extends InputWidget
{
    /**
     * @var array the HTML attributes for the input tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = ['data-placeholder' => 'Please select...', 'multiple' => false];

    /**
     * @var array select items
     */
    public $items = [];

    /**
     * @var array Plugin options
     */
    public $pluginOptions = ['width' => '100%'];

    /**
     * Initializes the object.
     * This method is invoked at the end of the constructor after the object is initialized with the
     * given configuration.
     */
    public function init()
    {
        parent::init();
    }

    /**
     * Render chosen select
     * @return string|void
     */
    public function run()
    {
        if ($this->hasModel()) {
            echo Html::activeDropDownList($this->model, $this->attribute, $this->items, $this->options);
        } else {
            echo Html::dropDownList($this->name, $this->value, $this->items, $this->options);
        }
        $this->registerAssets();
    }

    /**
     * Register client assets
     */
    protected function registerAssets()
    {
        $view = $this->getView();
        ChosenSelectAsset::register($view);
        $js = '$("#' . $this->getInputId() . '").chosen(' . $this->getPluginOptions() . ');';
        $view->registerJs($js, $view::POS_END);
    }

    /**
     * Return plugin options in json format
     * @return string
     */
    public function getPluginOptions()
    {
        return Json::encode($this->pluginOptions);
    }

    /**
     * Return input id
     */
    public function getInputId()
    {
        return $this->options['id'];
    }
}


text:
CREATE OR REPLACE VIEW vw_stat_statements_history AS
WITH stat_history AS (
          SELECT  PSSH.*
                 ,PR.rolname as user_name
            FROM   pg_stat_statements_history PSSH
      inner join   pg_roles pr on (PSSH.userid = pr.OID )
            WHERE  1=1
              AND  ( pr.rolname != 'rdsadmin'  AND  PSSH.dbid  != 16384 and query not like '%history%' and query not like '%snapshot%') -- let system objects out of this
  ),  stat_window AS (
		select  row_number() OVER w as row_pos
               ,dbid
		       ,user_name
		       ,queryid
		       ,query
		       ,inserted_at
		      -- ,total_time
		      -- ,min_time
		      -- ,max_time
		      -- ,mean_time
		      -- ,stddev_time
		       ,CASE WHEN (row_number() OVER w =1 )
                      THEN calls
                      ELSE coalesce((calls - lag(calls) OVER w),0)
                  END AS calls_df
               ,calls
       		   ,CASE WHEN (row_number() OVER w =1 )
                      THEN rows
                      ELSE coalesce((rows - lag(rows) OVER w),0)
                  END AS rows_df
               ,rows
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN shared_blks_hit
                      ELSE coalesce((shared_blks_hit - lag(shared_blks_hit) OVER w),0)
                  END AS shared_blks_hit_df
               ,shared_blks_hit
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN shared_blks_read
                      ELSE coalesce((shared_blks_read - lag(shared_blks_read) OVER w),0)
                  END AS shared_blks_read_df
               ,shared_blks_read
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN shared_blks_dirtied
                      ELSE coalesce((shared_blks_dirtied - lag(shared_blks_dirtied) OVER w),0)
                  END AS shared_blks_dirtied_df
               ,shared_blks_dirtied
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN shared_blks_written
                      ELSE coalesce((shared_blks_written - lag(shared_blks_written) OVER w),0)
                  END AS shared_blks_written_df
               ,shared_blks_written
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN local_blks_hit
                      ELSE coalesce((local_blks_hit - lag(local_blks_hit) OVER w),0)
                  END AS local_blks_hit_df
               ,local_blks_hit
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN local_blks_read
                      ELSE coalesce((local_blks_read - lag(local_blks_read) OVER w),0)
                  END AS local_blks_read_df
               ,local_blks_read
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN local_blks_dirtied
                      ELSE coalesce((local_blks_dirtied - lag(local_blks_dirtied) OVER w),0)
                  END AS local_blks_dirtied_df
               ,local_blks_dirtied
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN local_blks_written
                      ELSE coalesce((local_blks_written - lag(local_blks_written) OVER w),0)
                  END AS local_blks_written_df
               ,local_blks_written
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN temp_blks_read
                      ELSE coalesce((temp_blks_read - lag(temp_blks_read) OVER w),0)
                  END AS temp_blks_read_df
               ,temp_blks_read
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN temp_blks_written
                      ELSE coalesce((temp_blks_written - lag(temp_blks_written) OVER w),0)
                  END AS temp_blks_written_df
               ,temp_blks_written
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN blk_read_time
                      ELSE coalesce((blk_read_time - lag(blk_read_time) OVER w),0)
                  END AS blk_read_time_df
               ,blk_read_time
               ,CASE WHEN (row_number() OVER w =1 )
                      THEN blk_write_time
                      ELSE coalesce((blk_write_time - lag(blk_write_time) OVER w),0)
                  END AS blk_write_time_df
               ,blk_write_time
		  from stat_history
		 WINDOW w AS (PARTITION BY queryid  ORDER BY date_trunc('minute', inserted_at))
 )
   select *
     from stat_window
     where 1=1
      -- and queryid = -2950157672037395628
     order by inserted_at asc, queryid asc;


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

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.wso2.ppaas.cartridges</groupId>
        <artifactId>configurator-parent</artifactId>
        <version>4.1.3-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <artifactId>configurator-integration</artifactId>
    <packaging>jar</packaging>
    <name>Configurator Integration Tests</name>

    <profiles>
        <profile>
            <id>default</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <configuration>
                            <excludes>
                                <exclude>**/*</exclude>
                            </excludes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>live</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <inherited>false</inherited>
                        <configuration>
                            <systemProperties>
                                <property>
                                    <name>distribution.path</name>
                                    <value>
                                        ${basedir}/../distribution/target/${configurator.distribution.name}-${project.version}.zip
                                    </value>
                                </property>
                                <property>
                                    <name>distribution.name</name>
                                    <value>${configurator.distribution.name}-${project.version}</value>
                                </property>
                            </systemProperties>
                            <suiteXmlFiles>
                                <suiteXmlFile>src/test/resources/configurator-testng.xml
                                </suiteXmlFile>
                            </suiteXmlFiles>
                            <workingDirectory>${basedir}/target</workingDirectory>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-jar-plugin</artifactId>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>test-jar</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-dependency-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-exec</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans-xpath</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
    </dependencies>
</project>


text:
/**
 * \file ccm.h
 *
 * \brief CCM combines Counter mode encryption with CBC-MAC authentication
 *        for 128-bit block ciphers.
 *
 * Input to CCM includes the following elements:
 *

Payload - data that is both authenticated and encrypted.

 *
Associated data (Adata) - data that is authenticated but not
 * encrypted, For example, a header.

 *
Nonce - A unique value that is assigned to the payload and the
 * associated data.

 *
 */
/*
 *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  This file is part of Mbed TLS (https://tls.mbed.org)
 */

#ifndef MBEDTLS_CCM_H
#define MBEDTLS_CCM_H

#include "cipher.h"

#define MBEDTLS_ERR_CCM_BAD_INPUT       -0x000D /**< Bad input parameters to the function. */
#define MBEDTLS_ERR_CCM_AUTH_FAILED     -0x000F /**< Authenticated decryption failed. */
#define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */

#if !defined(MBEDTLS_CCM_ALT)
// Regular implementation
//

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \brief    The CCM context-type definition. The CCM context is passed
 *           to the APIs called.
 */
typedef struct {
    mbedtls_cipher_context_t cipher_ctx;    /*!< The cipher context used. */
}
mbedtls_ccm_context;

/**
 * \brief           This function initializes the specified CCM context,
 *                  to make references valid, and prepare the context
 *                  for mbedtls_ccm_setkey() or mbedtls_ccm_free().
 *
 * \param ctx       The CCM context to initialize.
 */
void mbedtls_ccm_init( mbedtls_ccm_context *ctx );

/**
 * \brief           This function initializes the CCM context set in the
 *                  \p ctx parameter and sets the encryption key.
 *
 * \param ctx       The CCM context to initialize.
 * \param cipher    The 128-bit block cipher to use.
 * \param key       The encryption key.
 * \param keybits   The key size in bits. This must be acceptable by the cipher.
 *
 * \return          \c 0 on success, or a cipher-specific error code.
 */
int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
                        mbedtls_cipher_id_t cipher,
                        const unsigned char *key,
                        unsigned int keybits );

/**
 * \brief   This function releases and clears the specified CCM context
 *          and underlying cipher sub-context.
 *
 * \param ctx       The CCM context to clear.
 */
void mbedtls_ccm_free( mbedtls_ccm_context *ctx );

/**
 * \brief           This function encrypts a buffer using CCM.
 *
 * \param ctx       The CCM context to use for encryption.
 * \param length    The length of the input data in Bytes.
 * \param iv        Initialization vector (nonce).
 * \param iv_len    The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13.
 * \param add       The additional data field.
 * \param add_len   The length of additional data in Bytes.
 *                  Must be less than 2^16 - 2^8.
 * \param input     The buffer holding the input data.
 * \param output    The buffer holding the output data.
 *                  Must be at least \p length Bytes wide.
 * \param tag       The buffer holding the tag.
 * \param tag_len   The length of the tag to generate in Bytes:
 *                  4, 6, 8, 10, 12, 14 or 16.
 *
 * \note            The tag is written to a separate buffer. To concatenate
 *                  the \p tag with the \p output, as done in RFC-3610:
 *                  Counter with CBC-MAC (CCM), use
 *                  \p tag = \p output + \p length, and make sure that the
 *                  output buffer is at least \p length + \p tag_len wide.
 *
 * \return          \c 0 on success.
 */
int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
                         const unsigned char *iv, size_t iv_len,
                         const unsigned char *add, size_t add_len,
                         const unsigned char *input, unsigned char *output,
                         unsigned char *tag, size_t tag_len );

/**
 * \brief           This function performs a CCM authenticated decryption of a
 *                  buffer.
 *
 * \param ctx       The CCM context to use for decryption.
 * \param length    The length of the input data in Bytes.
 * \param iv        Initialization vector.
 * \param iv_len    The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13.
 * \param add       The additional data field.
 * \param add_len   The length of additional data in Bytes.
 *                  Must be less than 2^16 - 2^8.
 * \param input     The buffer holding the input data.
 * \param output    The buffer holding the output data.
 *                  Must be at least \p length Bytes wide.
 * \param tag       The buffer holding the tag.
 * \param tag_len   The length of the tag in Bytes.
 *                  4, 6, 8, 10, 12, 14 or 16.
 *
 * \return          0 if successful and authenticated, or
 *                  #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.
 */
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
                      const unsigned char *iv, size_t iv_len,
                      const unsigned char *add, size_t add_len,
                      const unsigned char *input, unsigned char *output,
                      const unsigned char *tag, size_t tag_len );

#ifdef __cplusplus
}
#endif

#else  /* MBEDTLS_CCM_ALT */
#include "ccm_alt.h"
#endif /* MBEDTLS_CCM_ALT */

#ifdef __cplusplus
extern "C" {
#endif

#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/**
 * \brief          The CCM checkup routine.
 *
 * \return         \c 0 on success, or \c 1 on failure.
 */
int mbedtls_ccm_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

#ifdef __cplusplus
}
#endif

#endif /* MBEDTLS_CCM_H */


text:
/**
 * \file CSimpleWorkflowExecutor.cpp
 * \date Mar 25, 2010
 * \author samael
 */

#include "CSimpleWorkflowExecutor.h"

#include <unistd.h>
#include <iostream>
#include <sstream>
#include "HelperMacros.h"

using namespace std;

namespace wolf
{

void CSimpleWorkflowExecutor::execute(const vector<AActor *> &actors)
{
	_all = actors;
	setPriority(minimumPriority());
	start();
	join();
}

void CSimpleWorkflowExecutor::run()
{
	setup();
	iterate();
	wrapup();
}

void CSimpleWorkflowExecutor::setup()
{
	for (unsigned i = 0; i < _all.size(); i++)
		_all[i]->setup();
}

void CSimpleWorkflowExecutor::iterate()
{
	_vwaitready = _all;

	findready();
	while (!(_vwaitready.empty() && _vwaitpost.empty() &&
			_qready.empty() && _qpost.empty())) {
		// Run all ready actors.
		while (!_qready.empty()) {
			AActor *a = _qready.front();
			_qready.pop_front();
			runactor(a);
		}
		findpost();

		// Postrun all postrunning actors.
		while (!_qpost.empty()) {
			AActor *a = _qpost.front();
			_qpost.pop_front();
			postrunactor(a);
		}
		findready();

		if (_qready.empty())
			usleep(10000);
	}

}

void CSimpleWorkflowExecutor::wrapup()
{
	for (unsigned i = 0; i < _all.size(); i++)
		_all[i]->wrapup();
}

void CSimpleWorkflowExecutor::findready()
{
	static int prcount = 0;
	static unsigned pwcount = 0;
	int rcount = 0;
	vector<AActor *>::iterator iter;
	for (iter = _vwaitready.begin(); iter != _vwaitready.end();) {
		if ((*iter)->state() == AActor::READY) {
			_qready.push_back(*iter);
			_vwaitready.erase(iter);
			rcount++;
		} else
			++iter;
	}

	if (rcount != prcount || _vwaitready.size() != pwcount) {
		PINF_3("Found " << rcount << " runners ready, " << _vwaitready.size() <<
			" actors are still waiting.");
	}

	prcount = rcount;
	pwcount = _vwaitready.size();
}

void CSimpleWorkflowExecutor::findpost()
{
	static int ppcount = 0;
	static unsigned pwcount = 0;
	int pcount = 0;
	vector<AActor *>::iterator iter;
	for (iter = _vwaitpost.begin(); iter != _vwaitpost.end();) {
		if ((*iter)->state() == AActor::POST_RUNNING) {
			_qpost.push_back(*iter);
			_vwaitpost.erase(iter);
			pcount++;
		} else
			++iter;
	}

	if (pcount != ppcount || _vwaitpost.size() != pwcount) {
		PINF_3("Found " << pcount << " runners postrunning, " <<
				_vwaitpost.size() << " actors are still waiting.");
	}

	ppcount = pcount;
	pwcount = _vwaitpost.size();
}

void CSimpleWorkflowExecutor::runactor(AActor *actor)
{
	actor->prefire();
	actor->fire();
	_vwaitpost.push_back(actor);
}

void CSimpleWorkflowExecutor::postrunactor(AActor *actor)
{
	actor->postfire();
	if (actor->testfire())
		_qready.push_back(actor);
}

}


text:
<#
.SYNOPSIS
    Retrieve Resource Provider Types, create an assignment
    for the policy definition 'Allowed resource types' and
    pass the resourcetypes as parameter (-listOfResourceTypesAllowed)
.DESCRIPTION
    Retrieve Resource Provider Types, create an assignment
    for the policy definition 'Allowed resource types' and
    pass the resourcetypes as parameter (-listOfResourceTypesAllowed)

    Script built with the help from a few resources:
    - https://stackoverflow.com/questions/49861955/list-of-all-azure-resource-types-in-azure
    - https://docs.microsoft.com/en-us/rest/api/resources/providers/list
    - https://docs.microsoft.com/en-us/rest/api/resources/providers/listattenantscope
    - https://docs.microsoft.com/en-us/azure/templates/microsoft.devices/iothub-allversions

.PARAMETER SubscriptionId
    Specify the subscriptionId to use
.PARAMETER PolicyDefinitionId
    Specify the PolicyDefinitionId to use
.PARAMETER PolicyAssignmentScope
    Specify on which resource the Policy Assignment need to apply
.PARAMETER AllowedNamespace
    Specify the

.EXAMPLE
    .\policy-allowed_resource_type.ps1 `
        -SubscriptionId '8f3a8176-f66f-420c-8fce-a797ac7cde89' `
        -PolicyDefinitionId '/subscriptions/8f3a8176-f66f-420c-8fce-a797ac7cde89/providers/Microsoft.Authorization/policyDefinitions/8c2f213e-decf-4016-a59e-5e7ce9903075' `
        -PolicyAssignmentScope '/subscriptions/8f3a8176-f66f-420c-8fce-a797ac7cde89/resourceGroups/LogicApp/' `
        -AllowedNamespace 'Microsoft.Compute','Microsoft.Storage','Microsoft.Network'

.EXAMPLE
    .\policy-allowed_resource_type.ps1 `
        -SubscriptionId '8f3a8176-f66f-420c-8fce-a797ac7cde89' `
        -PolicyDefinitionId '/subscriptions/8f3a8176-f66f-420c-8fce-a797ac7cde89/providers/Microsoft.Authorization/policyDefinitions/8c2f213e-decf-4016-a59e-5e7ce9903075' `
        -PolicyAssignmentScope '/subscriptions/8f3a8176-f66f-420c-8fce-a797ac7cde89/resourceGroups/LogicApp/'
.NOTES
Version history
1.0.0 | 2020/05/15 | Francois-Xavier Cat (github.com/lazywinadmin)
  initial version

TODO:
- Still missing a few resource types
    - Microsoft.Devices
        - IotHubs/certificates
    - Microsoft.Network
        - virtualNetworks/taggedTrafficConsumers
    - Microsoft.OperationalInsight
        - workspaces/views
    - Microsoft.Web
        - a bunch
        - hostingenvironments/metricdefinitions
        - hostingenvironments/metrics

    - Maybe investigate:
        - https://management.azure.com/providers/Microsoft.Authorization/providerOperations?api-version=2018-01-01-preview&$expand=resourceTypes#
#>

[CmdletBinding()]
param(
    [parameter(Mandatory)]
    $SubscriptionId,
    [parameter(Mandatory)]
    $PolicyDefinitionId,
    [parameter(Mandatory)]
    $PolicyAssignmentScope,
    [String[]]$AllowedNamespace
)
try{

    # Select Subscription context
    Write-Verbose -Message "Context - Set Context to Subscription id '$SubscriptionId'"
    Set-AzContext -Subscription $SubscriptionId

    # Resource Types from Resource Provider (on subscription level)
    if($AllowedNamespace){
        $SubProviders = $AllowedNamespace |
            ForEach-Object{
                Write-Verbose -Message "ResourceProvider - Namespace '$($_)' - Retrieving ..."
                Get-AzResourceProvider -ProviderNamespace $_
            }
    }else{
        # Retrieve Providers
        Write-Verbose -Message "ResourceProvider - All namespaces - Retrieving ..."
        $SubProviders = Get-AzResourceProvider -ListAvailable
    }

    # Resource Types from Policy Aliases (on subscription level)
    if($AllowedNamespace){
        $AllAliases = $AllowedNamespace |
            ForEach-Object{
                Write-Verbose -Message "PolicyAliases - Namespace '$($_)' - Retrieving ..."
                Get-AzPolicyAlias -Namespace $_
            }

    }else{
        Write-Verbose -Message "PolicyAliases - All namespaces - Retrieving ..."
        $AllAliases = Get-AzPolicyAlias -ListAvailable
    }

    # Process output from ResourceProvider and PolicyAliases
    Write-Verbose -Message "ResourceProvider/PolicyAliases - Processing output..."
    $SubResourceTypes = $SubProviders |
        Sort-Object -property ProviderNamespace |
        ForEach-Object {
            #Capture current namespace
            $CurrentNamespace = $_.ProviderNamespace

            # Output Resource type from resource providers
            $_.ResourceTypes |
                ForEach-Object{"$CurrentNamespace/$($_.ResourceTypeName)"}

            # Output Resource type from policy aliases
            $AllAliases|
                Where-Object{$_.Namespace -eq $CurrentNamespace}|
                ForEach-Object{"$($_.Namespace)/$($_.ResourceType)"}
    }

    # Retrieve ResourceTypes on Tenant level
    Write-Verbose -Message "ResourceProvider (Tenant scope) - Retrieving current access token..."
    $currentAzureContext = Get-AzContext
    $azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile;
    $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile);
    $token=$profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId).AccessToken;

    # Build Invoke-RestMethod header
    $authHeader = @{
        'Content-type' = 'application/json'
        'Authorization'="Bearer $token"
        #'ExpiresOn'=$accessToken.expires_in
    }

    # Providers - Tenant level
    #  https://docs.microsoft.com/en-us/rest/api/resources/providers/listattenantscope

    if($AllowedNamespace){
        $TenantResourceTypes = $AllowedNamespace |
            ForEach-Object {
                $ResourceProvider = $_
                Write-Verbose -Message "ResourceProvider (Tenant scope) - Retrieving for Namespace '$ResourceProvider'..."

                $uri = "https://management.azure.com/providers/$($ResourceProvider)?api-version=2019-10-01"
                $result = Invoke-RestMethod -Method Get -Uri $uri -Headers $authHeader
                $result.resourceTypes.resourceType |
                    ForEach-Object {"$ResourceProvider/$($_)"}
            }
    }else{
        Write-Verbose -Message "ResourceProvider (Tenant scope) - Retrieving all Namespaces ..."
        $uri = "https://management.azure.com/providers?`$expand=resourceTypes/aliases&api-version=2019-10-01"
        $result = Invoke-RestMethod -Method Get -Uri $uri -Headers $authHeader
        $TenantResourceTypes = $result.value |
            ForEach-Object {
                $ResourceProvider = $_.namespace
                $_.resourceTypes|
                    ForEach-Object{"$ResourceProvider/$($_.resourceType)"}
            }
    }

    Write-Verbose -Message "Processing final list..."
    $finalList = ($TenantResourceTypes + $SubResourceTypes)|
        Select-Object -Unique

    # $finalList=$finalList | %{
    #     $splitted=$_ -split '\/'
    #     if($splitted.count -gt 2){
    #         "$($splitted[0..1] -join '/')/*"
    #     }
    #     else{$splitted -join '/'}
    # }|select -Unique

    # Retrieve Policy Definition
    Write-Verbose -Message "Policy - Retrieving Definition '$PolicyDefinitionId'..."
    $def = Get-AzPolicyDefinition -Id $PolicyDefinitionId

    # Create Policy Assignment
    Write-Verbose -Message "Policy - Creating assignment ..."
    New-AzPolicyAssignment `
        -Name 'testing-allowed-resource' `
        -Scope $PolicyAssignmentScope `
        -listOfResourceTypesAllowed $finalList `
        -PolicyDefinition $def `
        -OutVariable NewAssign

    #Remove-AzPolicyAssignment -Id $NewAssign

}catch{
    throw $_
}


text:
#ifndef KAZMATH_AABB3D_H_INCLUDED
#define KAZMATH_AABB3D_H_INCLUDED

#include "vec3.h"
#include "utility.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * A struture that represents an axis-aligned
 * bounding box.
 */
typedef struct kmAABB3 {
    kmVec3 min; /** The max corner of the box */
    kmVec3 max; /** The min corner of the box */
} kmAABB3;

/**
    Initializes the AABB around a central point. If centre is NULL
    then the origin is used. Returns pBox.
*/
kmAABB3* kmAABB3Initialize(kmAABB3* pBox, const kmVec3* centre,
                           const kmScalar width, const kmScalar height,
                           const kmScalar depth);

/**
 * Returns KM_TRUE if point is in the specified AABB, returns KM_FALSE
 * otherwise.
 */
int kmAABB3ContainsPoint(const kmAABB3* pBox, const kmVec3* pPoint);

/**
 * Assigns pIn to pOut, returns pOut.
 */
kmAABB3* kmAABB3Assign(kmAABB3* pOut, const kmAABB3* pIn);

/**
 * Scales pIn by s, stores the resulting AABB in pOut. Returns pOut
 */
kmAABB3* kmAABB3Scale(kmAABB3* pOut, const kmAABB3* pIn, kmScalar s);
kmBool kmAABB3IntersectsTriangle(kmAABB3* box, const kmVec3* p1,
                                 const kmVec3* p2, const kmVec3* p3);
kmBool kmAABB3IntersectsAABB(const kmAABB3* box, const kmAABB3* other);
kmEnum kmAABB3ContainsAABB(const kmAABB3* container, const kmAABB3* to_check);
kmScalar kmAABB3DiameterX(const kmAABB3* aabb);
kmScalar kmAABB3DiameterY(const kmAABB3* aabb);
kmScalar kmAABB3DiameterZ(const kmAABB3* aabb);
kmVec3* kmAABB3Centre(const kmAABB3* aabb, kmVec3* pOut);

/**
 * @brief kmAABB3ExpandToContain
 * @param pOut - The resulting AABB
 * @param pIn - The original AABB
 * @param other - Another AABB that you want pIn expanded to contain
 * @return
 */
kmAABB3* kmAABB3ExpandToContain(kmAABB3* pOut, const kmAABB3* pIn, const kmAABB3* other);

#ifdef __cplusplus
}
#endif

#endif


text:
@interface MyWebSocket : WebSocket
{

}

@end