text:
using AutoMapper;
using ReMi.BusinessEntities.ReleaseExecution;
using ReMi.Common.Constants.ReleaseExecution;
using ReMi.Common.Constants.ReleasePlan;
using ReMi.DataEntities.Api;
using ReMi.DataEntities.Auth;
using ReMi.DataEntities.BusinessRules;
using ReMi.DataEntities.Evt;
using ReMi.DataEntities.ExecPoll;
using ReMi.DataEntities.Metrics;
using ReMi.DataEntities.ProductRequests;
using ReMi.DataEntities.Products;
using ReMi.DataEntities.ReleaseCalendar;
using ReMi.DataEntities.ReleasePlan;
using System;
using System.Linq;
using ReMi.BusinessEntities.DeploymentTool;
using ReMi.Common.Constants.ReleaseCalendar;
using ReMi.Common.Utils.Enums;
using ReMi.DataEntities.Plugins;
using ReleaseJob = ReMi.DataEntities.ReleasePlan.ReleaseJob;

namespace ReMi.DataAccess.AutoMapper
{
    public class DataEntityToBusinessEntityMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "DataEntityToBusinessEntityMapping"; }
        }

        protected override void Configure()
        {
            Mapper.CreateMap<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindow>()
                .ForMember(target => target.Products, option => option.MapFrom(source => source.ReleaseProducts.Select(o => o.Product.Description)))
                .ForMember(target => target.StartTime,
                    option => option.MapFrom(source => source.StartTime.ToLocalTime()))
                .ForMember(target => target.OriginalStartTime,
                    option => option.MapFrom(source => source.OriginalStartTime.ToLocalTime()))
                .ForMember(target => target.ApprovedOn,
                    option =>
                        option.MapFrom(
                            source =>
                                source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
                                    ? source.Metrics.First(x => x.MetricType == MetricType.Approve).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.ReleaseTypeDescription,
                    option => option.MapFrom(source => EnumDescriptionHelper.GetDescription(source.ReleaseType)))
                .ForMember(target => target.ReleaseDecision,
                    option => option.MapFrom(source => EnumDescriptionHelper.GetDescription(source.ReleaseDecision)))
                .ForMember(target => target.EndTime,
                    option =>
                        option.MapFrom(
                            source => source.Metrics.Any(x => x.MetricType == MetricType.EndTime && x.ExecutedOn.HasValue)
                                    ? source.Metrics.First(x => x.MetricType == MetricType.EndTime).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.ClosedOn,
                    option =>
                        option.MapFrom(
                            source => source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.Close && x.ExecutedOn.HasValue)
                                    ? source.Metrics.First(x => x.MetricType == MetricType.Close).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.SignedOff,
                    option =>
                        option.MapFrom(
                            source => source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.SignOff && x.ExecutedOn.HasValue)
                                    ? source.Metrics.First(x => x.MetricType == MetricType.SignOff).ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.Status, option => option.MapFrom(
                    source => !source.Metrics.Any()
                        ? EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)
                        : source.Metrics.Any(x => x.MetricType == MetricType.Close && x.ExecutedOn.HasValue)
                            ? EnumDescriptionHelper.GetDescription(ReleaseStatus.Closed)
                            : source.Metrics.Any(x => x.MetricType == MetricType.SignOff && x.ExecutedOn.HasValue)
                                ? EnumDescriptionHelper.GetDescription(ReleaseStatus.SignedOff)
                                : source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
                                    ? EnumDescriptionHelper.GetDescription(ReleaseStatus.Approved)
                                    : EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)))
                .ForMember(target => target.Issues,
                    option =>
                        option.MapFrom(
                            source => source.Metrics.Any() && source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
                                ? source.ReleaseNotes.Issues : null))
                .ForMember(target => target.ReleaseNotes, o => o.Ignore());

            Mapper.CreateMap<ReleaseWindow, BusinessEntities.ReleaseCalendar.ReleaseWindowView>()
                .ForMember(target => target.Products,
                    option => option.MapFrom(source => source.ReleaseProducts.Select(o => o.Product.Description)))
                .ForMember(target => target.StartTime,
                    option => option.MapFrom(source => source.StartTime.ToLocalTime()))
                .ForMember(target => target.EndTime,
                    option =>
                        option.MapFrom(
                            source =>
                                source.Metrics.Any(x => x.MetricType == MetricType.EndTime && x.ExecutedOn.HasValue)
                                    ? source.Metrics.First(x => x.MetricType == MetricType.EndTime)
                                        .ExecutedOn.Value.ToLocalTime()
                                    : (DateTime?) null))
                .ForMember(target => target.Status, option => option.MapFrom(
                    source => !source.Metrics.Any()
                        ? EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)
                        : source.Metrics.Any(x => x.MetricType == MetricType.Close && x.ExecutedOn.HasValue)
                            ? EnumDescriptionHelper.GetDescription(ReleaseStatus.Closed)
                            : source.Metrics.Any(x => x.MetricType == MetricType.SignOff && x.ExecutedOn.HasValue)
                                ? EnumDescriptionHelper.GetDescription(ReleaseStatus.SignedOff)
                                : source.Metrics.Any(x => x.MetricType == MetricType.Approve && x.ExecutedOn.HasValue)
                                    ? EnumDescriptionHelper.GetDescription(ReleaseStatus.Approved)
                                    : EnumDescriptionHelper.GetDescription(ReleaseStatus.Opened)))
                .ForMember(target => target.IsMaintenance,
                    options => options.MapFrom(source => source.ReleaseType.ToEnumDescription<ReleaseType, ReleaseTypeDescription>().IsMaintenance));

            Mapper.CreateMap<CommandExecution, BusinessEntities.ExecPoll.CommandExecution>()
                .ForMember(
                    target => target.State,
                    option => option.MapFrom(source => source.CommandHistory.LastOrDefault() != null ?
                        (BusinessEntities.ExecPoll.CommandStateType)((int)source.CommandHistory.Last().State) :
                        BusinessEntities.ExecPoll.CommandStateType.NotRegistered))
                .ForMember(
                    target => target.Details,
                    option => option.MapFrom(source =>
                        source.CommandHistory.LastOrDefault() != null ? source.CommandHistory.Last().Details : null));

            Mapper.CreateMap<Role, BusinessEntities.Auth.Role>();

            Mapper.CreateMap<Account, BusinessEntities.Auth.Account>()
                .ForMember(target => target.Products,
                option => option.MapFrom(source => source.AccountProducts == null || !source.AccountProducts.Any() ?
                    Enumerable.Empty<BusinessEntities.Products.ProductView>() :
                    source.AccountProducts.Select(Mapper.Map<AccountProduct, BusinessEntities.Products.ProductView>).ToArray()));

            Mapper.CreateMap<Session, BusinessEntities.Auth.Session>()
                .ForMember(target => target.AccountId, option => option.MapFrom(source => source.Account.ExternalId));

            Mapper.CreateMap<Event, BusinessEntities.Evt.Event>()
                .ForMember(target => target.State, option => option.MapFrom(source => source.EventHistory.LastOrDefault() != null ? source.EventHistory.Last().State : EventStateType.NotRegistered));

            Mapper.CreateMap<ReleaseTask, BusinessEntities.ReleasePlan.ReleaseTaskView>()
                .ForMember(target => target.ReleaseWindowId, option => option.MapFrom(x => x.ReleaseWindow.ExternalId))
                .ForMember(target => target.CreatedBy, option => option.MapFrom(source => source.CreatedBy.FullName))
                .ForMember(target => target.CompletedOn,
                    option =>
                        option.MapFrom(
                            source =>
                                source.CompletedOn != null ? source.CompletedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.Assignee, option => option.MapFrom(source => source.Assignee.FullName))
                .ForMember(target => target.AssigneeExternalId,
                    option => option.MapFrom(source => source.Assignee.ExternalId))
                .ForMember(target => target.ReceiptConfirmedOn,
                    option =>
                        option.MapFrom(
                            source => source.ReceiptConfirmedOn == null ? (DateTime?)null : source.ReceiptConfirmedOn.Value.ToLocalTime()))
                ;

            Mapper.CreateMap<ReleaseTask, BusinessEntities.ReleasePlan.ReleaseTask>()
                .ForMember(target => target.ReleaseWindowId, option => option.MapFrom(x => x.ReleaseWindow.ExternalId))
                .ForMember(target => target.CreatedBy, option => option.MapFrom(source => source.CreatedBy != null ? source.CreatedBy.FullName : null))
                .ForMember(target => target.CreatedByExternalId, option => option.MapFrom(source => source.CreatedBy != null ? source.CreatedBy.ExternalId : (Guid?)null))
                .ForMember(target => target.CreatedOn, option => option.MapFrom(source => source.CreatedOn.ToLocalTime()))
                .ForMember(target => target.CompletedOn, option => option.MapFrom(source => source.CompletedOn != null ? source.CompletedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.Assignee, option => option.MapFrom(source => source.Assignee != null ? source.Assignee.FullName : null))
                .ForMember(target => target.HelpDeskTicketReference, option => option.MapFrom(source => source.HelpDeskReference))
                .ForMember(target => target.HelpDeskTicketUrl, option => option.MapFrom(source => source.HelpDeskUrl))
                .ForMember(target => target.AssigneeExternalId, option => option.MapFrom(source => source.Assignee != null ? source.Assignee.ExternalId : (Guid?)null));

            Mapper.CreateMap<ReleaseTaskAttachment, BusinessEntities.ReleasePlan.ReleaseTaskAttachment>()
                .ForMember(x => x.ReleaseTaskId, o => o.Ignore());

            Mapper.CreateMap<ReleaseTaskAttachment, BusinessEntities.ReleasePlan.ReleaseTaskAttachmentView>()
                .ForMember(x => x.ServerName, o => o.Ignore())
                .ForMember(x => x.Size, o => o.MapFrom(source => source.Attachment.Length))
                .ForMember(x => x.Type, o => o.Ignore());

            Mapper.CreateMap<Product, BusinessEntities.Products.Product>();

            Mapper.CreateMap<BusinessUnit, BusinessEntities.Products.BusinessUnit>()
                .ForMember(target => target.Packages, option => option.Ignore());

            Mapper.CreateMap<AccountProduct, BusinessEntities.Products.ProductView>()
                .ForMember(target => target.Name, option => option.MapFrom(source => source.Product.Description))
                .ForMember(target => target.ExternalId, option => option.MapFrom(source => source.Product.ExternalId));

            Mapper.CreateMap<Product, BusinessEntities.Products.ProductView>()
                .ForMember(target => target.Name, option => option.MapFrom(source => source.Description));

            Mapper.CreateMap<ReleaseApprover, BusinessEntities.ReleasePlan.ReleaseApprover>()
                .ForMember(target => target.ApprovedOn, option => option.MapFrom(source => source.ApprovedOn.HasValue ? source.ApprovedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.Account, option => option.MapFrom(source => source.Account))
                .ForMember(target => target.ReleaseWindowId, option => option.MapFrom(source => source.ReleaseWindow.ExternalId));

            Mapper.CreateMap<ReleaseContent, BusinessEntities.ReleasePlan.ReleaseContentTicket>()
                .ForMember(target => target.TicketId, option => option.MapFrom(source => source.TicketId))
                .ForMember(target => target.Risk, option => option.MapFrom(source => source.TicketRisk))
                .ForMember(target => target.TicketDescription, option => option.MapFrom(source => source.Description))
                .ForMember(target => target.TicketName, option => option.MapFrom(source => source.TicketKey))
                .ForMember(target => target.LastChangedByAccount, option => option.MapFrom(source => source.LastChangedByAccount.ExternalId));

            Mapper.CreateMap<Command, BusinessEntities.Api.Command>()
                .ForMember(target => target.Description, option => option.MapFrom(source => source.Description))
                .ForMember(target => target.Group, option => option.MapFrom(source => source.Group))
                .ForMember(target => target.IsBackground, option => option.MapFrom(source => source.IsBackground))
                .ForMember(target => target.Name, option => option.MapFrom(source => source.Name))
                .ForMember(target => target.Roles, option => option.MapFrom(source => source.CommandPermissions.Select(x => x.Role)))
                .ForMember(target => target.HasRuleApplied, option => option.MapFrom(source => source.Rule != null))
                .ForMember(target => target.Description, option => option.MapFrom(source => source.Description));

            Mapper.CreateMap<Query, BusinessEntities.Api.Query>()
                .ForMember(target => target.Description, option => option.MapFrom(source => source.Description))
                .ForMember(target => target.Group, option => option.MapFrom(source => source.Group))
                .ForMember(target => target.IsStatic, option => option.MapFrom(source => source.IsStatic))
                .ForMember(target => target.Name, option => option.MapFrom(source => source.Name))
                .ForMember(target => target.Roles, option => option.MapFrom(source => source.QueryPermissions.Select(x => x.Role)))
                .ForMember(target => target.HasRuleApplied, option => option.MapFrom(source => source.Rule != null))
                .ForMember(target => target.Description, option => option.MapFrom(source => source.Description));

            Mapper.CreateMap<Role, BusinessEntities.Auth.Role>();
            Mapper.CreateMap<DataEntities.ReleaseExecution.SignOff, SignOff>()
                .ForMember(target => target.Signer, option => option.MapFrom(source => source.Account))
                .ForMember(target => target.SignedOff, option => option.MapFrom(source => source.SignedOff.HasValue));
            Mapper.CreateMap<Metric, BusinessEntities.Metrics.Metric>()
                .ForMember(target => target.ExecutedOn,
                    option =>
                        option.MapFrom(
                            source =>
                                source.ExecutedOn != null ? source.ExecutedOn.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.Order,
                    option =>
                        option.MapFrom(
                            source => EnumDescriptionHelper.GetOrder(source.MetricType)));

            Mapper.CreateMap<ReleaseJob, BusinessEntities.DeploymentTool.ReleaseJob>();

            Mapper.CreateMap<ReleaseDeploymentMeasurement, JobMeasurement>()
                .ForMember(target => target.ChildSteps, option => option.Ignore())
                .ForMember(target => target.StartTime, option => option.MapFrom(source => source.StartTime != null ? source.StartTime.Value.ToLocalTime() : (DateTime?)null))
                .ForMember(target => target.FinishTime, option => option.MapFrom(source => source.FinishTime != null ? source.FinishTime.Value.ToLocalTime() : (DateTime?)null));

            Mapper.CreateMap<BusinessRuleParameter, BusinessEntities.BusinessRules.BusinessRuleParameter>();
            Mapper.CreateMap<BusinessRuleTestData, BusinessEntities.BusinessRules.BusinessRuleTestData>();
            Mapper.CreateMap<BusinessRuleDescription, BusinessEntities.BusinessRules.BusinessRuleDescription>();
            Mapper.CreateMap<BusinessRuleAccountTestData, BusinessEntities.BusinessRules.BusinessRuleAccountTestData>();
            Mapper.CreateMap<BusinessRuleDescription, BusinessEntities.BusinessRules.BusinessRuleView>()
                .ForMember(target => target.CodeBeggining,
                    option => option.MapFrom(source => string.IsNullOrEmpty(source.Script)
                        ? string.Empty
                        : source.Script.Length >= 30 ? source.Script.Substring(0, 30) + " ..." : source.Script));

            Mapper.CreateMap<ProductRequestGroupAssignee, BusinessEntities.Auth.Account>()
                .ConvertUsing(requestAssignee => Mapper.Map<Account, BusinessEntities.Auth.Account>(requestAssignee.Account));

            Mapper.CreateMap<ProductRequestType, BusinessEntities.ProductRequests.ProductRequestType>();
            Mapper.CreateMap<ProductRequestGroup, BusinessEntities.ProductRequests.ProductRequestGroup>()
                .ForMember(target => target.ProductRequestTypeId, option => option.MapFrom(source => source.RequestType.ExternalId))
                .ForMember(target => target.Assignees, option => option.MapFrom(source => source.Assignees));
            Mapper.CreateMap<ProductRequestTask, BusinessEntities.ProductRequests.ProductRequestTask>()
                .ForMember(target => target.ProductRequestGroupId, option => option.MapFrom(source => source.RequestGroup.ExternalId));

            Mapper.CreateMap<ProductRequestRegistrationTask, BusinessEntities.ProductRequests.ProductRequestRegistrationTask>()
                .ForMember(target => target.ProductRequestTaskId, option => option.MapFrom(source => source.ProductRequestTask.ExternalId))
                .ForMember(target => target.LastChangedByAccountId, option => option.MapFrom(source => source.LastChangedBy != null ? source.LastChangedBy.ExternalId : new Guid?()))
                .ForMember(target => target.LastChangedBy, option => option.MapFrom(source => source.LastChangedBy != null ? source.LastChangedBy.FullName : null))
                .ForMember(target => target.LastChangedOn, option => option.MapFrom(source => source.LastChangedOn.HasValue ? source.LastChangedOn.Value.ToLocalTime() : new DateTime?()));

            Mapper.CreateMap<ProductRequestRegistration, BusinessEntities.ProductRequests.ProductRequestRegistration>()
                .ForMember(target => target.ProductRequestTypeId, option => option.MapFrom(source => source.ProductRequestType.ExternalId))
                .ForMember(target => target.ProductRequestType, option => option.MapFrom(source => source.ProductRequestType.Name))
                .ForMember(target => target.CreatedByAccountId, option => option.MapFrom(source => source.CreatedBy.ExternalId))
                .ForMember(target => target.CreatedBy, option => option.MapFrom(source => source.CreatedBy.FullName))
                .ForMember(target => target.CreatedOn, option => option.MapFrom(source => source.CreatedOn.ToLocalTime()))
                .ForMember(target => target.Status, option => option.ResolveUsing<TasksToProductRequestRegistrationStatusResolver>().FromMember(source => source.Tasks));

            Mapper.CreateMap<PluginConfiguration, BusinessEntities.Plugins.GlobalPluginConfiguration>()
                .ForMember(target => target.PluginId, option => option.MapFrom(source => source.Plugin != null ? source.Plugin.ExternalId : (Guid?)null));

            Mapper.CreateMap<PluginPackageConfiguration, BusinessEntities.Plugins.PackagePluginConfiguration>()
                .ForMember(target => target.PackageId, option => option.MapFrom(source => source.Package.ExternalId))
                .ForMember(target => target.PackageName, option => option.MapFrom(source => source.Package.Description))
                .ForMember(target => target.BusinessUnit, option => option.MapFrom(source => source.Package.BusinessUnit.Description))
                .ForMember(target => target.PluginId, option => option.MapFrom(source => source.Plugin != null ? source.Plugin.ExternalId : (Guid?)null));

            Mapper.CreateMap<DataEntities.Plugins.Plugin, BusinessEntities.Plugins.Plugin>()
                .ForMember(target => target.PluginId, option => option.MapFrom(source => source.ExternalId))
                .ForMember(target => target.PluginKey, option => option.MapFrom(source => source.Key))
                .ForMember(target => target.PluginTypes,
                    option => option.MapFrom(source => source.PluginType.ToFlagList()));
        }
    }

}


text:
describe('Notification', function() {
  let modules = {
    module1: null,
    module2: null,
  }

  beforeEach(() => {
    const container1Id = 'notifications-container'
    addHtmlSnippet(container1Id)
    modules.module1 = new MNModule({
      container: `#${container1Id}`,
      onNotificationsCountChange: function(number) {
        console.info('Number of notifs = ' + number)
      },
    })

    const container2Id = 'notifications-container2'
    addHtmlSnippet(container2Id)
    modules.module2 = new MNModule({
      container: `#${container2Id}`,
    })
  })

  it('should be able to be pushed to module', function() {
    const testNotifsOptions = [
      {
        title: 'title1',
        message: 'message1',
        icon: 'music',
        closeInMS: 5000,
        type: 'info',
        template: () => {
          return '

'
        },
      },
      {
        title: 'title2',
        message: 'message2',
        icon: 'music',
        closeInMS: 6000,
        type: 'success',
        template: () => {
          return '

'
        },
      },
      {
        title: 'title3',
        message: 'message3',
        icon: 'ok-sign',
        closeInMS: 7000,
        type: 'success',
        template: () => {
          return '

'
        },
      },
    ]

    for (let i = 0; i < testNotifsOptions.length; i++) {
      const testNotifOptions = testNotifsOptions[i]
      //push notif
      const notif = modules.module1.pushNotification(testNotifOptions)
      //check if ref is not null
      expect(notif).not.toBeNull()
      //check if notif was pushed with specified params
      // const { mode, ...options } = notif.options;
      // expect(options).toEqual(testNotifOptions);
    }
  })

  it('should be able to be pushed to specified group', function() {
    const testNotifsOptions = [
      {
        groupId: 'common1',
        expectedNumberOfNotifsAfterPushing: 1,
      },
      {
        groupId: 'common2',
        expectedNumberOfNotifsAfterPushing: 1,
      },
      {
        groupId: 'common2',
        expectedNumberOfNotifsAfterPushing: 2,
      },
      {
        groupId: 'common3',
        expectedNumberOfNotifsAfterPushing: 1,
      },
      {
        groupId: 'common3',
        expectedNumberOfNotifsAfterPushing: 2,
      },
    ]

    for (let i = 0; i < testNotifsOptions.length; i++) {
      const testNotifOptions = testNotifsOptions[i]
      //push notif
      const notif = modules.module1.pushNotification(testNotifOptions)
      //check if notif was pushed to appropriate group
      expect(
        groupUtils
          .getGroupById(modules.module1, testNotifOptions.groupId)
          ._getLength()
      ).toEqual(testNotifOptions.expectedNumberOfNotifsAfterPushing)
    }
  })

  it('should be able to be pushed to greedy group only ones', function() {
    const greedyGroupName = 'some greedy group'
    const greedyGroupOptions = {
      id: greedyGroupName,
      greedy: true,
    }
    modules.module1.createEmptyGroup(greedyGroupOptions)

    const testNotifsOptions = [
      {
        groupId: greedyGroupName,
        expectedNumberOfNotifsAfterPushing: 1,
        isResultNull: false,
      },
      {
        groupId: greedyGroupName,
        expectedNumberOfNotifsAfterPushing: 1,
        isResultNull: true,
      },
    ]

    for (let i = 0; i < testNotifsOptions.length; i++) {
      const testNotifOptions = testNotifsOptions[i]
      //push notif
      const notif = modules.module1.pushNotification(testNotifOptions)
      //check the size of the group
      expect(
        groupUtils
          .getGroupById(modules.module1, testNotifOptions.groupId)
          ._getLength()
      ).toEqual(testNotifOptions.expectedNumberOfNotifsAfterPushing)
      //check returned result
      expect(notif == null).toEqual(testNotifOptions.isResultNull)
    }
  })

  it('should be able to be pulled', function() {
    const numberOfNotifsToCreate = 10
    for (let i = 0; i < numberOfNotifsToCreate.length; i++) {
      //push notif
      const notif = modules.module1.pushNotification({ closeInMS: false })
      //check the number of notifs after pushing
      const expectedNumberOfNotifsAfterPushing = 1
      expect(modules.module1.notificationsCount).toEqual(
        expectedNumberOfNotifsAfterPushing
      )
      //remove notif
      notif.remove()
      //check the number of notifs after pulling
      const expectedNumberOfNotifsAfterPulling = 0
      expect(modules.module1.notificationsCount).toEqual(
        expectedNumberOfNotifsAfterPulling
      )
    }
    expect(modules.module1.notificationsCount).toEqual(0)
  })

  function pushNotifs(notifsCount, groupId, module) {
    for (let i = 0; i < notifsCount; i++) {
      module.pushNotification({
        groupId: groupId,
        closeInMS: false,
      })
    }
  }

  it('should be able to be pulled from group', function() {
    const numberOfNotifsInFirstGroup = 10
    const numberOfNotifsInSecondGroup = 20
    const firstGroupName = 'first group'
    const secondGroupName = 'second group'
    const groups = {
      [firstGroupName]: {
        count: numberOfNotifsInFirstGroup,
      },
      [secondGroupName]: {
        count: numberOfNotifsInSecondGroup,
      },
    }
    pushNotifs(numberOfNotifsInFirstGroup, firstGroupName, modules.module1)
    pushNotifs(numberOfNotifsInSecondGroup, secondGroupName, modules.module1)
    //check total number of notifs
    expect(modules.module1.notificationsCount).toEqual(
      numberOfNotifsInFirstGroup + numberOfNotifsInSecondGroup
    )

    //check number of notifs in first group
    for (let group of groupUtils.getGroups(modules.module1)) {
      expect(group._getLength()).toEqual(groups[group.__getId()].count)
    }

    //remove notifs of first group
    modules.module1.removeNotifications(firstGroupName)
    wait(getRemoveWaitingTimeMSByGroupId(modules.module1, firstGroupName)).then(
      () => {
        //check number of notifs of module
        expect(modules.module1.notificationsCount).toEqual(
          numberOfNotifsInSecondGroup
        )
        //remove notifs of second group
        modules.module1.removeNotifications(secondGroupName)
        wait(
          getRemoveWaitingTimeMSByGroupId(modules.module1, secondGroupName)
        ).then(() => {
          //check number of notifs of module
          expect(modules.module1.notificationsCount).toEqual(0)
        })
      }
    )
  })

  it('should be able to be pulled from module (all notifs)', function() {
    const numberOfNotifsInFirstGroup = 10
    const numberOfNotifsInSecondGroup = 20
    const firstGroupName = 'first group'
    const secondGroupName = 'second group'

    pushNotifs(numberOfNotifsInFirstGroup, firstGroupName, modules.module1)
    pushNotifs(numberOfNotifsInSecondGroup, secondGroupName, modules.module1)
    pushNotifs(numberOfNotifsInFirstGroup, firstGroupName, modules.module2)
    pushNotifs(numberOfNotifsInSecondGroup, secondGroupName, modules.module2)

    //remove notifs from first group
    modules.module1.removeNotifications()

    //check if second group is ok
    expect(modules.module2.notificationsCount).toEqual(
      numberOfNotifsInFirstGroup + numberOfNotifsInSecondGroup
    )

    //remove notifs from second group
    modules.module2.removeNotifications()

    wait(
      Math.max(
        getRemoveWaitingTimeMS(modules.module1),
        getRemoveWaitingTimeMS(modules.module2)
      )
    ).then(() => {
      expect(modules.module1.notificationsCount).toEqual(0)
      expect(modules.module2.notificationsCount).toEqual(0)
    })
  })
})

redpajama_set_name: RedPajamaGithub


text:
#include <sys/poll.h>
#include <stdlib.h>

#ifdef HAVE_CONFIG_H
#  include <dtn-config.h>
#endif

// If ax25 support found at configure time...
#ifdef OASYS_AX25_ENABLED

#include <oasys/io/NetUtils.h>
#include <oasys/util/OptParser.h>
#include <oasys/util/HexDumpBuffer.h>
#include <oasys/util/CRC32.h>

#include "AX25CMConvergenceLayer.h"
#include "IPConvergenceLayerUtils.h"
#include "bundling/BundleDaemon.h"
#include "contacts/ContactManager.h"

#include <iostream>
#include <sstream>

namespace dtn {

AX25CMConvergenceLayer::AX25CMLinkParams
                            AX25CMConvergenceLayer::default_link_params_(true);

//----------------------------------------------------------------------
AX25CMConvergenceLayer::AX25CMLinkParams::AX25CMLinkParams(bool init_defaults)
    :   SeqpacketLinkParams(init_defaults),
        hexdump_(false),
        local_call_("NO_CALL"),
        remote_call_("NO_CALL"),
        digipeater_("NO_CALL"),
        axport_("None")
{
    SeqpacketLinkParams::keepalive_interval_=30;
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::AX25CMLinkParams::serialize(oasys::SerializeAction *a)
{
    SeqpacketConvergenceLayer::SeqpacketLinkParams::serialize(a);
    a->process("hexdump", &hexdump_);
    a->process("local_call", &local_call_);
    a->process("remote_call", &remote_call_);
    a->process("digipeater", &digipeater_);
    a->process("axport", &axport_);

}

//----------------------------------------------------------------------
AX25CMConvergenceLayer::AX25CMConvergenceLayer()
    : SeqpacketConvergenceLayer("AX25CMConvergenceLayer", "ax25cm", AX25CMCL_VERSION)
{
    log_debug("AX25CMConvergenceLayer instantiated. ***");

}

//----------------------------------------------------------------------
CLInfo*
AX25CMConvergenceLayer::new_link_params()
{
    return new AX25CMLinkParams(default_link_params_);
}

//----------------------------------------------------------------------
bool
AX25CMConvergenceLayer::init_link(const LinkRef& link,
                                  int argc, const char* argv[])
{
    ASSERT(link != NULL);
    ASSERT(!link->isdeleted());
    ASSERT(link->cl_info() == NULL);

    log_debug("adding %s link %s", link->type_str(), link->nexthop());

    // Create a new parameters structure, parse the options, and store
    // them in the link's cl info slot.
    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams *>(new_link_params());
    ASSERT(params != NULL);

    // Try to parse the link's next hop, but continue on even if the
    // parse fails since the hostname may not be resolvable when we
    // initialize the link. Each subclass is responsible for
    // re-checking when opening the link.
    parse_nexthop(link, params);

    const char* invalid;
    if (! parse_link_params(params, argc, argv, &invalid)) {
        log_err("error parsing link options: invalid option '%s'", invalid);
        delete params;
        return false;
    }

	// Calls the SeqpacketConvergenceLayer method
    if (! finish_init_link(link, params)) {
        log_err("error in finish_init_link");
        delete params;
        return false;
    }

    link->set_cl_info(params);

    return true;
}

//----------------------------------------------------------------------
bool
AX25CMConvergenceLayer::parse_link_params(LinkParams* lparams,
                                        int argc, const char** argv,
                                        const char** invalidp)
{
    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams*>(lparams);
    ASSERT(params != NULL);

    oasys::OptParser p;

    p.addopt(new oasys::BoolOpt("hexdump", &params->hexdump_));
    p.addopt(new oasys::StringOpt("local_call", &params->local_call_));
    p.addopt(new oasys::StringOpt("remote_call", &params->remote_call_));
    p.addopt(new oasys::StringOpt("digipeater", &params->digipeater_));
    p.addopt(new oasys::StringOpt("axport", &params->axport_));

    int count = p.parse_and_shift(argc, argv, invalidp);
    if (count == -1) {
        return false; // bogus value
    }
    argc -= count;

    if (params->local_call_ == "NO_CALL") {
        log_err("invalid local callsign setting of NO_CALL");
        return false;
    }

    if (params->remote_call_ == "NO_CALL") {
        log_err("invalid remote callsign setting of NO_CALL");
        return false;
    }

    if (params->axport_ == "None") {
        log_err("invalid local axport setting of None");
        return false;
    }

    // continue up to parse the parent class
    return SeqpacketConvergenceLayer::parse_link_params(lparams, argc, argv,
                                                     invalidp);
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::dump_link(const LinkRef& link, oasys::StringBuffer* buf)
{
    ASSERT(link != NULL);
    ASSERT(!link->isdeleted());
    ASSERT(link->cl_info() != NULL);

    SeqpacketConvergenceLayer::dump_link(link, buf);

    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams*>(link->cl_info());
    ASSERT(params != NULL);

    buf->appendf("hexdump: %s\n", params->hexdump_ ? "enabled" : "disabled");
    buf->appendf("local_call: %s\n", params->local_call_.c_str());
    buf->appendf("remote_call: %s\n", params->remote_call_.c_str());
    buf->appendf("digipeater: %s\n", params->digipeater_.c_str());
    buf->appendf("axport: %s\n", params->axport_.c_str());
}

//----------------------------------------------------------------------
bool
AX25CMConvergenceLayer::set_link_defaults(int argc, const char* argv[],
                                       const char** invalidp)
{
    return parse_link_params(&default_link_params_, argc, argv, invalidp);
}

//----------------------------------------------------------------------
bool
AX25CMConvergenceLayer::parse_nexthop(const LinkRef& link, LinkParams* lparams)
{
    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams*>(lparams);
    ASSERT(params != NULL);

    if (params->remote_call_ == "NO_CALL" || params->axport_ == "None")
    {
        if (! AX25ConvergenceLayerUtils::parse_nexthop(logpath_, link->nexthop(),
                                                     &params->local_call_,
                                                     &params->remote_call_,
                                                     &params->digipeater_,
                                                     &params->axport_)) {
            return false;
        }
    }

    //std::cout<<"local_call:"<<params->local_call_<<std::endl;
    //std::cout<<"axport:"<<params->axport_<<std::endl;
    //std::cout<<"remote_call:"<<params->remote_call_<<std::endl;

    if (params->remote_call_ == "NO_CALL")    {
        log_warn("can't lookup callsign in next hop address '%s'",
                 link->nexthop());
        return false;
    }

    // make sure the port was specified
    if (params->axport_ == "None") {
        log_err("axport not specified in next hop address '%s'",
                link->nexthop());
        return false;
    }

    return true;
}

//----------------------------------------------------------------------
CLConnection*
AX25CMConvergenceLayer::new_connection(const LinkRef& link, LinkParams* p)
{
    (void)link;
    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams*>(p);
    ASSERT(params != NULL);
    return new Connection(this, params);
}

//----------------------------------------------------------------------
bool
AX25CMConvergenceLayer::interface_up(Interface* iface,
                                  int argc, const char* argv[])
{
    log_debug("adding interface %s", iface->name().c_str());
    std::string local_call = "NO_CALL";
    std::string axport = "None";

    oasys::OptParser p;
    p.addopt(new oasys::StringOpt("local_call", &local_call));
    p.addopt(new oasys::StringOpt("axport", &axport));

    const char* invalid = NULL;
    if (! p.parse(argc, argv, &invalid)) {
        log_err("error parsing interface options: invalid option '%s'",
                invalid);
        return false;
    }

    // check that the local interface / port are valid
    if (local_call == "NO_CALL") {
        log_err("invalid local call setting of NO_CALL");
        return false;
    }

    if (axport == "None") {
        log_err("invalid local axport setting of None");
        return false;
    }

    // create a new server socket for the requested interface
    Listener* listener = new Listener(this);
    listener->logpathf("%s/iface/%s", logpath_, iface->name().c_str());

    int ret = listener->bind(axport, local_call);

    // be a little forgiving -- if the address is in use, wait for a
    // bit and try again
    if (ret != 0 && errno == EADDRINUSE) {
        listener->logf(oasys::LOG_WARN,
                        "WARNING: error binding to requested socket: %s",
                       strerror(errno));
        listener->logf(oasys::LOG_WARN,
                        "waiting for 10 seconds then trying again");
        sleep(10);

        ret = listener->bind(axport, local_call);    }

    if (ret != 0) {
        return false; // error already logged
    }

    // start listening and then start the thread to loop calling accept()
    listener->listen();
    listener->start();

    // store the new listener object in the cl specific portion of the
    // interface
    iface->set_cl_info(listener);

    return true;
}

//----------------------------------------------------------------------
bool
AX25CMConvergenceLayer::interface_down(Interface* iface)
{
    // grab the listener object, set a flag for the thread to stop and
    // then close the socket out from under it, which should cause the
    // thread to break out of the blocking call to accept() and
    // terminate itself
    Listener* listener = dynamic_cast<Listener*>(iface->cl_info());
    ASSERT(listener != NULL);

    listener->stop();
    delete listener;
    return true;
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::dump_interface(Interface* iface,
                                    oasys::StringBuffer* buf)
{
    Listener* listener = dynamic_cast<Listener*>(iface->cl_info());
    ASSERT(listener != NULL);

    buf->appendf("\tlocal_call: %s axport: %s\n",
                    listener->local_call().c_str(), listener->axport().c_str());
}

//----------------------------------------------------------------------
AX25CMConvergenceLayer::Listener::Listener(AX25CMConvergenceLayer* cl)
    :    AX25ConnectedModeServerThread("AX25CMConvergenceLayer::Listener",
                        "/dtn/cl/ax25cm/listener"), cl_(cl)
{
    logfd_  = false;
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Listener::accepted(int fd, const std::string& addr)
{
    log_debug("new connection from %s", addr.c_str());

    Connection* conn =
        new Connection(cl_, &AX25CMConvergenceLayer::default_link_params_,
                       fd, local_call(), addr, axport());
    conn->start();
}

//----------------------------------------------------------------------
AX25CMConvergenceLayer::Connection::Connection(AX25CMConvergenceLayer* cl,
                                            AX25CMLinkParams* params)
    : SeqpacketConvergenceLayer::Connection("AX25CMConvergenceLayer::Connection",
                                            cl->logpath(), cl, params,
                                            true /* call connect() */)
{
    logpathf("%s/conn/%p", cl->logpath(), this);

    // set up the base class' nexthop parameter
    std::stringstream ss;
    ss<<params->local_call_<<":"<<params->remote_call_;
    if(params->digipeater_ != "NO_CALL")
    {
        ss<<","<<params->digipeater_;
    }
    ss<<":"<<params->axport_<<std::ends;
    oasys::StringBuffer nexthop("%s", ss.str().c_str());
    set_nexthop(nexthop.c_str());

    // the actual socket
    sock_ = new oasys::AX25ConnectedModeClient(logpath_);

    // XXX/demmer the basic socket logging emits errors and the like
    // when connections break. that may not be great since we kinda
    // expect them to happen... so either we should add some flag as
    // to the severity of error messages that can be passed into the
    // IO routines, or just suppress the IO output altogether
    sock_->logpathf("%s/sock", logpath_);
    sock_->set_logfd(false);

    sock_->init_socket();
    sock_->set_nonblocking(true);

    // if the parameters specify a local address, do the bind here --
    // however if it fails, we can't really do anything about it, so
    // just log and go on
    if (params->local_call_ != "NO_CALL")
    {
        if (sock_->bind(params->axport_, params->local_call_) != 0) {
            log_err("error binding to %s axport=%s : %s",
                    params->local_call_.c_str(),params->axport_.c_str(),
                    strerror(errno));
        }
    }
}

//----------------------------------------------------------------------
AX25CMConvergenceLayer::Connection::Connection(AX25CMConvergenceLayer* cl,
                                               AX25CMLinkParams* params,
                                               int fd,
                                               const std::string& local_call,
                                               const std::string& addr,
                                               const std::string& axport)
    : SeqpacketConvergenceLayer::Connection("AX25CMConvergenceLayer::Connection",
                                         cl->logpath(), cl, params,
                                         false /* call accept() */)
{
    logpathf("%s/conn/%p", cl->logpath(), this);

    // set up the base class' nexthop parameter
    std::stringstream ss;
    ss<<local_call<<":"<<addr<<":"<<axport<<std::ends;
    oasys::StringBuffer nexthop("%s", ss.str().c_str());
    set_nexthop(nexthop.c_str());

    sock_ = new oasys::AX25ConnectedModeClient(fd, addr, logpath_);
    sock_->set_logfd(false);
    sock_->set_nonblocking(true);
}

//----------------------------------------------------------------------
AX25CMConvergenceLayer::Connection::~Connection()
{
    sock_->shutdown(SHUT_RDWR);
    delete sock_;
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::initialize_pollfds()
{
    sock_pollfd_ = &pollfds_[0];
    num_pollfds_ = 1;

    sock_pollfd_->fd     = sock_->fd();
    sock_pollfd_->events = POLLIN;

    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams*>(params_);
    ASSERT(params != NULL);

    poll_timeout_ = params->data_timeout_;

    if (params->keepalive_interval_ != 0 &&
        (params->keepalive_interval_ * 1000) < params->data_timeout_)
    {
        poll_timeout_ = params->keepalive_interval_ * 1000;
    }
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::connect()
{
    // the first thing we do is try to parse the next hop address...
    // if we're unable to do so, the link can't be opened.
    if (! cl_->parse_nexthop(contact_->link(), params_)) {
        log_info("can't resolve nexthop address '%s'",
                 contact_->link()->nexthop());
        break_contact(ContactEvent::BROKEN);
        return;
    }

    // cache the remote addr and port in the fields in the socket
    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams*>(params_);
    ASSERT(params != NULL);
    sock_->set_remote_call(params->remote_call_);
    sock_->set_axport(params->axport_);
    //sock_->set_via_route(params->digipeater_);
    // start a connection to the other side... in most cases, this
    // returns EINPROGRESS, in which case we wait for a call to
    // handle_poll_activity
    log_debug("connect: connecting to %s axport=%s...",
              sock_->remote_call().c_str(), sock_->axport().c_str());
    ASSERT(contact_ == NULL || contact_->link()->isopening());
    ASSERT(sock_->state() != oasys::AX25Socket::ESTABLISHED);

    std::vector<std::string> rr;
    std::string rp = sock_->axport();
    std::string rc = sock_->remote_call();
    if(params->digipeater_ != "NO_CALL")
    {
        rr.push_back(params->digipeater_);
    }

    int ret = sock_->oasys::AX25Socket::connect(rp, rc, rr);

    if (ret == 0) {
        log_debug("connect: succeeded immediately");
        ASSERT(sock_->state() == oasys::AX25Socket::ESTABLISHED);

        initiate_contact();

    } else if (ret == -1 && errno == EINPROGRESS) {
        log_debug("connect: EINPROGRESS returned, waiting for write ready");
        sock_pollfd_->events |= POLLOUT;

    } else {
        log_info("connection attempt to %s axport=%s failed... %s",
                 sock_->remote_call().c_str(), sock_->axport().c_str(),
                 strerror(errno));
        break_contact(ContactEvent::BROKEN);
        // DML - Attempted bug fix hack here below
        disconnect();
    }
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::accept()
{
    ASSERT(sock_->state() == oasys::AX25Socket::ESTABLISHED);

    log_debug("accept: got connection from %s axport=%s...",
              sock_->remote_call().c_str(), sock_->axport().c_str());
    initiate_contact();
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::process_data()
{

    log_always("AX25CMConvergenceLayer::Connection::process_data() called");
    SeqpacketConvergenceLayer::Connection::process_data();

}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::disconnect()
{
    if (sock_->state() != oasys::AX25Socket::CLOSED) {
        log_debug("closing socket");
        sock_->close();
    }
    else {
        log_debug("attempting to close socket in state oasys::AX25Socket::CLOSED");
        sock_->close();
    }
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::handle_poll_activity()
{
    if (sock_pollfd_->revents & POLLHUP) {
        log_info("remote socket closed connection -- returned POLLHUP");
        break_contact(ContactEvent::BROKEN);
        return;
    }

    if (sock_pollfd_->revents & POLLERR) {
        log_info("error condition on remote socket -- returned POLLERR");
        break_contact(ContactEvent::BROKEN);
        return;
    }

    // first check for write readiness, meaning either we're getting a
    // notification that the deferred connect() call completed, or
    // that we are no longer write blocked
    if (sock_pollfd_->revents & POLLOUT)
    {
        log_debug("poll returned write ready, clearing POLLOUT bit");
        sock_pollfd_->events &= ~POLLOUT;

        if (sock_->state() == oasys::AX25Socket::CONNECTING) {
            int result = sock_->async_connect_result();
            if (result == 0 && sendbuf_.fullbytes() == 0) {
                log_debug("delayed_connect to %s axport=%s succeeded",
                          sock_->remote_call().c_str(), sock_->axport().c_str());
                initiate_contact();

            } else {
                log_info("connection attempt to %s axport=%s failed... %s",
                          sock_->remote_call().c_str(), sock_->axport().c_str(),
                         strerror(errno));
                break_contact(ContactEvent::BROKEN);
            }

            return;
        }

        send_data();
    }

    //check that the connection was not broken during the data send
    if (contact_broken_)
    {
        return;
    }

    // finally, check for incoming data
    if (sock_pollfd_->revents & POLLIN) {
        recv_data();
        this->process_data();

        // Sanity check to make sure that there's space in the buffer
        // for a subsequent read_data() call
        if (recvbuf_.tailbytes() == 0) {
            log_err("process_data left no space in recvbuf!!");
        }

        if (contact_up_ && ! contact_broken_) {
            check_keepalive();
        }

    }

}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::send_data()
{

    // DML: If we have any sequence delimiters on the queue, then try and send the first sequence,
    // and if not, all we can do here is try and send the whole buffer.  Whichever we send,
    // the whole thing should go through the socket, or it is a protocol error.
    // When we've selected either the first sequence in the queue or the entire buffer for
    // sending, then we'll create a temporary buffer for the payload, calculate the CRC, append it,
    // and try and send the packet payload through the socket.
    // If it works, then we'll pop the sequence off the queue, consume the appropriate length of
    // data from the buffer and be done.
    // If we get a WOULDBLOCK and we're not sending a sequence, then push a sequence on the queue.
    // If we get a WOULDBLOCK, and we are sending a sequence, then leave the sequence on the queue.
    // We have to recalculate the CRC every time we try and send the same payload.  Shame.

    // XXX/demmer this assertion is mostly for debugging to catch call
    // chains where the contact is broken but we're still using the
    // socket
    ASSERT(! contact_broken_);

    AX25CMLinkParams* params = dynamic_cast<AX25CMLinkParams*>(params_);
    ASSERT(params != NULL);
    u_int towrite = 0;
    u_int payload_length = 0;

//    if (params_->test_write_limit_ != 0) {
//        towrite = std::min(towrite, params_->test_write_limit_);
//    }

    //  see if we have any length delimiters queued from previous attempts where EWOULDBLOCK
    //  was set. if so, only send that much data through the socket write and leave the rest
    // for subsequent calls to take care of.

    ASSERT(!sendbuf_sequence_delimiters_.empty() );
    payload_length = sendbuf_sequence_delimiters_.front();
    log_debug("send_data: trying to drain %u bytes from pending sequence in send buffer...",
               payload_length);

    ASSERT(payload_length > 0);
    //ASSERT(towrite <= params->segment_length_);

    log_debug("generating CRC32 for payload length: %u", payload_length);
    oasys::CRC32 crc;
    crc.update(sendbuf_.start(), payload_length);
    u_int crc_generated = htonl(crc.value());
    log_debug("appending CRC32 to payload: %x", crc.value());
    towrite = payload_length + sizeof(u_int);
    oasys::StreamBuffer temp(towrite);
    ASSERT(temp.tailbytes() >= payload_length);
    memcpy(temp.end(), sendbuf_.start(), payload_length);
    temp.fill(payload_length);
    ASSERT(temp.tailbytes() >= sizeof(crc_generated));
    memcpy(temp.end(), reinterpret_cast<char*>(&crc_generated), sizeof(crc_generated));
    temp.fill(sizeof(crc_generated));

    if (ax25cm_lparams()->hexdump_) {
        log_always("send_data sending %i bytes as below...",towrite);
        oasys::HexDumpBuffer hex;
        hex.append((u_char*)temp.start(), towrite);
        log_multiline(oasys::LOG_ALWAYS, hex.hexify().c_str());
    }

    int cc = sock_->write(temp.start(), towrite);

    // we really don't want to have leftovers with SOCK_SEQPACKET
    if (static_cast<u_int>(cc) == towrite) {
        log_debug("send_data: wrote %d/%zu bytes from send buffer", cc, sendbuf_.fullbytes());

        sendbuf_.consume(payload_length);

        //  if there's a delimiter on the queue, we've now consumed it, so pop the queue...
        if( !sendbuf_sequence_delimiters_.empty() ) {
            ASSERT(sendbuf_sequence_delimiters_.front() + sizeof(crc_generated) == static_cast<u_int>(cc));
            // well, the assert kicked in too often.   so I'm just gonna
            // declare a protocl error and ditch the link
            if(sendbuf_sequence_delimiters_.front() + sizeof(crc_generated) != static_cast<u_int>(cc))
            {
                std::stringstream ss;
                ss<<"CL attempted to send a "<<sendbuf_sequence_delimiters_.front()+ sizeof(crc_generated);
                ss<<" byte packet, but only "<<cc<<" bytes were sent"<<std::ends;
                log_err(ss.str().c_str());
                log_err("CL Protocol error: send_buf underrun breaks SOCK_SEQPACKET SEMANTICS");
                break_contact(ContactEvent::CL_ERROR);
                return;
            }
            else
            {

                log_info("removing pending sequence: %u from sequence delimiters queue, queue depth now: %u",
                    sendbuf_sequence_delimiters_.front(),   sendbuf_sequence_delimiters_.size()-1);
                sendbuf_sequence_delimiters_.pop();
            }

        }

        if (sendbuf_.fullbytes() != 0) {
            log_info("send_data: incomplete write (%u bytes remain in %u segments), setting POLLOUT bit",
                        sendbuf_.fullbytes(), sendbuf_sequence_delimiters_.size());
            sock_pollfd_->events |= POLLOUT;

            ASSERT(!sendbuf_sequence_delimiters_.empty() );
            ASSERT(sendbuf_sequence_delimiters_.front() <= sendbuf_.fullbytes());

        }
        else
        {
            if (sock_pollfd_->events & POLLOUT) {
                ASSERT(!sendbuf_sequence_delimiters_.empty() );
                log_debug("send_data: drained buffer, clearing POLLOUT bit");
                sock_pollfd_->events &= ~POLLOUT;
                // if we get here, the queue of delimiters should be empty ...
                ASSERT(sendbuf_sequence_delimiters_.empty());
            }
        }
    }
    else if (errno == EWOULDBLOCK) {
        ASSERT(cc < 0 );

        ASSERT(!sendbuf_sequence_delimiters_.empty() );
        log_info("send_data: write returned EWOULDBLOCK with %u bytes queued, in %u segments - setting POLLOUT bit",
                    sendbuf_.fullbytes(), sendbuf_sequence_delimiters_.size());
        sock_pollfd_->events |= POLLOUT;
        // so, we're gong to record the length of the send_buf contents
        // so we can extract the right ammount of data next time round to maintain SEQ_PACKET
        // sematics, but only if we're not trying to service the sendbuf_sequence_delimiters_ queue

    }
    else {
        log_info("send_data: whilst sending %i bytes of data, with %i bytes buffered, remote connection unexpectedly closed: %s",
                    towrite,
                    sendbuf_.fullbytes(),
                    strerror(errno));
        break_contact(ContactEvent::BROKEN);
    }
}

//----------------------------------------------------------------------
void
AX25CMConvergenceLayer::Connection::recv_data()
{
    // XXX/demmer this assertion is mostly for debugging to catch call
    // chains where the contact is broken but we're still using the
    // socket
    ASSERT(! contact_broken_);

    // this shouldn't ever happen
    if (recvbuf_.tailbytes() < 256) {
        log_err("no space in receive buffer to accept data!!!");
        return;
    }

    if (params_->test_read_delay_ != 0) {
        log_debug("recv_data: sleeping for test_read_delay msecs %u",
                  params_->test_read_delay_);

        usleep(params_->test_read_delay_ * 1000);
    }

    u_int toread = recvbuf_.tailbytes();
    if (params_->test_read_limit_ != 0) {
        toread = std::min(toread, params_->test_read_limit_);
    }

    log_debug("recv_data: draining up to %u bytes into recv buffer...", toread);
    int cc = sock_->read(recvbuf_.end(), toread);
    if (cc < 1) {
        log_info("remote connection unexpectedly closed");
        break_contact(ContactEvent::BROKEN);
        return;
    }

    log_debug("recv_data: read %d bytes, rcvbuf has %zu bytes",
                cc, recvbuf_.fullbytes());
    if (ax25cm_lparams()->hexdump_) {
        oasys::HexDumpBuffer hex;
        hex.append((u_char*)recvbuf_.end(), cc);
        log_always("recv_data received %i bytes as below...",cc);
        log_multiline(oasys::LOG_ALWAYS, hex.hexify().c_str());
    }

    oasys::CRC32 crc;
    if(static_cast<uint>(cc) <= sizeof(oasys::CRC32::CRC_t)) {
        // DML: I had an assert here to see if we ever get 'packets' that are smaller than
        // the CRC size.  Well, we did, and I can't for the life of me figure out why.
        // So, we have to protect ourselves from this kind of thing happening, and for
        // now I think the thing to do is to disconnect the other end, because obviously
        // their AX.25 CL implementation sucks ;-) or there's a problem somewhere else
        // in the stack or kit. Still, bye-bye time.
        log_err("CL Protocol error: Format error in recv_data");
        break_contact(ContactEvent::CL_ERROR);
        return;
    }

    // check the CRC is good
    uint crc_offset = static_cast<uint>(cc) - sizeof(oasys::CRC32::CRC_t);
    crc.update(recvbuf_.start(), crc_offset);
    uint crc_calculated = crc.value();
    uint crc_received = *reinterpret_cast<uint*>(recvbuf_.start() + crc_offset);
    crc_received = ntohl(crc_received);
    log_debug("crc received: %x, crc calculated: %x", crc_received, crc_calculated);
    if(crc_received != crc_calculated) {
        log_err("CL Protocol error: CRC failure detected in recv_data");
        break_contact(ContactEvent::CL_ERROR);
        return;
    }

    recvbuf_.fill(cc- sizeof(oasys::CRC32::CRC_t));
}

/**
 * Parse a next hop address specification of the form
 * LOCAL_CALL:REMOTE_CALL:AXPORT or REMOTE_CALL<,DIGIPEATER>:axport
 *
 * @return true if the conversion was successful, false
 */
bool
AX25ConvergenceLayerUtils::parse_nexthop(const char* logpath, const char* nexthop,
                            std::string* local_call, std::string* remote_call,
                            std::string* digipeater,std::string* axport)
{
    *local_call = "NO_CALL";
    *remote_call = "NO_CALL";
    *digipeater = "NO_CALL";
    *axport = "None";
    std::string temp = nexthop, temp2;
    //std::cout<<"Nexthop:"<<temp<<std::endl;

    const char* comma = strchr(nexthop, ',');
    const char* colon1 = strchr(nexthop, ':');
    const char* colon2 = strrchr(nexthop, ':');

    if(comma != NULL)
    {
        // we have a digi to deal with, so we must be the link initiator
        // we need to parse out the remote_call, digipeater and axport
        remote_call->assign(nexthop, comma - nexthop);
        temp2.assign(comma+1, ( temp.size()-remote_call->size() ) -1);

        colon1 = strchr(temp2.c_str(),':');

        if(colon1 != NULL)
        {
            digipeater->assign(temp2.c_str(),colon1-temp2.c_str());
            axport->assign(colon1+1, ( temp2.size() -  digipeater->size() ) -1 );
        }

        if ("None" == *axport  || "NO_CALL" == *remote_call || "NO_CALL" == *digipeater) {
            log_warn_p(logpath, "invalid remote_call,digipeater:axport in next hop '%s'",
                       nexthop);
            return false;
        }

    }
    else
    {
        //we don't have a digipeater, but we may be the link initiator meaning
        // that we need remote_call and axport, or we're the listener, in which case
        // we need the local_call, remote_call and axport.  if we have two colons,
        // then we are the listener ...

        if( colon2 == NULL)
        {
            // we're the initiator
            //so look for the remote call and axport
            remote_call->assign(nexthop,colon1-nexthop);
            axport->assign(colon1+1,temp.size()-remote_call->size() - 1);

            if ("None" == *axport  || "NO_CALL" == *remote_call) {
                log_warn_p(logpath, "invalid remote_call:axport in next hop '%s'",
                           nexthop);
                return false;
            }

        }
        else if(colon1 != NULL)
        {
            // we're the listener
            local_call->assign(nexthop,colon1-nexthop);
            remote_call->assign(colon1+1,colon2-colon1);
            axport->assign(colon2+1,temp.size()-remote_call->size() - local_call->size() -2);

            if ("None" == *axport  || "NO_CALL" == *remote_call || "NO_CALL" == *local_call) {
                log_warn_p(logpath, "invalid local_call:remote_call:axport in next hop '%s'",
                           nexthop);
                return false;
            }

        }
    }

    return true;
}

} // namespace dtn

#endif /* #ifdef OASYS_AX25_ENABLED  */


text:
<?php

namespace Apache\Usergrid\Native\Facades;

use Apache\Usergrid\Native\UsergridBootstrapper;

/**
 * Class Usergrid
 *
 * @package    Apache/Usergrid
 * @version    1.0.0
 * @author     Jason Kristian <jasonkristian@gmail.com>
 * @license    Apache License, Version  2.0
 * @copyright  (c) 2008-2014, Baas Platform Pty. Ltd
 * @link       http://baas-platform.com
 */
class Usergrid
{
    /**
     * The Native Bootstrap instance.
     *
     * @var \Apache\Usergrid\Native\UsergridBootstrapper
     */
    protected static $instance;
    /**
     * The Usergrid API instance.
     *
     * @var \Apache\Usergrid\Api\Usergrid
     */
    protected $usergrid;

    /**
     * Constructor.
     *
     * @param  \Apache\Usergrid\Native\UsergridBootstrapper $bootstraper
     * @return \Apache\Usergrid\Native\Facades\Usergrid
     */
    public function __construct(UsergridBootstrapper $bootstraper = null)
    {
        if (!$bootstraper) {
            $bootstraper = new UsergridBootstrapper;
        }

        $this->usergrid = $bootstraper->createUsergrid();
    }

    /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string $method
     * @param  array $args
     * @return mixed
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::instance()->getUsergrid();

        switch (count($args)) {
            case 0:
                return $instance->{$method}();

            case 1:
                return $instance->{$method}($args[0]);

            case 2:
                return $instance->{$method}($args[0], $args[1]);

            case 3:
                return $instance->{$method}($args[0], $args[1], $args[2]);

            case 4:
                return $instance->{$method}($args[0], $args[1], $args[2], $args[3]);

            default:
                return call_user_func_array([$instance, $method], $args);
        }
    }

    /**
     * Creates a new Native Bootstraper instance.
     *
     * @param  \Apache\Usergrid\Native\UsergridBootstrapper $bootstrapper
     * @return static
     */
    public static function instance(UsergridBootstrapper $bootstrapper = null)
    {
        if (static::$instance === null) {
            static::$instance = new static($bootstrapper);
        }

        return static::$instance;
    }

    /**
     * Returns the Usergrid API instance.
     *
     * @return \Apache\Usergrid\Api\Usergrid
     */
    public function getUsergrid()
    {
        return $this->usergrid;
    }
}


text:
from __future__ import print_function, unicode_literals

from os import getcwd, path, makedirs

import yaml
import click

from algen.compilers import ModelCompiler

__author__ = "danishabdullah"

class DirectoryCreationException(Exception):
    pass

class FileNotFound(Exception):
    pass

class InvalidModelDefinition(Exception):
    pass

def check_or_create_models_dir(destination=None):
    dir = destination or "{}/models".format(getcwd())
    if not path.exists(dir):
        click.echo("Didn't find {}. Creating now.".format(dir))
        try:
            makedirs(dir)
        except Exception as e:
            raise DirectoryCreationException
    return dir

def create_col_def_dict_from_cli_input(col_input):
    col_name, col_type = col_input.split(':')
    return {'name': col_name, 'type': col_type}

def parse_cli_columns(name, columns):
    column_defs = [create_col_def_dict_from_cli_input(n) for n in columns]
    res = {name: {'columns': column_defs}}
    ensure_names(res)
    ensure_types(res)
    return res

def ensure_names(model_defs):
    for model_def in model_defs.values():
        for column in model_def['columns']:
            if not column.get('name', None):
                raise InvalidModelDefinition("Missing 'name")

def ensure_types(model_defs):
    for model_def in model_defs.values():
        for column in model_def['columns']:
            if not column.get('type', None):
                raise InvalidModelDefinition("Missing 'type")

def ensure_foreign_keys(model_defs):
    for model_def in model_defs.values():
        for column in model_def.get('foreign_keys', []):
            if not column.get('name', None):
                raise InvalidModelDefinition("Missing 'name")
            if not column.get('type', None):
                raise InvalidModelDefinition("Missing 'type")
            reference = column.get('reference', None)
            if not reference:
                raise InvalidModelDefinition("Missing 'reference' from foreign key")
            assert isinstance(reference, dict)
            if not reference.get('table', None):
                raise InvalidModelDefinition("Missing 'reference.name' from foreign key")
            if not reference.get('column', None):
                raise InvalidModelDefinition("Missing 'reference.column' from foreign key")

def ensure_relationships(model_defs):
    for model_def in model_defs.values():
        for column in model_def.get('relationships', []):
            if not column.get('name', None):
                raise InvalidModelDefinition("Missing 'name")
            if not column.get('class', None):
                raise InvalidModelDefinition("Missing 'class' from relationship")

def parse_yaml(pth):
    if not path.exists(pth):
        raise FileNotFound

    with open(pth, 'r') as fyle:
        model_defs = yaml.load(fyle)
    assert isinstance(model_defs, dict)
    ensure_names(model_defs)
    ensure_types(model_defs)
    ensure_foreign_keys(model_defs)
    ensure_relationships(model_defs)
    return model_defs

def get_model_defs(name=None, columns=None, yaml=None):
    if yaml:
        model_defs = parse_yaml(yaml)
    else:
        model_defs = parse_cli_columns(name, columns)
    return model_defs

@click.command()
@click.option('--name', '-n', help='Name of model', type=str)
@click.option('--columns', '-c',
              help=("Column definition. e.g. col_name:col_type"
                    " Can be used multiple times hence named "
                    "columns. e.g. -c foo:Int -c bar:Unicode(20)"),
              type=str, multiple=True)
@click.option('--destination', '-d', help=("Destination directory. Default will "
                                           "assume 'models' directory inside the"
                                           " current working directory"),
              type=click.Path(exists=True))
@click.option('--yaml', '-y', help=("Yaml file describing the Model. This "
                                    "supersedes the column definition provided "
                                    "through --columns option."),
              type=click.Path(exists=True))
def cli(name, columns, destination, yaml):
    click.echo('Creating Models with the following options:\n'
               '  --name:{}\n  --columns:{}\n  --destination:{}\n'
               '  --yaml:{}'.format(name, columns, destination, yaml))
    if destination:
        if destination.endswith('/'):
            destination = destination[:len(destination) - 1]
            click.echo('Trimmed destination to {}'.format(destination))
    try:
        # destination cannot be created or accessed
        destination = check_or_create_models_dir(destination=destination)
    except DirectoryCreationException as e:
        click.echo("An error happened while trying to access/create the 'models' "
                   "directory. Please make sure that you have the "
                   "appropriate ownership and right provided by the os.")
        return
    if not (columns or yaml):
        click.echo("You must provide at least one of --columns or --yaml")
        return
    try:
        # invalid definitions
        if yaml:
            if columns:
                click.echo("Ignoring columns provided through cli since a yaml"
                           " file was also provided")
            try:
                # not found errors
                model_defs = get_model_defs(yaml=yaml)
            except FileNotFound:
                click.echo("The yaml file does not exist. Exiting!")
                return
        else:
            if not name:
                click.echo("Model must have a name!")
                return
            model_defs = get_model_defs(columns=columns, name=name)
    except InvalidModelDefinition:
        click.echo('All columns must have a name!')
        return
    for name, column_defs in model_defs.items():
        model = ModelCompiler(name, column_defs).compiled_model
        filename = "{}/{}.py".format(destination, ModelCompiler.convert_case(name))
        try:
            # file is not writeable
            with open(filename, 'w') as fyle:
                click.echo("Writing {} to {}".format(name, filename))
                fyle.write(model)
        except IOError:
            click.echo("The following python model was generated:\n\n{}"
                       "Cannot write model  to {}. Make sure the "
                       "destination is writable.\n"
                       .format(name, filename))

if __name__ == '__main__':
    cli()


text:
using System;

namespace ManagedWin32.Api
{
    public delegate IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
}


text:
package com.amazonaws.services.snowdevicemanagement.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TagResourceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) of the device or task.
     *

     */
    private String resourceArn;
    /**
     *

     * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways,
     * such as by purpose, owner, or environment.
     *

     */
    private java.util.Map<String, String> tags;

    /**
     *

     * The Amazon Resource Name (ARN) of the device or task.
     *

     *
     * @param resourceArn
     *        The Amazon Resource Name (ARN) of the device or task.
     */

    public void setResourceArn(String resourceArn) {
        this.resourceArn = resourceArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the device or task.
     *

     *
     * @return The Amazon Resource Name (ARN) of the device or task.
     */

    public String getResourceArn() {
        return this.resourceArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the device or task.
     *

     *
     * @param resourceArn
     *        The Amazon Resource Name (ARN) of the device or task.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TagResourceRequest withResourceArn(String resourceArn) {
        setResourceArn(resourceArn);
        return this;
    }

    /**
     *

     * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways,
     * such as by purpose, owner, or environment.
     *

     *
     * @return Optional metadata that you assign to a resource. You can use tags to categorize a resource in different
     *         ways, such as by purpose, owner, or environment.
     */

    public java.util.Map<String, String> getTags() {
        return tags;
    }

    /**
     *

     * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways,
     * such as by purpose, owner, or environment.
     *

     *
     * @param tags
     *        Optional metadata that you assign to a resource. You can use tags to categorize a resource in different
     *        ways, such as by purpose, owner, or environment.
     */

    public void setTags(java.util.Map<String, String> tags) {
        this.tags = tags;
    }

    /**
     *

     * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways,
     * such as by purpose, owner, or environment.
     *

     *
     * @param tags
     *        Optional metadata that you assign to a resource. You can use tags to categorize a resource in different
     *        ways, such as by purpose, owner, or environment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TagResourceRequest withTags(java.util.Map<String, String> tags) {
        setTags(tags);
        return this;
    }

    /**
     * Add a single Tags entry
     *
     * @see TagResourceRequest#withTags
     * @returns a reference to this object so that method calls can be chained together.
     */

    public TagResourceRequest addTagsEntry(String key, String value) {
        if (null == this.tags) {
            this.tags = new java.util.HashMap<String, String>();
        }
        if (this.tags.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.tags.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into Tags.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TagResourceRequest clearTagsEntries() {
        this.tags = null;
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getResourceArn() != null)
            sb.append("ResourceArn: ").append(getResourceArn()).append(",");
        if (getTags() != null)
            sb.append("Tags: ").append(getTags());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof TagResourceRequest == false)
            return false;
        TagResourceRequest other = (TagResourceRequest) obj;
        if (other.getResourceArn() == null ^ this.getResourceArn() == null)
            return false;
        if (other.getResourceArn() != null && other.getResourceArn().equals(this.getResourceArn()) == false)
            return false;
        if (other.getTags() == null ^ this.getTags() == null)
            return false;
        if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getResourceArn() == null) ? 0 : getResourceArn().hashCode());
        hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
        return hashCode;
    }

    @Override
    public TagResourceRequest clone() {
        return (TagResourceRequest) super.clone();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="isLarge">false</bool>
</resources>


text:
package com.intellij.psi.util.proximity;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.util.NotNullLazyKey;
import com.intellij.openapi.util.NullableLazyKey;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.ProximityLocation;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.List;

/**
 * @author peter
*/
public class ExplicitlyImportedWeigher extends ProximityWeigher {
  private static final NullableLazyKey<PsiPackage, ProximityLocation> PLACE_PACKAGE = NullableLazyKey.create("placePackage", location -> {
    PsiElement position = location.getPosition();
    return position == null ? null : getContextPackage(position);
  });
  private static final NotNullLazyKey<List<String>, ProximityLocation> PLACE_IMPORTED_NAMES =
    NotNullLazyKey.create("importedNames", location -> {
      final PsiJavaFile psiJavaFile = PsiTreeUtil.getContextOfType(location.getPosition(), PsiJavaFile.class, false);
      final PsiImportList importList = psiJavaFile == null ? null : psiJavaFile.getImportList();
      if (importList == null) return Collections.emptyList();

      List<String> importedNames = ContainerUtil.newArrayList();
      for (PsiImportStatementBase statement : importList.getAllImportStatements()) {
        PsiJavaCodeReferenceElement reference = statement.getImportReference();
        ContainerUtil.addIfNotNull(importedNames, reference == null ? null : reference.getQualifiedName());
      }

      return importedNames;
    });

  @Nullable
  private static PsiPackage getContextPackage(PsiElement position) {
    PsiFile file = position.getContainingFile();
    if (file == null) return null;

    PsiFile originalFile = file.getOriginalFile();
    while (true) {
      PsiElement context = originalFile.getContext();
      if (context == null) {
        PsiDirectory parent = originalFile.getParent();
        if (parent != null) {
          return JavaDirectoryService.getInstance().getPackage(parent);
        }
        return null;
      }

      PsiFile containingFile = context.getContainingFile();
      if (containingFile == null) return null;

      originalFile = containingFile.getOriginalFile();
    }
  }

  @Override
  public Integer weigh(@NotNull final PsiElement element, @NotNull final ProximityLocation location) {
    final PsiElement position = location.getPosition();
    if (position == null){
      return 0;
    }

    PsiUtilCore.ensureValid(position);

    final PsiFile elementFile = element.getContainingFile();
    final PsiFile positionFile = position.getContainingFile();
    if (positionFile != null && elementFile != null && positionFile.getOriginalFile().equals(elementFile.getOriginalFile())) {
      return 300;
    }

    if (element instanceof PsiClass) {
      final String qname = ((PsiClass) element).getQualifiedName();
      if (qname != null) {
        List<String> importedNames = PLACE_IMPORTED_NAMES.getValue(location);
        if (importedNames.contains(qname) || "java.lang".equals(StringUtil.getPackageName(qname))) {
          return 100;
        }

        // check if anything from the same package is already imported in the file:
        //    people are likely to refer to the same subsystem as they're already working
        if (containsImport(importedNames, StringUtil.getPackageName(qname))) {
          return 50;
        }
      }

    }
    if (element instanceof PsiMember) {
      String qname = PsiUtil.getMemberQualifiedName((PsiMember)element);
      if (qname != null && PLACE_IMPORTED_NAMES.getValue(location).contains(qname)) {
        return 400;
      }

      final PsiPackage placePackage = PLACE_PACKAGE.getValue(location);
      if (placePackage != null) {
        Module elementModule = ModuleUtilCore.findModuleForPsiElement(element);
        if (location.getPositionModule() == elementModule && placePackage.equals(getContextPackage(element))) {
          return 200;
        }
      }
    }
    return 0;
  }

  private static boolean containsImport(List<String> importedNames, final String pkg) {
    return ContainerUtil.or(importedNames, s -> s.startsWith(pkg + '.') || s.equals(pkg));
  }
}


text:
Sign Up

						<form action="javascript:app.signUp.signUp()" class="authForm" autocomplete="on">

										Name

									<input class="mdl-textfield__input" id="signup-name" type="text" name="name" title="Name" required>

									Required

										Email

									<input class="mdl-textfield__input" id="signup-email" name="email" title="Email" oninput="SignUp.validateSignUp()" type="email" required>

									Valid email address required

										Password

									<input class="mdl-textfield__input" id="signup-password" type="password" name="new-password" title="Password" oninput="SignUp.validateSignUp()" required>

										Retype Password

									<input class="mdl-textfield__input" id="signup-password2" type="password" name="new-password" title="Password Repeat" oninput="SignUp.validateSignUp()" required>

										<input type="checkbox" id="switch-1" class="mdl-switch__input"
										onclick="app.signUp.showAdditionalInfo()">
										Care to tell us more about yourself?

												Employer

											<input class="mdl-textfield__input" id="signup-employer" type="text" title="Employer" name="organization">

												Job Title

											<input class="mdl-textfield__input" id="signup-title" type="text" title="Title" name="organization-title">

											When's your birthday?

											<input class="mdl-textfield__input" id="signup-birthday" type="date" title="Birthday" name="bday">

								<input class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" id="submit-password-button" type="submit" value="Sign Up" title="Sign Up">

						</form>

								Already have an account?  Sign In

								Forgot your password?  Reset Password


text:
describe GitRepositoryService do
  let(:git_repository_service) { described_class.new }
  describe "#setup" do
    let(:git_url) { "http://example.com/" }
    let(:git_username) { nil }
    let(:git_password) { nil }
    let(:new_record) { false }

    context "when the git repository already exists" do
      let!(:git_repo) { GitRepository.create!(:url => "http://example.com/") }

      shared_examples_for "GitRepositoryService#setup when verify_ssl is 'true'" do
        it "sets the verify_ssl setting to verify_peer" do
          git_repository_service.setup(git_url, git_username, git_password, verify_ssl)
          expect(git_repo.reload.verify_ssl).to eq(OpenSSL::SSL::VERIFY_PEER)
        end
      end

      shared_examples_for "GitRepositoryService#setup with an existing repo" do
        it "returns the id and the fact that it is not a new repo" do
          expect(git_repository_service.setup(git_url, git_username, git_password, verify_ssl)).to eq(
            :git_repo_id => git_repo.id, :new_git_repo? => false
          )
        end
      end

      context "when verify_ssl is 'true'" do
        let(:verify_ssl) { "true" }

        context "when git username is present" do
          let(:git_username) { "username" }

          context "when git password is present" do
            let(:git_password) { "password" }

            before do
              allow(MiqQueue).to receive(:put_unless_exists)
            end

            it "updates the authentication" do
              git_repository_service.setup(git_url, git_username, git_password, verify_ssl)
              authentication = git_repo.default_authentication
              expect(authentication.userid).to eq("username")
              expect(authentication.password).to eq("password")
            end

            it_behaves_like "GitRepositoryService#setup when verify_ssl is 'true'"
            it_behaves_like "GitRepositoryService#setup with an existing repo"
          end

          context "when git password is not present" do
            it_behaves_like "GitRepositoryService#setup when verify_ssl is 'true'"
            it_behaves_like "GitRepositoryService#setup with an existing repo"
          end
        end

        context "when git username is not present" do
          it_behaves_like "GitRepositoryService#setup when verify_ssl is 'true'"
          it_behaves_like "GitRepositoryService#setup with an existing repo"
        end
      end

      context "when verify_ssl is not 'true'" do
        let(:verify_ssl) { "not true" }

        it "sets the verify_ssl setting to verify_none" do
          git_repository_service.setup(git_url, git_username, git_password, verify_ssl)
          expect(git_repo.reload.verify_ssl).to eq(OpenSSL::SSL::VERIFY_NONE)
        end

        it_behaves_like "GitRepositoryService#setup with an existing repo"
      end
    end

    context "when the git repository does not already exist" do
      shared_examples_for "GitRepositoryService#setup when a git repo does not exist" do
        it "returns the id and the fact that it is a new repo" do
          expect(git_repository_service.setup(git_url, git_username, git_password, verify_ssl)).to eq(
            :git_repo_id => GitRepository.first.id, :new_git_repo? => true
          )
        end
      end

      context "when verify_ssl is 'true'" do
        let(:verify_ssl) { "true" }

        it "creates a git repository with verify_peer" do
          git_repository_service.setup(git_url, git_username, git_password, verify_ssl)
          git_repo = GitRepository.first
          expect(git_repo.verify_ssl).to eq(OpenSSL::SSL::VERIFY_PEER)
        end

        it_behaves_like "GitRepositoryService#setup when a git repo does not exist"
      end

      context "when verify_ssl is not 'true'" do
        let(:verify_ssl) { "not true" }

        it "creates a git repository with verify_none" do
          git_repository_service.setup(git_url, git_username, git_password, verify_ssl)
          git_repo = GitRepository.first
          expect(git_repo.verify_ssl).to eq(OpenSSL::SSL::VERIFY_NONE)
        end

        it_behaves_like "GitRepositoryService#setup when a git repo does not exist"
      end
    end
  end
end


text:
using System;
using System.ComponentModel;
using bv.model.BLToolkit;
using bv.winclient.Core;
using eidss.model.Core;
using eidss.model.Reports.AZ;
using eidss.model.Reports.OperationContext;
using EIDSS.Reports.BaseControls.Filters;
using EIDSS.Reports.BaseControls.Keeper;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Parameterized.Human.AJ.Reports;

namespace EIDSS.Reports.Parameterized.Human.AJ.Keepers
{
    public partial class ZoonoticComparativeReportKeeper : BaseYearKeeper
    {
        public ZoonoticComparativeReportKeeper()
        {
            ReportType = typeof (ZoonoticAZReport);
            InitializeComponent();
            SetMandatory();
            m_HasLoad = true;
        }

        #region Properties

        [Browsable(false)]
        protected long? RegionIdParam
        {
            get { return RegionFilter.RegionId > 0 ? (long?) RegionFilter.RegionId : null; }
        }

        [Browsable(false)]
        protected long? RayonIdParam
        {
            get { return RayonFilter.RayonId > 0 ? (long?) RayonFilter.RayonId : null; }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        private long? DiagnosisIdParam { get; set; }

        #endregion

        protected override BaseReport GenerateReport(DbManagerProxy manager, DbManagerProxy archiveManager)
        {
            if (WinUtils.IsComponentInDesignMode(this))
            {
                return new BaseReport();
            }
            var model = new ZoonoticSurrogateModel(CurrentCulture.ShortName, YearParam,
                RegionIdParam, RayonIdParam,
                RegionFilter.SelectedText, RayonFilter.SelectedText,
                DiagnosisIdParam, diagnosisFilter.GetDisplayText(),
                Convert.ToInt64(EidssUserContext.User.OrganizationID),
                EidssUserContext.User.ForbiddenPersonalDataGroups,
                UseArchive);
            var reportAz = (ZoonoticAZReport) CreateReportObject();
            reportAz.SetParameters(model, manager, archiveManager);
            return reportAz;
        }

        protected internal override void ApplyResources(DbManagerProxy manager)
        {
            base.ApplyResources(manager);

            // Note: do not load resources for spinEdit because it reset it's value
            //m_Resources.ApplyResources(spinEdit, "spinEdit");

            diagnosisFilter.DefineBinding();
            RegionFilter.DefineBinding();
            RayonFilter.DefineBinding();
            if (ContextKeeper.ContainsContext(ContextValue.ReportKeeperFirstLoading))
            {
                LocationHelper.SetDefaultFilters(manager, ContextKeeper, RegionFilter, RayonFilter);
            }
        }

        private void SetMandatory()
        {
//            LayoutCorrector.SetStyleController(YearSpinEdit, LayoutCorrector.MandatoryStyleController);
        }

        private void region1Filter_ValueChanged(object sender, SingleFilterEventArgs e)
        {
            using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
            {
                LocationHelper.RegionFilterValueChanged(RegionFilter, RayonFilter, e);
            }
        }

        private void rayon1Filter_ValueChanged(object sender, SingleFilterEventArgs e)
        {
            if (ContextKeeper.ContainsContext(ContextValue.ReportFilterResetting))
            {
                return;
            }
            using (ContextKeeper.CreateNewContext(ContextValue.ReportFilterResetting))
            {
                LocationHelper.RayonFilterValueChanged(RegionFilter, RayonFilter, e);
            }
        }

        private void Diagnosis_ValueChanged(object sender, MultiFilterEventArgs e)
        {
            DiagnosisIdParam = null;

            if (e.KeyArray.Length > 0)
            {
                long id;
                if (long.TryParse(e.KeyArray[0], out id))
                {
                    DiagnosisIdParam = id;
                }
            }
        }
    }
}


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

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

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.button1 = new System.Windows.Forms.Button();
            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
            this.toolStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(255, 274);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // toolStrip1
            //
            this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripButton1});
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Size = new System.Drawing.Size(673, 25);
            this.toolStrip1.TabIndex = 1;
            this.toolStrip1.Text = "toolStrip1";
            //
            // toolStripButton1
            //
            this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
            this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButton1.Name = "toolStripButton1";
            this.toolStripButton1.Size = new System.Drawing.Size(23, 22);
            this.toolStripButton1.Text = "toolStripButton1";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(673, 391);
            this.Controls.Add(this.toolStrip1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.toolStrip1.ResumeLayout(false);
            this.toolStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.ToolStrip toolStrip1;
        private System.Windows.Forms.ToolStripButton toolStripButton1;
    }
}


text:
bari-vs-addon
=============

VisualStudio addon for bari, an advanced build management tool for .NET projects.

As is
=====

This is a proof of concept version. Use at your own risk.


text:
<!DOCTYPE html>
<html>
  <head>
    <title>bsusensjackson</title>
    <link rel="stylesheet" type="text/css" href="reset.css" />
  </head>
  <body>
    <p>
    computer programmer based in new york city
    </p>
  </body>
  <script type="text/javascript">
    console.log('say hello sometime => bsusensjackson at gmail dot com');
    </script>
  </html>


text:
@interface SettingViewController : RootViewController

@end


text:
using namespace std;

void binarySearch(int *arr, int start, int end, int number)
{
	int middleElement = arr[(start + end) / 2];
	if (middleElement == number) {
		binarySearchResult(true, number);
	}
	else if ((middleElement != number && ((end - start) == 0) || (end < start))) {
		binarySearchResult(false, number);
	}
	else {
		if (number < middleElement)
			binarySearch(arr, start, ((start + end) / 2) - 1, number);
		else
			binarySearch(arr, ((start + end) / 2) + 1, end, number);
	}
}