text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*             CLIPS Version 6.24  07/01/05            */
   /*                                                     */
   /*                 CONSTRAINT MODULE                   */
   /*******************************************************/

/*************************************************************/
/* Purpose: Provides functions for creating and removing     */
/*   constraint records, adding them to the contraint hash   */
/*   table, and enabling and disabling static and dynamic    */
/*   constraint checking.                                    */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*      Brian Donnell                                        */
/*                                                           */
/* Revision History:                                         */
/*      6.23: Correction for FalseSymbol/TrueSymbol. DR0859  */
/*                                                           */
/*      6.24: Added allowed-classes slot facet.              */
/*                                                           */
/*            Renamed BOOLEAN macro type to intBool.         */
/*                                                           */
/*************************************************************/

#define _CONSTRNT_SOURCE_

#include <stdio.h>
#define _STDIO_INCLUDED_
#include <stdlib.h>

#include "setup.h"

#include "argacces.h"
#include "constant.h"
#include "envrnmnt.h"
#include "extnfunc.h"
#include "memalloc.h"
#include "multifld.h"
#include "router.h"
#include "scanner.h"

#include "constrnt.h"

/***************************************/
/* LOCAL INTERNAL FUNCTION DEFINITIONS */
/***************************************/

#if (! RUN_TIME) && (! BLOAD_ONLY)
   static void                     InstallConstraintRecord(void *,CONSTRAINT_RECORD *);
   static int                      ConstraintCompare(struct constraintRecord *,struct constraintRecord *);
#endif
#if (! RUN_TIME)
   static void                     ReturnConstraintRecord(void *,CONSTRAINT_RECORD *);
   static void                     DeinstallConstraintRecord(void *,CONSTRAINT_RECORD *);
#endif
   static void                     DeallocateConstraintData(void *);

/*****************************************************/
/* InitializeConstraints: Initializes the constraint */
/*   hash table to NULL and defines the static and   */
/*   dynamic constraint access functions.            */
/*****************************************************/
globle void InitializeConstraints(
  void *theEnv)
  {
#if (! RUN_TIME) && (! BLOAD_ONLY)
   int i;
#endif

   AllocateEnvironmentData(theEnv,CONSTRAINT_DATA,sizeof(struct constraintData),DeallocateConstraintData);

   ConstraintData(theEnv)->StaticConstraintChecking = TRUE;

#if (! RUN_TIME) && (! BLOAD_ONLY)

    ConstraintData(theEnv)->ConstraintHashtable = (struct constraintRecord **)
                          gm2(theEnv,(int) sizeof (struct constraintRecord *) *
                                    SIZE_CONSTRAINT_HASH);

    if (ConstraintData(theEnv)->ConstraintHashtable == NULL) EnvExitRouter(theEnv,EXIT_FAILURE);

    for (i = 0; i < SIZE_CONSTRAINT_HASH; i++) ConstraintData(theEnv)->ConstraintHashtable[i] = NULL;
#endif

#if (! RUN_TIME)
   EnvDefineFunction2(theEnv,"get-dynamic-constraint-checking",'b',GDCCommand,"GDCCommand", "00");
   EnvDefineFunction2(theEnv,"set-dynamic-constraint-checking",'b',SDCCommand,"SDCCommand", "11");

   EnvDefineFunction2(theEnv,"get-static-constraint-checking",'b',GSCCommand,"GSCCommand", "00");
   EnvDefineFunction2(theEnv,"set-static-constraint-checking",'b',SSCCommand,"SSCCommand", "11");
#endif
  }

/*****************************************************/
/* DeallocateConstraintData: Deallocates environment */
/*    data for constraints.                          */
/*****************************************************/
static void DeallocateConstraintData(
  void *theEnv)
  {
#if ! RUN_TIME
   struct constraintRecord *tmpPtr, *nextPtr;
   int i;

   for (i = 0; i < SIZE_CONSTRAINT_HASH; i++)
     {
      tmpPtr = ConstraintData(theEnv)->ConstraintHashtable[i];
      while (tmpPtr != NULL)
        {
         nextPtr = tmpPtr->next;
         ReturnConstraintRecord(theEnv,tmpPtr);
         tmpPtr = nextPtr;
        }
     }

   rm(theEnv,ConstraintData(theEnv)->ConstraintHashtable,
      (int) sizeof (struct constraintRecord *) * SIZE_CONSTRAINT_HASH);
#else
#if MAC_MCW || IBM_MCW || MAC_XCD
#pragma unused(theEnv)
#endif
#endif

#if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE) && (! RUN_TIME)
   if (ConstraintData(theEnv)->NumberOfConstraints != 0)
     {
      genlongfree(theEnv,(void *) ConstraintData(theEnv)->ConstraintArray,
                  (unsigned long) (sizeof(CONSTRAINT_RECORD) *
                                  ConstraintData(theEnv)->NumberOfConstraints));
     }
#endif
  }

#if (! RUN_TIME)

/*************************************************************/
/* ReturnConstraintRecord: Frees the data structures used by */
/*   a constraint record. If the returnOnlyFields argument   */
/*   is FALSE, then the constraint record is also freed.     */
/*************************************************************/
static void ReturnConstraintRecord(
  void *theEnv,
  CONSTRAINT_RECORD *constraints)
  {
   if (constraints == NULL) return;

   if (constraints->bucket < 0)
     {
      ReturnExpression(theEnv,constraints->classList);
      ReturnExpression(theEnv,constraints->restrictionList);
      ReturnExpression(theEnv,constraints->maxValue);
      ReturnExpression(theEnv,constraints->minValue);
      ReturnExpression(theEnv,constraints->minFields);
      ReturnExpression(theEnv,constraints->maxFields);
     }

   ReturnConstraintRecord(theEnv,constraints->multifield);

   rtn_struct(theEnv,constraintRecord,constraints);
  }

/***************************************************/
/* DeinstallConstraintRecord: Decrements the count */
/*   values of all occurrences of primitive data   */
/*   types found in a constraint record.           */
/***************************************************/
static void DeinstallConstraintRecord(
  void *theEnv,
  CONSTRAINT_RECORD *constraints)
  {
   if (constraints->bucket >= 0)
     {
      RemoveHashedExpression(theEnv,constraints->classList);
      RemoveHashedExpression(theEnv,constraints->restrictionList);
      RemoveHashedExpression(theEnv,constraints->maxValue);
      RemoveHashedExpression(theEnv,constraints->minValue);
      RemoveHashedExpression(theEnv,constraints->minFields);
      RemoveHashedExpression(theEnv,constraints->maxFields);
     }
   else
     {
      ExpressionDeinstall(theEnv,constraints->classList);
      ExpressionDeinstall(theEnv,constraints->restrictionList);
      ExpressionDeinstall(theEnv,constraints->maxValue);
      ExpressionDeinstall(theEnv,constraints->minValue);
      ExpressionDeinstall(theEnv,constraints->minFields);
      ExpressionDeinstall(theEnv,constraints->maxFields);
     }

   if (constraints->multifield != NULL)
     { DeinstallConstraintRecord(theEnv,constraints->multifield); }
  }

/******************************************/
/* RemoveConstraint: Removes a constraint */
/*   from the constraint hash table.      */
/******************************************/
globle void RemoveConstraint(
  void *theEnv,
  struct constraintRecord *theConstraint)
  {
   struct constraintRecord *tmpPtr, *prevPtr = NULL;

   if (theConstraint == NULL) return;

   /*========================================*/
   /* If the bucket value is less than zero, */
   /* then the constraint wasn't stored in   */
   /* the hash table.                        */
   /*========================================*/

   if (theConstraint->bucket < 0)
     {
      ReturnConstraintRecord(theEnv,theConstraint);
      return;
     }

   /*================================*/
   /* Find and remove the constraint */
   /* from the contraint hash table. */
   /*================================*/

   tmpPtr = ConstraintData(theEnv)->ConstraintHashtable[theConstraint->bucket];
   while (tmpPtr != NULL)
     {
      if (tmpPtr == theConstraint)
        {
         theConstraint->count--;
         if (theConstraint->count == 0)
           {
            if (prevPtr == NULL)
              { ConstraintData(theEnv)->ConstraintHashtable[theConstraint->bucket] = theConstraint->next; }
            else
              { prevPtr->next = theConstraint->next; }
            DeinstallConstraintRecord(theEnv,theConstraint);
            ReturnConstraintRecord(theEnv,theConstraint);
           }
         return;
        }

      prevPtr = tmpPtr;
      tmpPtr = tmpPtr->next;
     }

   return;
  }

#endif /* (! RUN_TIME) */

#if (! RUN_TIME) && (! BLOAD_ONLY)

/***********************************/
/* HashConstraint: Returns a hash  */
/*   value for a given constraint. */
/***********************************/
globle int HashConstraint(
  struct constraintRecord *theConstraint)
  {
   int i = 0;
   unsigned int count = 0;
   int hashValue;
   struct expr *tmpPtr;

   count += (unsigned)
      (theConstraint->anyAllowed * 17) +
      (theConstraint->symbolsAllowed * 5) +
      (theConstraint->stringsAllowed * 23) +
      (theConstraint->floatsAllowed * 19) +
      (theConstraint->integersAllowed * 29) +
      (theConstraint->instanceNamesAllowed * 31) +
      (theConstraint->instanceAddressesAllowed * 17);

   count += (unsigned)
      (theConstraint->externalAddressesAllowed * 29) +
      (theConstraint->voidAllowed * 29) +
      (theConstraint->multifieldsAllowed * 29) +
      (theConstraint->factAddressesAllowed * 79) +
      (theConstraint->anyRestriction * 59) +
      (theConstraint->symbolRestriction * 61);

   count += (unsigned)
      (theConstraint->stringRestriction * 3) +
      (theConstraint->floatRestriction * 37) +
      (theConstraint->integerRestriction * 9) +
      (theConstraint->classRestriction * 11) +
      (theConstraint->instanceNameRestriction * 7);

   for (tmpPtr = theConstraint->classList; tmpPtr != NULL; tmpPtr = tmpPtr->nextArg)
     { count += GetAtomicHashValue(tmpPtr->type,tmpPtr->value,i++); }

   for (tmpPtr = theConstraint->restrictionList; tmpPtr != NULL; tmpPtr = tmpPtr->nextArg)
     { count += GetAtomicHashValue(tmpPtr->type,tmpPtr->value,i++); }

   for (tmpPtr = theConstraint->minValue; tmpPtr != NULL; tmpPtr = tmpPtr->nextArg)
     { count += GetAtomicHashValue(tmpPtr->type,tmpPtr->value,i++); }

   for (tmpPtr = theConstraint->maxValue; tmpPtr != NULL; tmpPtr = tmpPtr->nextArg)
     { count += GetAtomicHashValue(tmpPtr->type,tmpPtr->value,i++); }

   for (tmpPtr = theConstraint->minFields; tmpPtr != NULL; tmpPtr = tmpPtr->nextArg)
     { count += GetAtomicHashValue(tmpPtr->type,tmpPtr->value,i++); }

   for (tmpPtr = theConstraint->maxFields; tmpPtr != NULL; tmpPtr = tmpPtr->nextArg)
     { count += GetAtomicHashValue(tmpPtr->type,tmpPtr->value,i++); }

   if (theConstraint->multifield != NULL)
     { count += (unsigned) HashConstraint(theConstraint->multifield); }

   hashValue = (int) (count % SIZE_CONSTRAINT_HASH);
   if (hashValue < 0) hashValue = - hashValue;
   return(hashValue);
  }

/**********************************************/
/* ConstraintCompare: Compares two constraint */
/*   records and returns TRUE if they are     */
/*   identical, otherwise FALSE.              */
/**********************************************/
static int ConstraintCompare(
  struct constraintRecord *constraint1,
  struct constraintRecord *constraint2)
  {
   struct expr *tmpPtr1, *tmpPtr2;

   if ((constraint1->anyAllowed != constraint2->anyAllowed) ||
       (constraint1->symbolsAllowed != constraint2->symbolsAllowed) ||
       (constraint1->stringsAllowed != constraint2->stringsAllowed) ||
       (constraint1->floatsAllowed != constraint2->floatsAllowed) ||
       (constraint1->integersAllowed != constraint2->integersAllowed) ||
       (constraint1->instanceNamesAllowed != constraint2->instanceNamesAllowed) ||
       (constraint1->instanceAddressesAllowed != constraint2->instanceAddressesAllowed) ||
       (constraint1->externalAddressesAllowed != constraint2->externalAddressesAllowed) ||
       (constraint1->voidAllowed != constraint2->voidAllowed) ||
       (constraint1->multifieldsAllowed != constraint2->multifieldsAllowed) ||
       (constraint1->singlefieldsAllowed != constraint2->singlefieldsAllowed) ||
       (constraint1->factAddressesAllowed != constraint2->factAddressesAllowed) ||
       (constraint1->anyRestriction != constraint2->anyRestriction) ||
       (constraint1->symbolRestriction != constraint2->symbolRestriction) ||
       (constraint1->stringRestriction != constraint2->stringRestriction) ||
       (constraint1->floatRestriction != constraint2->floatRestriction) ||
       (constraint1->integerRestriction != constraint2->integerRestriction) ||
       (constraint1->classRestriction != constraint2->classRestriction) ||
       (constraint1->instanceNameRestriction != constraint2->instanceNameRestriction))
     { return(FALSE); }

   for (tmpPtr1 = constraint1->classList, tmpPtr2 = constraint2->classList;
        (tmpPtr1 != NULL) && (tmpPtr2 != NULL);
        tmpPtr1 = tmpPtr1->nextArg, tmpPtr2 = tmpPtr2->nextArg)
     {
      if ((tmpPtr1->type != tmpPtr2->type) || (tmpPtr1->value != tmpPtr2->value))
        { return(FALSE); }
     }
   if (tmpPtr1 != tmpPtr2) return(FALSE);

   for (tmpPtr1 = constraint1->restrictionList, tmpPtr2 = constraint2->restrictionList;
        (tmpPtr1 != NULL) && (tmpPtr2 != NULL);
        tmpPtr1 = tmpPtr1->nextArg, tmpPtr2 = tmpPtr2->nextArg)
     {
      if ((tmpPtr1->type != tmpPtr2->type) || (tmpPtr1->value != tmpPtr2->value))
        { return(FALSE); }
     }
   if (tmpPtr1 != tmpPtr2) return(FALSE);

   for (tmpPtr1 = constraint1->minValue, tmpPtr2 = constraint2->minValue;
        (tmpPtr1 != NULL) && (tmpPtr2 != NULL);
        tmpPtr1 = tmpPtr1->nextArg, tmpPtr2 = tmpPtr2->nextArg)
     {
      if ((tmpPtr1->type != tmpPtr2->type) || (tmpPtr1->value != tmpPtr2->value))
        { return(FALSE); }
     }
   if (tmpPtr1 != tmpPtr2) return(FALSE);

   for (tmpPtr1 = constraint1->maxValue, tmpPtr2 = constraint2->maxValue;
        (tmpPtr1 != NULL) && (tmpPtr2 != NULL);
        tmpPtr1 = tmpPtr1->nextArg, tmpPtr2 = tmpPtr2->nextArg)
     {
      if ((tmpPtr1->type != tmpPtr2->type) || (tmpPtr1->value != tmpPtr2->value))
        { return(FALSE); }
     }
   if (tmpPtr1 != tmpPtr2) return(FALSE);

   for (tmpPtr1 = constraint1->minFields, tmpPtr2 = constraint2->minFields;
        (tmpPtr1 != NULL) && (tmpPtr2 != NULL);
        tmpPtr1 = tmpPtr1->nextArg, tmpPtr2 = tmpPtr2->nextArg)
     {
      if ((tmpPtr1->type != tmpPtr2->type) || (tmpPtr1->value != tmpPtr2->value))
        { return(FALSE); }
     }
   if (tmpPtr1 != tmpPtr2) return(FALSE);

   for (tmpPtr1 = constraint1->maxFields, tmpPtr2 = constraint2->maxFields;
        (tmpPtr1 != NULL) && (tmpPtr2 != NULL);
        tmpPtr1 = tmpPtr1->nextArg, tmpPtr2 = tmpPtr2->nextArg)
     {
      if ((tmpPtr1->type != tmpPtr2->type) || (tmpPtr1->value != tmpPtr2->value))
        { return(FALSE); }
     }
   if (tmpPtr1 != tmpPtr2) return(FALSE);

   if (((constraint1->multifield == NULL) && (constraint2->multifield != NULL)) ||
       ((constraint1->multifield != NULL) && (constraint2->multifield == NULL)))
     { return(FALSE); }
   else if (constraint1->multifield == constraint2->multifield)
     { return(TRUE); }

   return(ConstraintCompare(constraint1->multifield,constraint2->multifield));
  }

/************************************/
/* AddConstraint: Adds a constraint */
/*   to the constraint hash table.  */
/************************************/
globle struct constraintRecord *AddConstraint(
  void *theEnv,
  struct constraintRecord *theConstraint)
  {
   struct constraintRecord *tmpPtr;
   int hashValue;

   if (theConstraint == NULL) return(NULL);

   hashValue = HashConstraint(theConstraint);

   for (tmpPtr = ConstraintData(theEnv)->ConstraintHashtable[hashValue];
        tmpPtr != NULL;
        tmpPtr = tmpPtr->next)
     {
      if (ConstraintCompare(theConstraint,tmpPtr))
        {
         tmpPtr->count++;
         ReturnConstraintRecord(theEnv,theConstraint);
         return(tmpPtr);
        }
     }

   InstallConstraintRecord(theEnv,theConstraint);
   theConstraint->count = 1;
   theConstraint->bucket = hashValue;
   theConstraint->next = ConstraintData(theEnv)->ConstraintHashtable[hashValue];
   ConstraintData(theEnv)->ConstraintHashtable[hashValue] = theConstraint;
   return(theConstraint);
  }

/*************************************************/
/* InstallConstraintRecord: Increments the count */
/*   values of all occurrences of primitive data */
/*   types found in a constraint record.         */
/*************************************************/
static void InstallConstraintRecord(
  void *theEnv,
  CONSTRAINT_RECORD *constraints)
  {
   struct expr *tempExpr;

   tempExpr = AddHashedExpression(theEnv,constraints->classList);
   ReturnExpression(theEnv,constraints->classList);
   constraints->classList = tempExpr;

   tempExpr = AddHashedExpression(theEnv,constraints->restrictionList);
   ReturnExpression(theEnv,constraints->restrictionList);
   constraints->restrictionList = tempExpr;

   tempExpr = AddHashedExpression(theEnv,constraints->maxValue);
   ReturnExpression(theEnv,constraints->maxValue);
   constraints->maxValue = tempExpr;

   tempExpr = AddHashedExpression(theEnv,constraints->minValue);
   ReturnExpression(theEnv,constraints->minValue);
   constraints->minValue = tempExpr;

   tempExpr = AddHashedExpression(theEnv,constraints->minFields);
   ReturnExpression(theEnv,constraints->minFields);
   constraints->minFields = tempExpr;

   tempExpr = AddHashedExpression(theEnv,constraints->maxFields);
   ReturnExpression(theEnv,constraints->maxFields);
   constraints->maxFields = tempExpr;

   if (constraints->multifield != NULL)
     { InstallConstraintRecord(theEnv,constraints->multifield); }
  }

#endif /* (! RUN_TIME) && (! BLOAD_ONLY) */

/**********************************************/
/* SDCCommand: H/L access routine for the     */
/*   set-dynamic-constraint-checking command. */
/**********************************************/
globle int SDCCommand(
  void *theEnv)
  {
   int oldValue;
   DATA_OBJECT arg_ptr;

   oldValue = EnvGetDynamicConstraintChecking(theEnv);

   if (EnvArgCountCheck(theEnv,"set-dynamic-constraint-checking",EXACTLY,1) == -1)
     { return(oldValue); }

   EnvRtnUnknown(theEnv,1,&arg_ptr);

   if ((arg_ptr.value == EnvFalseSymbol(theEnv)) && (arg_ptr.type == SYMBOL))
     { EnvSetDynamicConstraintChecking(theEnv,FALSE); }
   else
     { EnvSetDynamicConstraintChecking(theEnv,TRUE); }

   return(oldValue);
  }

/**********************************************/
/* GDCCommand: H/L access routine for the     */
/*   get-dynamic-constraint-checking command. */
/**********************************************/
globle int GDCCommand(
  void *theEnv)
  {
   int oldValue;

   oldValue = EnvGetDynamicConstraintChecking(theEnv);

   if (EnvArgCountCheck(theEnv,"get-dynamic-constraint-checking",EXACTLY,0) == -1)
     { return(oldValue); }

   return(oldValue);
  }

/*********************************************/
/* SSCCommand: H/L access routine for the    */
/*   set-static-constraint-checking command. */
/*********************************************/
globle int SSCCommand(
  void *theEnv)
  {
   int oldValue;
   DATA_OBJECT arg_ptr;

   oldValue = EnvGetStaticConstraintChecking(theEnv);

   if (EnvArgCountCheck(theEnv,"set-static-constraint-checking",EXACTLY,1) == -1)
     { return(oldValue); }

   EnvRtnUnknown(theEnv,1,&arg_ptr);

   if ((arg_ptr.value == EnvFalseSymbol(theEnv)) && (arg_ptr.type == SYMBOL))
     { EnvSetStaticConstraintChecking(theEnv,FALSE); }
   else
     { EnvSetStaticConstraintChecking(theEnv,TRUE); }

   return(oldValue);
  }

/*********************************************/
/* GSCCommand: H/L access routine for the    */
/*   get-static-constraint-checking command. */
/*********************************************/
globle int GSCCommand(
  void *theEnv)
  {
   int oldValue;

   oldValue = EnvGetStaticConstraintChecking(theEnv);

   if (EnvArgCountCheck(theEnv,"get-static-constraint-checking",EXACTLY,0) == -1)
     { return(oldValue); }

   return(oldValue);
  }

/******************************************************/
/* EnvSetDynamicConstraintChecking: C access routine  */
/*   for the set-dynamic-constraint-checking command. */
/******************************************************/
globle intBool EnvSetDynamicConstraintChecking(
  void *theEnv,
  int value)
  {
   int ov;
   ov = ConstraintData(theEnv)->DynamicConstraintChecking;
   ConstraintData(theEnv)->DynamicConstraintChecking = value;
   return(ov);
  }

/******************************************************/
/* EnvGetDynamicConstraintChecking: C access routine  */
/*   for the get-dynamic-constraint-checking command. */
/******************************************************/
globle intBool EnvGetDynamicConstraintChecking(
  void *theEnv)
  {
   return(ConstraintData(theEnv)->DynamicConstraintChecking);
  }

/*****************************************************/
/* EnvSetStaticConstraintChecking: C access routine  */
/*   for the set-static-constraint-checking command. */
/*****************************************************/
globle intBool EnvSetStaticConstraintChecking(
  void *theEnv,
  int value)
  {
   int ov;

   ov = ConstraintData(theEnv)->StaticConstraintChecking;
   ConstraintData(theEnv)->StaticConstraintChecking = value;
   return(ov);
  }

/*****************************************************/
/* EnvGetStaticConstraintChecking: C access routine  */
/*   for the get-static-constraint-checking command. */
/*****************************************************/
globle intBool EnvGetStaticConstraintChecking(
  void *theEnv)
  {
   return(ConstraintData(theEnv)->StaticConstraintChecking);
  }


text:
NLog.Extensions
===============

Extends ExceptionLayoutRenderer, EventPropertyLayoutRenderer, AsyncTargetWrapper and provides ExceptionUnwrapper

#### Extends ExceptionLayoutRenderer
Normally when `ExceptionLayoutRenderer` renders `Method`, we will get method from top of stack. This extension will search for application method and line number. It will give you better idea where to fix the problem, no need to look into stack trace.

##### usage
All implementations are exactly the same as normal `ExceptionLayoutRenderer`, but `Method` format will search for application method.
```
${exception:format=Method}
```
##### example
This expression will always generate ArgumentNullException if args is null.
```
string.Join(",", args);
```
Normal `ExceptionLayoutRenderer` will return `System.String Join(System.String, System.String[])`, and then you need to look into stack trace to identify the problem. But with extended `ExceptionLayoutRenderer` will return `Program.TestMethod-line27`. So it gives you better idea where to fix the problem.

#### Extends EventPropertyLayoutRenderer
Normal `EventPropertyLayoutRenderer` will only convert property to string, but this one will allow writing path to access member inside that property.

##### usage
All implementations are exactly the same as normal `EventPropertyLayoutRenderer`, but you can write path to access member.
```
${event-properties:Item=key.Prop1.Prop2['test'][0]}
```
- **property access**: for property access just write `.` (dot) follow by property name.
- **indexer access**: for indexer access just write `[` parameter and close by `]`. Currently only single string and integer are allowed as parameter. String identify by `'` (single quote).

You can chain property access and indexer access as long as you want. If one of properties is null, this will return null without create exception.

#### Extends AsyncTargetWrapper
Current `AsyncTargetWrapper` is using normal queue, and handling concurrency by locking. This extension change to ConcurrentQueue to make it non-blocking.

##### usage
All implementation is the same as normal `AsyncTargetWrapper`, but internal queue will use ConcurrentQueue instead of normal queue. And you can add `parallelWrite="true"` in case log target support concurrent write (such as log to html).
```
<target name="test" xsi:type="AsyncWrapper">
    <target xsi:type="Console" layout="${Message}" />
</target>
```
#### ExceptionUnwrapper
This is to unwrap certain kinds of exceptions such as `AggregateException` or your custom exceptions. It is useful if you would like to see real exception type.
##### usage
By default, this will always unwrap `AggregateException` and you can specify your own exceptions to unwrap by `unwrapExceptions="..."`. Value is comma separated.
```
<target name="test" xsi:type="ExceptionUnwrapper" unwrapExceptions="UnhandledException,HttpUnhandleException">
    <target xsi:type="Console" layout="${exception:format=ShortType}" />
</target>

```

redpajama_set_name: RedPajamaGithub


text:
@implementation ZCDuangLabel

- (instancetype) initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.onlyDrawDirtyArea = YES;
    }
    return self;
}

- (void) appearStateDrawingForRect: (CGRect) rect textBlock: (ZCTextBlock *) textBlock
{
    if (textBlock.progress <= 0) {
        return;
    }
    CGFloat realProgress = [ZCEasingUtil bounceWithStiffness:kZCAnimatedLabelStiffnessMedium numberOfBounces:3 time:textBlock.progress shake:YES shouldOvershoot:YES];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, CGRectGetMidX(textBlock.charRect), CGRectGetMaxY(textBlock.charRect));
    CGContextScaleCTM(context, 1, realProgress);
    CGRect newRect = CGRectMake(-textBlock.charRect.size.width / 2, -textBlock.charRect.size.height, textBlock.charRect.size.width, textBlock.charRect.size.height);
    [textBlock.derivedAttributedString drawInRect:newRect];
    CGContextRestoreGState(context);
}

@end


text:
package org.apache.activemq.artemis.jms.tests;

import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport;
import org.junit.Test;

public class QueueReceiverTest extends JMSTestCase
{
   /**
    * com.sun.ts.tests.jms.ee.all.queueconn.QueueConnTest line 171
    */
   @Test
   public void testCreateReceiverWithMessageSelector() throws Exception
   {
      QueueConnection qc = null;

      try
      {
         qc = createQueueConnection();
         QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

         QueueReceiver qreceiver = qs.createReceiver(queue1, "targetMessage = TRUE");

         qc.start();

         TextMessage m = qs.createTextMessage();
         m.setText("one");
         m.setBooleanProperty("targetMessage", false);

         QueueSender qsender = qs.createSender(queue1);

         qsender.send(m);

         m.setText("two");
         m.setBooleanProperty("targetMessage", true);

         qsender.send(m);

         TextMessage rm = (TextMessage)qreceiver.receive(1000);

         ProxyAssertSupport.assertEquals("two", rm.getText());
      }
      finally
      {
         if (qc != null)
         {
            qc.close();
         }
         Thread.sleep(2000);
         removeAllMessages(queue1.getQueueName(), true);
         checkEmpty(queue1);
      }
   }
}


text:
module Abalone {
export module Engine {
	export enum Player {White, Black}
	export function next(p: Player) {
		return (p === Player.White) ? Player.Black : Player.White;
	}

	export function player2str(p: Player): string {
		return p === Player.White ? "white" : "black"
	}
	export function str2player(s: String): Player {
		switch (s) {
			case "white":
			return Player.White;
			case "black":
			return Player.Black;
			default:
			return null;
		}
	}
}
}


text:
      <menu-button></menu-button>

            {{ $ctrl.user.name.first }} {{ $ctrl.user.name.last }}
            {{ $ctrl.user.login.username }}

            Email
            {{ $ctrl.user.email }}

            Phone
            {{ $ctrl.user.cell }}

        <md-progress-circular class="md-primary md-hue-1"></md-progress-circular>


text:
package io.crate.replication.logical.action;

import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.Level;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.test.MockLogAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import io.crate.metadata.RelationName;
import io.crate.metadata.Schemas;
import io.crate.replication.logical.metadata.Publication;
import io.crate.replication.logical.metadata.RelationMetadata;
import io.crate.sql.tree.QualifiedName;
import io.crate.test.integration.CrateDummyClusterServiceUnitTest;
import io.crate.testing.SQLExecutor;
import io.crate.user.Privilege;
import io.crate.user.User;
import io.crate.user.UserLookup;

public class PublicationsStateActionTest extends CrateDummyClusterServiceUnitTest {

    private MockLogAppender appender;

    @Before
    public void appendLogger() throws Exception {
        appender = new MockLogAppender();
        appender.start();
        Loggers.addAppender(Loggers.getLogger(Publication.class), appender);

    }

    @After
    public void removeLogger() {
        Loggers.removeAppender(Loggers.getLogger(Publication.class), appender);
        appender.stop();
    }

    @Test
    public void test_resolve_relation_names_for_all_tables_ignores_table_with_soft_delete_disabled() throws Exception {
        var user = new User("dummy", Set.of(), Set.of(), null) {
            @Override
            public boolean hasPrivilege(Privilege.Type type, Privilege.Clazz clazz, String ident, String defaultSchema) {
                return true; // This test case doesn't check privileges.
            }
        };
        // Soft-deletes are mandatory from 5.0, so let's use 4.8 to create a table with soft-deletes disabled
        clusterService = createClusterService(additionalClusterSettings().stream().filter(Setting::hasNodeScope).toList(),
                                                  Metadata.EMPTY_METADATA,
                                                  Version.V_4_8_0);
        SQLExecutor.builder(clusterService)
            .addTable("CREATE TABLE doc.t1 (id int)")
            .addTable("CREATE TABLE doc.t2 (id int) with (\"soft_deletes.enabled\" = false)")
            .build();
        var publication = new Publication("some_user", true, List.of());

        var expectedLogMessage = "Table 'doc.t2' won't be replicated as the required table setting " +
                                 "'soft_deletes.enabled' is set to: false";
        appender.addExpectation(new MockLogAppender.SeenEventExpectation(
            expectedLogMessage,
            Loggers.getLogger(Publication.class).getName(),
            Level.WARN,
            expectedLogMessage
        ));

        Map<RelationName, RelationMetadata> resolvedRelations = publication.resolveCurrentRelations(clusterService.state(), user, user, "dummy");
        assertThat(resolvedRelations.keySet(), contains(new RelationName("doc", "t1")));
        appender.assertAllExpectationsMatched();
    }

    @Test
    public void test_resolve_relation_names_for_all_tables_ignores_table_when_pub_owner_doesnt_have_read_write_define_permissions() throws Exception {
        var publicationOwner = new User("publisher", Set.of(), Set.of(), null) {
            @Override
            public boolean hasPrivilege(Privilege.Type type, Privilege.Clazz clazz, String ident, String defaultSchema) {
                return ident.equals("doc.t1");
            }
        };
        var subscriber = new User("subscriber", Set.of(), Set.of(), null) {
            @Override
            public boolean hasPrivilege(Privilege.Type type, Privilege.Clazz clazz, String ident, String defaultSchema) {
                return true;
            }
        };

        UserLookup userLookup = mock(UserLookup.class);
        when(userLookup.findUser("publisher")).thenReturn(publicationOwner);
        when(userLookup.findUser("subscriber")).thenReturn(subscriber);

        SQLExecutor.builder(clusterService)
            .addTable("CREATE TABLE doc.t1 (id int)")
            .addTable("CREATE TABLE doc.t3 (id int)")
            .build();
        var publication = new Publication("publisher", true, List.of());

        var resolvedRelations = publication.resolveCurrentRelations(
            clusterService.state(),
            publicationOwner,
            subscriber,
            "dummy"
        );

        assertThat(resolvedRelations.keySet(), contains(new RelationName("doc", "t1")));
    }

    @Test
    public void test_resolve_relation_names_for_all_tables_ignores_table_when_subscriber_doesnt_have_read_permissions() throws Exception {
        var publicationOwner = new User("publisher", Set.of(), Set.of(), null) {
            @Override
            public boolean hasPrivilege(Privilege.Type type, Privilege.Clazz clazz, String ident, String defaultSchema) {
                return true;
            }
        };

        var subscriber = new User("subscriber", Set.of(), Set.of(), null) {
            @Override
            public boolean hasPrivilege(Privilege.Type type, Privilege.Clazz clazz, String ident, String defaultSchema) {
                return ident.equals("doc.t1");
            }
        };

        UserLookup userLookup = mock(UserLookup.class);
        when(userLookup.findUser("publisher")).thenReturn(publicationOwner);
        when(userLookup.findUser("subscriber")).thenReturn(subscriber);

        SQLExecutor.builder(clusterService)
            .addTable("CREATE TABLE doc.t1 (id int)")
            .addTable("CREATE TABLE doc.t3 (id int)")
            .build();
        var publication = new Publication("publisher", true, List.of());

        var resolvedRelations = publication.resolveCurrentRelations(clusterService.state(), publicationOwner, subscriber, "dummy");
        assertThat(resolvedRelations.keySet(), contains(new RelationName("doc", "t1")));
    }

    @Test
    public void test_resolve_relation_names_for_fixed_tables_ignores_table_when_subscriber_doesnt_have_read_permissions() throws Exception {
        var publicationOwner = new User("publisher", Set.of(), Set.of(), null) {
            @Override
            public boolean hasPrivilege(Privilege.Type type, Privilege.Clazz clazz, String ident, String defaultSchema) {
                return true;
            }
        };

        var subscriber = new User("subscriber", Set.of(), Set.of(), null) {
            @Override
            public boolean hasPrivilege(Privilege.Type type, Privilege.Clazz clazz, String ident, String defaultSchema) {
                return ident.equals("doc.t1");
            }
        };

        UserLookup userLookup = mock(UserLookup.class);
        when(userLookup.findUser("publisher")).thenReturn(publicationOwner);
        when(userLookup.findUser("subscriber")).thenReturn(subscriber);

        SQLExecutor.builder(clusterService)
            .addTable("CREATE TABLE doc.t1 (id int)")
            .addTable("CREATE TABLE doc.t2 (id int)")
            .build();
        var publication = new Publication("publisher", false,
            List.of(
                RelationName.of(QualifiedName.of("t1"), Schemas.DOC_SCHEMA_NAME),
                RelationName.of(QualifiedName.of("t2"), Schemas.DOC_SCHEMA_NAME)
            )
        );

        var resolvedRelations = publication.resolveCurrentRelations(
            clusterService.state(),
            publicationOwner,
            subscriber,
            "dummy"
        );
        assertThat(resolvedRelations.keySet(), contains(new RelationName("doc", "t1")));
    }
}


text:
Debug:

                            {{bean|json}}

                        <form name="outerForm" class="form-horizontal text-left"  ng-show="!status">

                                    <clabel wide="2" name="f.name" longname="f.longname" required="f.required"></clabel>
                                    <key class="col-md-3" ide="bean[f.name]" name="f.name" disable="false"></key>

                                        *
                                        {{f.longname}}:

                                        <input ng-model="bean[f.name]"
                                               type="text"
                                               class="form-control"
                                               id="{{f.name}}"
                                               name="{{f.name}}"
                                               ng-pattern="f.pattern"
                                               placeholder="{{f.name}}"
                                               maxlength="{{f.maxlength}}"
                                               ng-required="{{f.required}}"
                                               />
                                        El campo es obligatorio
                                        El campo no tiene formato adecuado: {{f.help}}

                                    <clabel wide="2" name="f.name" longname="f.longname" required="f.required" />

                                        <date-picker ng-show="f.type == 'date'"
                                                     name="f.name"
                                                     required="f.required"
                                                     fecha="bean.fecha"
                                                     form="outerForm" />
                                        El campo es obligatorio

                                <div class="form-group"
                                     ng-show="show_obj_tipodiagnostico && (f.name == 'obj_tipodiagnostico')"
                                     ng-class="{'has-error': (outerForm.obj_tipodiagnostico.$error.required ||
                                                             outerForm.obj_tipodiagnostico.$error.exists ||
                                                             outerForm.obj_tipodiagnostico.$error.validatemin)
                                                             && !outerForm.obj_tipodiagnostico.$pristine}"
                                     ng-show="show_obj_tipodiagnostico">
                                    Tipo de Diagnostico:

                                            <input type="text"
                                                   ng-model-options="{debounce: 1000}"
                                                   ng-change="obj_tipodiagnostico_change"
                                                   ng-model="bean.obj_tipodiagnostico.id"
                                                   validatemin="1"
                                                   ng-required="true"
                                                   aria-describedby="basic-addon2"
                                                   class="form-control"
                                                   id="obj_diagnostico"
                                                   name="obj_tipodiagnostico"
                                                   size="5"
                                                   maxlength="5">

                                                {{bean.obj_tipodiagnostico.descripcion}}

                                        El tipo de diagnostico es obligatorio
                                        Debes elegir un tipo de diagnostico
                                        El tipo de diagnostico no existe

                                <div class="form-group"
                                     ng-show="show_obj_episodio && (f.name == 'obj_episodio')"
                                     ng-class="{'has-error': (outerForm.obj_episodio.$error.required ||
                                                             outerForm.obj_episodio.$error.exists ||
                                                             outerForm.obj_episodio.$error.validatemin)
                                                             && !outerForm.obj_episodio.$pristine}"
                                     ng-show="show_obj_episodio">
                                    Episodio:

                                            <input type="text"
                                                   ng-model-options="{debounce: 1000}"
                                                   ng-change="obj_episodio_change"
                                                   ng-model="bean.obj_episodio.id"
                                                   validatemin="1"
                                                   ng-required="true"
                                                   aria-describedby="basic-addon2"
                                                   class="form-control"
                                                   id="obj_episodio"
                                                   name="obj_episodio"
                                                   size="5"
                                                   maxlength="5">

                                                {{bean.obj_episodio.informe|clipString2}}

                                        El episodio es obligatorio
                                        Debes elegir un episodio
                                        El episodio no existe

                                    Guardar
                                    Ir al listado de diagnosticos
                                    Cerrar

                        </form>

{{status}}

                                Ver {{obtitle}}

{{status}}


text:
require './lib/dsl/style_dsl'

class StyleList

  def initialize(tags, element_name='span')
    @element_name = element_name
    @list = []
    @tags = tags || []
  end

  def add(klass_name, prop_name, value)
    selector = "#{@element_name}.#{klass_name}"
    @list << select(selector, prop_name, value) if @tags.include? klass_name
  end

  def each
    @list.each { |item| yield item }
  end

end


text:
from __future__ import print_function, division

from .matexpr import MatrixExpr
from sympy.core.function import FunctionClass, Lambda
from sympy.core.sympify import _sympify, sympify
from sympy.matrices import Matrix
from sympy.functions.elementary.complexes import re, im

class FunctionMatrix(MatrixExpr):
    """Represents a matrix using a function (``Lambda``) which gives
    outputs according to the coordinates of each matrix entries.

    Parameters
    ==========

    rows : nonnegative integer. Can be symbolic.

    cols : nonnegative integer. Can be symbolic.

    lamda : Function, Lambda or str
        If it is a SymPy ``Function`` or ``Lambda`` instance,
        it should be able to accept two arguments which represents the
        matrix coordinates.

        If it is a pure string containing python ``lambda`` semantics,
        it is interpreted by the SymPy parser and casted into a SymPy
        ``Lambda`` instance.

    Examples
    ========

    Creating a ``FunctionMatrix`` from ``Lambda``:

    >>> from sympy import FunctionMatrix, symbols, Lambda, MatPow, Matrix
    >>> i, j, n, m = symbols('i,j,n,m')
    >>> FunctionMatrix(n, m, Lambda((i, j), i + j))
    FunctionMatrix(n, m, Lambda((i, j), i + j))

    Creating a ``FunctionMatrix`` from a sympy function:

    >>> from sympy.functions import KroneckerDelta
    >>> X = FunctionMatrix(3, 3, KroneckerDelta)
    >>> X.as_explicit()
    Matrix([
    [1, 0, 0],
    [0, 1, 0],
    [0, 0, 1]])

    Creating a ``FunctionMatrix`` from a sympy undefined function:

    >>> from sympy.core.function import Function
    >>> f = Function('f')
    >>> X = FunctionMatrix(3, 3, f)
    >>> X.as_explicit()
    Matrix([
    [f(0, 0), f(0, 1), f(0, 2)],
    [f(1, 0), f(1, 1), f(1, 2)],
    [f(2, 0), f(2, 1), f(2, 2)]])

    Creating a ``FunctionMatrix`` from python ``lambda``:

    >>> FunctionMatrix(n, m, 'lambda i, j: i + j')
    FunctionMatrix(n, m, Lambda((i, j), i + j))

    Example of lazy evaluation of matrix product:

    >>> Y = FunctionMatrix(1000, 1000, Lambda((i, j), i + j))
    >>> isinstance(Y*Y, MatPow) # this is an expression object
    True
    >>> (Y**2)[10,10] # So this is evaluated lazily
    342923500

    Notes
    =====

    This class provides an alternative way to represent an extremely
    dense matrix with entries in some form of a sequence, in a most
    sparse way.
    """
    def __new__(cls, rows, cols, lamda):
        rows, cols = _sympify(rows), _sympify(cols)
        cls._check_dim(rows)
        cls._check_dim(cols)

        lamda = sympify(lamda)
        if not isinstance(lamda, (FunctionClass, Lambda)):
            raise ValueError(
                "{} should be compatible with SymPy function classes."
                .format(lamda))

        if 2 not in lamda.nargs:
            raise ValueError(
                '{} should be able to accept 2 arguments.'.format(lamda))

        return super(FunctionMatrix, cls).__new__(cls, rows, cols, lamda)

    @property
    def shape(self):
        return self.args[0:2]

    @property
    def lamda(self):
        return self.args[2]

    def _entry(self, i, j, **kwargs):
        return self.lamda(i, j)

    def _eval_trace(self):
        from sympy.matrices.expressions.trace import Trace
        from sympy import Sum
        return Trace(self).rewrite(Sum).doit()

    def as_real_imag(self):
        return (re(Matrix(self)), im(Matrix(self)))


text:
#import <Foundation/NSOutputStream.h>

@interface NSOutputStream_buffer : NSOutputStream {
    id _delegate;
    NSError *_error;
    NSStreamStatus _status;
    uint8_t *_buffer;
    NSUInteger _capacity;
    NSUInteger _position;
}

@end


text:
var React = require("react");
var MessageForm = require("./MessageForm");
var MessagesList = require("./MessagesList");

var MessageActions = require("./Actions/MessageActions");
var Emitter = require("./Emitter");

var MessagesStore = require("./Stores/MessagesStore");

var Chat = React.createClass({displayName: "Chat",
	getInitialState: function() {
		Emitter.on("MESSAGES_RECEIVED", this.showMessages);
		MessageActions.get();
		return { messages: [] };
	},
	showMessages: function() {
		console.log("messages received")
		var messages =  MessagesStore.get();
		this.setState({ messages: messages });
		MessageActions.get();
	},
	render: function() {
		return React.createElement("div", null,
					React.createElement(MessagesList, {messages: this.state.messages}),

					React.createElement(MessageForm, null)
				)
	}
});

module.exports = Chat;


text:
package opts

import (
	"os"
)

// ParseEnvFile reads a file with environment variables enumerated by lines
//
// ``Environment variable names used by the utilities in the Shell and
// Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase
// letters, digits, and the '_' (underscore) from the characters defined in
// Portable Character Set and do not begin with a digit. *But*, other
// characters may be permitted by an implementation; applications shall
// tolerate the presence of such names.''
// -- http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html
//
// As of #16585, it's up to application inside docker to validate or not
// environment variables, that's why we just strip leading whitespace and
// nothing more.
func ParseEnvFile(filename string) ([]string, error) {
	return parseKeyValueFile(filename, os.Getenv)
}


text:
layout: post
title: "Advancing: Secrets and Mailer Configs (Part 18)"
cover-title:
cover-title-color: white
cover: /public/assets/secrets.jpg
cover-position: 50% 50%
---

Configuring any type of external service likely requires a username and password.
We want to avoid storing sensitive information in the source code, as the repository may be public or accessef by a group of people.

We'll use the Figaro gem to secure our secrets, and then use it to config ActionMailer.

###Figaro

####1. Install Figaro Gem
[Figaro](https://github.com/laserlemon/figaro) is a easy gem that stores secrets in a central file `application.yml`, takes care of repository commits, and also manages heroku production secrets.

gemfile
{% highlight ruby %}
...
gem 'figaro'
...
{% endhighlight %}

`bundle install`

####2. Install Figaro Instance

`$figaro install`

This command creates `config/application.yml`, and this file will be the central location for secret environment variables.
It will also add this file to `.gitignore`, preventing secrets from being committed into source.

####3. Set Secret Variables
config/application.yml
{% highlight ruby %}
GMAIL_USERNAME: "user@gmail.com"
GMAIL_PASSWORD: "password"

#You can split the same environment variables into development and production with the following groups:
development:
  GMAIL_USERNAME: "dev_user@gmail.com"
  GMAIL_PASSWORD: "dev_password"
  #ENV variable in development
production:
  GMAIL_USERNAME: "production_user@gmail.com"
  GMAIL_PASSWORD: "production_password"
  #ENV variable in production
{% endhighlight %}

####4. Accessing Secrets
That's it! You may now access these variables in the following ways:

Application-wide accesss:

`ENV["GMAIL_USERNAME"]`

Test-environment access:

`Figaro.env.gmail_username`

Heroku-production access:

`$figaro heroku:set -e production`

This command will set Heroku's config to include the environment variables figaro has set on your local `application.yml`

###Mailer Config

####1. Install Letter Opener
Email isn't a web page that is served by Rails. Letter Opener is a gem that stores emails in a tmp folder, and opens it in the browser during development.

gemfile
{% highlight ruby %}
...
gem 'letter_opener'
...
{% endhighlight %}

`$bundle install`

####2. Configurate ActionMailer

config/environments/development.rb
{% highlight ruby %}
config.action_mailer.delivery_method = :letter_opener
#opens letter in browser for development
config.action_mailer.default_url_options = { host: '127.0.0.1:3000' }
#if dynamic urls need to be generated in your emails, this points them to the right address
{% endhighlight %}

config/environments/production.rb
{% highlight ruby %}
config.action_mailer.delivery_method = :smtp
#delivers mail instead of dumping in server log
config.action_mailer.smtp_settings = {
  address:              'smtp.gmail.com',
  port:                 587,
  domain:               'example.com',
  #Domain field can be left out if not using a custom GApp domain
  user_name:            ENV["GMAIL_USERNAME"],
  password:             ENV["GMAIL_PASSWORD"],
  #Accesses Figaro's set secret
  authentication:       'plain',
  enable_starttls_auto: true  }
config.action_mailer.default_url_options = { host: 'your_app_domain.com' }
{% endhighlight %}

config/environments/test.rb
{% highlight ruby %}
config.action_mailer.default_url_options = { host: '127.0.0.1:3000' }
#urls from generated test emails need a host
{% endhighlight %}


text:
![](http://auth0.github.io/auth0-extension-boilerplate-with-react/assets/boilerplate.png)

# Usage

1. Install project dependencies `npm install`
2. Install [Webpack](https://github.com/webpack/webpack) - `npm install webpack -g`
3. Then run `npm start` and navigate to [http://localhost:3000](http://localhost:3000)

## Client Side

By default there are two templates `layout.jade` and `index.jade` which will help you to start working with an extension.

#### layout.jade

The file contains the styles of an [Auth0](https://auth0.com/) extension and also you can add the link to the js/css libraries you want to use.

#### index.jade

This is the file which contains your code.

### Supporting sections

To support sections you have to address the following steps:

1. Add the following lines to `layout.jade`
```jade
script(type='text/javascript', src='https://npmcdn.com/react-router/umd/ReactRouter.min.js')
script(type='text/javascript', src='https://npmcdn.com/history/umd/History.min.js')
```
2. Replace `section.content-page.current` on `./templates/layout.jade` with the following code:
```jade
section.content-page.current
  .col-xs-12
    .row
      .col-xs-12.content-header
        ol.breadcrumb
          li
            a(href='http://manage.auth0.com/') Auth0 Dashboard
          li
            a(href='#') Extensions

    #sidebar.col-xs-2
      .sidebar-fixed
        ul
          li.active
            a(href='/#/section-1')
              i.icon.icon-budicon-519
              span Section 1

    #extension
      block content
```
3. Replace the `Extension` component by `Section1` component on `./templates/index.jade`
```js
var Section1 = React.createClass({
  render: function() {
    return (
      <div className="content-wrapper">
        <div className="content-header">
          <h1>My Extension - Section 1</h1>
        </div>
      </div>
    );
  }
});
```
4. Remove the following lines from `./templates/index.jade`

```js
ReactDOM.render(
  <Extension />,
  document.getElementById('extension')
);
```

5. Add router configuration on `./templates/index.jade`

```js
var Router  = ReactRouter.Router;
var Route   = ReactRouter.Route;
var history = History.createHashHistory({queryKey: false});

ReactDOM.render((
  <Router history={history}>
    <Route path="/section-1" component={Section1}></Route>
    <Route path="*" component={Section1}/>
  </Router>
), document.getElementById('extension'));
```

5 Enjoy!

![](http://auth0.github.io/auth0-extension-boilerplate-with-react/assets/new-section.png)

## Running locally

To run the sample extension locally:

```bash
$ npm install
$ npm start
```

## Deploying as Auth0 Custom Extension

1. Go to [Auth0 Extensions](https://manage.auth0.com/#/extensions)
2. Click on `+ Create Extension`
3. Fill in the textbox with `https://github.com/auth0/auth0-extension-boilerplate`
4. Click on `continue`
5. Finally, click on `install`

## Author

[Auth0](auth0.com)

## What is Auth0?

Auth0 helps you to:

* Add authentication with [multiple authentication sources](https://docs.auth0.com/identityproviders), either social like **Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others**, or enterprise identity systems like **Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider**.
* Add authentication through more traditional **[username/password databases](https://docs.auth0.com/mysql-connection-tutorial)**.
* Add support for **[linking different user accounts](https://docs.auth0.com/link-accounts)** with the same user.
* Support for generating signed [Json Web Tokens](https://docs.auth0.com/jwt) to call your APIs and **flow the user identity** securely.
* Analytics of how, when and where users are logging in.
* Pull data from other sources and add it to the user profile, through [JavaScript rules](https://docs.auth0.com/rules).

## Create a free Auth0 Account

1. Go to [Auth0](https://auth0.com/signup) and click Sign Up.
2. Use Google, GitHub or Microsoft Account to login.

## Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.

## License

This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.


text:
import ImportStatement from '../ImportStatement';

describe('ImportStatement', () => {
  describe('.hasNamedImports()', () => {
    it('is false without a default import or named imports', () => {
      const statement = new ImportStatement();
      expect(statement.hasNamedImports()).toBe(false);
    });

    it('is false with a default import', () => {
      const statement = new ImportStatement({ defaultImport: 'foo' });
      expect(statement.hasNamedImports()).toBe(false);
    });

    it('is false when a default import is removed', () => {
      const statement = new ImportStatement({ defaultImport: 'foo' });
      statement.deleteVariable('foo');
      expect(statement.hasNamedImports()).toBe(false);
    });

    it('is true with named imports', () => {
      const statement = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      expect(statement.hasNamedImports()).toBe(true);
    });

    it('is false when named imports are all removed', () => {
      const statement = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      statement.deleteVariable('foo');
      expect(statement.hasNamedImports()).toBe(false);
    });
  });

  describe('.isParsedAndUntouched()', () => {
    it('is true initially', () => {
      const statement = new ImportStatement({
        declarationKeyword: 'import',
        defaultImport: 'foo',
        hasSideEffects: false,
        originalImportString: "import foo, { bar, type baz } from './lib/foo';",
        namedImports: [{ localName: 'bar' }, { localName: 'bar', isType: true }],
        path: './lib/foo',
      });
      expect(statement.isParsedAndUntouched()).toBe(true);
    });

    it(
      'is false when a default import is deleted from a parsed statement',
      () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          hasSideEffects: false,
          originalImportString: "import foo, { bar, type baz } from './lib/foo';",
          namedImports: [{ localName: 'bar' }, { localName: 'bar', isType: true }],
          path: './lib/foo',
        });
        statement.deleteVariable('foo');
        expect(statement.isParsedAndUntouched()).toBe(false);
      },
    );

    it(
      'is false when a named import is deleted from a parsed statement',
      () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          hasSideEffects: false,
          originalImportString: "import foo, { bar, type baz } from './lib/foo';",
          namedImports: [{ localName: 'bar' }, { localName: 'bar', isType: true }],
          path: './lib/foo',
        });
        statement.deleteVariable('bar');
        expect(statement.isParsedAndUntouched()).toBe(false);
      },
    );

    it('is true when nothing is deleted from a parsed statement', () => {
      const statement = new ImportStatement({
        declarationKeyword: 'import',
        defaultImport: 'foo',
        hasSideEffects: false,
        originalImportString: "import foo, { bar, type baz } from './lib/foo';",
        namedImports: [{ localName: 'bar' }, { localName: 'bar', isType: true }],
        path: './lib/foo',
      });
      statement.deleteVariable('somethingElse');
      expect(statement.isParsedAndUntouched()).toBe(true);
    });
  });

  describe('.isEmpty()', () => {
    it('is true without a default import or named imports', () => {
      const statement = new ImportStatement();
      expect(statement.isEmpty()).toBe(true);
    });

    it('is false with a default import', () => {
      const statement = new ImportStatement({ defaultImport: 'foo' });
      expect(statement.isEmpty()).toBe(false);
    });

    it('is true when default import is removed', () => {
      const statement = new ImportStatement({ defaultImport: 'foo' });
      statement.deleteVariable('foo');
      expect(statement.isEmpty()).toBe(true);
    });

    it('is false with named imports', () => {
      const statement = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      expect(statement.isEmpty()).toBe(false);
    });

    it('is true when all named imports are removed', () => {
      const statement = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      statement.deleteVariable('foo');
      expect(statement.isEmpty()).toBe(true);
    });

    it('is true with an empty array of named imports', () => {
      const statement = new ImportStatement({ namedImports: [] });
      expect(statement.isEmpty()).toBe(true);
    });
  });

  describe('.variables()', () => {
    it('is an empty array without a default or named imports', () => {
      const statement = new ImportStatement();
      expect(statement.variables()).toEqual([]);
    });

    it('has the default import', () => {
      const statement = new ImportStatement({ defaultImport: 'foo' });
      expect(statement.variables()).toEqual(['foo']);
    });

    it('has named imports', () => {
      const statement = new ImportStatement({
        namedImports: [
          { localName: 'foo' },
          { localName: 'bar' },
          { localName: 'baz', isType: true },
        ],
      });

      expect(statement.variables()).toEqual(['foo', 'bar', 'baz']);
    });

    it('has default and named imports', () => {
      const statement = new ImportStatement({
        defaultImport: 'foo',
        namedImports: [
          { localName: 'bar' },
          { localName: 'baz', isType: true },
        ],
      });

      expect(statement.variables()).toEqual(['foo', 'bar', 'baz']);
    });
  });

  describe('.merge()', () => {
    it('uses the existing default import without a new default import', () => {
      const existing = new ImportStatement({ defaultImport: 'foo' });
      const newStatement = new ImportStatement();
      existing.merge(newStatement);
      expect(existing.defaultImport).toEqual('foo');
    });

    it('uses the new default import without an existing default import', () => {
      const existing = new ImportStatement();
      const newStatement = new ImportStatement({ defaultImport: 'foo' });
      existing.merge(newStatement);
      expect(existing.defaultImport).toEqual('foo');
    });

    it('uses the new default import when an existing and new one exist', () => {
      const existing = new ImportStatement({ defaultImport: 'foo' });
      const newStatement = new ImportStatement({ defaultImport: 'bar' });
      existing.merge(newStatement);
      expect(existing.defaultImport).toEqual('bar');
    });

    it('uses the existing named imports without a new named imports', () => {
      const existing = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      const newStatement = new ImportStatement();
      existing.merge(newStatement);
      expect(existing.namedImports).toEqual([{ localName: 'foo' }]);
    });

    it('uses the new named imports without existing named imports', () => {
      const existing = new ImportStatement();
      const newStatement = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      existing.merge(newStatement);
      expect(existing.namedImports).toEqual([{ localName: 'foo' }]);
    });

    it('merges the named imports when both existing and new ones exist', () => {
      const existing = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      const newStatement = new ImportStatement({ namedImports: [{ localName: 'bar', isType: true }] });
      existing.merge(newStatement);
      expect(existing.namedImports).toEqual([
        { localName: 'bar', isType: true },
        { localName: 'foo' },
      ]);
    });

    it('handles the inclusion of non-type named imports into type-only imports', () => {
      const existing = new ImportStatement({ namedImports: [{ localName: 'foo', isType: true }], areOnlyTypes: true });
      const newStatement = new ImportStatement({ namedImports: [{ localName: 'bar' }] });
      existing.merge(newStatement);
      expect(existing.areOnlyTypes).toBeFalsy();
      expect(existing.namedImports).toEqual([
        { localName: 'bar' },
        { localName: 'foo', isType: true },
      ]);
    });

    it('merges the named imports when both existing and new ones exist', () => {
      const existing = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      const newStatement = new ImportStatement({ namedImports: [{ localName: 'bar', isType: true }] });
      existing.merge(newStatement);
      expect(existing.namedImports).toEqual([
        { localName: 'bar', isType: true },
        { localName: 'foo' },
      ]);
    });

    it('does not duplicate named imports', () => {
      const existing = new ImportStatement({ namedImports: [{ localName: 'foo' }] });
      const newStatement = new ImportStatement({ namedImports: [{ localName: 'foo', isType: true }] });
      existing.merge(newStatement);
      expect(existing.namedImports).toEqual([{ localName: 'foo' }]);
    });
  });

  describe('.toImportStrings()', () => {
    describe('with the "import" declaration keyword', () => {
      it('is ok with a default import', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "import foo from './lib/foo';",
        ]);
      });

      it('is ok with a default import and an importFunction', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          path: './lib/foo',
          importFunction: 'myCustomRequire',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "import foo from './lib/foo';",
        ]);
      });

      it('is ok with a side-effect import', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          hasSideEffects: true,
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "import './lib/foo';",
        ]);
      });

      it('wraps long imports', () => {
        const defaultImport = 'ReallyReallyReallyReallyLong';
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport,
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `import ${defaultImport} from\n  '${path}';`,
        ]);
      });

      it('uses the provided tab when wrapping', () => {
        const defaultImport = 'ReallyReallyReallyReallyLong';
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport,
          path,
        });

        expect(statement.toImportStrings(50, '\t')).toEqual([
          `import ${defaultImport} from\n\t'${path}';`,
        ]);
      });

      it('is ok with named imports', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          namedImports: [{ localName: 'foo' }, { localName: 'bar', isType: true }, { localName: 'baz' }],
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "import { foo, type bar, baz } from './lib/foo';",
        ]);
      });

      it('wraps long imports with named imports', () => {
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          namedImports: [
            { localName: 'foo', isType: true },
            { localName: 'bar' },
            { localName: 'baz', isType: true },
            { localName: 'fizz' },
            { localName: 'buzz' },
          ],
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `import {\n  type foo,\n  bar,\n  type baz,\n  fizz,\n  buzz,\n} from '${path}';`,
        ]);
      });

      it('avoids dangling commas if explicitly told so', () => {
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          namedImports: [
            { localName: 'foo', isType: true },
            { localName: 'bar' },
            { localName: 'baz', isType: true },
            { localName: 'fizz' },
            { localName: 'buzz' },
          ],
          path,
          danglingCommas: false,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `import {\n  type foo,\n  bar,\n  type baz,\n  fizz,\n  buzz\n} from '${path}';`,
        ]);
      });

      it('is ok with default import and named imports', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          namedImports: [{ localName: 'bar' }, { localName: 'baz', isType: true }],
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "import foo, { bar, type baz } from './lib/foo';",
        ]);
      });

      it('wraps long imports with default and named imports', () => {
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          namedImports: [
            { localName: 'bar' },
            { localName: 'baz', isType: true },
            { localName: 'fizz' },
            { localName: 'buzz', isType: true },
          ],
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `import foo, {\n  bar,\n  type baz,\n  fizz,\n  type buzz,\n} from '${path}';`,
        ]);
      });

      it('is ok with only type named imports', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          namedImports: [{ localName: 'foo', isType: true }, { localName: 'bar', isType: true }],
          areOnlyTypes: true,
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "import type { foo, bar } from './lib/foo';",
        ]);
      });

      it('wraps long imports with only type named imports', () => {
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          namedImports: [
            { localName: 'foo', isType: true },
            { localName: 'bar', isType: true },
            { localName: 'baz', isType: true },
          ],
          areOnlyTypes: true,
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `import type {\n  foo,\n  bar,\n  baz,\n} from '${path}';`,
        ]);
      });

      it('is ok with default import and only type named imports', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          namedImports: [{ localName: 'bar', isType: true }, { localName: 'baz', isType: true }],
          areOnlyTypes: true,
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "import foo, { type bar, type baz } from './lib/foo';",
        ]);
      });

      it('wraps long imports with default and only type named imports', () => {
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'import',
          defaultImport: 'foo',
          namedImports: [
            { localName: 'bar', isType: true },
            { localName: 'baz', isType: true },
            { localName: 'fizz', isType: true },
            { localName: 'buzz', isType: true },
          ],
          areOnlyTypes: true,
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `import foo, {\n  type bar,\n  type baz,\n  type fizz,\n  type buzz,\n} from '${path}';`,
        ]);
      });
    });

    describe('with the "const" declaration keyword', () => {
      it('is ok with a default import', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          defaultImport: 'foo',
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "const foo = require('./lib/foo');",
        ]);
      });

      it('is ok with a default import and an importFunction', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          defaultImport: 'foo',
          path: './lib/foo',
          importFunction: 'myCustomRequire',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "const foo = myCustomRequire('./lib/foo');",
        ]);
      });

      it('is ok with a side-effect import', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          hasSideEffects: true,
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "require('./lib/foo');",
        ]);
      });

      it('wraps long imports', () => {
        const defaultImport = 'ReallyReallyReallyReallyLong';
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          defaultImport,
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `const ${defaultImport} =\n  require('${path}');`,
        ]);
      });

      it('uses the provided tab when wrapping', () => {
        const defaultImport = 'ReallyReallyReallyReallyLong';
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          defaultImport,
          path,
        });

        expect(statement.toImportStrings(50, '\t')).toEqual([
          `const ${defaultImport} =\n\trequire('${path}');`,
        ]);
      });

      it('is ok with named imports', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          namedImports: [{ localName: 'foo' }, { localName: 'bar' }],
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "const { foo, bar } = require('./lib/foo');",
        ]);
      });

      it('is ok with named imports and an importFunction', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          namedImports: [{ localName: 'foo' }, { localName: 'bar' }],
          path: './lib/foo',
          importFunction: 'myCustomRequire',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "const { foo, bar } = myCustomRequire('./lib/foo');",
        ]);
      });

      it('is ok with a side-effect import and an importFunction', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          hasSideEffects: true,
          importFunction: 'foo',
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "foo('./lib/foo');",
        ]);
      });

      it('wraps long imports with named imports', () => {
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          namedImports: [
            { localName: 'foo' },
            { localName: 'bar' },
            { localName: 'baz' },
            { localName: 'fizz' },
            { localName: 'buzz' },
          ],
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `const {\n  foo,\n  bar,\n  baz,\n  fizz,\n  buzz,\n} = require('${path}');`,
        ]);
      });

      it('is ok with default import and named imports', () => {
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          defaultImport: 'foo',
          namedImports: [{ localName: 'bar' }, { localName: 'baz' }],
          path: './lib/foo',
        });
        expect(statement.toImportStrings(80, '  ')).toEqual([
          "const foo = require('./lib/foo');",
          "const { bar, baz } = require('./lib/foo');",
        ]);
      });

      it(
        'is ok with default import, named imports, and an importFunction',
        () => {
          const statement = new ImportStatement({
            declarationKeyword: 'const',
            defaultImport: 'foo',
            namedImports: [{ localName: 'bar' }, { localName: 'baz' }],
            path: './lib/foo',
            importFunction: 'myCustomRequire',
          });
          expect(statement.toImportStrings(80, '  ')).toEqual([
            "const foo = myCustomRequire('./lib/foo');",
            "const { bar, baz } = myCustomRequire('./lib/foo');",
          ]);
        },
      );

      it('wraps long imports with default and named imports', () => {
        const path = 'also_very_long_for_some_reason';
        const statement = new ImportStatement({
          declarationKeyword: 'const',
          defaultImport: 'foo',
          namedImports: [
            { localName: 'bar' },
            { localName: 'baz' },
            { localName: 'fizz' },
            { localName: 'buzz' },
          ],
          path,
        });

        expect(statement.toImportStrings(50, '  ')).toEqual([
          `const foo =\n  require('${path}');`,
          `const {\n  bar,\n  baz,\n  fizz,\n  buzz,\n} = require('${path}');`,
        ]);
      });
    });
  });
});


text:
package org.elasticsearch.search.builder;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.io.stream.StreamInput;

import java.io.IOException;

public class SearchSourceBuilderException extends ElasticsearchException {

    public SearchSourceBuilderException(String msg) {
        super(msg);
    }

    public SearchSourceBuilderException(String msg, Throwable cause) {
        super(msg, cause);
    }

    public SearchSourceBuilderException(StreamInput in) throws IOException {
        super(in);
    }
}


text:
var Deferred = function( func ) {
	if (!(this instanceof Deferred)) return new Deferred();
	// arrays for `done` and `fail` callbacks
	this.doneFuncs = [];
	this.failFuncs = [];

	this.resultArgs = null;
	this.status = "";

	// check for option function: call it with this as context and as first
	// parameter, as specified in jQuery api
	func && func.call(this, this);
}

Deferred.when = function() {
	var args = h.map(arguments);
	if ( args.length < 2 ) {
		var obj = args[0];
		if ( obj && (h.isFn(obj.isResolved) && h.isFn(obj.isRejected)) ) {
			return obj;
		} else {
			return Deferred().resolve(obj);
		}
	} else {

		var df = Deferred(),
			done = 0,
			// resolve params: params of each resolve, we need to track down
			// them to be able to pass them in the correct order if the master
			// needs to be resolved
			rp = [];

		h.each(args, function( j, arg ) {
			arg.done(function() {
				rp[j] = (arguments.length < 2) ? arguments[0] : arguments;
				if (++done == args.length ) {
					df.resolve.apply(df, rp);
				}
			}).fail(function() {
				df.reject(arguments);
			});
		});

		return df;

	}
}
// call resolve functions
var resolveFunc = function( type, status ) {
	return function( context ) {
		var args = this.resultArgs = (arguments.length > 1) ? arguments[1] : [];
		return this.exec(context, this[type], args, status);
	}
},

	doneFunc = function( type, status ) {
		return function() {
			var self = this;
			h.each(arguments, function( i, v, args ) {
				if (!v ) return;
				if ( v.constructor === Array ) {
					args.callee.apply(self, v)
				} else {
					// immediately call the function if the deferred has been resolved
					if ( self.status === status ) v.apply(this, self.resultArgs || []);

					self[type].push(v);
				}
			});
			return this;
		}
	};

h.extend(Deferred.prototype, {
	resolveWith: resolveFunc("doneFuncs", "rs"),
	rejectWith: resolveFunc("failFuncs", "rj"),
	done: doneFunc("doneFuncs", "rs"),
	fail: doneFunc("failFuncs", "rj"),
	always: function() {
		var args = h.map(arguments);
		if ( args.length && args[0] ) this.done(args[0]).fail(args[0]);

		return this;
	},
	then: function() {
		var args = h.map(arguments);
		// fail function(s)
		if ( args.length > 1 && args[1] ) this.fail(args[1]);

		// done function(s)
		if ( args.length && args[0] ) this.done(args[0]);

		return this;
	},
	isResolved: function() {
		return this.status === "rs";
	},
	isRejected: function() {
		return this.status === "rj";
	},
	reject: function() {
		return this.rejectWith(this, arguments);
	},
	resolve: function() {
		return this.resolveWith(this, arguments);
	},
	exec: function( context, dst, args, st ) {
		if ( this.status !== "" ) return this;

		this.status = st;

		h.each(dst, function( i, d ) {
			d.apply(context, args);
		});

		return this;
	}
});
// ## HELPER METHODS FOR DEFERREDS
// Used to call a method on an object or resolve a
// deferred on it when a group of deferreds is resolved.
//
//     whenEach(resources,"complete",resource,"execute")
var whenEach = function( arr, func, obj, func2 ) {

	var deferreds = h.map(arr, func)
	return Deferred.when.apply(Deferred, deferreds).then(function() {
		if ( h.isFn(obj[func2]) ) {
			obj[func2]()
		} else {
			obj[func2].resolve();
		}

	});
};


text:
(function() {
  /**
  Status codes for HackMyResume.
  @module core/status-codes
  @license MIT. See LICENSE.MD for details.
  */
  module.exports = {
    success: 0,
    themeNotFound: 1,
    copyCss: 2,
    resumeNotFound: 3,
    missingCommand: 4,
    invalidCommand: 5,
    resumeNotFoundAlt: 6,
    inputOutputParity: 7,
    createNameMissing: 8,
    pdfGeneration: 9,
    missingPackageJSON: 10,
    invalid: 11,
    invalidFormat: 12,
    notOnPath: 13,
    readError: 14,
    parseError: 15,
    fileSaveError: 16,
    generateError: 17,
    invalidHelperUse: 18,
    mixedMerge: 19,
    invokeTemplate: 20,
    compileTemplate: 21,
    themeLoad: 22,
    invalidParamCount: 23,
    missingParam: 24,
    createError: 25,
    validateError: 26,
    invalidOptionsFile: 27,
    optionsFileNotFound: 28,
    unknownSchema: 29,
    themeHelperLoad: 30,
    invalidSchemaVersion: 31
  };

}).call(this);

//# sourceMappingURL=status-codes.js.map


text:
CREATE TABLE embedded_app_url_regex (
    name TEXT,
    url_regex TEXT,
    PRIMARY KEY (name, url_regex)
);

CREATE INDEX embedded_app_url_regex_name ON embedded_app_url_regex ("name");


text:
package de.kuei.metafora.gwt.smack.client;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.TimeZone;

public class DateConverter extends DateTimeFormat {
	String time;
	Date date;
	String cdate;
	TimeZone tz;
	long currentTime;

	public DateConverter(String time) {
		super("");
		this.time = time;
	}

	public String convertTime() {
		long xmlTime = Long.parseLong(time);
		date = new Date(xmlTime);
		currentTime = System.currentTimeMillis();
		long offset = currentTime - xmlTime;

		long aDay = 1000l * 60l * 60l * 24l;
		long aWeek = aDay * 7l;
		if (offset < aDay) {
			cdate = DateTimeFormat.getFormat("HH:mm ', 'z").format(date);
		} else {
			if (aDay <= offset && offset < aWeek) {
				int day = date.getDay();
				if (day == 1) {
					cdate = "Monday";
				}
				if (day == 2) {
					cdate = "Tuesday";
				}
				if (day == 3) {
					cdate = "Wednesday";
				}
				if (day == 4) {
					cdate = "Thursday";
				}
				if (day == 5) {
					cdate = "Friday";
				}
				if (day == 6) {
					cdate = "Saturday";
				}
				if (day == 0) {
					cdate = "Sunday";
				}
			} else {
				cdate = this.getLongDateFormat().format(date);
			}
		}

		return cdate;
	}
}


text:
module A {
    export class Calculator {
        public handelChar() {
        }
    }
}

module B {
    import a = A;
}

//// [unusedImports10.js]
var A;
(function (A) {
    var Calculator = (function () {
        function Calculator() {
        }
        Calculator.prototype.handelChar = function () {
        };
        return Calculator;
    }());
    A.Calculator = Calculator;
})(A || (A = {}));


text:
<?php

namespace flat\core;
/**
 * low level event class. events are objects (typically accumulated within a collection)
 *    the collection is passed along to different controllers that desire to handle same group the events.
 *
 * @see \flat\core\event::call() events can be called. a child of \flat\core\event can use via
 * @see \flat\core\event\triggerable events can be triggered
 *       ...some outside thing can cause event to occur via \flat\core\event\triggerable::trigger()
 *
 * @see \flat\core\event\listener events can be listened to...
 *    multiple listeners can accumulate on a single event. when event occurs
 *
 * @see \flat\core\event\factory events are ideally controlled through
 *    extending the event factory class
 *
 *
 * @package    flat\event
 * @author     D. Bird <retran@gmail.com>
 * @copyright  Copyright (c) 2012-2014 Doug Bird. All Rights Reserved.
 * @version    0.1.0-alpha
 * @abstract
 */
abstract class event extends \flat\core {

   /**
    * @var string $name name of event
    */
   private $name;

   /**
    * @var callable[] $listener any listeners attached event
    */
   protected $listener;

   /**
    * @var callable $handler function to invoke for event occurrance
    */
   private $handler;

   /**
    * @var mixed $data optional data to pass to event handler and listeners
    */
   private $data;

   /**
    * @var array $keyval keyval storage
    */
   private $_keyval;

   /**
    * sets a data keyval
    *
    * @param string $key data key to set
    * @param mixed $val data value
    * @param bool $no_overwrite if true, will only set value to key 1 time
    *
    * @return void
    * @throws \flat\core\event\exception\invalid_key\is_not_string if key not string
    * @throws \flat\core\event\exception\invalid_key\cannot_be_empty if key empty
    */
   final public function set_data($key,$val,$no_overwrite=false) {
      if (!is_string($key)) throw new event\exception\invalid_key\is_not_string();
      if (empty($key)) throw new event\exception\invalid_key\cannot_be_empty();
      if (!is_array($this->_keyval)) $this->_keyval = array();
      if ($no_overwrite) if (isset($this->_keyval[$key])) return;
      $this->_keyval[$key] = $val;
   }

   /**
    * retrieve name of event
    *
    * @return string
    *
    * @see $name
    * @see \flat\core\event::set_params()
    * @final
    */
   final public function get_name() {
      return $this->name;
   }
   /**
    * add listener to event. multiple listeners can attach to a single event
    *    simply by calling this method multiple times.
    *
    * @param callable $listener function invoked after event occurance
    * @return void
    * @see $listener
    * @final
    */
   final public function add_listener(callable $listener) {

      if (!is_array($this->listener)) $this->listener = array();

      $this->listener[] = $listener;

   }
   /**
    * set handler for event. only the last handler set will be invoked for
    *    event occurrance with event::call(). if the handler returns bool false on event occurance
    *    the event is considered to have failed and exception will be thrown.
    *
    * @param callable $handler
    * @return void
    *
    * @final
    * @see \flat\core\event\exception\failure
    * @see \flat\core\event::call()
    */
   final public function set_handler(callable $handler) {
      $this->handler = $handler;
   }
   /**
    * invoke event occurrance
    * @param mixed $call_data (optional) data associated with a to particular
    *    occurance to pass to event handler and any listeners
    * @return void
    *
    * @throws \flat\core\event\exception\failure if handler returns false
    *
    * @see $handler if handler set, handler is first invoked
    * @see $listener if listeners exist, these are invoked after event handler
    * @see $data data associated with event is passed to handler and listeners
    *
    * @final
    */
   final protected function call($call_data=NULL) {
      /**
       * @var array $arr fuction arguments to pass to handler and listeners
       * @see call_user_func_array()
       */
      $arr = array();
      if ($call_data!=NULL) $arr['call'] = $call_data;
      if ($this->data != NULL) $arr['event'] = $this->data;
      if ($this->_keyval !=NULL) $arr['data'] = (object) $this->_keyval;
      if (count($arr)>1) $arr = array('data'=>$arr);

      /*
       * invoke handler first as appropriate
       */
      $h_data = NULL;
      if (is_callable($this->handler)) {
         $h_data = call_user_func_array($this->handler, $arr);
         if (false === $h_data) {
            throw new event\exception\failure($this);
         }
      }
      //var_dump($h_data);echo "dump: flat/core/event ".$this->get_name();
      /*
       * invoke listeners after preparing data in priority order
       *    if handler provides data, it will be all that is passed
       */
      if($this->listener) {
         $arr = array();
         if ($call_data!=NULL) $arr = array( $call_data );
         if ($this->data != NULL) $arr = array( $this->data );
         if ($this->_keyval !=NULL) $arr = array( (object) $this->_keyval );
         if (!empty($h_data)) $arr = array( $h_data );
         foreach ($this->listener as $listener) call_user_func_array($listener, $arr);
      }
   }
   /**
    * convenience function for child classes to set some minimal event parameters
    *
    * @final
    * @return void
    * @param string $event_string name of event
    * @param callable $handler (optional)
    * @param mixed $event_data (optional)
    *
    * @see $name
    * @see $data
    * @see $handler
    * @throws \flat\core\event\exception\invalid_name\is_not_string if event name not string
    * @throws \flat\core\event\exception\invalid_name\cannot_be_empty if event name empty
    */
   final protected function set_params($event_name,callable $handler=NULL,$event_data=NULL) {
      if (empty($event_name)) throw new event\exception\invalid_name\cannot_be_empty();

      if (!is_string($event_name)) throw new event\exception\invalid_name\is_not_string();

      $this->name = $event_name;
      $this->data = $event_data;
      $this->handler = $handler;

   }

}


text:
title:  Anvi Plis
date:  04/09/2021
---

### Lekti pou etid semenn sa a
1 Korentyen 10.1-11 ; Levitik 4.32-35 ; Jan 1.29 ; Ebre 4.1-11 ; Sòm 95.8-11

>
Pasaj pou n memorize a

> " Tout bagay sa yo rive pou sa sèvi nou leson pou nou pa kite move lanvi kaye nan kè nou tankou yo te genyen l lan" (Jeremi 31.31, HCV).

Nan mize Queens, New-York, Etazini, se la w ap jwenn pi gwo fanal ki (makèt*) nan mond lan ki reprezante vil New-York, li gen tout konstwiksyon vil la. Sou yon echèl 1/1200, l ap fè anviwon yon teren 30 santyèm. Se yon ekip anviwon san (100) atizan ki te fini fanal sa a an 1964, yo te travay pandan plis pase twa (3) lane pou yo te kapab fini pwojè sa a.

Men, finalman, sa pa anyen lòt bagay : se yon kopi, yon reprezantasyon yon bagay ki pi gran, ki pi laj, pi wo e pi konplike pase fanal la.

Se menm bagay la pou tout reprezantasyon : yo se senbòl yon bagay ki orijinal. Yon reprezantasyon ki kapab ede n konprann nannan (esans) bagay ki orijinal la, men, li p ap janm kapab ranplase l. Olye sa a, li la pou ede n konprann pi byen kisa k orijinal la.

Nou jwenn nan Ekriti yo divès reprezantasyon aktivite ak enstitisyon ki fè n wè reyalite ki pi enpòtan nan sa ki konsène Bondye. Chapit 4 liv Ebre a ede n dekouvri yonn nan reyalite sa yo ki gen rapò ak kesyon repo biblik la.

_*Etidye leson semèn sa a pou saba 11 septanm._