text:
import type {Fiber} from './ReactFiber';
import type {FiberRoot} from './ReactFiberRoot';
import type {ExpirationTime} from './ReactFiberExpirationTime';
import type {CapturedValue} from './ReactCapturedValue';
import type {Update} from './ReactUpdateQueue';
import type {Thenable} from './ReactFiberScheduler';

import {
  ClassComponent,
  HostRoot,
  HostComponent,
  HostPortal,
  ContextProvider,
  TimeoutComponent,
} from 'shared/ReactTypeOfWork';
import {
  DidCapture,
  Incomplete,
  NoEffect,
  ShouldCapture,
} from 'shared/ReactTypeOfSideEffect';
import {
  enableGetDerivedStateFromCatch,
  enableProfilerTimer,
  enableSuspense,
} from 'shared/ReactFeatureFlags';
import {ProfileMode} from './ReactTypeOfMode';

import {createCapturedValue} from './ReactCapturedValue';
import {
  enqueueCapturedUpdate,
  createUpdate,
  enqueueUpdate,
  CaptureUpdate,
} from './ReactUpdateQueue';
import {logError} from './ReactFiberCommitWork';
import {Never, Sync, expirationTimeToMs} from './ReactFiberExpirationTime';
import {popHostContainer, popHostContext} from './ReactFiberHostContext';
import {
  popContextProvider as popLegacyContextProvider,
  popTopLevelContextObject as popTopLevelLegacyContextObject,
} from './ReactFiberContext';
import {popProvider} from './ReactFiberNewContext';
import {
  resumeActualRenderTimerIfPaused,
  recordElapsedActualRenderTime,
} from './ReactProfilerTimer';
import {
  suspendRoot,
  onUncaughtError,
  markLegacyErrorBoundaryAsFailed,
  isAlreadyFailedLegacyErrorBoundary,
  recalculateCurrentTime,
  computeExpirationForFiber,
  scheduleWork,
  retrySuspendedRoot,
} from './ReactFiberScheduler';

function createRootErrorUpdate(
  fiber: Fiber,
  errorInfo: CapturedValue<mixed>,
  expirationTime: ExpirationTime,
): Update<null> {
  const update = createUpdate(expirationTime);
  // Unmount the root by rendering null.
  update.tag = CaptureUpdate;
  // Caution: React DevTools currently depends on this property
  // being called "element".
  update.payload = {element: null};
  const error = errorInfo.value;
  update.callback = () => {
    onUncaughtError(error);
    logError(fiber, errorInfo);
  };
  return update;
}

function createClassErrorUpdate(
  fiber: Fiber,
  errorInfo: CapturedValue<mixed>,
  expirationTime: ExpirationTime,
): Update<mixed> {
  const update = createUpdate(expirationTime);
  update.tag = CaptureUpdate;
  const getDerivedStateFromCatch = fiber.type.getDerivedStateFromCatch;
  if (
    enableGetDerivedStateFromCatch &&
    typeof getDerivedStateFromCatch === 'function'
  ) {
    const error = errorInfo.value;
    update.payload = () => {
      return getDerivedStateFromCatch(error);
    };
  }

  const inst = fiber.stateNode;
  if (inst !== null && typeof inst.componentDidCatch === 'function') {
    update.callback = function callback() {
      if (
        !enableGetDerivedStateFromCatch ||
        getDerivedStateFromCatch !== 'function'
      ) {
        // To preserve the preexisting retry behavior of error boundaries,
        // we keep track of which ones already failed during this batch.
        // This gets reset before we yield back to the browser.
        // TODO: Warn in strict mode if getDerivedStateFromCatch is
        // not defined.
        markLegacyErrorBoundaryAsFailed(this);
      }
      const error = errorInfo.value;
      const stack = errorInfo.stack;
      logError(fiber, errorInfo);
      this.componentDidCatch(error, {
        componentStack: stack !== null ? stack : '',
      });
    };
  }
  return update;
}

function schedulePing(finishedWork) {
  // Once the promise resolves, we should try rendering the non-
  // placeholder state again.
  const currentTime = recalculateCurrentTime();
  const expirationTime = computeExpirationForFiber(currentTime, finishedWork);
  const recoveryUpdate = createUpdate(expirationTime);
  enqueueUpdate(finishedWork, recoveryUpdate, expirationTime);
  scheduleWork(finishedWork, expirationTime);
}

function throwException(
  root: FiberRoot,
  returnFiber: Fiber,
  sourceFiber: Fiber,
  value: mixed,
  renderIsExpired: boolean,
  renderExpirationTime: ExpirationTime,
  currentTimeMs: number,
) {
  // The source fiber did not complete.
  sourceFiber.effectTag |= Incomplete;
  // Its effect list is no longer valid.
  sourceFiber.firstEffect = sourceFiber.lastEffect = null;

  if (
    enableSuspense &&
    value !== null &&
    typeof value === 'object' &&
    typeof value.then === 'function'
  ) {
    // This is a thenable.
    const thenable: Thenable = (value: any);

    const expirationTimeMs = expirationTimeToMs(renderExpirationTime);
    const startTimeMs = expirationTimeMs - 5000;
    let elapsedMs = currentTimeMs - startTimeMs;
    if (elapsedMs < 0) {
      elapsedMs = 0;
    }
    const remainingTimeMs = expirationTimeMs - currentTimeMs;

    // Find the earliest timeout of all the timeouts in the ancestor path.
    // TODO: Alternatively, we could store the earliest timeout on the context
    // stack, rather than searching on every suspend.
    let workInProgress = returnFiber;
    let earliestTimeoutMs = -1;
    searchForEarliestTimeout: do {
      if (workInProgress.tag === TimeoutComponent) {
        const current = workInProgress.alternate;
        if (current !== null && current.memoizedState === true) {
          // A parent Timeout already committed in a placeholder state. We
          // need to handle this promise immediately. In other words, we
          // should never suspend inside a tree that already expired.
          earliestTimeoutMs = 0;
          break searchForEarliestTimeout;
        }
        let timeoutPropMs = workInProgress.pendingProps.ms;
        if (typeof timeoutPropMs === 'number') {
          if (timeoutPropMs <= 0) {
            earliestTimeoutMs = 0;
            break searchForEarliestTimeout;
          } else if (
            earliestTimeoutMs === -1 ||
            timeoutPropMs < earliestTimeoutMs
          ) {
            earliestTimeoutMs = timeoutPropMs;
          }
        } else if (earliestTimeoutMs === -1) {
          earliestTimeoutMs = remainingTimeMs;
        }
      }
      workInProgress = workInProgress.return;
    } while (workInProgress !== null);

    // Compute the remaining time until the timeout.
    const msUntilTimeout = earliestTimeoutMs - elapsedMs;

    if (renderExpirationTime === Never || msUntilTimeout > 0) {
      // There's still time remaining.
      suspendRoot(root, thenable, msUntilTimeout, renderExpirationTime);
      const onResolveOrReject = () => {
        retrySuspendedRoot(root, renderExpirationTime);
      };
      thenable.then(onResolveOrReject, onResolveOrReject);
      return;
    } else {
      // No time remaining. Need to fallback to placeholder.
      // Find the nearest timeout that can be retried.
      workInProgress = returnFiber;
      do {
        switch (workInProgress.tag) {
          case HostRoot: {
            // The root expired, but no fallback was provided. Throw a
            // helpful error.
            const message =
              renderExpirationTime === Sync
                ? 'A synchronous update was suspended, but no fallback UI ' +
                  'was provided.'
                : 'An update was suspended for longer than the timeout, ' +
                  'but no fallback UI was provided.';
            value = new Error(message);
            break;
          }
          case TimeoutComponent: {
            if ((workInProgress.effectTag & DidCapture) === NoEffect) {
              workInProgress.effectTag |= ShouldCapture;
              const onResolveOrReject = schedulePing.bind(null, workInProgress);
              thenable.then(onResolveOrReject, onResolveOrReject);
              return;
            }
            // Already captured during this render. Continue to the next
            // Timeout ancestor.
            break;
          }
        }
        workInProgress = workInProgress.return;
      } while (workInProgress !== null);
    }
  }

  // We didn't find a boundary that could handle this type of exception. Start
  // over and traverse parent path again, this time treating the exception
  // as an error.
  value = createCapturedValue(value, sourceFiber);
  let workInProgress = returnFiber;
  do {
    switch (workInProgress.tag) {
      case HostRoot: {
        const errorInfo = value;
        workInProgress.effectTag |= ShouldCapture;
        const update = createRootErrorUpdate(
          workInProgress,
          errorInfo,
          renderExpirationTime,
        );
        enqueueCapturedUpdate(workInProgress, update, renderExpirationTime);
        return;
      }
      case ClassComponent:
        // Capture and retry
        const errorInfo = value;
        const ctor = workInProgress.type;
        const instance = workInProgress.stateNode;
        if (
          (workInProgress.effectTag & DidCapture) === NoEffect &&
          ((typeof ctor.getDerivedStateFromCatch === 'function' &&
            enableGetDerivedStateFromCatch) ||
            (instance !== null &&
              typeof instance.componentDidCatch === 'function' &&
              !isAlreadyFailedLegacyErrorBoundary(instance)))
        ) {
          workInProgress.effectTag |= ShouldCapture;
          // Schedule the error boundary to re-render using updated state
          const update = createClassErrorUpdate(
            workInProgress,
            errorInfo,
            renderExpirationTime,
          );
          enqueueCapturedUpdate(workInProgress, update, renderExpirationTime);
          return;
        }
        break;
      default:
        break;
    }
    workInProgress = workInProgress.return;
  } while (workInProgress !== null);
}

function unwindWork(
  workInProgress: Fiber,
  renderIsExpired: boolean,
  renderExpirationTime: ExpirationTime,
) {
  if (enableProfilerTimer) {
    if (workInProgress.mode & ProfileMode) {
      recordElapsedActualRenderTime(workInProgress);
    }
  }

  switch (workInProgress.tag) {
    case ClassComponent: {
      popLegacyContextProvider(workInProgress);
      const effectTag = workInProgress.effectTag;
      if (effectTag & ShouldCapture) {
        workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture;
        return workInProgress;
      }
      return null;
    }
    case HostRoot: {
      popHostContainer(workInProgress);
      popTopLevelLegacyContextObject(workInProgress);
      const effectTag = workInProgress.effectTag;
      if (effectTag & ShouldCapture) {
        workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture;
        return workInProgress;
      }
      return null;
    }
    case HostComponent: {
      popHostContext(workInProgress);
      return null;
    }
    case TimeoutComponent: {
      const effectTag = workInProgress.effectTag;
      if (effectTag & ShouldCapture) {
        workInProgress.effectTag = (effectTag & ~ShouldCapture) | DidCapture;
        return workInProgress;
      }
      return null;
    }
    case HostPortal:
      popHostContainer(workInProgress);
      return null;
    case ContextProvider:
      popProvider(workInProgress);
      return null;
    default:
      return null;
  }
}

function unwindInterruptedWork(interruptedWork: Fiber) {
  if (enableProfilerTimer) {
    if (interruptedWork.mode & ProfileMode) {
      // Resume in case we're picking up on work that was paused.
      resumeActualRenderTimerIfPaused();
      recordElapsedActualRenderTime(interruptedWork);
    }
  }

  switch (interruptedWork.tag) {
    case ClassComponent: {
      popLegacyContextProvider(interruptedWork);
      break;
    }
    case HostRoot: {
      popHostContainer(interruptedWork);
      popTopLevelLegacyContextObject(interruptedWork);
      break;
    }
    case HostComponent: {
      popHostContext(interruptedWork);
      break;
    }
    case HostPortal:
      popHostContainer(interruptedWork);
      break;
    case ContextProvider:
      popProvider(interruptedWork);
      break;
    default:
      break;
  }
}

export {
  throwException,
  unwindWork,
  unwindInterruptedWork,
  createRootErrorUpdate,
  createClassErrorUpdate,
};


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using eLib;
using eStationCore.IManagers;
using eStationCore.Model;
using eStationCore.Model.Hr.Views;
using eStationCore.Model.Sale.Entity;
using eStationCore.Model.Sale.Enums;

namespace eStationCore.Store.SqlServer {

    /// <summary>
    /// Tresorerie
    /// </summary>
    public sealed class FinanceManager : IFinanceManager
    {
        private readonly StationContext _db;

        public FinanceManager(StationContext stationContext)
        {
            _db = stationContext;
        }

        #region CRUD

        /// <summary>
        ///
        /// </summary>
        /// <param name="newTransaction"></param>
        /// <returns></returns>
        public bool NewTransaction(Transaction newTransaction)
        {
            //todo security
            return StaticNewTransaction(newTransaction);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="transactionGuid"></param>
        /// <returns></returns>
        public bool CancelTransaction(Guid transactionGuid)
        {
            using (var db = new StationContext())
            {
                var theTransaction = db.Transactions.Find(transactionGuid);
                if (theTransaction == null) throw new InvalidOperationException("CAN_NOT_FIND_REFERENCE_TRANSACTION");

                theTransaction.IsDeleted = true;
                theTransaction.DeleteDate = DateTime.Now;
                theTransaction.DeleteUserGuid = Guid.Empty;

                theTransaction.LastEditDate = DateTime.Now;
                theTransaction.LastEditUserGuid = Guid.Empty;

                db.Transactions.Attach(theTransaction);
                db.Entry(theTransaction).State = EntityState.Modified;
                return db.SaveChanges() > 0;
            }
        }

        /// <summary>
        /// Nouvelle Numero de Reference
        /// </summary>
        public string GetNewTransactionReference()
        {
            string newId;
            do
                newId = "T" + RandomHelper.GetRandLetters(1) + "-" + DateTime.Today.Month +
                        DateTime.Today.Year.ToString().Substring(2) + "-" + RandomHelper.GetRandNum(4); while (
                RefTransactionExist(newId)
                );
            return newId;
        }

        /// <summary>
        /// Verifie si cette reference exist
        /// </summary>
        /// <param name="theReference"></param>
        /// <returns></returns>
        public bool RefTransactionExist(string theReference)
        {
            using (var mc = new StationContext())
                return
                    mc.Transactions.Any(
                        s => s.TransactionReference.Equals(theReference, StringComparison.CurrentCultureIgnoreCase));
        }

        /// <summary>
        /// liste des transactions
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="includeDeleted"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TransactionCard>> GetTransactions(DateTime? startDate, DateTime? endDate, bool includeDeleted = false)
        {
            return await Task.Run(() =>
            {
                if (includeDeleted)
                    using (var db = new StationContext())
                    {
                        if (startDate == null || endDate == null)
                            return
                                db.Transactions.OrderByDescending(t => t.TransactionDate)
                                    .ToList()
                                    .Select(t => new TransactionCard(t));

                        return db.Transactions.Where(t =>
                            t.TransactionDate >= startDate &&
                            t.TransactionDate <= endDate
                            ).OrderByDescending(t => t.TransactionDate).ToList().Select(t => new TransactionCard(t));
                    }

                using (var db = new StationContext())
                {
                    if (startDate == null || endDate == null)
                        return
                            db.Transactions.Where(t => !t.IsDeleted)
                                .OrderByDescending(t => t.TransactionDate)
                                .ToList()
                                .Select(t => new TransactionCard(t));

                    return db.Transactions.Where(t => !t.IsDeleted &&
                                                      t.TransactionDate >= startDate &&
                                                      t.TransactionDate <= endDate
                        ).OrderByDescending(t => t.TransactionDate).ToList().Select(t => new TransactionCard(t));
                }
            });
        }

        #endregion

        #region Views

        /// <summary>
        ///
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public async Task<double> GetTotalRecette(DateTime? startDate, DateTime? endDate)
            => await StaticGetRecette(startDate, endDate);

        /// <summary>
        ///
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public async Task<double> GetTotalDepense(DateTime? startDate, DateTime? endDate)
            => await StaticGetExpense(startDate, endDate);

        /// <summary>
        ///
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        public async Task<double> GetTotalPaidSalaries(DateTime? startDate, DateTime? endDate)
            => await StaticGetPaidSalary(startDate, endDate);

        /// <summary>
        ///
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        public async Task<double> GetSoldeCaisse(DateTime? startDate, DateTime? endDate)
            => await StaticGetSoldeCaisse(startDate, endDate);

        /// <summary>
        ///
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public async Task<double> GetRevenue(DateTime startDate, DateTime endDate)
            => await StaticGetRevenue(startDate, endDate);

        #endregion

        #region Analytic

        public async Task<IEnumerable<KeyValuePair<DateTime, double>>> MonthlySalary(DateTime fromDate, DateTime toDate)
        {
            var points = new List<KeyValuePair<DateTime, double>>();
            foreach (var date in DateTimeHelper.EachMonth(new DateTime(fromDate.Year, fromDate.Month, 1), new DateTime(toDate.Year, toDate.Month, 1)))
                points.Add(new KeyValuePair<DateTime, double>(date,
                    await StaticGetPaidSalary(date.Date, date.Date.AddMonths(1).AddDays(-1))));
            return points;
        }

        public async Task<List<KeyValuePair<DateTime, double>>> MonthlyExpense(DateTime fromDate, DateTime toDate)
        {
            var points = new List<KeyValuePair<DateTime, double>>();
            foreach (var date in DateTimeHelper.EachMonth(new DateTime(fromDate.Year, fromDate.Month, 1), new DateTime(toDate.Year, toDate.Month, 1)))
                points.Add(new KeyValuePair<DateTime, double>(date,
                    -await StaticGetExpense(date.Date, date.Date.AddMonths(1).AddDays(-1))));
            return points;
        }

        public async Task<List<KeyValuePair<DateTime, double>>> MonthlyRecette(DateTime fromDate, DateTime toDate)
        {
            var points = new List<KeyValuePair<DateTime, double>>();
            foreach (var date in DateTimeHelper.EachMonth(new DateTime(fromDate.Year, fromDate.Month, 1), new DateTime(toDate.Year, toDate.Month, 1)))
                points.Add(new KeyValuePair<DateTime, double>(date,
                    await StaticGetRecette(date.Date, date.Date.AddMonths(1).AddDays(-1))));
            return points;
        }

        public async Task<List<KeyValuePair<DateTime, double>>> MonthlyIncome(DateTime fromDate, DateTime toDate)
        {
            var points = new List<KeyValuePair<DateTime, double>>();
            foreach (var date in DateTimeHelper.EachMonth(new DateTime(fromDate.Year, fromDate.Month, 1), new DateTime(toDate.Year, toDate.Month, 1)))
                points.Add(new KeyValuePair<DateTime, double>(date,
                    await StaticGetRevenue(date.Date, date.Date.AddMonths(1).AddDays(-1))));
            return points;
        }

        #endregion

        #region Protected Internal Static

        internal async static Task<double> StaticGetRecette (DateTime? startDate, DateTime? endDate) {
            return await Task.Run(() => {
                using (var db = new StationContext()) {
                if(!db.Transactions.Any(t => !t.IsDeleted&&t.Amount>0))
                    return 0;

                if(startDate==null||endDate==null)
                    return db.Transactions.Where(t => !t.IsDeleted&&t.Amount>0).Sum(t => t.Amount);

                if(!db.Transactions.Any(t =>
                                                !t.IsDeleted&&t.Amount>0&&
                                                t.TransactionDate>=startDate&&
                                                t.TransactionDate<=endDate
                                            ))
                    return 0;

                return db.Transactions.Where(t =>
                                                !t.IsDeleted&&t.Amount>0&&
                                                t.TransactionDate>=startDate&&
                                                t.TransactionDate<=endDate
                                            ).Sum(t => t.Amount);
                }
            });
        }

        internal async static Task<double> StaticGetExpense (DateTime? startDate, DateTime? endDate) {
            return await Task.Run(() => {
                using (var db = new StationContext()) {

                if(!db.Transactions.Any(t => !t.IsDeleted&&t.Amount<0))
                    return 0;

                if(startDate==null||endDate==null)
                    return db.Transactions.Where(t => !t.IsDeleted&&t.Amount<0).Sum(t => t.Amount);

                if(!db.Transactions.Any(t =>
                                                !t.IsDeleted&&t.Amount<0&&
                                                t.TransactionDate>=startDate&&
                                                t.TransactionDate<=endDate
                                            ))
                    return 0;

                return db.Transactions.Where(t =>
                                                !t.IsDeleted&&t.Amount<0&&
                                                t.TransactionDate>=startDate&&
                                                t.TransactionDate<=endDate
                                            ).Sum(t => t.Amount);
            }
            });
        }

        internal async static Task<double> StaticGetPaidSalary (DateTime? startDate, DateTime? endDate) {
            return await Task.Run(() => {
                using (var db = new StationContext()) {
                if(!db.Payrolls.Any(t => !t.IsDeleted&&t.IsPaid))
                    return 0;

                if(startDate==null||endDate==null)
                    return db.Payrolls.Where(t => !t.IsDeleted&&t.IsPaid).Sum(t => t.FinalPaycheck);

                return db.Payrolls.Any(t =>
                    !t.IsDeleted && t.IsPaid &&
                    t.DatePaid >= startDate &&
                    t.DatePaid <= endDate)
                    ? db.Payrolls.Where(t =>
                        !t.IsDeleted && t.IsPaid &&
                        t.DatePaid >= startDate &&
                        t.DatePaid <= endDate
                        ).Sum(t => t.FinalPaycheck)
                    : 0;
            }});
        }

        internal async static Task<double> StaticGetSoldeCaisse (DateTime? startDate, DateTime? endDate) {
            return await Task.Run(() => {
                using (var db = new StationContext()) {
                if(!db.Transactions.Any(t => !t.IsDeleted))
                    return 0;

                if(startDate==null||endDate==null)
                    return db.Transactions.Where(t => !t.IsDeleted).Sum(t => t.Amount);

                return db.Transactions.Any(t =>
                    !t.IsDeleted &&
                    t.TransactionDate >= startDate &&
                    t.TransactionDate <= endDate)
                    ? db.Transactions.Where(t =>
                        !t.IsDeleted &&
                        t.TransactionDate >= startDate &&
                        t.TransactionDate <= endDate
                        ).Sum(t => t.Amount)
                    : 0;
            }});
        }

        internal async static Task<double> StaticGetRevenue (DateTime startDate, DateTime endDate) {
            double solde = 0;

            solde += await OilManager.GetSold(startDate, endDate);
            solde += await FuelManager.GetSold(startDate, endDate);
            solde += await SalesManager.StaticGetPurchasedSum(ProductType.Service, PurchaseState.Paid, startDate, endDate);

            solde += await StaticGetSoldeCaisse(startDate, endDate);

            solde -= await StaticGetPaidSalary(startDate, endDate);

            solde -= await SalesManager.StaticGetPurchasedSum(ProductType.Fuel, PurchaseState.UnPaid, startDate, endDate);
            solde -= await SalesManager.StaticGetPurchasedSum(ProductType.Oil, PurchaseState.UnPaid, startDate, endDate);

            solde -= await SalesManager.StaticGetPurchasedSum(ProductType.Fuel, PurchaseState.NotPaying, startDate, endDate);
            solde -= await SalesManager.StaticGetPurchasedSum(ProductType.Oil, PurchaseState.NotPaying, startDate, endDate);

            return solde;
        }

        internal static bool StaticNewTransaction (Transaction newTransaction) {

            if(TransactionExist(newTransaction))
                throw new InvalidOperationException("TRANSACTION_REFERENCE_ALREADY_EXIST");

            if(newTransaction.TransactionDate < DateTime.Today.AddDays(-1))
                throw new InvalidOperationException("TRANSACTION_DATE_NOT_VALIDE");

            using (var db = new StationContext())
            {
                newTransaction.TransactionGuid =newTransaction.TransactionGuid == Guid.Empty ? Guid.NewGuid() : newTransaction.TransactionGuid;
                var transDate = newTransaction.TransactionDate.GetValueOrDefault();
                newTransaction.TransactionDate = new DateTime(transDate.Year, transDate.Month, transDate.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                if (string.IsNullOrEmpty(newTransaction.Description)) newTransaction.Description =newTransaction.Designation;

                newTransaction.DateAdded        = DateTime.Now;
                newTransaction.AddUserGuid      = Guid.Empty;
                newTransaction.LastEditDate     = DateTime.Now;
                newTransaction.LastEditUserGuid = Guid.Empty;

                db.Transactions.Add(newTransaction);
                return db.SaveChanges()>0;
            }
        }

        internal static bool TransactionExist (Transaction newTransaction) {
            using (var db = new StationContext())
            {
                if(db.Transactions.Find(newTransaction.TransactionGuid)!=null)
                    return true;
                return db.Transactions.Any(t =>
                        t.TransactionReference.Equals(newTransaction.TransactionReference,
                            StringComparison.CurrentCultureIgnoreCase)) ||
                       db.Transactions.Any(t => t.PaymentMethode == newTransaction.PaymentMethode &&
                                                t.Designation.Equals(newTransaction.Designation) &&
                                                t.TransactionDate == newTransaction.TransactionDate &&
                                                Math.Abs(t.Amount - newTransaction.Amount) < .0000001);
            }
        }

        #endregion

    }
}

redpajama_set_name: RedPajamaGithub


text:
var assert = require("assert"); // node.js core module
var ospos = require("./ospos");

describe("giftcard numbering test", function () {
    this.timeout(25000);

    it("should be able to login",  function (done) {
        return ospos.login(this.browser, done);
    });

    it.skip("issue #65: giftcard numbering should add properly", function(done) {
        return this.browser.get(ospos.url("/index.php/giftcards")).waitForElementByCss(".big_button").click()
            .waitForElementByName("value", 10000).type("100").elementById('giftcard_number').clear().type("10")
            .elementById("submit").click().waitForElementByXPath("//table/tbody/tr[td/text()='10']/td[4]", 2000).text().then(function (value) {
                assert.ok(value, "giftcard failed to be added properly!");
            }).elementByCss(".big_button").click().waitForElementByName("value", 4000).type("100").elementById("submit").click()
            .waitForElementByXPath("//table/tbody/tr[td/text()='11']/td[4]").text().then(function (value) {
                assert.equal(value, "11", "giftcard number not incrementing properly!!");
            }).then(done, done);
    });

});


text:
<?php

namespace App\Http\Controllers\Admin\Event;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\ProductCategory;
use App\ProductPlate;
use App\ProductTopic;
use App\eventfacades\EventCommodity;
use Image;

class EventCommodityController extends Controller
{
    public function index()
    {
        $commodities = EventCommodity::paginate(8);
        return view('admin.event.index')->with(['commodities' => $commodities]);
    }

    public function create()
    {
        // 不需要
        // $categories = ProductCategory::where('parent_id', '>', 0)->orderBy('id', 'desc')->get();
        // $plates = ProductPlate::where('disabled', '=', '显示')->orderBy('id', 'desc')->get();
        // $topics = ProductTopic::where('disabled', '=', '显示')->orderBy('id', 'desc')->get();
        return view('admin.event.create');
        //->with(['categories' => $categories, 'plates' => $plates, 'topics' => $topics]);
    }

    public function store(Request $request)
    {
        $commodity = new EventCommodity();
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $filePath = '/uploads/commodity/';
            $fileName = str_random(10) . '.png';
            Image::make($request->file('file'))
                ->encode('png')
                ->resize(600, 300)
                ->save('.' . $filePath . $fileName);
            $commodity->event_img = $filePath . $fileName;
        }
        $commodity->event_name = $request->input('event_name');
        $commodity->manager = $request->input('manager');
        $commodity->event_place = $request->input('event_place');
        $commodity->event_number = $request->input('event_number');
        $commodity->event_original_price = $request->input('event_original_price');
        $commodity->event_current_price = $request->input('event_current_price');
        $commodity->event_stock_number = $request->input('event_stock_number');
        $commodity->event_sold_number = $request->input('event_sold_number');
        $commodity->event_detail_info = $request->input('event_detail_info');
        $commodity->status = $request->input('status');
        $commodity->event_page_url = $request->input('event_page_url');
        $commodity->end_time = $request->input('end_time');
        $base_info = $request->input('event_base_info');
        $placeholder = "======For Example======\n尺寸:14*14;\n颜色:白色;\n产地:中国。";
        if ($base_info != $placeholder) {
            $commodity->event_base_info = $base_info;
        }
        $commodity->event_disabled = $request->input('event_disabled');
        $commodity->event_sort = $request->input('event_sort');
        if ($commodity->save()) {
            return redirect()->to('admin/event/commodity')->withSuccess('新增商品成功!');
        } else {
            return redirect()->to('admin/event/commodity')->withError('新增商品失败!');
        }
    }

    public function editorUpload(Request $request)
    {
        if ($request->hasFile('editorFile') && $request->file('editorFile')->isValid()) {
            $filePath = '/uploads/editor/';
            $fileName = str_random(10) . '.png';
            Image::make($request->file('editorFile'))
                ->encode('png')
                ->save('.' . $filePath . $fileName);
            return $filePath . $fileName;
        } else {
            return "error|上传失败!";
        }

    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $commodity = EventCommodity::findOrFail($id);

        return view('admin.event.edit',compact('commodity'));
    }

    public function update(Request $request, $id)
    {
        $commodity = EventCommodity::findOrFail($id);
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $filePath = '/uploads/commodity/';
            $fileName = str_random(10) . '.png';
            Image::make($request->file('file'))
                ->encode('png')
                ->resize(600, 300)
                ->save('.' . $filePath . $fileName);
           $commodity->event_img = $filePath . $fileName;
        }
        $commodity->event_name = $request->input('event_name');
        $commodity->manager = $request->input('manager');
        $commodity->event_place = $request->input('event_place');
        $commodity->event_number = $request->input('event_number');
        $commodity->event_original_price = $request->input('event_original_price');
        $commodity->event_current_price = $request->input('event_current_price');
        $commodity->event_stock_number = $request->input('event_stock_number');
        $commodity->event_sold_number = $request->input('event_sold_number');
        $commodity->event_detail_info = $request->input('event_detail_info');
        $commodity->status = $request->input('status');
        $commodity->event_page_url = $request->input('event_page_url');
        $commodity->end_time = $request->input('end_time');
        $base_info = $request->input('event_base_info');
        $placeholder = "======For Example======\n尺寸:14*14;\n颜色:白色;\n产地:中国。";
        if ($base_info != $placeholder) {
            $commodity->event_base_info = $base_info;
        }
        $commodity->event_disabled = $request->input('event_disabled');
        $commodity->event_sort = $request->input('event_sort');
        if ($commodity->save()) {
            return redirect()->to('admin/event/commodity')->withSuccess('修改商品成功!');
        } else {
            return redirect()->to('admin/event/commodity')->withError('修改商品失败!');
        }
    }

    public function destroy($id)
    {
        $commodity = EventCommodity::findOrFail($id);
        $commodity->delete();
        return redirect()->to('admin/event/commodity')->withSuccess('删除商品成功!');
    }
}


text:
<?php

namespace Lechimp\Dicto\App;

use Lechimp\Dicto\Indexer\InsertTwice;
use Lechimp\Dicto\Indexer\IndexerFactory;
use Lechimp\Dicto\Analysis\Listener;
use Lechimp\Dicto\Analysis\AnalyzerFactory;
use Lechimp\Dicto\Analysis\Index;
use Lechimp\Dicto\DB;
use Lechimp\Dicto\Indexer\Insert;
use Lechimp\Dicto\Graph;
use Psr\Log\LoggerInterface as Log;

/**
 * The Engine of the App drives the analysis process.
 */
class Engine
{
    /**
     * @var Log
     */
    protected $log;

    /**
     * @var Config
     */
    protected $config;

    /**
     * @var DB\IndexDBFactory
     */
    protected $db_factory;

    /**
     * @var IndexerFactory
     */
    protected $indexer_factory;

    /**
     * @var AnalyzerFactory
     */
    protected $analyzer_factory;

    /**
     * @var Listener
     */
    protected $analysis_listener;

    /**
     * @var SourceStatus
     */
    protected $source_status;

    public function __construct(
        Log $log,
        Config $config,
        DB\IndexDBFactory $db_factory,
        IndexerFactory $indexer_factory,
        AnalyzerFactory $analyzer_factory,
        Listener $analysis_listener,
        SourceStatus $source_status
    ) {
        $this->log = $log;
        $this->config = $config;
        $this->db_factory = $db_factory;
        $this->indexer_factory = $indexer_factory;
        $this->analyzer_factory = $analyzer_factory;
        $this->analysis_listener = $analysis_listener;
        $this->source_status = $source_status;
    }

    /**
     * Run the analysis.
     *
     * @return null
     */
    public function run()
    {
        $index_db_path = $this->index_database_path();
        if (!$this->db_factory->index_db_exists($index_db_path)) {
            $index = $this->build_index();
            $this->run_indexing($index);
            if ($index instanceof InsertTwice) {
                $index_db = $this->force_app_index_db($index->second());
                $index_db->write_cached_inserts();
                $index = $this->force_graph_index_db($index->first());
            }
        } else {
            $index_db = $this->db_factory->load_index_db($index_db_path);
            $this->log->notice("Reading index from database '$index_db_path'...");
            $index = $this->read_index_from($index_db);
        }
        $this->run_analysis($index);
    }

    protected function index_database_path()
    {
        $commit_hash = $this->source_status->commit_hash();
        return $this->config->project_storage() . "/$commit_hash.sqlite";
    }

    protected function run_indexing(Insert $index)
    {
        $this->log->notice("Building index...");
        $indexer = $this->indexer_factory->build($index);
        $this->with_time_measurement(function ($s) {
                return "Indexing took $s seconds to run.";
            }, function () use ($indexer) {
                $indexer->index_directory(
                        $this->config->project_root(),
                        $this->config->analysis_ignore()
                    );
            });
    }

    protected function run_analysis(Index $index)
    {
        $this->log->notice("Running analysis...");
        $commit_hash = $this->source_status->commit_hash();
        $this->analysis_listener->begin_run($commit_hash);
        $analyzer = $this->analyzer_factory->build($index, $this->analysis_listener);
        $this->with_time_measurement(function ($s) {
                return "Analysis took $s seconds to run.";
            }, function () use ($analyzer) {
                $analyzer->run();
            });
        $this->analysis_listener->end_run();
    }

    protected function build_index()
    {
        if ($this->config->analysis_store_index()) {
            $index_db_path = $this->index_database_path();
            $index_db = $this->db_factory->build_index_db($index_db_path);
            $this->log->notice("Writing index to database '$index_db_path'...");
            return new InsertTwice(new Graph\IndexDB, $index_db);
        }

        return new Graph\IndexDB;
    }

    /**
     * @return  Graph\IndexDB
     */
    protected function read_index_from(DB\IndexDB $db)
    {
        $index = null;
        $this->with_time_measurement(function ($s) {
                return "Loading the index took $s seconds.";
            }, function () use ($db, &$index) {
                $index = $db->to_graph_index();
            });
        return $this->force_graph_index_db($index);
    }

    protected function with_time_measurement(\Closure $message, \Closure $what)
    {
        $start_time = microtime(true);
        $what();
        $time_elapsed_secs = microtime(true) - $start_time;
        $this->log->notice($message($time_elapsed_secs));
    }

    /**
     * @param   mixed   $index
     * @return  Graph\IndexDB
     */
    protected function force_graph_index_db($index)
    {
        if ($index instanceof Graph\IndexDB) {
            return $index;
        } else {
            throw new \LogicException(
                "Expected index to be of type Graph\IndexDB, but it is '" .
                get_class($index) . "'"
            );
        }
    }

    /**
     * @param   mixed   $index
     * @return  IndexDB
     */
    protected function force_app_index_db($index)
    {
        if ($index instanceof DB\IndexDB) {
            return $index;
        } else {
            throw new \LogicException(
                "Expected index to be of type App\IndexDB, but it is '" .
                get_class($index) . "'"
            );
        }
    }
}


text:
Web Fundamentals [![Build Status](https://travis-ci.org/google/WebFundamentals.svg?branch=master)](https://travis-ci.org/google/WebFundamentals)
================

Web Fundamentals is a technical documentation center for multi-device web
development.  Our goal is to build a resource for modern web developers
that's as curated and thorough as developer.android.com or iOS Dev Center.

Content plan
------------
Content plan for Web Fundamentals is tracked through GitHub Issues and our [Site Structure + Content Inventory](http://goo.gl/nWDD0M) doc

Release status
--------------

The project was soft launched in late April with a formal v1 launch in June 2014.  We've now moved to a six-week rolling release cycle.

Technology
----------

This is a Jekyll build.

```
/appengine - the server to host the static content
/src - the documentation
  /_langs - the content in each language
    /en - the base language folder
      /getting-started - the getting started articles
      /multi-device-layouts - responsive design guide
      /introduction-to-media - the guide to using media
      /optimizing-performance - the perf articles
      /using-touch - managing touch
      /showcase - the case-studies
      ...etc...
    /<langcode> - overrides for that language, following the main path structure.
```

The site is generated in `/appengine/build`, but is never checked in.

Contributing
------------

Web Fundamentals is an open source project and we welcome your contributions!
Before submitting a pull request, please review [CONTRIBUTING.md](CONTRIBUTING.md)
and make sure that there is an issue filed describing the fix or new content.
If you don't complete these steps, we won't be able to accept your pull request, sorry.

Installing Dependencies
=======================

Docker (recommended)
--------------------
1. Download and install [Docker](https://docs.docker.com/installation/) for your platform.
1. Now it's installed check out the [Running the site section for Docker](https://github.com/google/webfundamentals#running-the-site) below.

**Note:** Googlers - You may need to complete a few extra steps, ask for more details.

Mac
---

1. Install [XCode Command Line Tools](https://developer.apple.com/xcode/downloads/)
1. Install [NVM](https://github.com/creationix/nvm)
    * `curl https://raw.githubusercontent.com/creationix/nvm/v0.23.3/install.sh | bash`
1. Install node 0.10.x
    * `nvm install 0.10`
    * `nvm use 0.10`
1. Install [RVM](https://rvm.io/rubies/default)
    * `curl -sSL https://get.rvm.io | bash`
1. Set RVM Default to 2.2.0
    * `rvm install ruby-2.2.0`
    * `rvm --default use 2.2.0`
1. Install [Pygments](http://pygments.org/)
    * `easy_install pygments`
1. Install [RubyGems](https://rubygems.org/) dependencies ([Jekyll](http://jekyllrb.com/) and [Kramdown](http://kramdown.gettalong.org/))
    * `rvm . do bundle install`
1. Install the [Grunt CLI](http://gruntjs.com/)
    * `npm install -g grunt-cli`
1. Install [npm](https://www.npmjs.org) dependencies
    * `npm install`
1. Install fontforge if required for grunt-webfont on your OS.  See [grunt-webfont installation instructions](https://github.com/sapegin/grunt-webfont/blob/master/Readme.md#installation) for details.
1. Get the [App Engine SDK](https://cloud.google.com/appengine/downloads) and unzip into the google_appengine folder inside the project root. Add it to your path accordingly (in bash, `$ PATH=./google_appengine:$PATH`)

**Note:** On OSX, you may see an error about *Warning: EMFILE, too many open files*.
If so you will need to increase the maximum number of open file handles.
Use `ulimit -n 1024` to increase the maximum number of open files to 2048 from
the default of 256, or add `launchctl limit maxfiles 2048 2048 ` to `.bashrc`
or `.zshrc`. See [https://github.com/gruntjs/grunt-contrib-watch#how-do-i-fix-the-error-emfile-too-many-opened-files](https://github.com/gruntjs/grunt-contrib-watch#how-do-i-fix-the-error-emfile-too-many-opened-files)
for further details.

**Note:** On OSX, you may also see an error about *Allow dev_appserver to check
for updates on startup? (Y/n)* and, many lines below it, *EOFError: EOF when
reading a line*. If so you need to run dev_appserver once in a GAE project to
allow `dev_appserver` to ask you about checking for updates. Choose whichever
answer you like; this just clears the prompt for future runs of `dev_appserver`
and you should be good to go.

Running the site
================

With Docker (recommended)
-------------------------

Prefixing a command with `tools/docker.sh` will run it inside the Docker container,
which includes all the dependencies needed to build the site.

Build the project:

```sh
tools/docker.sh grunt build
```

Run a local dev server:

```sh
tools/docker.sh grunt develop
```
Then point your browser to http://localhost:8081/web/fundamentals or the
IP address of your Docker instance

To build only a single language *FASTER*:

```sh
tools/docker.sh grunt develop --lang=en
```

Without Docker
--------------

Once you have all the dependencies installed go to the root of the checked out repo and type:

```
grunt develop
```

This will have Jekyll build the site, run a static server to listen on
port 8081 (which you can now reach at
[http://localhost:8081/web/fundamentals/](http://localhost:8081/web/fundamentals/)),
and watch for changes to site files. Every change will cause Jekyll to rebuild
the affected files.

If you want to build a single language then run this: `grunt develop --lang=en`.

Using project-level meta data
=============================

The table of contents is generated from `src/_project.yaml`

To parse the `_project.yaml` file, include `{% injectdata content _project.yaml %}` in the page. You then have access to the variables in the page object.

Generating Table of Contents
----------------------------

The table of contents is generated from `src/_book.yaml`

To parse the `_book.yaml` file, include `{% injectdata content _book.yaml %}` in the page and then iterate as follows:

     {% for section in page.content.toc %}
        SOME MARKUP
     {% endfor %}

Jekyll Special elements
-----------------------

* Code import: `{% highlight javascript %} {% include sample1.js %} {% endhighlight %}`
* `{{ articles _category_}}` a list of articles in divs, ordered by the "order" preamble.
* `{{ showcases _category_}}` a list of showcases.

Translations
============

See [our translations guide](TRANSLATION.md)


text:
<?php

/**
 * Contains the common configuration options for template managers.
 *
 * Whenever a template source or compiled code is accessed it will use the
 * $templatePath and $compilePath respectively as the base path. The full path
 * is generated by using the value of theses variables and then appending a slash
 * (/) and the subpath, this means it is possible to  have the templates in the
 * root of the filesystem by setting an empty string or a string starting with a
 * slash.

 * The next example demonstrates how the templatePath and compilePath can be set:
 *
 * // accessing templates in /usr/share and compile them in /var/cache
 * $conf->templatePath = "/usr/share/eztemplate";
 * $conf->compilePath = "/var/cache/eztemplate";
 *
 *
 * Accessing templates from the applications directory is done with a single dot
 * (.), these are also the default values.
 *
 * // uses current directory for accessing templates and compiling them
 * $conf->templatePath = ".";
 * $conf->compilePath = ".";
 *
 *
 * The $context property is by default assigned to an ezcTemplateXhtmlContext object.
 *
 * @property ezcTemplateOutputContext                   $context
 *           Contains the template context.
 * @property string                                     $templatePath
 *           Base path where the source templates are stored.
 * @property string                                     $compilePath
 *           Base path where the compiled templates are stored.
 * @property bool                                       $checkModifiedTemplates
 *           Set to true, to recompile outdated compiled templates.
 * @property bool                                       $executeTemplate
 *           False to only compile the template without executing it.
 * @property string                                     $cachedTemplatesPath
 *           Relative path from the compilePath.
 * @property string                                     $compiledTemplatesPath
 *           Relative path from the compilePath.
 * @property array(ezcTemplateCustomBlockDefinition)    $customBlock
 *           The currently registered custom blocks.
 * @property array(ezcTemplateCustomFunctionDefinition) $customFunctions
 *           The currently registered custom functions.
 * @property ezcTemplateCacheManager                    $cacheManager
 *           The object to use for caching of compile templates.
 * @property ezcTemplateLocator                         $locator
 *           Set the locator object to dynamically translate the template file.
 * @property bool                                       $disableCache
 *           Disable caching for development purposes.
 * @property string                                     $sourceCharset
 *           Charset of the literals in the original template file.
 * @property string                                     $targetCharset
 *           Desired charset of literals in the compiled.
 * @property bool                                       $trimWhitespace
 *           Whether the parser should strip whitespace from the templates.
 * @package Template
 * @version 1.4.2
 * @mainclass
 */
class ezcTemplateConfiguration
{
    /**
     * List of global instances, looked up using the identifier string.
     *
     * @var array(ezcTemplateConfiguration)
     */
    static private $instanceList = array();

    /**
     * An array containing the properties of this object.
     *
     * templatePath: The base path for all the source templates. e.g. 'design' or 'templates'.
     * compilepath : The base path for all the compiled templates. e.g. 'var/template/compiled'.
     *
     * @var array(string=>mixed)
     */
     private $properties = array( 'context' => false,
                                  'cacheManager' => null,
                                  'disableCache' => false,
                                  'locator' => null,
                                  'templatePath' => ".",
                                  'compilePath' => ".",
                                  'cachedTemplatesPath' => null,
                                  'compiledTemplatesPath' => null,
                                  'checkModifiedTemplates' => true,
                                  'executeTemplate' => true,
                                  'customBlocks' => array(),
                                  'customFunctions' => array(),

                                  'sourceCharset' => "UTF-8",
                                  'targetCharset' => "UTF-8",
                                  'translation' => null,

                                  'trimWhitespace' => true,
                              );
    /**
     * Returns the value of the property $name.
     *
     * @param string $name
     * @param string $name
     *
     * @throws ezcBasePropertyNotFoundException if the property does not exist.
     * @return mixed
     * @ignore
     */
    public function __get( $name )
    {
        switch ( $name )
        {
            case 'context':
            case 'cacheManager':
            case 'locator':
            case 'disableCache':
            case 'templatePath':
            case 'compilePath':
            case 'cachedTemplatesPath':       // Relative path to the compilePath
            case 'compiledTemplatesPath':     // Relative path to the compilePath
            case 'sourceCharset':
            case 'targetCharset':
            case 'translation':
            case 'checkModifiedTemplates':
            case 'executeTemplate':
            case 'trimWhitespace':
                return $this->properties[$name];
            case 'customBlocks':
            case 'customFunctions':
                return (array) $this->properties[$name];

            default:
                throw new ezcBasePropertyNotFoundException( $name );
        }
    }

    /**
     * Sets the property $name to the value $value
     *
     * The properties that can be set are:
     *
     * - ezcTemplateOutputCollection context    : Contains the template context.
     * - string templatePath                    : Base path where the source templates are stored.
     * - string compilePath                     : Base path where the compiled templates are stored.
     * - bool checkModifiedTemplates            : Set to true, to recompile outdated compiled templates.
     *
     * @param string $name
     * @param mixed $value
     * @param string $name
     * @param string $value
     *
     * @throws ezcBasePropertyNotFoundException if the property does not exist.
     * @throws ezcBaseValueException if the desired property value is out of range.
     * @ignore
     */
    public function __set( $name, $value )
    {
        switch ( $name )
        {
            case 'context':
                if ( !$value instanceof ezcTemplateOutputContext )
                {
                    throw new ezcBaseValueException( $name, $value, 'ezcTemplateContext' );
                }
                $this->properties[$name] = $value;
                break;

            case 'cacheManager':
                if ( !($value instanceof ezcTemplateCacheManager) && $value !== null )
                {
                    throw new ezcBaseValueException( $name, $value, 'ezcTemplateCacheManager' );
                }

                $this->properties[$name] = $value;
                break;

            case 'locator':
                if ( !($value instanceof ezcTemplateLocator) && $value !== null )
                {
                    throw new ezcBaseValueException( $name, $value, 'ezcTemplateLocator or null' );
                }

                $this->properties[$name] = $value;
                break;

            case 'templatePath':
            case 'compilePath':
            case 'cachedTemplatesPath':
            case 'compiledTemplatesPath':
            case 'sourceCharset':
            case 'targetCharset':
            case 'translation':
            // case 'cacheSystem':
            case 'checkModifiedTemplates':
            case 'executeTemplate':
            case 'customBlocks':
            case 'customFunctions':
            case 'disableCache':
            case 'trimWhitespace':
                $this->properties[$name] = $value;
                break;

            default:
                throw new ezcBasePropertyNotFoundException( $name );
        }
    }

    /**
     * Returns true if the property $name is set, otherwise false.
     *
     * @param string $name
     * @return bool
     * @ignore
     */
    public function __isset( $name )
    {
        switch ( $name )
        {
            case 'context':
            case 'disableCache':
            case 'sourceCharset':
            case 'targetCharset':
            case 'translation':
            case 'trimWhitespace':
                return true;

            case 'cacheManager':
            case 'locator':
            case 'templatePath':
            case 'compilePath':
            case 'cachedTemplatesPath':
            case 'compiledTemplatesPath':
            case 'checkModifiedTemplates':
            case 'executeTemplate':
                return isset( $this->properties[$name] );

            default:
                return false;
        }
    }

    /**
     * Initialises the configuration with default template, compiled path, and context.
     *
     * All requested templates are search from the defined $templatePath.
     * Use an empty string to fetch templates from the root of the filesystem.
     *
     * All compiled templates are placed in subfolders under the compiled templates.
     * Use an empty string to compile templates at the root of the filesystem.
     *
     * @param string $templatePath   Path where the source templates are stored.
     * @param string $compilePath    Path where the compiled templates should be stored.
     * @param ezcTemplateOutputContext $context  Context to use. Default is the ezcTemplateXhtmlContext.
     */
    public function __construct( $templatePath = ".", $compilePath = ".", ezcTemplateOutputContext $context = null )
    {
        $this->properties["templatePath"] = $templatePath;
        $this->properties["compilePath"] = $compilePath;

        $this->properties["cachedTemplatesPath"] =   "cached_templates";
        $this->properties["compiledTemplatesPath"] =  "compiled_templates";

        // $this->properties["cacheSystem"] = new ezcTemplateCacheFilesystem( $this );

        $this->properties['context'] = ( $context == null ? new ezcTemplateXhtmlContext() : $context );
    }

    /**
     * Returns the unique configuration instance named $name.
     *
     * Note: You only need to specify the name if you need multiple configuration
     *       objects.
     *
     * @param string $name  Name of the configuration to use.
     * @return ezcTemplateConfiguration
     */
    public static function getInstance( $name = "default" )
    {
        if ( !isset( self::$instanceList[$name] ) )
        {
            self::$instanceList[$name] = new ezcTemplateConfiguration();
            ezcBaseInit::fetchConfig( 'ezcInitTemplateConfiguration', self::$instanceList[$name] );
        }

        return self::$instanceList[$name];
    }

    /**
     * Adds custom tags or functions to the customBlock or customFunction
     * property and indirectly adds the custom extension to the template
     * language.
     *
     * The parameter $customBlockClass expects a class that implements either
     * the interface ezcTemplateCustomBlock, ezcTemplateCustomFunction, or both.
     *
     * New custom blocks are added to the
     * {@link ezcTemplateConfiguration::customBlocks $customBlocks} property while
     * custom functions are added to the
     * {@link ezcTemplateConfiguration::customFunctions $customFunctions} property.
     *
     * @param string $customClass
     * @throws ezcBaseValueException if the $customClass parameter is not a
     *         string, or when the classname that it represents does not
     *         implement either the ezcTemplateCustomBlock or
     *         ezcTemplateCustomFunction interface.
     */
    public function addExtension( $customClass )
    {
        if ( !is_string( $customClass ) || !ezcBaseFeatures::classExists( $customClass, true ) )
        {
            throw new ezcBaseValueException( 'customClass', $customClass, 'string with classname that implements the ezcTemplateCustomBlock or ezcTemplateCustomFunction interface', 'argument' );
        }

        $implements = class_implements( $customClass );

        $added = false;
        if ( in_array( "ezcTemplateCustomBlock", $implements ) )
        {
            $this->properties["customBlocks"][$customClass] = $customClass;
            $added = true;
        }

        if ( in_array( "ezcTemplateCustomFunction", $implements ) )
        {
            $this->properties["customFunctions"][$customClass] = $customClass;
            $added = true;
        }

        if ( !$added )
        {
            throw new ezcBaseValueException( 'customClass', $customClass, 'string with classname that implements the ezcTemplateCustomBlock or ezcTemplateCustomFunction interface', 'argument' );
        }
    }

}
?>


text:
namespace Umbraco.Cms.Core.Models.Entities;

/// <summary>
///     Represents an entity that can be managed by the entity service.
/// </summary>
/// <remarks>
///     <para>An IUmbracoEntity can be related to another via the IRelationService.</para>
///     <para>IUmbracoEntities can be retrieved with the IEntityService.</para>
///     <para>An IUmbracoEntity can participate in notifications.</para>
/// </remarks>
public interface IUmbracoEntity : ITreeEntity
{
}


text:
package com.intellij.vcs.log.ui.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcs.log.VcsLogDataKeys;
import com.intellij.vcs.log.VcsLogUi;
import com.intellij.vcs.log.data.index.VcsLogIndex;
import com.intellij.vcs.log.history.FileHistoryUiProperties;
import com.intellij.vcs.log.impl.VcsLogManager;
import com.intellij.vcs.log.impl.VcsLogUiProperties;
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys;
import com.intellij.vcsUtil.VcsUtil;
import icons.VcsLogIcons;
import org.jetbrains.annotations.NotNull;

public class ShowOtherBranchesAction extends BooleanPropertyToggleAction {

  public ShowOtherBranchesAction() {
    super("Show All Branches", "Switch between showing only current branch and all branches", VcsLogIcons.ShowOtherBranches);
  }

  @Override
  protected VcsLogUiProperties.VcsLogUiProperty<Boolean> getProperty() {
    return FileHistoryUiProperties.SHOW_ALL_BRANCHES;
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    super.update(e);

    Project project = e.getProject();
    FilePath filePath = e.getData(VcsDataKeys.FILE_PATH);
    VcsLogManager logManager = e.getData(VcsLogInternalDataKeys.LOG_MANAGER);
    VcsLogUi logUi = e.getData(VcsLogDataKeys.VCS_LOG_UI);
    if (project != null && logManager != null && filePath != null && logUi != null) {
      VcsLogIndex index = logManager.getDataManager().getIndex();
      VirtualFile root = VcsUtil.getVcsRootFor(project, filePath);
      if (root != null && !index.isIndexed(root)) {
        e.getPresentation().setEnabled(false);
      }
    }
  }
}


text:
#import <ParseUI/PFQueryTableViewController.h>

@interface SubtitleImageTableViewController : PFQueryTableViewController

@end


text:
<?php
/**
 * Allow to override propel operation for melody specific usage
 *
 * @author Maxime Picaud
 * @since 29 août 2010
 */
class sfMelodyDoctrineOrmAdapter extends sfMelodyOrmAdapter
{
  public function findByMelody($melody)
  {
    $this->checkModels('sfGuardUser', 'findByMelody');

    $user_factory = $melody->getUserFactory();
    $config = $user_factory->getConfig();
    $user = $user_factory->getUser();
    $keys = $user_factory->getKeys();

    if (count($keys) > 0)
    {
      $q = Doctrine::getTable('sfGuardUser')
           ->createQuery('u')
           ->limit(1);

      foreach($keys as $key)
      {
        $method = 'get'.sfInflector::classify($key);
        if(is_callable(array($user, $method)))
        {
          $q->addWhere('u.'.$key.' = ?', $user->$method());
        }
      }

      return $q->fetchOne();
    }

    return false;
  }
}


text:
import Colors from '../colors';
import ColorManipulator from '../../utils/color-manipulator';
import Spacing from '../spacing';

export default {
  spacing: Spacing,
  fontFamily: 'Roboto, sans-serif',
  zIndex: {
    layer: 20,
    popover: 20,
  },
  palette: {
    primary1Color: Colors.cyan700,
    primary2Color: Colors.cyan700,
    primary3Color: Colors.grey600,
    accent1Color: Colors.pinkA200,
    accent2Color: Colors.pinkA400,
    accent3Color: Colors.pinkA100,
    textColor: Colors.fullWhite,
    alternateTextColor: '#303030',
    canvasColor: '#303030',
    borderColor: ColorManipulator.fade(Colors.fullWhite, 0.3),
    disabledColor: ColorManipulator.fade(Colors.fullWhite, 0.3),
    pickerHeaderColor: ColorManipulator.fade(Colors.fullWhite, 0.12),
    clockCircleColor: ColorManipulator.fade(Colors.fullWhite, 0.12),
  },
};


text:
/* start css.sty */
.cmex-10{font-size:83%;}
.cmssbx-10x-x-120{ font-family: sans-serif; font-weight: bold;}
.cmssbx-10x-x-120{ font-family: sans-serif; font-weight: bold;}
.cmssbx-10x-x-248{font-size:206%; font-family: sans-serif; font-weight: bold;}
.cmssbx-10x-x-248{ font-family: sans-serif; font-weight: bold;}
.cmr-17{font-size:141%;}
.cmmi-12{font-style: italic;}
.cmtt-12{font-family: monospace;}
.cmtt-12{font-family: monospace;}
.cmtt-12{font-family: monospace;}
.cmbx-12{ font-weight: bold;}
.cmti-12{ font-style: italic;}
.cmr-8{font-size:66%;}
.cmr-6{font-size:50%;}
.cmmi-8{font-size:66%;font-style: italic;}
.cmsy-8{font-size:66%;}
.cmsy-6{font-size:50%;}
.cmtt-8{font-size:66%;font-family: monospace;}
.cmtt-8{font-family: monospace;}
.cmtt-8{font-family: monospace;}
.cmtt-8x-x-75{font-size:50%;font-family: monospace;}
.cmtt-8x-x-75{font-family: monospace;}
.cmtt-8x-x-75{font-family: monospace;}
p.noindent { text-indent: 0em }
td p.noindent { text-indent: 0em; margin-top:0em; }
p.nopar { text-indent: 0em; }
p.indent{ text-indent: 1.5em }
@media print {div.crosslinks {visibility:hidden;}}
a img { border-top: 0; border-left: 0; border-right: 0; }
center { margin-top:1em; margin-bottom:1em; }
td center { margin-top:0em; margin-bottom:0em; }
.Canvas { position:relative; }
img.math{vertical-align:middle;}
li p.indent { text-indent: 0em }
li p:first-child{ margin-top:0em; }
li p:last-child, li div:last-child { margin-bottom:0.5em; }
li p~ul:last-child, li p~ol:last-child{ margin-bottom:0.5em; }
.enumerate1 {list-style-type:decimal;}
.enumerate2 {list-style-type:lower-alpha;}
.enumerate3 {list-style-type:lower-roman;}
.enumerate4 {list-style-type:upper-alpha;}
div.newtheorem { margin-bottom: 2em; margin-top: 2em;}
.obeylines-h,.obeylines-v {white-space: nowrap; }
div.obeylines-v p { margin-top:0; margin-bottom:0; }
.overline{ text-decoration:overline; }
.overline img{ border-top: 1px solid black; }
td.displaylines {text-align:center; white-space:nowrap;}
.centerline {text-align:center;}
.rightline {text-align:right;}
div.verbatim {font-family: monospace; white-space: nowrap; text-align:left; clear:both; }
.fbox {padding-left:3.0pt; padding-right:3.0pt; text-indent:0pt; border:solid black 0.4pt; }
div.fbox {display:table}
div.center div.fbox {text-align:center; clear:both; padding-left:3.0pt; padding-right:3.0pt; text-indent:0pt; border:solid black 0.4pt; }
div.minipage{width:100%;}
div.center, div.center div.center {text-align: center; margin-left:1em; margin-right:1em;}
div.center div {text-align: left;}
div.flushright, div.flushright div.flushright {text-align: right;}
div.flushright div {text-align: left;}
div.flushleft {text-align: left;}
.underline{ text-decoration:underline; }
.underline img{ border-bottom: 1px solid black; margin-bottom:1pt; }
.framebox-c, .framebox-l, .framebox-r { padding-left:3.0pt; padding-right:3.0pt; text-indent:0pt; border:solid black 0.4pt; }
.framebox-c {text-align:center;}
.framebox-l {text-align:left;}
.framebox-r {text-align:right;}
span.thank-mark{ vertical-align: super }
span.footnote-mark sup.textsuperscript, span.footnote-mark a sup.textsuperscript{ font-size:80%; }
div.tabular, div.center div.tabular {text-align: center; margin-top:0.5em; margin-bottom:0.5em; }
table.tabular td p{margin-top:0em;}
table.tabular {margin-left: auto; margin-right: auto;}
td p:first-child{ margin-top:0em; }
td p:last-child{ margin-bottom:0em; }
div.td00{ margin-left:0pt; margin-right:0pt; }
div.td01{ margin-left:0pt; margin-right:5pt; }
div.td10{ margin-left:5pt; margin-right:0pt; }
div.td11{ margin-left:5pt; margin-right:5pt; }
table[rules] {border-left:solid black 0.4pt; border-right:solid black 0.4pt; }
td.td00{ padding-left:0pt; padding-right:0pt; }
td.td01{ padding-left:0pt; padding-right:5pt; }
td.td10{ padding-left:5pt; padding-right:0pt; }
td.td11{ padding-left:5pt; padding-right:5pt; }
table[rules] {border-left:solid black 0.4pt; border-right:solid black 0.4pt; }
.hline hr, .cline hr{ height : 1px; margin:0px; }
.tabbing-right {text-align:right;}
span.TEX {letter-spacing: -0.125em; }
span.TEX span.E{ position:relative;top:0.5ex;left:-0.0417em;}
a span.TEX span.E {text-decoration: none; }
span.LATEX span.A{ position:relative; top:-0.5ex; left:-0.4em; font-size:85%;}
span.LATEX span.TEX{ position:relative; left: -0.4em; }
div.float, div.figure {margin-left: auto; margin-right: auto;}
div.float img {text-align:center;}
div.figure img {text-align:center;}
.marginpar {width:20%; float:right; text-align:left; margin-left:auto; margin-top:0.5em; font-size:85%; text-decoration:underline;}
.marginpar p{margin-top:0.4em; margin-bottom:0.4em;}
table.equation {width:100%;}
.equation td{text-align:center; }
td.equation { margin-top:1em; margin-bottom:1em; }
td.equation-label { width:5%; text-align:center; }
td.eqnarray4 { width:5%; white-space: normal; }
td.eqnarray2 { width:5%; }
table.eqnarray-star, table.eqnarray {width:100%;}
div.eqnarray{text-align:center;}
div.array {text-align:center;}
div.pmatrix {text-align:center;}
table.pmatrix {width:100%;}
span.pmatrix img{vertical-align:middle;}
div.pmatrix {text-align:center;}
table.pmatrix {width:100%;}
span.bar-css {text-decoration:overline;}
img.cdots{vertical-align:middle;}
.partToc a, .partToc, .likepartToc a, .likepartToc {line-height: 200%; font-weight:bold; font-size:110%;}
.chapterToc a, .chapterToc, .likechapterToc a, .likechapterToc, .appendixToc a, .appendixToc {line-height: 200%; font-weight:bold;}
.index-item, .index-subitem, .index-subsubitem {display:block}
div.caption {text-indent:-2em; margin-left:3em; margin-right:1em; text-align:left;}
div.caption span.id{font-weight: bold; white-space: nowrap; }
h1.partHead{text-align: center}
p.bibitem { text-indent: -2em; margin-left: 2em; margin-top:0.6em; margin-bottom:0.6em; }
p.bibitem-p { text-indent: 0em; margin-left: 2em; margin-top:0.6em; margin-bottom:0.6em; }
.paragraphHead, .likeparagraphHead { margin-top:2em; font-weight: bold;}
.subparagraphHead, .likesubparagraphHead { font-weight: bold;}
.quote {margin-bottom:0.25em; margin-top:0.25em; margin-left:1em; margin-right:1em; text-align:justify;}
.verse{white-space:nowrap; margin-left:2em}
div.maketitle {text-align:center;}
h2.titleHead{text-align:center;}
div.maketitle{ margin-bottom: 2em; }
div.author, div.date {text-align:center;}
div.thanks{text-align:left; margin-left:10%; font-size:85%; font-style:italic; }
div.author{white-space: nowrap;}
.quotation {margin-bottom:0.25em; margin-top:0.25em; margin-left:1em; }
.abstract p {margin-left:5%; margin-right:5%;}
div.abstract {width:100%;}
span.footnote-mark sup.textsuperscript, span.footnote-mark a sup.textsuperscript{ font-size:80%; }
.figure img.graphics {margin-left:10%;}
P.fancyvrb {white-space: nowrap; margin:0em;}
/* end css.sty */


text:
package com.twosigma.cook.jobclient;
import com.google.common.base.Preconditions;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * An immutable fetchable Mesos URI.
 *
 * This class represents a resource that Mesos should fetch before launching a job.
 * The resource can optionally be cached, extracted, or made executable ({@code chmod +x}).
 * By default, the resource is treated as an archive, and will be unzipped/untarred/un-whatever-ed.
 *
 * @author dgrnbrg
 */
final public class FetchableURI {

    /**
     * URI builder
     */
    public static class Builder {
        private String _value;
        private boolean _cache = false;
        private boolean _extract = true;
        private boolean _executable = false;

        public FetchableURI build() {
            Preconditions.checkNotNull(_value, "value must be set");
            Preconditions.checkArgument(!(_executable && _extract), "URI cannot be executable and extracted");
            return new FetchableURI(_value, _cache, _extract, _executable);
        }

        /**
         * Intialize this builder from the given {@link FetchableURI}
         *
         * @param uri {@link FetchableURI} specifies the uri to copy from
         * @return this builder
         */
        public Builder of(FetchableURI uri) {
            setValue(uri.getValue());
            setCache(uri.isCache());
            setExtract(uri.isExtract());
            setExecutable(uri.isExecutable());
            return this;
        }

        /**
         * Set the URI to fetch using the Mesos fetcher.
         *
         * At a minimum, you should be able to fetch from HTTP, FTP, files, and hdfs (if configured).
         *
         * @param uri The uri to fetch from
         * @return this builder
         */
        public Builder setValue(String value) {
            _value = value;
            return this;
        }

        /**
         * Configure whether to cache the given URI.
         *
         * Artifacts are cached by the user and URI; if you'll be changing the data behind the URI,
         * you should make sure to add a unique, changing hash to the URI (aka a slug).
         *
         * @param cache Whether to cache this URI
         * @return this builder
         */
        public Builder setCache(boolean cache) {
            _cache = cache;
            return this;
        }

        /**
         * Configure whether to extract the given URI.
         *
         * Mesos can extract at least .tar.gz, .zip, and .tar.bz2.
         *
         * @param cache Whether to cache this URI
         * @return this builder
         */
        public Builder setExtract(boolean extract) {
            _extract = extract;
            return this;
        }

        /**
         * Configure whether to set the given URI to be executable.
         *
         * Artifacts are cached by the user and URI; if you'll be changing the data behind the URI,
         * you should make sure to add a unique, changing hash to the URI (aka a slug).
         *
         * @param cache Whether to cache this URI
         * @return this builder
         */
        public Builder setExecutable(boolean executable) {
            _executable = executable;
            return this;
        }
    }

    private final String _value;
    private final boolean _cache;
    private final boolean _extract;
    private final boolean _executable;

    private FetchableURI(String value, boolean cache, boolean extract, boolean executable) {
        _value = value;
        _cache = cache;
        _extract = extract;
        _executable = executable;
    }

    /**
     * @return the URI
     */
    public String getValue() {
        return _value;
    }

    /**
     * @return is this URI cached?
     */
    public boolean isCache() {
        return _cache;
    }

    /**
     * @return is this URI executable?
     */
    public boolean isExecutable() {
        return _executable;
    }

    /**
     * @return is this URI going to be extracted?
     */
    public boolean isExtract() {
        return _extract;
    }

    /**
     * Convert a FetchableURI to a JSON object
     *
     * @param uri specifies the URI
     * @return a JSON object which represents the URI
     * @throws JSONException
     */
    public static JSONObject jsonizeUri(FetchableURI uri)
        throws JSONException {
        final JSONObject object = new JSONObject();
        object.put("value", uri.getValue());
        object.put("executable", uri.isExecutable());
        object.put("extract", uri.isExtract());
        object.put("cache", uri.isCache());
        return object;
    }

    /**
     * Parse a JSON object into a URI
     *
     * @param object a JSON object representing a {@link FetchableURI}
     * @return a {@link FetchableURI}
     * @throws JSONException
     */
    public static FetchableURI parseFromJSON(JSONObject object)
        throws JSONException{
        Builder builder = new Builder();
        builder.setValue(object.getString("value"));
        builder.setExtract(object.getBoolean("extract"));
        builder.setExecutable(object.getBoolean("executable"));
        builder.setCache(object.getBoolean("cache"));
        return builder.build();
    }

    @Override
    public String toString() {
        return "FetchableURI [_value=" + _value
            + ", _extract=" + _extract
            + ", _executable=" + _executable
            + ", _cache=" + _cache
            + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 37;
        int result = 1;
        result = prime * result + _value.hashCode();
        result = prime * result + (_extract ? 0 : 1);
        result = prime * result + (_executable ? 0 : 3);
        result = prime * result + (_cache ? 0 : 5);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!getClass().equals(obj.getClass()))
            return false;
        FetchableURI other = (FetchableURI) obj;
        if (_extract != other._extract)
            return false;
        if (_executable != other._executable)
            return false;
        if (_cache != other._cache)
            return false;
        if (!_value.equals(other._value))
            return false;
        return true;
    }
}


text:
package org.ndexbio.task.parsingengines;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.Test;
import org.ndexbio.common.access.NdexDatabase;
import org.ndexbio.task.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SifParserTest {

	private static final Logger logger = LoggerFactory.getLogger(SifParserTest.class);

/*	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
//		db = NdexAOrientDBConnectionPool.getInstance().acquire();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
//		db.close();
	}
*/
/*
	@Test
	public void URITest () throws URISyntaxException {
		URI termStringURI = new URI("http://www.foo.bar.org/testpath/something#NW223");
		String scheme = termStringURI.getScheme();
		System.out.println(scheme);
		String p = termStringURI.getSchemeSpecificPart();
		System.out.println(p);
		String f = termStringURI.getFragment();
		System.out.println(f);

	}
*/
	@Test
	public void test() throws Exception {
    	// read configuration
    	Configuration configuration = Configuration.getInstance();

    	//and initialize the db connections
    	NdexDatabase db = NdexDatabase.createNdexDatabase(configuration.getHostURI(),
				configuration.getDBURL(),
    			configuration.getDBUser(),
    			configuration.getDBPasswd(), 1);

		String userAccount = "reactomeadmin";
		SifParser parser = new SifParser("ca-calmodulin-dependent_protein_kinase_activation.SIF", userAccount,
				db,"ca-calmodulin-dependent_protein_kinase_activation", "");
		parser.parseFile();
		parser = new SifParser("gal-filtered.sif", userAccount,db,"gal-filtered", "");
		parser.parseFile();

		parser = new SifParser("Calcineurin-regulated_NFAT-dependent_transcription_in_lymphocytes.SIF",userAccount,
				db,"Calcineurin-regulated_NFAT-dependent_transcription_in_lymphocytes", "");
		parser.parseFile();

		try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(
				Paths.get("/home/chenjing/working/ndex/networks/reactome46_human")))
		{
            for (Path path : directoryStream) {
              logger.info("Processing file " +path.toString());
              SifParser parser2 = new SifParser(path.toString(),userAccount,db, path.toString(), "");
         		parser2.parseFile();

  			 logger.info("file upload for  " + path.toString() +" finished.");
            }
        } catch (IOException | IllegalArgumentException e) {
        	logger.error(e.getMessage());
        	throw e;
        }

		db.close();

	}

}


text:
package org.gwtproject.core.client;

import elemental2.dom.DomGlobal;
import elemental2.dom.Window;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsType;
import jsinterop.base.Js;

/**
 * Supports core functionality that in some cases requires direct support from the compiler and
 * runtime systems such as runtime type information and deferred binding.
 */
public final class GWT {

  /**
   * This interface is used to catch exceptions at the "top level" just before they escape to the
   * browser. This is used in places where the browser calls into user code such as event callbacks,
   * timers, and RPC.
   *
   *
In Development Mode, the default handler prints a stack trace to the log window. In
   * Production Mode, the default handler is null and thus exceptions are allowed to escape, which
   * provides an opportunity to use a JavaScript debugger.
   */
  public interface UncaughtExceptionHandler {
    void onUncaughtException(Throwable e);
  }

  private static UncaughtExceptionHandler uncaughtExceptionHandler = null;
  private static boolean onErrorInitialized;

  @Deprecated
  public static <T> T create(Class<?> clazz) {
    return org.gwtproject.core.shared.GWT.create(clazz);
  }

  /**
   * Throws an exception so that it is handled by the browser, but doesn't interrupt the execution
   * of this iteration of the event loop.
   *
   * @param e the exception to report to the browser
   */
  @Deprecated
  public static void reportUncaughtException(Throwable e) {
    // throw an exception "later" so that it ends up handled by the global
    // error handler. Same code as in GWT2's Impl.reportToBrowser()
    DomGlobal.setTimeout(
        ignore -> {
          throw_(e);
        },
        0);
  }

  /**
   * Returns the currently active uncaughtExceptionHandler.
   *
   * @return the currently active handler, or null if no handler is active.
   * @see #reportUncaughtException(Throwable)
   */
  public static UncaughtExceptionHandler getUncaughtExceptionHandler() {
    return uncaughtExceptionHandler;
  }

  /**
   * Sets a custom uncaught exception handler. See {@link #getUncaughtExceptionHandler()} for
   * details.
   *
   * @param handler the handler that should be called when an exception is about to escape to the
   *     browser, or null to clear the handler and allow exceptions to escape.
   */
  public static void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
    uncaughtExceptionHandler = handler;
    if (handler == null) {
      return;
    }
    if (onErrorInitialized) {
      return;
    }
    onErrorInitialized = true;

    // transliterated from gwt2's Impl.registerWindowOnError
    Window.OnerrorFn errorHandler =
        (msg, url, line, column, error) -> {
          if (uncaughtExceptionHandler == null) {
            return null;
          }
          // IE8, IE9, IE10, safari 9, do not have an error passed. While
          // we don't necessarily support these browsers, when chasing an
          // error there is already enough frustration, so we'll still
          // synthesize a new one

          if (error == null) {
            String errorString = msg + " (" + url + ":" + line;
            // IE8 and IE9 do not have the column number
            if (Js.asAny(column) == null) {
              errorString += ":" + column;
            }
            errorString += ")";
            uncaughtExceptionHandler.onUncaughtException(fromObject(errorString));

          } else {
            uncaughtExceptionHandler.onUncaughtException(fromObject(error));
          }

          return null;
        };

    addOnErrorHandler(DomGlobal.window, errorHandler);
    if (DomGlobal.window != InnerWindow.window) {
      // if the local window is the same as the global one (SSO linker in gwt2, or default in j2cl)
      // we skip this
      addOnErrorHandler(InnerWindow.window, errorHandler);
    }
  }

  /**
   * Appends a new onerror handler so that both original and new are called, or just assigns the new
   * one if there was no existing one.
   */
  private static void addOnErrorHandler(Window window, Window.OnerrorFn onerrorFn) {
    Window.OnerrorFn original = window.onerror;
    if (original == null) {
      window.onerror = onerrorFn;
    }
    window.onerror =
        (p0, p1, p2, p3, p4) -> {
          onerrorFn.onInvoke(p0, p1, p2, p3, p4);
          original.onInvoke(p0, p1, p2, p3, p4);
          return null;
        };
  }

  /**
   * Ugly hack to let j2cl and gwt both call the fake method Throwable.of, which only exists in our
   * emul code, not in the proper JRE.
   */
  @JsMethod
  private static native Throwable fromObject(Object obj) /*-{
    //GWT2 impl using JSNI, see GWT.native.js for the j2cl impl
    var throwable = @java.lang.Throwable::of(*)(obj);
  }-*/;

  @JsType(isNative = true, name = "window", namespace = "<window>")
  private static class InnerWindow {
    static Window window;
  }

  @JsMethod(namespace = "<window>", name = "throw")
  private static native void throw_(Object object);

  public static boolean isClient() {
    return org.gwtproject.core.shared.GWT.isClient();
  }

  public static boolean isProdMode() {
    return org.gwtproject.core.shared.GWT.isProdMode();
  }

  public static boolean isScript() {
    return org.gwtproject.core.shared.GWT.isScript();
  }

  public static void log(String message) {
    org.gwtproject.core.shared.GWT.log(message);
  }

  public static void log(String message, Throwable e) {
    org.gwtproject.core.shared.GWT.log(message, e);
  }

  public static void debugger() {
    org.gwtproject.core.shared.GWT.debugger();
  }

  public static void runAsync(Class<?> name, Object ignore) {
    throw new UnsupportedOperationException(
        "Pick either GWT2 split point or Closure-Compiler chunks");
  }

  public static void runAsync(Object ignore) {
    throw new UnsupportedOperationException(
        "Pick either GWT2 split point or Closure-Compiler chunks");
  }
}


text:
.. _API_ops:

Interval operations
===================

.. automodule:: bioframe.ops
   :autosummary:
   :members:


text:
package org.switchyard.quickstarts.soap.attachment;

import javax.inject.Named;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

@Named("internalCustomProcessor")
public class InternalCustomProcessor implements Processor {

    /**
     * Creates new processor.
     */
    public InternalCustomProcessor() {
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        String newFileName = "internal-switchyard.png";
        exchange.getOut().addAttachment(newFileName, exchange.getIn().getAttachment(exchange.getIn().getBody(String.class)));
        exchange.getOut().setBody(newFileName);
    }

}


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Articulate")]
[assembly: AssemblyDescription("Blogging for Umbraco")]
[assembly: AssemblyProduct("Articulate")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e8328f5-ce8d-4300-8509-97b3a39e1810")]

[assembly: InternalsVisibleTo("Articulate.Console")]


text:
import requests, urllib, urllib.request, re
import os, sys, time
from imgurpython import ImgurClient

counter = 0

def getPosts(subreddit, postLimit):
	url = 'http://www.reddit.com/r/' + subreddit + '/.json?limit=' + str(postLimit)
	headers = {
		'User-Agent': 'Reddit Image Scraper 1.1'
	}
	r = requests.get(url, headers=headers)
	if r.status_code == requests.codes.ok:
		data = r.json()
		print('Sleeping for 3 seconds...\n')
		time.sleep(3)
		return data['data']['children']
	else:
		print('Sorry, but there was an error retrieving the subreddit\'s data!')
		return None

def saveImages(posts, scoreLimit, save_dir='scraped_wallpapers'):
	for post in posts:
		url = post['data']['url']
		score = post['data']['score']
		title = post['data']['title']
		if 'http://i.imgur.com' in url and score > scoreLimit:
			saveImage(url, title, save_dir)
		elif 'http://imgur.com/a/' in url and score > scoreLimit:
			saveAlbum(url, save_dir)

def saveImage(url, title, save_dir):
	global counter
	save_dir = makeSaveDir(save_dir)
	title = re.sub(r'\W+', '', title)
	dot_location = url.rfind('.')
	filename = (save_dir + title.replace('/', ':') + url[dot_location: dot_location + 4]).encode('utf-8')
	if not os.path.exists(filename):
		print('Saving ' + filename.decode('utf-8') + '!\n')
		counter += 1
		urllib.request.urlretrieve(url, filename)

def saveAlbum(url, save_dir):
	#Sign up for an imgur api here (Oauth with no callback) and paste your keys here
	client_id = 'REDACTED'
	client_secret = 'REDACTED'
	icounter = 0

	client = ImgurClient(client_id, client_secret)

	if '/#0' in url:
	    url = url[:-3]

	album_id = url.split('/')[-1]

	if '#' in album_id:
	    album_id = album_id[:5]

	print(url)
	print(album_id)

	album_title = client.get_album(album_id).title
	if album_title is None:
		album_title = 'Untitled ' + album_id

	print(album_title)

	album_title = album_title.replace(' ', '')
	album_title = re.sub(r'\W+', '', album_title)

	save_dir = save_dir + '/' + album_title
	if not os.path.exists(save_dir):
		os.makedirs(save_dir)

	for image in client.get_album_images(album_id):
		icounter += 1
		title = album_title + '_' + str(icounter)
		saveImage(image.link, title, save_dir)

def makeSaveDir(dir):
	if not os.path.exists(dir):
		 os.makedirs(dir)
	return dir + '/'

def downloadImagesFromReddit(subreddits, postLimit=100, scoreLimit=10):
	for subreddit in subreddits:
		posts = getPosts(subreddit, postLimit)
		saveImages(posts, scoreLimit, subreddit.lower())
	print(str(counter) + ' images have been scraped!')

def main():
    if len(sys.argv) > 1:
	    downloadImagesFromReddit(sys.argv[1:])
    else:
	    downloadImagesFromReddit([
		    'wallpapers'
	    ])

if __name__ == '__main__':
	main()


text:
description("Test for page-break-inside:avoid");

function test()
{
    createBlockWithRatioToPageHeight("page1-1", 0.5).style.pageBreakBefore = "always";
    // block 'page1-2' should be splitted.
    createBlockWithNumberOfLines("page1-2", 20);
    createBlockWithRatioToPageHeight("page2", 0.1);

    createBlockWithRatioToPageHeight("page3", 0.5).style.pageBreakBefore = "always";
    // We should place block 'page4' in the next page because of 'page-break-inside: avoid'.
    createBlockWithNumberOfLines("page4", 20).style.pageBreakInside = "avoid";

    createBlockWithRatioToPageHeight("page5", 0.8).style.pageBreakBefore = "always";
    // block 'page5-2' is a very large block, occupying more than 2 pages.
    // We don't define from where this large block starts. Maybe from the next page.
    createBlockWithNumberOfLines("page5or6", 20 * 2 + 10).style.pageBreakInside = "avoid";
    createBlockWithRatioToPageHeight("page8", 0.1);

    createBlockWithRatioToPageHeight("page9-1", 0.1).style.pageBreakBefore = "always";
    createBlockWithRatioToPageHeight("page9-2", 0.1).style.pageBreakAfter = "always";
    // Make sure page-break only happens once, not twice.
    createBlockWithNumberOfLines("page10", 20).style.pageBreakInside = "avoid";

    pageNumberForElementShouldBe('page1-1', 1);
    pageNumberForElementShouldBe('page1-2', 1);
    pageNumberForElementShouldBe('page2', 2);

    pageNumberForElementShouldBe('page3', 3);
    pageNumberForElementShouldBe('page4', 4);

    pageNumberForElementShouldBe('page5', 5);
    pageNumberForElementShouldBe('page8', 8);

    pageNumberForElementShouldBe('page9-1', 9);
    pageNumberForElementShouldBe('page9-2', 9);
    pageNumberForElementShouldBe('page10', 10);

    document.body.removeChild(document.getElementById("sandbox"));
}

var successfullyParsed = true;


text:
<component name="libraryTable">
  <library name="Maven: mysql:mysql-connector-java:5.1.9">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.9/mysql-connector-java-5.1.9.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.9/mysql-connector-java-5.1.9-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.9/mysql-connector-java-5.1.9-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
require 'spec_helper'

describe User do

  it 'is available' do
    user = create(:user)
    expect(user).not_to be_nil
  end

  it 'create with omniauth without email' do
    auth = {
        'provider' => 'open_id',
        'uid' => 'xxxxxx',
        'info' => {}
    }
    created = User.create_with_omniauth(auth)
    expect(created.omniauth_provider).to eq('open_id')
    expect(created.omniauth_uid).to eq('xxxxxx')
    expect(created.email).to be_nil
    expect(created.nickname).to be_nil
  end

  it 'create with omniauth with email' do
    auth = {
        'provider' => 'open_id',
        'uid' => 'xxxxxx',
        'info' => {
          'email' => 'test@test.org'
        }
    }
    created = User.create_with_omniauth(auth)
    expect(created.omniauth_provider).to eq('open_id')
    expect(created.omniauth_uid).to eq('xxxxxx')
    expect(created.email).to eq('test@test.org')
    expect(created.nickname).to be_nil
  end

end