text:
using ReturnTrue.Utilities.Cryptography;
using SADFM.Data.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SADFM.Data.EntityAccess
{
    public class Account : EntityAccessBase
    {
        internal Account(ConnectionStringSettings connection)
            : base(connection)
        { }

        public List<Data.Models.TrainingReportItem> GetTrainingReport(Guid? clientId)
        {

            var result = Execute(cx =>
            {

                var scales = cx.ListItems.Where(x => x.Parent.Name == "Scale").Select(x => new
                {
                    ScaleId = x.ListItemId,
                    ScaleName = x.Description

                }).ToList();

                return cx.ScalePermissions.Where(x => x.Account.FunderAccountPermissions.Count(y => y.FunderId == clientId) > 0 ||
                x.Account.ProviderAccountPermissions.Count(y => y.ProviderId == clientId) > 0 || !clientId.HasValue).ToList().Select(x => new Data.Models.TrainingReportItem()
                {
                    Username = x.Account.Username,
                    Firstname = x.Account.FirstName,
                    Lastname = x.Account.LastName,
                    Updated = x.LastUpdateTimestamp,
                    EmailAdress = x.Account.EmailAddress,
                    UpdatedDisplay = x.LastUpdateTimestamp.ToString("dd MMM yyyy HH:mm"),
                    Grade = x.Grade.HasValue ? x.Grade.Value : -1,
                    Scale = scales.FirstOrDefault(y => y.ScaleId == x.ScaleId) == null ? "" : scales.FirstOrDefault(y => y.ScaleId == x.ScaleId).ScaleName
                }).ToList();

            });

            return result;
        }

        public Models.Account GetAccountByUsername(string username)
        {
            return Execute(cx =>
            {
                var tmp = cx.Accounts.SingleOrDefault(a => a.Username.ToLower() == username.ToLower());
                if (tmp == null)
                    return null;
                return (Models.Account)tmp;
            });
        }

        public List<SADFM.Data.Models.TrainingReportItem> GetTrainingReport(Guid AccountId, List<Permission> Permissions, Guid? SelectedClientId)
        {

            return Execute(context =>
            {

                var scalePermissions = context.ScalePermissions.ToList();
                var scales = context.ListItems.Where(x => x.Parent.Name == "Scale").ToList().Select(x => new Models.ListItem(x, false)).ToList();

                return scalePermissions.Where(y => y.AccountId == AccountId && (Permissions
                .Where(x => x.GetClientId() == SelectedClientId).Count() > 0 || !SelectedClientId.HasValue)).GroupBy(x => x.ScaleId).Select(x => x.OrderByDescending(y => y.DateCreatedTimestamp).FirstOrDefault())
                .Select(x => new SADFM.Data.Models.TrainingReportItem()
                {
                    Grade = x.Grade.HasValue ? x.Grade.Value : -1,
                    Scale = scales.FirstOrDefault(y => y.GetId() == x.ScaleId) != null ? scales.FirstOrDefault(y => y.GetId() == x.ScaleId).Description : ""
                }).ToList();

            });

        }

        public UpdateResult AddScalePermission(Data.ScalePermission model)
        {
            return Execute(cx =>
            {

                cx.ScalePermissions.Add(model);
                cx.SaveChanges();

                return new UpdateResult(true);
            });

        }

        public Guid? GetAccountSecurityQuestionId(string username)
        {
            return Execute(cx =>
            {
                var tmp = cx.Accounts.SingleOrDefault(a => a.Username.ToLower() == username.ToLower()).SecurityQuestionId;
                return tmp ?? Guid.NewGuid();
            });
        }

        public string GetAccountSecurityAnswer(string username)
        {
            return Execute(cx =>
            {
                return cx.Accounts.SingleOrDefault(a => a.Username.ToLower() == username.ToLower()).SecurityQuestionAnswer;

            });
        }

        public Models.Account GetAccountByAccountId(Guid accountId)
        {
            return Execute(context =>
            {
                return (Models.Account)context.Accounts.First(a => a.AccountId.Equals(accountId));
            });
        }

        public string GetAccountEmailAddress(string username)
        {
            return Execute(cx =>
            {
                return cx.Accounts.SingleOrDefault(a => a.Username.ToLower() == username.ToLower()).EmailAddress;

            });
        }

        public Guid GetAccountIdByUsername(string username)
        {
            return Execute(cx =>
            {
                return cx.Accounts.SingleOrDefault(a => a.Username.ToLower() == username.ToLower()).AccountId;

            });

        }

        public string Validate(string username, string password)
        {
            return Execute(cx =>
            {
                var tmp = cx.Accounts.SingleOrDefault(a => a.Username.ToLower() == username.ToLower());
                if (tmp == null)
                    return (string)null;

                if (tmp.Password == MD5.Hex(password))
                    return tmp.Status.Name;

                return (string)null;
            });
        }

        public string GetAccountUserNameByAccountId(Guid accountId)
        {
            return Execute(cx =>
            {
                return cx.Accounts.SingleOrDefault(a => a.AccountId.Equals(accountId)).Username;

            });

        }

        public List<Models.Account> GetAllAccounts()
        {
            return Execute(cx =>
            {

                return cx.Accounts.ToList().Select(a => (Models.Account)a).ToList();
            });
        }

        public List<Models.Account> GetAllAccountsLightWeight(int startIndex, int length, string search, int columnSort, string direction, out int count, out int filtered)
        {

            int c = 0;
            int f = 0;

            var result = Execute(cx =>
            {
                SADFM.Base.NLogHelper.WriteEvent(NLog.LogLevel.Info, "Account.GetAllAccountsLightWeight:  -  Started");

                var result1 = cx.Accounts;
                IOrderedQueryable<Data.Account> result2 = null;
                switch (columnSort)
                {
                    case 1:
                        result2 = cx.Accounts.OrderBy(x => x.FirstName);
                        break;
                    case 2:
                        result2 = cx.Accounts.OrderBy(x => x.LastName);
                        break;
                    case 3:
                        result2 = cx.Accounts.OrderBy(x => x.EmailAddress);
                        break;
                    default:
                        result2 = cx.Accounts.OrderBy(x => x.Username);
                        break;

                }

                var result3 = result2.Where(x => x.Username.Contains(search) ||
                x.FirstName.Contains(search) || x.LastName.Contains(search));

                var result4 = result3.Skip(startIndex).Take(length).ToList().Select(a => new Models.Account(a)).ToList();

                c = result2.Count();
                f = result3.Count();

                SADFM.Base.NLogHelper.WriteEvent(NLog.LogLevel.Info, "Account.GetAllAccountsLightWeight:  -  End");
                return result4;
            });

            count = c;
            filtered = f;

            return result;
        }

        public bool ResetUserPassword(string newpassword, string username, string securityquestion, string securityquestionanswer, string id, Guid QuestionId)
        {
            if (securityquestion != null && securityquestionanswer != null)
            {
                bool success = false;
                Execute(context =>
                {
                    Guid lastUpdateAccountId = context.Accounts.Single(a => a.Username == username).AccountId;
                    // Guid QuestionId = context.ListItemLabels.FirstOrDefault(l => l.Label.Equals(securityquestion)).ListItemId;
                    securityquestion = context.ListItemLabels.FirstOrDefault(l => l.ListItemId.Equals(QuestionId)).Label;
                    Data.Account act = context.Accounts.SingleOrDefault(a => a.Username.ToLower().Equals(username.ToLower()));
                    if (act == null)
                        return false;
                    if (!string.IsNullOrWhiteSpace(newpassword))
                        act.Password = MD5.Hex(newpassword);
                    act.SecurityQuestionId = QuestionId;
                    act.SecurityQuestionAnswer = securityquestionanswer;
                    try
                    {
                        if (context.ChangeTracker.HasChanges())
                        {
                            WriteAudit(context, lastUpdateAccountId);

                            act.LastUpdateTimestamp = DateTime.Now;
                            act.LastUpdateAccountId = lastUpdateAccountId;
                            act.FirstSignIn = false;

                            context.SaveChanges();
                        }
                        success = true;
                        return success;
                    }
                    catch (Exception ex)
                    {
                        success = false;
                        return success;
                    }
                });
                return success;
            }

            else
            {

                bool success = false;

                Execute(context =>
                {
                    Guid lastUpdateAccountId = context.Accounts.Single(a => a.Username == username).AccountId;

                    //  Data.Account act = context.Accounts.SingleOrDefault(a => a.Username.ToLower().Equals(username.ToLower()));

                    Data.Account act = context.Accounts.SingleOrDefault(a => a.AccountId.ToString().Equals(id)) ?? context.Accounts.Single(a => a.Username == username);
                    // else
                    //  act = context.Accounts.SingleOrDefault(a => a.Username.ToLower().Equals(username.ToLower()));
                    if (act == null)
                        return false;
                    if (!string.IsNullOrWhiteSpace(newpassword))
                        act.Password = MD5.Hex(newpassword);

                    try
                    {
                        if (context.ChangeTracker.HasChanges())
                        {
                            WriteAudit(context, lastUpdateAccountId);

                            act.LastUpdateTimestamp = DateTime.Now;
                            act.LastUpdateAccountId = lastUpdateAccountId;
                            act.FirstSignIn = false;

                            context.SaveChanges();
                        }
                        success = true;
                        return success;
                    }
                    catch (Exception ex)
                    {
                        success = false;
                        return success;
                    }
                });
                return success;
            }
        }

        public Models.Account GetAccountByEmailAddress(string emailAddress)
        {
            return Execute(context =>
            {
                return (Models.Account)context.Accounts.FirstOrDefault(a => a.EmailAddress.ToLower().Equals(emailAddress.ToLower()));
            });
        }

        public UpdateResult Update(Models.Account account, string lastUpdateUsername)
        {
            return Execute(cx =>
            {
                Guid findId = account.GetId();
                Guid lastUpdateAccountId = cx.Accounts.Single(a => a.Username == lastUpdateUsername).AccountId;
                Data.Account act = cx.Accounts.SingleOrDefault(a => a.AccountId == findId);

                if (act == null)
                    return new UpdateResult("Cannot find account for username: {0}", account.Username);

                if (act.LastUpdateTimestamp.Ticks != account.Age)
                    return new UpdateResult(UpdateResult.ResultType.DataChanged);

                try
                {
                    act.FirstName = account.FirstName;
                    act.LastName = account.LastName;
                    act.EmailAddress = account.EmailAddress;
                    act.PracticeNumber = account.PracticeNumber;
                    act.ProfessionalBodyId = account.ProfessionalBody;
                    act.RegistrationNumber = account.RegistrationNumber;

                    if (!string.IsNullOrEmpty(account.TitleId))
                        act.TitleId = Models.BaseModel.DecryptNullableId(account.TitleId);

                    if (account.AccountRoles != null)
                    {

                        List<Data.AccountRole> accountRoleList = new List<Data.AccountRole>();
                        if (act.AccountRoles.Count != 0)
                        {
                            accountRoleList = act.AccountRoles.GroupBy(x => x.RoleId).FirstOrDefault().ToList();
                        }

                        foreach (Data.AccountRole ar in accountRoleList)
                        {
                            act.AccountRoles.Remove(ar);
                            cx.AccountRoles.Remove(ar);
                        }

                        foreach (Data.Models.AccountRole ar in account.AccountRoles)
                        {
                            Guid id = BaseModel.DecryptId(ar.RoleID);
                            if (act.AccountRoles.Where(x => x.RoleId == id).ToList().Count == 0)
                            {
                                act.AccountRoles.Add(new AccountRole()
                                {
                                    RoleId = id,
                                    AccountId = act.AccountId,
                                    AccountRoleId = Guid.NewGuid()
                                });

                            }

                        }

                    }

                    act.ContactNumber = account.ContactNumber;
                    act.IDNumberType = account.IDType;
                    act.IDNumber = account.IDNumber;
                    if (account.Avatar != null)
                        act.Avatar = Convert.FromBase64String(account.Avatar.Substring(22));

                    if (cx.ChangeTracker.HasChanges())
                    {
                        WriteAudit(cx, lastUpdateAccountId);

                        act.LastUpdateTimestamp = DateTime.Now;
                        act.LastUpdateAccountId = lastUpdateAccountId;
                        act.FirstSignIn = false;

                        cx.SaveChanges();
                    }
                    return new UpdateResult(true);
                }
                catch (Exception ex)
                {
                    return new UpdateResult("Error updating profile: {0}", ex.Message);
                }

            });
        }

        public List<string> VerifyNewUsernames(List<string> verification)
        {
            List<string> ver = verification.Select(v => v.ToLower()).ToList();
            List<string> result = new List<string>();
            return Execute(context =>
            {
                foreach (var account in context.Accounts.Select(a => new { Username = a.Username.ToLower(), Email = a.EmailAddress.ToLower() }))
                {
                    if (ver.Contains(account.Username))
                        result.Add(account.Username);
                    if (ver.Contains(account.Email))
                        result.Add(account.Email);
                }
                return result;
            });
        }

        public bool AllowScale(Guid accountId, string scaleID)
        {

            Guid scaleId = BaseModel.DecryptId(scaleID);
            return Execute(context =>
            {

                ScalePermission sp = (ScalePermission)context.ScalePermissions.OrderByDescending(x => x.DateCreatedTimestamp).FirstOrDefault(x => x.AccountId == accountId && x.ScaleId == scaleId);
                return sp != null && !olderThanYear(sp.LastUpdateTimestamp) && sp.Grade >= 80;
            });
        }

        public List<ScalePermission> AllPermissions()
        {
            return Execute(context =>
            {

                return context.ScalePermissions.ToList();
            });
        }

        private static bool olderThanYear(DateTime date)
        {

            DateTime expiryDate = date.AddYears(1).AddMonths(1).Subtract(new TimeSpan(date.Day + 1, 0, 0, 0));

            return DateTime.Now > expiryDate;
        }

        public UpdateResult AddNewUsers(List<Models.Account> newUsers, string clientId, List<string> permissions, string lastUpdateUsername)
        {
            try
            {
                return Execute(context =>
                {
                    Guid lastUpdateAccountId = context.Accounts.Single(a => a.Username == lastUpdateUsername).AccountId;
                    Guid cid = BaseModel.DecryptId(clientId);
                    Data.Provider provider = context.Providers.SingleOrDefault(p => p.ProviderId == cid);
                    Data.ListItem funder = context.ListItems.SingleOrDefault(li => li.ListItemId == cid);

                    List<Data.Account> inserts = new List<Data.Account>();
                    foreach (var user in newUsers)
                    {
                        var newData = new Data.Account
                        {
                            Username = user.Username,
                            FirstName = user.FirstName,
                            LastName = user.LastName,
                            EmailAddress = user.EmailAddress,
                            Password = string.Empty,
                            FirstSignIn = true,
                            ResetBySuperAdmin = false,
                            AccountTypeId = DataAccess.ListItem.GetListItem("AccountType", "User").GUID,
                            StatusId = DataAccess.ListItem.GetListItem("Status", "Active").GUID
                        };

                        foreach (var permissionId in permissions)
                        {
                            Guid pid = BaseModel.DecryptId(permissionId);
                            if (provider != null)
                                newData.ProviderAccountPermissions.Add(new ProviderAccountPermission
                                {
                                    ProviderId = cid,
                                    PermissionId = pid
                                });
                            else if (funder != null)
                                newData.FunderAccountPermissions.Add(new FunderAccountPermission
                                {
                                    FunderId = cid,
                                    PermissionId = pid
                                });
                        }

                        context.Accounts.Add(newData);
                        inserts.Add(newData);
                    }

                    WriteAudit(context, lastUpdateAccountId);

                    inserts.ForEach(a =>
                    {
                        a.LastUpdateAccountId = lastUpdateAccountId;
                        a.LastUpdateTimestamp = DateTime.Now;
                        a.DateCreatedTimestamp = DateTime.Now;
                    });

                    context.SaveChanges();

                    return new UpdateResult(true);

                });
            }
            catch (Exception ex)
            {
                return new UpdateResult("Error inserting new users");
            }
        }

        public Models.Account VerifyAccount(Models.Account model)
        {
            return Execute(context =>
            {
                Guid accountId;
                if (!Guid.TryParse(model.ID, out accountId))
                    return null;

                Data.Account account;
                try
                {
                    account = context.Accounts.Single(a => a.AccountId == accountId);
                }
                catch
                {
                    return null;
                }

                account.SecurityQuestionId = BaseModel.DecryptId(model.SecurityQuestionID);
                account.SecurityQuestionAnswer = model.SecurityQuestionAnswer;
                account.Password = MD5.Hex(model.Password);

                Guid lastUpdateAccountId = context.Accounts.OrderBy(a => a.DateCreatedTimestamp).First().AccountId;

                WriteAudit(context, lastUpdateAccountId);

                account.LastUpdateAccountId = account.AccountId;
                account.LastUpdateTimestamp = DateTime.Now;

                context.SaveChanges();

                return (Models.Account)account;

            });
        }

        public UpdateResult DeletePermission(Permission permission)
        {
            return Execute(context =>
            {
                Guid id = permission.GetId();
                FunderAccountPermission fap = context.FunderAccountPermissions.SingleOrDefault(x => x.FunderAccountPermissionId == id);
                if (fap != null)
                    context.FunderAccountPermissions.Remove(fap);
                else
                {
                    ProviderAccountPermission pap = context.ProviderAccountPermissions.SingleOrDefault(x => x.ProviderAccountPermissionId == id);
                    if (pap != null)
                        context.ProviderAccountPermissions.Remove(pap);
                }
                context.SaveChanges();
                return new UpdateResult(true);
            });
        }

        public UpdateResult SetNewPassword(string accountID, string newPassword, string oldPassword, bool verifyOldPassword)
        {
            return Execute(context =>
            {
                Guid accountId = BaseModel.DecryptId(accountID);
                Data.Account account = context.Accounts.SingleOrDefault(a => a.AccountId == accountId);
                if (account == null)
                    return new UpdateResult("Invalid user");

                if (verifyOldPassword)
                    if (account.Password != MD5.Hex(oldPassword))
                        return new UpdateResult("Invalid old password");

                account.Password = MD5.Hex(newPassword);
                if (!verifyOldPassword)
                    account.ResetBySuperAdmin = true;
                context.SaveChanges();

                return new UpdateResult(true);

            });
        }

        public UpdateResult AddPermission(Permission permission)
        {
            return Execute(context =>
            {
                Guid cid = BaseModel.DecryptId(permission.ClientID);
                Guid pid = BaseModel.DecryptId(permission.PermissionID);
                Guid aid = BaseModel.DecryptId(permission.AccountID);

                Data.Provider provider = context.Providers.SingleOrDefault(p => p.ProviderId == cid);
                if (provider != null)
                {
                    if (provider.ProviderAccountPermissions.SingleOrDefault(pap => pap.AccountId == aid && pap.PermissionId == pid) == null)
                        provider.ProviderAccountPermissions.Add(new ProviderAccountPermission
                        {
                            AccountId = aid,
                            PermissionId = pid,
                        });
                }
                else
                    if (context.FunderAccountPermissions.SingleOrDefault(fap => fap.AccountId == aid && fap.PermissionId == pid && fap.FunderId == cid) == null)
                    context.FunderAccountPermissions.Add(new FunderAccountPermission
                    {
                        AccountId = aid,
                        FunderId = cid,
                        PermissionId = pid
                    });

                context.SaveChanges();

                return new UpdateResult(true);

            });
        }

        public UpdateResult SetActiveStatus(string id, bool active, string lastUpdateUsername)
        {
            return Execute(context =>
             {

                 Guid lastUpdateAccountId = context.Accounts.Single(a => a.Username == lastUpdateUsername).AccountId;

                 Guid accountId = BaseModel.DecryptId(id);

                 if (lastUpdateAccountId == accountId)
                     return new UpdateResult("Cannot update your own status");

                 Models.ListItem listItem = DataAccess.ListItem.GetListItem("Status", active ? "Active" : "InActive");

                 Data.Account account = context.Accounts.Single(acc => acc.AccountId == accountId);

                 account.StatusId = listItem.GUID;

                 WriteAudit(context, lastUpdateAccountId);
                 account.LastUpdateAccountId = account.AccountId;
                 account.LastUpdateTimestamp = DateTime.Now;

                 context.SaveChanges();

                 return new UpdateResult(true);

             });

        }

        public UpdateResult SignDisclaimer(string username)
        {
            return Execute(context =>
            {

                Data.Account account = context.Accounts.Single(a => a.Username == username);

                account.DisclaimerAgreeTimestamp = DateTime.Now;

                WriteAudit(context, account.AccountId);

                account.LastUpdateAccountId = account.AccountId;
                account.LastUpdateTimestamp = DateTime.Now;
                account.FirstSignIn = false;
                account.ResetBySuperAdmin = false;
                context.SaveChanges();

                return new UpdateResult(true);

            });

        }

        public UpdateResult AddPatient(Data.Patient patient, Guid accountId)
        {
            return Execute(context =>
            {

                context.Patients.Add(patient);

                WriteAudit(context, accountId);

                context.SaveChanges();

                return new UpdateResult(true);

            });

        }

        public UpdateResult UpdatePatient(Data.Models.Patient model, Guid accountId)
        {
            return Execute(context =>
            {
                Guid patientId = BaseModel.DecryptId(model.ID);

                Data.Patient patient = context.Patients.FirstOrDefault(x => x.PatientId == patientId);

                patient.FirstName = model.FirstName;
                patient.LastName = model.LastName;
                patient.TitleId = BaseModel.DecryptNullableId(model.TitleId);
                patient.BirthDate = model.BirthDate;
                patient.GenderId = BaseModel.DecryptNullableId(model.GenderID);
                patient.RaceId = BaseModel.DecryptNullableId(model.RaceID);
                patient.ContactNumber = model.ContactNumber;
                patient.IDNumber = model.IDNumber;
                patient.Street = model.Street;
                patient.CityId = BaseModel.DecryptNullableId(model.CityId);
                patient.ProvinceId = BaseModel.DecryptNullableId(model.ProvinceId);
                patient.CountryId = BaseModel.DecryptNullableId(model.CountryID);
                patient.PostalCode = model.PostalCode;
                patient.NextOfKinName = model.NextOfKinName;
                patient.NextOfKinContact = model.NextOfKinContact;
                patient.MedicalSchemeMembershipNumber = model.MedicalSchemeNo;
                patient.MedicalSchemeId = BaseModel.DecryptNullableId(model.MedicalSchemeID);
                patient.NextOfKinEmail = model.NextOfKinEmail;
                patient.NextOfKinRelationship = model.NextOfKinRelationship;
                patient.ResidentialEnvironmentId = BaseModel.DecryptNullableId(model.ResidentialEnvironmentID);
                patient.AdmitFromId = BaseModel.DecryptNullableId(model.AdmitFromID);
                patient.DischargeToId = BaseModel.DecryptNullableId(model.DischargeToID);

                var deleteList = new List<PatientSupportService>();

                foreach (var supportService in patient.PatientSupportServices)
                {
                    if (model.SupportServices.Count(x => x.SupportServiceId == supportService.SupportServiceId) == 0)
                    {
                        deleteList.Add(supportService);
                    }
                    else
                    {
                        supportService.Note = model.SupportServices.Single(x => x.SupportServiceId == supportService.SupportServiceId).Note;
                    }
                }

                foreach (var supportService in deleteList)
                {
                    context.PatientSupportServices.Remove(supportService);
                }

                if (model.SupportServices != null)
                    foreach (var supportService in model.SupportServices)
                    {
                        if (patient.PatientSupportServices.Count(x => x.SupportServiceId == supportService.SupportServiceId) == 0)
                        {
                            patient.PatientSupportServices.Add(new PatientSupportService()
                            {
                                SupportServiceId = supportService.SupportServiceId,
                                Note = supportService.Note,
                                LastUpdatedTimestamp = DateTime.Now,
                                LastUpdatedAccountId = accountId

                            });
                        }
                    }

                WriteAudit(context, accountId);

                patient.LastUpdateTimestamp = DateTime.Now;
                patient.LastUpdateAccountId = accountId;

                context.SaveChanges();

                return new UpdateResult(true);

            });

        }

        public UpdateResult AddCase(Case patientCase, Guid accountId)
        {
            return Execute(context =>
            {
                context.Cases.Add(patientCase);

                Data.Patient patient = context.Patients.Single(x => x.PatientId == patientCase.PatientId);
                patient.LastUpdateTimestamp = DateTime.Now;
                patient.LastUpdateAccountId = accountId;

                if (patientCase.ImpairmentGroupId.HasValue)
                {
                    foreach (var c in patient.Cases)
                    {
                        c.ImpairmentGroupId = patientCase.ImpairmentGroupId;
                    }

                    context.PatientImpairmentGroupHistories.Add(new Data.PatientImpairmentGroupHistory()
                    {
                        ImpairmentGroupId = patientCase.ImpairmentGroupId,
                        PatientId = patient.PatientId,
                        Timestamp = DateTime.Now
                    });
                }

                WriteAudit(context, accountId);

                context.SaveChanges();

                return new UpdateResult(true);

            });

        }
        public UpdateResult UpdateCase(Case patientCase, Guid accountId)
        {
            return Execute(context =>
            {

                Case caseCurrent = context.Cases.Single(c => c.CaseId == patientCase.CaseId);

                bool hasImpairmentGroupChanged = caseCurrent.ImpairmentGroupId != patientCase.ImpairmentGroupId;

                caseCurrent.StartDate = patientCase.StartDate;
                caseCurrent.PatientProviders = patientCase.PatientProviders;
                caseCurrent.ICD10Id = patientCase.ICD10Id;
                caseCurrent.ImpairmentGroupId = patientCase.ImpairmentGroupId;
                caseCurrent.ReferringDoctor = patientCase.ReferringDoctor;
                caseCurrent.ReferringDoctorContact = patientCase.ReferringDoctorContact;
                caseCurrent.ReferringDoctorEmail = patientCase.ReferringDoctorEmail;
                caseCurrent.ReferringDoctorPracticeNumber = patientCase.ReferringDoctorPracticeNumber;
                caseCurrent.TreatingDoctor = patientCase.TreatingDoctor;
                caseCurrent.TreatingDoctorContact = patientCase.TreatingDoctorContact;
                caseCurrent.TreatingDoctorEmail = patientCase.TreatingDoctorEmail;
                caseCurrent.TreatingDoctorPracticeNumber = patientCase.TreatingDoctorPracticeNumber;
                caseCurrent.AdmissionStatusId = patientCase.AdmissionStatusId;

                caseCurrent.EndDate = patientCase.EndDate;

                Data.Patient patient = context.Patients.Single(x => x.PatientId == patientCase.PatientId);
                patient.LastUpdateTimestamp = DateTime.Now;
                patient.LastUpdateAccountId = accountId;

                foreach (var c in patient.Cases)
                {
                    c.ImpairmentGroupId = patientCase.ImpairmentGroupId;
                }

                if (hasImpairmentGroupChanged)
                {
                    context.PatientImpairmentGroupHistories.Add(new Data.PatientImpairmentGroupHistory()
                    {
                        ImpairmentGroupId = patientCase.ImpairmentGroupId,
                        PatientId = patient.PatientId,
                        Timestamp = DateTime.Now
                    });
                }

                WriteAudit(context, accountId);

                caseCurrent.LastUpdateAccountId = accountId;
                caseCurrent.LastUpdateTimestamp = DateTime.Now;
                context.SaveChanges();

                return new UpdateResult(true);

            });

        }

        public UpdateResult AddScale(string patientId, string scaleId, string freqId, Guid accountId)
        {
            return Execute(context =>
            {

                PatientScale scale = new PatientScale()
                {
                    FrequencyId = Data.Models.BaseModel.DecryptId(freqId),
                    ScaleId = Data.Models.BaseModel.DecryptId(scaleId),
                    PatientId = Data.Models.BaseModel.DecryptId(patientId),
                };

                context.PatientScales.Add(scale);

                WriteAudit(context, accountId);

                context.SaveChanges();

                return new UpdateResult(true);

            });

        }

        public List<Data.Models.Message> GetMessagesByUsername(string username, string patientId = null)
        {
            return Execute(context =>
            {

                Guid accountId = context.Accounts.Single(a => a.Username.ToLower() == username).AccountId;

                var allUserMessages = context.Messages.Where(m => (m.FromAccountId == accountId && !m.Archived) || m.MessageRecipients.Count(mr => mr.RecipientAccountId == accountId && !mr.Archived) > 0).ToList().Select(m =>
                {
                    Models.Message result = (Models.Message)m;
                    result.IsRead = !result.IsMessageUnread(username);
                    return result;
                }).ToList();

                if (!string.IsNullOrWhiteSpace(patientId))
                    allUserMessages = allUserMessages.Where(m => m.PatientId == patientId).ToList();

                return allUserMessages;

            });
        }

        public Data.Models.Message GetMessage(Guid messageId, string username)
        {
            return Execute(context =>
            {
                var result = context.Messages.Single(m => m.MessageId == messageId);
                var recipient = result.MessageRecipients.SingleOrDefault(mr => mr.RecipientAccount.Username.ToLower() == username);
                bool isread = result.FromAccount.Username.ToLower() == username;
                if (recipient != null)
                    if (!recipient.ReadTimestamp.HasValue)
                    {
                        isread = false;
                        recipient.ReadTimestamp = DateTime.Now;
                        context.SaveChanges();
                    }
                    else
                    {
                        isread = true;
                    }
                var message = (Models.Message)result;
                message.IsRead = isread;
                return message;
            });
        }

        public void UpdateMesssages(string username, string[] messageIDs, Action<Data.Message> messageUpdate, Action<Data.MessageRecipient> recipientUpdate)
        {
            Execute(context =>
            {
                List<Guid> messageIds = messageIDs.Select(s => BaseModel.DecryptId(s)).ToList();

                if (messageUpdate != null)
                    foreach (Data.Message message in context.Messages.Where(m => m.FromAccount.Username.ToLower() == username && messageIds.Contains(m.MessageId)))
                        messageUpdate(message);

                foreach (Data.MessageRecipient recipient in context.MessageRecipients.Where(mr => mr.RecipientAccount.Username.ToLower() == username && messageIds.Contains(mr.MessageId)))
                    recipientUpdate(recipient);

                context.SaveChanges();
                return true;

            });
        }

        public void MarkMessagesAsUnread(string username, string[] messageIDs)
        {
            UpdateMesssages(username, messageIDs, null, mr => mr.ReadTimestamp = null);
        }

        public void MarkMessagesAsArchived(string username, string[] messageIDs)
        {
            UpdateMesssages(username, messageIDs, m => m.Archived = true, mr => mr.Archived = true);
        }

        public List<Models.Account> RecipientSearch(string query)
        {
            return Execute(context =>
            {
                List<Models.Account> result = new List<Models.Account>();
                foreach (var account in context.Accounts)
                {

                    Models.Account act = new Models.Account();
                    act.Username = account.Username;
                    act.DisplayName = string.Format("{0} {1}", account.FirstName, account.LastName);

                    act.RecipientSearchName = string.Format("{0} {1} ({2})", account.FirstName, account.LastName, account.Username);
                    if (act.RecipientSearchName.ToLower().Contains(query))
                        result.Add(act);

                }
                return result;
            });
        }

        public void SendMessage(string patientID, string senderUsername, List<string> recipientUsernames, string body)
        {
            Execute(context =>
            {

                var fromAccountId = context.Accounts.Single(a => a.Username.ToLower() == senderUsername.ToLower()).AccountId;
                //var recipientAccountIds = recipientUsernames.Select(un => context.Accounts.Single(a => a.Username.ToLower() == un.ToLower()).AccountId).ToList();

                Data.Message message = new Message
                {
                    Body = body,
                    FromAccountId = fromAccountId,
                    PatientId = Guid.ParseExact(patientID, "N"),
                    SentTimestamp = DateTime.Now
                };
                recipientUsernames.ForEach(un =>
                {
                    Guid recipient = context.Accounts.Single(a => a.FirstName.ToLower() + " " + a.LastName.ToLower() == un.ToLower()).AccountId;
                    message.MessageRecipients.Add(new MessageRecipient
                    {
                        RecipientAccountId = recipient
                    });
                });

                context.Messages.Add(message);

                context.SaveChanges();

                return true;

            });
        }

        public long GetLatestPermission()
        {
            return Execute(context =>
            {
                if (context.ScalePermissions.Count() == 0)
                    return 0;
                DateTime result = context.ScalePermissions.OrderByDescending(sp => sp.LastUpdateTimestamp).First().LastUpdateTimestamp;
                TimeSpan span = (result - new DateTime(1970, 1, 1));
                return (long)span.TotalSeconds;
            });
        }

        public List<Models.Account> GetAccountsOfProvider(string ProviderId, string AccountId)
        {
            return Execute(context =>
            {
                if (string.IsNullOrWhiteSpace(ProviderId))
                {
                    return new List<Models.Account>();
                }
                Guid providerId = BaseModel.DecryptId(ProviderId);

                List<Models.Account> result = new List<Models.Account>();
                foreach (var act in context.ProviderAccountPermissions.Where(pap => pap.ProviderId == providerId && pap.Permission.Description.Equals("Clinician")).Select(pap => pap.Account))
                    if (result.Count(a => a.GUID == act.AccountId) == 0)
                        result.Add((Models.Account)act);
                return result;
            });
        }

        public List<Models.Account> GetAccountsForPatient(string patientID, List<SADFM.Data.Models.Permission> permissions, string ClientType)
        {
            Guid patientId = Guid.ParseExact(patientID, "N");

            return Execute(context =>
            {
                List<Guid> result = new List<Guid>();

                if (ClientType != null)
                {

                    if (ClientType.Equals("Provider"))
                    {
                        result = context.PatientProviders.Where(cp => cp.Case.PatientId == patientId).Select(cp => cp.AccountId).ToList();

                    }
                    if (permissions.FirstOrDefault(x => x.PermissionDescription == "Case Manager") != null)
                    {
                        result.AddRange(context.PatientProviders.Where(cp => cp.Case.PatientId == patientId).SelectMany(cp => cp.Provider.ProviderAccountPermissions).Where(pap => pap.Permission.Name == "Admin" || pap.Permission.Name == "ProviderCaseManager" || pap.Permission.Name == "FunderCaseManager").Select(pap => pap.AccountId));

                        result.AddRange(context.PatientProviders.SelectMany(cp => cp.Provider.ProviderAccountPermissions).Where(pap => pap.Permission.Name == "FunderCaseManager").Select(pap => pap.AccountId));
                    }

                }
                else
                {
                    result.AddRange(context.PatientProviders.Where(cp => cp.Case.PatientId == patientId).SelectMany(cp => cp.Provider.ProviderAccountPermissions).Where(pap => pap.Permission.Name == "Admin" || pap.Permission.Name == "ProviderCaseManager" || pap.Permission.Name == "FunderCaseManager").Select(pap => pap.AccountId));

                    result.AddRange(context.PatientProviders.SelectMany(cp => cp.Provider.ProviderAccountPermissions).Where(pap => pap.Permission.Name == "FunderCaseManager").Select(pap => pap.AccountId));
                }

                List<Models.Account> res = new List<Models.Account>();
                foreach (Guid accountId in result.Distinct())
                {
                    res.Add((Models.Account)context.Accounts.Single(a => a.AccountId == accountId));
                }

                return res.OrderBy(a => a.FirstName).ThenBy(a => a.LastName).ToList();

            });
        }

    }
}


text:
Server: Netscape-Enterprise/2.0a
Date: Tue, 26 Nov 1996 18:38:31 GMT
Accept-ranges: bytes
Last-modified: Thu, 07 Nov 1996 22:34:18 GMT
Content-length: 9883
Content-type: text/html

<title>Florida Tech, CS:  Graphical User Interfaces (Fall 1996)</title>

CSE 5257: Graphical User Interfaces (Fall 1996)

General Information

Instructor

<!WA0>Ryan Stansifer <ryan@cs.fit.edu>

Lectures

Lectures are from 20:00 to 21:15 Tuesdays and Thursdays in
A-121.

Class URL

<!WA1>
<tt>http://www.cs.fit.edu/~ryan/cse5257/</tt>

Catalog Description

<!WA2>CSE 5257.
The theories and techniques of human-computer interaction, and the design of direct manipulation graphical
user interfaces that support menus, buttons, sliders, and other widgets for input, text, and graphics for
output. Students design, implement, and evaluate a graphical user interface. (Prerequisite: CSE 5020.)

Humor

<!WA3>

Course Goals

We will learn Java and Tcl/TK.
Also we expect students to develop
a significant X Window application.

Textbook

The textbook for this class is

John K. Ousterhout.
<!WA4>Tcl & the Tk Toolkit.
<!WA5>Addison Wesley, Reading, Massachusetts, 1994.
ISBN 0-201-63337-X.

A well-known book about user interfaces:

Shneiderman, Ben.
Designing the User Interface:  Strategies for Effective
Human-Computer Interaction, 2nd edition.
Reading, Massachusetts, Addison-Wesley, 1992.
ISBN 0201572869.

Chapters 8, 9 and 10 of Foley, van Dam, Feiner, and Hughes is
even better.

Information on the Net

Java

<!WA6>JavaSoft, a division of Sun Microsystems

<!WA7>Java language specification

Man pages on SPARC Solaris
      <!WA8>javac, <!WA9>java

Man pages on Microsoft Windows NT and Windows 95
      <!WA10>javac, <!WA11>java

<!WA12>API Documentation

JavaSoft's list of bugs in the JDK

      <!WA13><tt>http://java.sun.com/java.sun.com/JDK-1.0/knownbugs.html</tt>

<!WA14>Sun's Java FAQ's

<!WA15>Java FAQ
      for comp.lang.java by Elliotee Harold

<!WA16>JavaScript FAQ by Andy Augustine

<!WA17>Gamelan, extensive collection of applets

<!WA18>JavaSoft Contest Winners
      winning applets in the contest run by JavaSoft

<!WA19>Java World, a WWW magazine

<!WA20>comp.lang.java newsgroup

<!WA21>Digital Espresso
      A weekly summary from Mentor Software of the traffic appearing in the Java mailing lists and news groups.

<!WA22>Java News
      on-line articles in the trade press

<!WA23>ACME Java by Jeff Poskanzer
      contains some libraries of Java code

<!WA24>Java Oasis archive a freely available
      Java code

<!WA25>Java Enabled Browsers
      a Java World.

      <tt>http://www.javaworld.com/javaworld/jw-04-1996/jw-04-browsertable.html</tt>

<!WA26>Concurrent Programming
       in Java by Doug Lea

Tcl/TK

<!WA27>My list of Widget examples

<!WA28>Tcl/Tk Project At Sun Microsystems

<!WA29>Tcl/Tk Resources

<!WA30>Tcl and TK man pages

X Window System

<!WA31>X Windows FAQ
from Europe (EXUG), better organized than Ohio State.

<!WA32>X Windows FAQ at Ohio Stae.

<!WA33>comp.windows.x

<!WA34>X lib man pages

<!WA35>Xt man pages

<!WA36>Athena Widgets X11R6,
    the PostScript document over 100 pages from the MIT distribution.
    Note you may require
    <tt>application/postscript; /usr/local/X11R6/bin/ghostview %s</tt>
    in your <tt>$HOME/.mailcap</tt> file,
    cf <!WA37>Netscape Handbook.

<!WA38>Index to Athena Widgets X11R6,
    the five page PostScript document from the MIT distribution

Classwork and grading

There will be no tests.
Grading will be based subjectively on the assignments
and three medium-sized projects.
Throughout the course there will be a few
small assignments.
Most of the grade will be based on three medium-sized
projects to be done individually.
Students may choose whatever projects they wish.
Oral presentations,
demonstrations of the application
and written reports
are expected.

We will use <tt>tuck.cs.fit.edu</tt> which has
all the software we need installed on it.

<!WA39>Harris Lab

Possible projects

Games

Mastermind, go, orthello, crossword puzzles, minesweeper

Tutoring

Elementary arithmetic, multiple choice tests,
      foreign languages (with sound), programming languages,
      Academic advising

Commerical

Inventory control, real estate (with pictures), form entry

Genealogy

database management, match engine

Drawing

Interface to pstricks

GIS

map of campus, kiosks

Final report

The following is a possible outline of a report:

Introduction

context, motivation

similar software that influenced the project

sources of code and ideas

User manual

Command line options

User interaction

Menus

Screen dumps

Error messages

Implementation

Toolkit used, other tools

Implementation strategy

A table of significant widgets, classes, procedures,
	    and concepts used

Overview of the code

Analysis

Techniques discovered

Comparision with similar applications

Deficiencies

Bugs

Unsolved problems

Appendices

Layout of the components

Widget hierarchy--
	    list all class and instance names of the instance
	    hierarachy and document all resources used.

Code outline

Code

Calendar and Important Dates

         Aug                    Sep                    Oct
 S  M Tu  W Th  F  S    S  M Tu  W Th  F  S    S  M Tu  W Th  F  S
             1  2  3    1  2  3  4  5  6  7          1  2  3  4  5
 4  5  6  7  8  9 10    8  9 10 11 12 13 14    6  7  8  9 10 11 12
11 12 13 14 15 16 17   15 16 17 18 19 20 21   13 14 15 16 17 18 19
18 19 20 21 22 23 24   22 23 24 25 26 27 28   20 21 22 23 24 25 26
25 26 27 28 29 30 31   29 30                  27 28 29 30 31

                    Nov                    Dec
            S  M Tu  W Th  F  S    S  M Tu  W Th  F  S
                           1  2    1  2  3  4  5  6  7
            3  4  5  6  7  8  9    8  9 10 11 12 13 14
           10 11 12 13 14 15 16   15 16 17 18 19 20 21
           17 18 19 20 21 22 23   22 23 24 25 26 27 28
           24 25 26 27 28 29 30   29 30 31

    Tuesday,  August    27, 1996	first lecture

    Friday,  September 6, 1996	<!WA40>asgn #1 due

    Friday,  September 13, 1996	<!WA41>asgn #2 due

Java projects

<!WA42>Palette Applet by Yiqun Lin

Sugar Real Estate by Qing Lu

Mathematician by Ting Zhao

UNO by Miguel A. Guerra

Guess by Anothony Polomik

MasterMind by Mahmut Basak

Simon by Antoine Rolle

Real Estate by Susan Collins

Ice Cream Shop by Hong Zhang

Digital Alarm Clock by A. S. Colomberti

<!WA43>Thumb by Michael Terry

Course Description by Stephen Suhling

3D by Jaewoong Chang

Physics Tutor by Jennifer C. Boelke

Campus Map by Qing Zhang

Campus Map by Nileema Ravindran

McDowell's Burger by Stephen Johnson

<address><!WA44>Ryan Stansifer <ryan@cs.fit.edu></address>

Last modified: Thu Nov  7 17:34:18 EST 1996

redpajama_set_name: RedPajamaGithub


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const RuntimeGlobals = require("../RuntimeGlobals");
const { evaluateToString } = require("../javascript/JavascriptParserHelpers");
const CommonJsExportsDependency = require("./CommonJsExportsDependency");
const CommonJsSelfReferenceDependency = require("./CommonJsSelfReferenceDependency");
const DynamicExports = require("./DynamicExports");
const HarmonyExports = require("./HarmonyExports");
const ModuleDecoratorDependency = require("./ModuleDecoratorDependency");

/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */

/** @type {WeakMap<NormalModule, boolean>} */
const moduleExportsState = new WeakMap();

const getValueOfPropertyDescription = expr => {
	if (expr.type !== "ObjectExpression") return;
	for (const property of expr.properties) {
		if (property.computed) continue;
		const key = property.key;
		if (key.type !== "Identifier" || key.name !== "value") continue;
		return property.value;
	}
};

const isTruthyLiteral = expr => {
	switch (expr.type) {
		case "Literal":
			return !!expr.value;
		case "UnaryExpression":
			if (expr.operator === "!") return isFalsyLiteral(expr.argument);
	}
	return false;
};

const isFalsyLiteral = expr => {
	switch (expr.type) {
		case "Literal":
			return !expr.value;
		case "UnaryExpression":
			if (expr.operator === "!") return isTruthyLiteral(expr.argument);
	}
	return false;
};

class CommonJsExportsParserPlugin {
	static bailout(module) {
		const value = moduleExportsState.get(module);
		moduleExportsState.set(module, false);
		if (value === true) {
			module.buildMeta.exportsType = undefined;
			module.buildMeta.defaultObject = false;
		}
	}

	/**
	 * @param {JavascriptParser} parser the parser
	 */
	apply(parser) {
		const enableStructuredExports = () => {
			DynamicExports.enable(parser.state);
		};
		const checkNamespace = (members, valueExpr) => {
			if (!DynamicExports.isEnabled(parser.state)) return;
			if (members.length > 0 && members[0] === "__esModule") {
				if (isTruthyLiteral(valueExpr)) {
					DynamicExports.setFlagged(parser.state);
				} else {
					DynamicExports.bailout(parser.state);
				}
			}
		};
		const bailout = () => {
			DynamicExports.bailout(parser.state);
		};

		// metadata //
		parser.hooks.evaluateTypeof
			.for("module")
			.tap("CommonJsExportsParserPlugin", evaluateToString("object"));
		parser.hooks.evaluateTypeof
			.for("exports")
			.tap("CommonJsPlugin", evaluateToString("object"));

		// exporting //
		parser.hooks.assignMemberChain
			.for("exports")
			.tap("CommonJsExportsParserPlugin", (expr, members) => {
				if (HarmonyExports.isEnabled(parser.state)) return;
				enableStructuredExports();
				checkNamespace(members, expr.right);
				const dep = new CommonJsExportsDependency(
					expr.left.range,
					null,
					"exports",
					members
				);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				return true;
			});
		parser.hooks.assignMemberChain
			.for("this")
			.tap("CommonJsExportsParserPlugin", (expr, members) => {
				if (HarmonyExports.isEnabled(parser.state)) return;
				if (!parser.scope.topLevelScope) return;
				enableStructuredExports();
				checkNamespace(members, expr.right);
				const dep = new CommonJsExportsDependency(
					expr.left.range,
					null,
					"this",
					members
				);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				return true;
			});
		parser.hooks.assignMemberChain
			.for("module")
			.tap("CommonJsExportsParserPlugin", (expr, members) => {
				if (HarmonyExports.isEnabled(parser.state)) return;
				if (members[0] !== "exports" || members.length <= 1) return;
				enableStructuredExports();
				checkNamespace(members, expr.right);
				const dep = new CommonJsExportsDependency(
					expr.left.range,
					null,
					"module.exports",
					members.slice(1)
				);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				return true;
			});
		parser.hooks.call
			.for("Object.defineProperty")
			.tap("CommonJsExportsParserPlugin", expression => {
				const expr = /** @type {import("estree").CallExpression} */ (expression);
				if (expr.arguments.length !== 3) return;
				if (expr.arguments[0].type === "SpreadElement") return;
				if (expr.arguments[1].type === "SpreadElement") return;
				if (expr.arguments[2].type === "SpreadElement") return;
				const exportsArg = parser.evaluateExpression(expr.arguments[0]);
				if (!exportsArg || !exportsArg.isIdentifier()) return;
				if (
					exportsArg.identifier !== "exports" &&
					exportsArg.identifier !== "module.exports" &&
					(exportsArg.identifier !== "this" || !parser.scope.topLevelScope)
				) {
					return;
				}
				const propertyArg = parser.evaluateExpression(expr.arguments[1]);
				if (!propertyArg) return;
				const property = propertyArg.asString();
				if (typeof property !== "string") return;
				enableStructuredExports();
				const descArg = expr.arguments[2];
				checkNamespace([property], getValueOfPropertyDescription(descArg));
				const dep = new CommonJsExportsDependency(
					expr.range,
					expr.arguments[2].range,
					`Object.defineProperty(${exportsArg.identifier})`,
					[property]
				);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);

				parser.walkExpression(expr.arguments[2]);
				return true;
			});

		// Self reference //
		parser.hooks.expression
			.for("exports")
			.tap("CommonJsExportsParserPlugin", expr => {
				if (HarmonyExports.isEnabled(parser.state)) return;
				bailout();
				const dep = new CommonJsSelfReferenceDependency(
					expr.range,
					"exports",
					[]
				);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				return true;
			});
		parser.hooks.expression
			.for("module.exports")
			.tap("CommonJsExportsParserPlugin", expr => {
				if (HarmonyExports.isEnabled(parser.state)) return;
				bailout();
				const dep = new CommonJsSelfReferenceDependency(
					expr.range,
					"module.exports",
					[]
				);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				return true;
			});
		parser.hooks.expression
			.for("this")
			.tap("CommonJsExportsParserPlugin", expr => {
				if (HarmonyExports.isEnabled(parser.state)) return;
				if (!parser.scope.topLevelScope) return;
				bailout();
				const dep = new CommonJsSelfReferenceDependency(expr.range, "this", []);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				return true;
			});

		// Bailouts //
		parser.hooks.expression.for("module").tap("CommonJsPlugin", expr => {
			bailout();
			const isHarmony = HarmonyExports.isEnabled(parser.state);
			const dep = new ModuleDecoratorDependency(
				isHarmony
					? RuntimeGlobals.harmonyModuleDecorator
					: RuntimeGlobals.nodeModuleDecorator
			);
			dep.loc = expr.loc;
			parser.state.module.addDependency(dep);
			return true;
		});
	}
}
module.exports = CommonJsExportsParserPlugin;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teradata.dmp</groupId>
    <artifactId>apisdk</artifactId>
    <version>${revision}</version>

    <properties>
        <!-- Sane default when no revision property is passed in from the commandline -->
        <revision>0-SNAPSHOT</revision>
    </properties>

    <distributionManagement>
        <repository>
            <id>m2repo</id>
            <url>https://m2repo.muc.ecircle.de/repo/content/repositories/weirdstuff/</url>
        </repository>
    </distributionManagement>

    <dependencies>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
        </dependency>
    </dependencies>
</project>


text:
/**
 * Helix utility classes
 *
 */
package org.apache.helix.util;


text:
(function(Lazy) {

  /**
   * A seqence of DOM nodes.
   *
   * You can get a `DomSequence` by wrapping a `NodeList` or `HTMLCollection`
   * with `Lazy`:
   *
   *     var paragraphs = Lazy(document.querySelectorAll('p'));
   *
   * @public
   * @constructor
   * @param {NodeList|HTMLCollection} source The underlying collection of DOM
   *     nodes.
   */
  function DomSequence(source) {
    this.source = source;
  }

  DomSequence.prototype = new Lazy.ArrayLikeSequence();

  DomSequence.prototype.get = function(i) {
    return this.source[i];
  };

  DomSequence.prototype.length = function() {
    return this.source.length;
  };

  /**
   * Provides a sequence comprising all of this sequence's nodes and their
   * descendents (children, grandchildren, etc.).
   *
   * @public
   * @returns {Sequence}
   */
  DomSequence.prototype.flatten = function() {
    return new FlattenedDomSequence(this.source);
  };

  function FlattenedDomSequence(source) {
    this.source = source;
  }

  FlattenedDomSequence.prototype = new Lazy.Sequence();

  FlattenedDomSequence.prototype.each = function(fn) {
    var i    = 0,
        done = false;

    Lazy(this.source).each(function(child) {
      if (fn(child, i++) === false) {
        return false;
      }

      Lazy(child.children).flatten().each(function(descendent) {
        if (fn(descendent, i++) === false) {
          done = true;
          return false;
        }
      });

      if (done) {
        return false;
      }
    });
  };

  /**
   * Creates a sequence comprising all of the `Event` objects from the given
   * event propagating through the node(s) in the current sequence.
   *
   * @public
   * @param {string} eventName The name of the event to catch.
   * @returns {AsyncSequence}
   */
  DomSequence.prototype.on = function(eventName) {
    return new DomEventSequence(this.source, eventName);
  };

  function DomEventSequence(elements, eventName) {
    this.elements = elements;
    this.eventName = eventName;
  }

  DomEventSequence.prototype = new Lazy.Sequence();

  /**
   * Handles every event in this sequence.
   *
   * @param {function(Event):*} fn The function to call on each event in the
   *     sequence. Return false from the function to stop handling the events.
   */
  DomEventSequence.prototype.each = function(fn) {
    var elements = this.elements,
        eventName = this.eventName;

    var listener = function(e) {
      if (fn(e) === false) {
        for (var i = 0; i < elements.length; ++i) {
          elements[i].removeEventListener(eventName, listener);
        }
      }
    };

    for (var i = 0; i < elements.length; ++i) {
      elements[i].addEventListener(this.eventName, listener);
    }
  };

  /**
   * Creates a {@link Sequence} from the specified DOM events triggered on the
   * given element. This sequence works asynchronously, so synchronous methods
   * such as {@code indexOf}, {@code any}, and {@code toArray} won't work.
   *
   * @param {Element} element The DOM element to capture events from.
   * @param {string} eventName The name of the event type (e.g., 'keypress')
   *     that will make up this sequence.
   * @return {Sequence} The sequence of events.
   */
  Lazy.events = Lazy.deprecate(
    "Lazy.events is deprecated. Use Lazy(element[s]).on('event') instead",
    function(element, eventName) {
      return new DomEventSequence(element, eventName);
    }
  );

  /**
   * A `StreamingHttpSequence` is a {@link StreamLikeSequence} comprising the
   * chunks of data that are streamed in response to an HTTP request.
   *
   * @public
   * @param {string} url The URL of the HTTP request.
   * @constructor
   */
  function StreamingHttpSequence(url) {
    this.url = url;
  }

  StreamingHttpSequence.prototype = new Lazy.StreamLikeSequence();

  StreamingHttpSequence.prototype.each = function each(fn) {
    var request = new XMLHttpRequest(),
        index   = 0,
        aborted = false;

    request.open("GET", this.url);

    var listener = function listener(data) {
      if (!aborted) {
        data = request.responseText.substring(index);
        if (fn(data) === false) {
          request.removeEventListener("progress", listener, false);
          request.abort();
          aborted = true;
        }
        index += data.length;
      }
    };

    request.addEventListener("progress", listener, false);

    request.send();
  };

  /*
   * Add support for `Lazy(NodeList)` and `Lazy(HTMLCollection)`.
   */
  Lazy.extensions || (Lazy.extensions = []);

  Lazy.extensions.push(function(source) {
    if (source instanceof NodeList || source instanceof HTMLCollection) {
      return new DomSequence(source);
    } else if (source instanceof Element) {
      return new DomSequence([source]);
    }
  });

}(window.Lazy));


text:
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3" name="name.mikkoostlund.loginmodules">
    <resources>
        <resource-root path="wildfly_8.2.0.Final-SaltedDatabaseServerLoginModule-0.0.1.Final.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="org.picketbox"/>
    </dependencies>
</module>


text:
package com.example.android.apis.app;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;
import com.example.android.apis.R;

/**
 * Target launch activity for demonstrations from {@link ActionBarNavigation}.
 */
public class ActionBarNavigationTarget extends org.bbs.apklauncher.api.Base_Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.action_bar_navigation_target);

        // Turn on the up affordance.
        final ActionBar bar = getActionBar();
        bar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP);
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>My HTML HW</title>

    <link rel="stylesheet" href="main.css">

Hello my name is Eran Bar

           I am a UX designer learning to code

I solve problems with creative ideas

          who am I?

           Curiosity & Empathy helps me simplify the product's goals and needs.

In order to fulfill them I refine my best ideas into one complete solution.

          As a user experience designer I bring order

and intuition into a communication process

I do it in a unique and fun way.


text:
Shell4Win
=========

Shell4Win is a shell interpreter accepting UNIX/Linux style shell commands and shell scripts,it enables you to use shell on windows platform. it realised many important features of shell,including pipes,colon seperating commands in one line and redirection

As a former UNIX administrator, batch is a little too messy for me and I have wasted too much time on its strange syntaxes and arguments.
If you happen to be familiar with shell and have to deal with Windows from now and then,There is a great chance you will like Shell4Win

How to get
=========

Download zip files and all executables can be found in the bin directory.

How to use
=========

Shell4Win.exe in the bin directory is our main program,double click and you can get an interactive window where you can type in any available commands.

Shell4Win is also capable of explaining shell scripts by typing in sh example.sh

Available Commands
=========

Shell4Win realised many commands in common use and the list of available commands keeps growing.
[echo,cd,ls,cat,rm,grep,wc,mkdir,touch,cp,mv,read,sh,diff...]

Detailed usage information can be found in the [wiki](https://github.com/log4leo/Shell4Win/wiki/Command-Usage)

Some Special Things in Shell4Win
=========

* Execute commands as far as possible

 For example, if you specified a directory as destination that doesn't exist in cp command, Shell4Win will create a directory for you instead of quit the program. So you should be careful when typing some dangerous commands

* Do the same thing to directory and file

 Since I don't enough time to add arguments support for every command, So Shell4Win regards files and directories as the same thing in many cases. e.g rm 1 will remove 1 no matter it is a file or directory, it works the same with other similar commands like cp mv and so on

Dependecies
=========

Shell4Win uses following third party tools:
* [ply](http://www.dabeaz.com/ply/):generate lexical analyzer and syntax analyzer
* [py2exe](http://www.py2exe.org/):generate executable exe files on Windows

License
=========
[MIT]()

Examples
=========

```shell
[Administrator@PC-20121113XYVZ]#ls
parser.out
parsetab.py
parsetab.pyc
ply
Shell4Win.py
tools.py
tools.pyc
utilities.py
utilities.pyc
```

```shell
[Administrator@PC-20121113XYVZ]#ls|grep Shell
Shell4Win.py
```

```shell
[Administrator@PC-20121113XYVZ]#pwd
C:\Users\Administrator\Documents\GitHub\Shell4Win\src
```

```shell
[Administrator@PC-20121113XYVZ]#cat example.sh
echo "#This is a example shell script written to demostrate a shell interpreter named Shell4Win#"

echo "Let's start with some simple commands"

echo "ls can show files under current directory:"

ls

read "Press Enter key to continue"

echo "pwd can show you current directory:"

pwd

read "Press Enter key to continue"

echo "mkdir can make a directory,and grep can be used with pipes:"

mkdir test

ls|grep test

echo "cd can change current directory:"

cd test

echo "redirection can create files:"

echo "test content1">1

echo "test content2">2

cat 1

cat 2

echo "diff can be used to compare two text files:"

diff 1 2

[Administrator@PC-20121113XYVZ]#sh example.sh
#This is a example shell script written to demostrate a shell interpreter named Shell4Win#
Let's start with some simple commands
ls can show files under current directory:
example.sh
parser.out
parsetab.py
parsetab.pyc
ply
Shell4Win.py
test
tools.py
tools.pyc
utilities.py
utilities.pyc
Press Enter key to continue
pwd can show you current directory:
C:\Users\Administrator\Documents\GitHub\Shell4Win\src
Press Enter key to continue
mkdir can make a directory,and grep can be used with pipes:
Directory already existed!
test
cd can change current directory:
change current directory to test
redirection can create files:
test content1
test content2
diff can be used to compare two text files:
line 1:   test content1 	test content2
```


text:
package jibe.tools.sr.api;

import com.google.common.base.Optional;
import com.google.common.base.Strings;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;

/**
 *
 */
public class SRProgram {
    private String description;
    private String email;
    private String phone;
    private String programurl;
    private String programimage;
    private Collection<SRSocialMediaPlatform> socialmediaplatforms = Collections.emptySet();
    private SRChannel channel;
    private Boolean hasondemand;
    private Boolean haspod;
    private String responsibleeditor;
    private int id;
    private String name;

    public Optional<SRChannel> getChannel() {
        return Optional.fromNullable(channel);
    }

    public Optional<String> getDescription() {
        return Optional.fromNullable(Strings.emptyToNull(description));
    }

    public Optional<String> getEmail() {
        return Optional.fromNullable(Strings.emptyToNull(email));
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Optional<String> getPhone() {
        return Optional.fromNullable(Strings.emptyToNull(phone));
    }

    public Optional<URL> getProgramimage() {
        if (Strings.isNullOrEmpty(programimage)) {
            return Optional.absent();
        }
        try {
            return Optional.of(new URL(programimage));
        } catch (MalformedURLException e) {
            return Optional.absent();
        }
    }

    public Optional<URL> getProgramurl() {
        if (Strings.isNullOrEmpty(programurl)) {
            return Optional.absent();
        }
        try {
            return Optional.of(new URL(programurl));
        } catch (MalformedURLException e) {
            return Optional.absent();
        }
    }

    public Collection<SRSocialMediaPlatform> getSocialmediaplatforms() {
        return socialmediaplatforms;
    }
}


text:
Haskell library for interfacing with the [Codeship JSON API](https://codeship.com/documentation/integrations/api/).

## Example

``` haskell
module Main where

import Control.Applicative
import Network.API.Codeship
import System.Environment

main :: IO ()
main = do
  result <- projects =<< CodeshipKey <$> getEnv "CODESHIP_API_KEY"
  print result
```

## TODO

- [x] `GET /api/v1/projects.json`
- [x] `GET /api/v1/projects/:project_id.json`
- [x] `GET /api/v1/builds/:build_id/restart.json`
- [ ] Docs
- [ ] Tests
- [ ] More type safety


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>text-combine-upright:digits</title>
<link rel="author" title="Richard Ishida" href="mailto:ishida@w3.org"/>
<link rel="help" href="https://drafts.csswg.org/css-writing-modes-4/#text-combine-upright"/>
<meta name="assert" content="text-combine-upright:digits will display two-digit numbers horizontally, but not others."/>

Test passes if 5 and 12 are upright, and 2016 and 242 are not.

今日は2016年5月12日です。242日目です。


text: hello home


text:
from os.path import dirname
import unittest

class TestSentencePiece(unittest.TestCase):

    # Based on https://github.com/google/sentencepiece/blob/v0.1.95/python/README.md
    def test_basic(self):
        import sentencepiece as spm
        sp = spm.SentencePieceProcessor(model_file=f"{dirname(__file__)}/test_model.model")
        self.assertEqual([284, 47, 11, 4, 15, 400],
                         sp.encode("This is a test"))


text:
package godot

import (
	"github.com/shadowapex/godot-go/gdnative"
)

/*------------------------------------------------------------------------------
//   This code was generated by a tool.
//
//   Changes to this file may cause incorrect behavior and will be lost if
//   the code is regenerated. Any updates should be done in
//   "class.go.tmpl" so they can be included in the generated
//   code.
//----------------------------------------------------------------------------*/

//func NewNavigationPolygonFromPointer(ptr gdnative.Pointer) NavigationPolygon {
func newNavigationPolygonFromPointer(ptr gdnative.Pointer) NavigationPolygon {
	owner := gdnative.NewObjectFromPointer(ptr)
	obj := NavigationPolygon{}
	obj.SetBaseObject(owner)

	return obj
}

/*

 */
type NavigationPolygon struct {
	Resource
	owner gdnative.Object
}

func (o *NavigationPolygon) BaseClass() string {
	return "NavigationPolygon"
}

/*
        Undocumented
	Args: [], Returns: Array
*/
func (o *NavigationPolygon) X_GetOutlines() gdnative.Array {
	//log.Println("Calling NavigationPolygon.X_GetOutlines()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "_get_outlines")

	// Call the parent method.
	// Array
	retPtr := gdnative.NewEmptyArray()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewArrayFromPointer(retPtr)
	return ret
}

/*
        Undocumented
	Args: [], Returns: Array
*/
func (o *NavigationPolygon) X_GetPolygons() gdnative.Array {
	//log.Println("Calling NavigationPolygon.X_GetPolygons()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "_get_polygons")

	// Call the parent method.
	// Array
	retPtr := gdnative.NewEmptyArray()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewArrayFromPointer(retPtr)
	return ret
}

/*
        Undocumented
	Args: [{ false outlines Array}], Returns: void
*/
func (o *NavigationPolygon) X_SetOutlines(outlines gdnative.Array) {
	//log.Println("Calling NavigationPolygon.X_SetOutlines()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromArray(outlines)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "_set_outlines")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Undocumented
	Args: [{ false polygons Array}], Returns: void
*/
func (o *NavigationPolygon) X_SetPolygons(polygons gdnative.Array) {
	//log.Println("Calling NavigationPolygon.X_SetPolygons()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromArray(polygons)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "_set_polygons")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [{ false outline PoolVector2Array}], Returns: void
*/
func (o *NavigationPolygon) AddOutline(outline gdnative.PoolVector2Array) {
	//log.Println("Calling NavigationPolygon.AddOutline()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromPoolVector2Array(outline)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "add_outline")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [{ false outline PoolVector2Array} { false index int}], Returns: void
*/
func (o *NavigationPolygon) AddOutlineAtIndex(outline gdnative.PoolVector2Array, index gdnative.Int) {
	//log.Println("Calling NavigationPolygon.AddOutlineAtIndex()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 2, 2)
	ptrArguments[0] = gdnative.NewPointerFromPoolVector2Array(outline)
	ptrArguments[1] = gdnative.NewPointerFromInt(index)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "add_outline_at_index")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [{ false polygon PoolIntArray}], Returns: void
*/
func (o *NavigationPolygon) AddPolygon(polygon gdnative.PoolIntArray) {
	//log.Println("Calling NavigationPolygon.AddPolygon()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromPoolIntArray(polygon)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "add_polygon")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [], Returns: void
*/
func (o *NavigationPolygon) ClearOutlines() {
	//log.Println("Calling NavigationPolygon.ClearOutlines()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "clear_outlines")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [], Returns: void
*/
func (o *NavigationPolygon) ClearPolygons() {
	//log.Println("Calling NavigationPolygon.ClearPolygons()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "clear_polygons")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [{ false idx int}], Returns: PoolVector2Array
*/
func (o *NavigationPolygon) GetOutline(idx gdnative.Int) gdnative.PoolVector2Array {
	//log.Println("Calling NavigationPolygon.GetOutline()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(idx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "get_outline")

	// Call the parent method.
	// PoolVector2Array
	retPtr := gdnative.NewEmptyPoolVector2Array()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewPoolVector2ArrayFromPointer(retPtr)
	return ret
}

/*

	Args: [], Returns: int
*/
func (o *NavigationPolygon) GetOutlineCount() gdnative.Int {
	//log.Println("Calling NavigationPolygon.GetOutlineCount()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "get_outline_count")

	// Call the parent method.
	// int
	retPtr := gdnative.NewEmptyInt()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewIntFromPointer(retPtr)
	return ret
}

/*

	Args: [{ false idx int}], Returns: PoolIntArray
*/
func (o *NavigationPolygon) GetPolygon(idx gdnative.Int) gdnative.PoolIntArray {
	//log.Println("Calling NavigationPolygon.GetPolygon()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(idx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "get_polygon")

	// Call the parent method.
	// PoolIntArray
	retPtr := gdnative.NewEmptyPoolIntArray()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewPoolIntArrayFromPointer(retPtr)
	return ret
}

/*

	Args: [], Returns: int
*/
func (o *NavigationPolygon) GetPolygonCount() gdnative.Int {
	//log.Println("Calling NavigationPolygon.GetPolygonCount()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "get_polygon_count")

	// Call the parent method.
	// int
	retPtr := gdnative.NewEmptyInt()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewIntFromPointer(retPtr)
	return ret
}

/*

	Args: [], Returns: PoolVector2Array
*/
func (o *NavigationPolygon) GetVertices() gdnative.PoolVector2Array {
	//log.Println("Calling NavigationPolygon.GetVertices()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "get_vertices")

	// Call the parent method.
	// PoolVector2Array
	retPtr := gdnative.NewEmptyPoolVector2Array()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewPoolVector2ArrayFromPointer(retPtr)
	return ret
}

/*

	Args: [], Returns: void
*/
func (o *NavigationPolygon) MakePolygonsFromOutlines() {
	//log.Println("Calling NavigationPolygon.MakePolygonsFromOutlines()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "make_polygons_from_outlines")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [{ false idx int}], Returns: void
*/
func (o *NavigationPolygon) RemoveOutline(idx gdnative.Int) {
	//log.Println("Calling NavigationPolygon.RemoveOutline()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(idx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "remove_outline")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [{ false idx int} { false outline PoolVector2Array}], Returns: void
*/
func (o *NavigationPolygon) SetOutline(idx gdnative.Int, outline gdnative.PoolVector2Array) {
	//log.Println("Calling NavigationPolygon.SetOutline()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 2, 2)
	ptrArguments[0] = gdnative.NewPointerFromInt(idx)
	ptrArguments[1] = gdnative.NewPointerFromPoolVector2Array(outline)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "set_outline")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*

	Args: [{ false vertices PoolVector2Array}], Returns: void
*/
func (o *NavigationPolygon) SetVertices(vertices gdnative.PoolVector2Array) {
	//log.Println("Calling NavigationPolygon.SetVertices()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromPoolVector2Array(vertices)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("NavigationPolygon", "set_vertices")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

// NavigationPolygonImplementer is an interface that implements the methods
// of the NavigationPolygon class.
type NavigationPolygonImplementer interface {
	ResourceImplementer
	X_GetOutlines() gdnative.Array
	X_GetPolygons() gdnative.Array
	X_SetOutlines(outlines gdnative.Array)
	X_SetPolygons(polygons gdnative.Array)
	AddOutline(outline gdnative.PoolVector2Array)
	AddOutlineAtIndex(outline gdnative.PoolVector2Array, index gdnative.Int)
	AddPolygon(polygon gdnative.PoolIntArray)
	ClearOutlines()
	ClearPolygons()
	GetOutline(idx gdnative.Int) gdnative.PoolVector2Array
	GetOutlineCount() gdnative.Int
	GetPolygon(idx gdnative.Int) gdnative.PoolIntArray
	GetPolygonCount() gdnative.Int
	GetVertices() gdnative.PoolVector2Array
	MakePolygonsFromOutlines()
	RemoveOutline(idx gdnative.Int)
	SetOutline(idx gdnative.Int, outline gdnative.PoolVector2Array)
	SetVertices(vertices gdnative.PoolVector2Array)
}


text:
package com.brewerydb.api.result.ingredient;

import com.brewerydb.api.model.Ingredient;
import com.brewerydb.api.result.AbstractListResult;

public class GetIngredientsResult extends AbstractListResult<Ingredient> {
}


text:
UPGRADE FROM 2.x to 3.0
=======================

## PHP

The minimum requirement is php 7.2.

## Interfaces

The `Pager\PagerInterface` implements `\Iterator` and `\Countable`.
All public methods of `Pager\BasePager` were moved to `Pager\PagerInterface`.

## Type hinting and API closing

Now that only PHP >= 7.1 is supported, many signatures have changed: type hinting was
added for the parameters or the return value. Also all classes were made final to
allow slightly modification in upcoming minor releases.


text:
export default {
  precision: 'mediump',

  /**
   *
   * @param {WebGLRenderer} renderer
   */
  init(renderer) {
    this.precision = renderer.capabilities.getMaxPrecision('highp')
  }
}


text:
package org.hisp.dhis.importexport;

import java.util.Properties;

/**
 * @author Lars Helge Overland
 * @version $Id: IbatisConfigurationManager.java 6270 2008-11-13 11:49:21Z larshelg $
 */
public interface IbatisConfigurationManager
{
    String ID = IbatisConfigurationManager.class.getName();

    Properties getPropertiesConfiguration();

    void setConfiguration( String connectionUrl, String username, String password, String levels );

    boolean fileIsValid( String path );
}


text:
Inconsolata for Powerline
=========================

:Font creator: Raph Levien
:Source: http://levien.com/type/myfonts/inconsolata.html
:Patched by:
    `Kha <https://github.com/Kha>`_,
    `Joel Chippindale <https://github.com/mocoso>`_ (bold variant)


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

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

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

    /**
     *

     * A list of detection jobs.
     *

     */
    private java.util.List<ExecutionStatus> executionList;
    /**
     *

     * The pagination token that's included if more results are available.
     *

     */
    private String nextToken;

    /**
     *

     * A list of detection jobs.
     *

     *
     * @return A list of detection jobs.
     */

    public java.util.List<ExecutionStatus> getExecutionList() {
        return executionList;
    }

    /**
     *

     * A list of detection jobs.
     *

     *
     * @param executionList
     *        A list of detection jobs.
     */

    public void setExecutionList(java.util.Collection<ExecutionStatus> executionList) {
        if (executionList == null) {
            this.executionList = null;
            return;
        }

        this.executionList = new java.util.ArrayList<ExecutionStatus>(executionList);
    }

    /**
     *

     * A list of detection jobs.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setExecutionList(java.util.Collection)} or {@link #withExecutionList(java.util.Collection)} if you want
     * to override the existing values.
     *

     *
     * @param executionList
     *        A list of detection jobs.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAnomalyDetectionExecutionsResult withExecutionList(ExecutionStatus... executionList) {
        if (this.executionList == null) {
            setExecutionList(new java.util.ArrayList<ExecutionStatus>(executionList.length));
        }
        for (ExecutionStatus ele : executionList) {
            this.executionList.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of detection jobs.
     *

     *
     * @param executionList
     *        A list of detection jobs.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAnomalyDetectionExecutionsResult withExecutionList(java.util.Collection<ExecutionStatus> executionList) {
        setExecutionList(executionList);
        return this;
    }

    /**
     *

     * The pagination token that's included if more results are available.
     *

     *
     * @param nextToken
     *        The pagination token that's included if more results are available.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The pagination token that's included if more results are available.
     *

     *
     * @return The pagination token that's included if more results are available.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The pagination token that's included if more results are available.
     *

     *
     * @param nextToken
     *        The pagination token that's included if more results are available.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAnomalyDetectionExecutionsResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        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 (getExecutionList() != null)
            sb.append("ExecutionList: ").append(getExecutionList()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof DescribeAnomalyDetectionExecutionsResult == false)
            return false;
        DescribeAnomalyDetectionExecutionsResult other = (DescribeAnomalyDetectionExecutionsResult) obj;
        if (other.getExecutionList() == null ^ this.getExecutionList() == null)
            return false;
        if (other.getExecutionList() != null && other.getExecutionList().equals(this.getExecutionList()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getExecutionList() == null) ? 0 : getExecutionList().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeAnomalyDetectionExecutionsResult clone() {
        try {
            return (DescribeAnomalyDetectionExecutionsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package nl.knaw.dans.common.lang.service.exceptions;

public class TooManyFilesException extends FileSizeException
{
    private static final long serialVersionUID = -5031587075131504991L;

    public TooManyFilesException(String message)
    {
        super(message);
    }

    public TooManyFilesException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public TooManyFilesException(Throwable cause)
    {
        super(cause);
    }

    public TooManyFilesException(int amount, int limit)
    {
        super("The zip file exceeds the max number (" + limit + ") of files.");
        this.amount = amount;
        this.limit = limit;
    }

}


text:
This package contains classes that can be used as input types for Lambda functions that process Amazon Cognito events.

# Sample Function

The following is a sample class and Lambda function that receives Amazon Cognito event record data as an input and writes the record data to CloudWatch Logs. (Note that by default anything written to Console will be logged as CloudWatch Logs events.)

```csharp
public class Function
{
    public void Handler(CognitoEvent cognitoEvent)
    {
        foreach(var datasetKVP in cognitoEvent.DatasetRecords)
        {
            var datasetName = datasetKVP.Key;
            var datasetRecord = datasetKVP.Value;

            Console.WriteLine($"[{cognitoEvent.EventType}-{datasetName}] {datasetRecord.OldValue} -> {datasetRecord.Op} -> {datasetRecord.NewValue}");
        }
    }
}
```