问:
C# - Look up direct reports in active directory
I am using System.DirectoryServices.AccountManagement to manage my login user account.

I am able to get information for login user, but not able to get direct reports user id based on manager.

```<code>var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
</code>```

I have refer to this link: C# - Look up a users manager in active directory

But still didn't get any clue. Anyone can help me on this?

答:
I have designed class for active directory search.

This class support.

Search Employee By Same Account Name

Search Employee By Employee Id

Search Employee By Employee Code

Search Employee By Employee Email

Search Employee Manage

Search Team Member

CLASS CODE

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace UAT.COMMON
{
    #region RefranceHelpers
    /*
        //https://www.c-sharpcorner.com/article/active-directory-and-net/
        //https://ianatkinson.net/computing/adcsharp.htm
        //https://ianatkinson.net/computing/adcsharp.htm
    */
    #endregion

    public enum SearchBy
    {
        StartNTID=0,
    }
    public class ManageDirectoryServices : IDisposable
    {
        public ContextType contextType = ContextType.Domain;
        public PrincipalContext Context { get; protected set; }
        public UserPrincipal User { get; protected set; }
        public UserPrincipal Manager { get; protected set; }
        public bool IsManager { get; protected set; }
        public List<UserPrincipal> DirectReports { get; protected set; }

        public class AuthenticationResult
        {
            public AuthenticationResult()
            {
                IdentityError = new List<IdentityError>();
                IsSuccess = IdentityError.Count > 0;
            }
            public List<IdentityError> IdentityError { get; private set; }
            public String RoleName { get; private set; }
            public Boolean IsSuccess { get; set; }
            public ManageDirectoryServices Context { get; set; }
        }

        public ManageDirectoryServices()
        {
            Context = new PrincipalContext(contextType);
            DirectReports = new List<UserPrincipal>();
        }

        public ManageDirectoryServices(string ntid)
        {
            Context = new PrincipalContext(contextType);
            DirectReports = new List<UserPrincipal>();
            GetEmployeeByNTID(NormalizeNTID(ntid));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="ntid">This is SamAccountName</param>
        /// <returns></returns>
        public ManageDirectoryServices GetEmployeeByNTID(string ntid)
        {
            if (string.IsNullOrWhiteSpace(ntid)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                SamAccountName = ntid
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        public ManageDirectoryServices GetEmployee(string strSearch,string prop)
        {
            if (string.IsNullOrWhiteSpace(strSearch)) return this;
            if (string.IsNullOrWhiteSpace(prop)) return this;

            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(cn={0})", strSearch);
            search.PropertiesToLoad.Add(prop);
            var result = search.FindAll();

            if (result != null)
            {
                int directReports = result.Count; //result.Properties["displayname"].Count;
                if (directReports < 0) return null;

                for (int counter = 0; counter < directReports; counter++)
                {
                    var user = (string)result[counter].Properties["givenname"][counter];
                    var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
                    this.DirectReports.Add(reporte);
                    IsManager = true;
                }
                return this;
            }
            return null;
        }

        public ManageDirectoryServices GetEmployee(UserPrincipal searchTemplate)
        {
            if (searchTemplate == null) return null;
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="NTID">This is SamAccountName</param>
        /// <returns></returns>
        public bool IsUserExist(string NTID)
        {
            var data = GetEmployeeByNTID(NormalizeNTID(NTID));
            return !string.IsNullOrWhiteSpace(data?.User?.SamAccountName);
        }

        public bool IsUserExist()
        {
            var data = User;
            return !string.IsNullOrWhiteSpace(data?.SamAccountName);
        }

        public ManageDirectoryServices GetEmployeeByEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                EmailAddress = email
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        public ManageDirectoryServices GetEmployeeByEmpId(string employeeId)
        {
            if (string.IsNullOrWhiteSpace(employeeId)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                EmployeeId = employeeId
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        public ManageDirectoryServices GetManager()
        {
            if (this.User == null) return null;
            DirectoryEntry ManagerDE = this.User.GetUnderlyingObject() as DirectoryEntry;
            var manager = ManagerDE.Properties["manager"].Value.ToString();
            UserPrincipal oManager = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, manager);
            this.Manager = oManager;
            return this;
        }

        public ManageDirectoryServices GetDirectReports()
        {
            if (this.User == null) return this;
            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(cn={0})", this.User.SamAccountName);
            search.PropertiesToLoad.Add("directReports");
            SearchResult result = search.FindOne();
            if (result != null)
            {
                int directReports = result.Properties["directReports"].Count;
                if (directReports < 0) return null;

                for (int counter = 0; counter < directReports; counter++)
                {
                    var user = (string)result.Properties["directReports"][counter];
                    var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
                    this.DirectReports.Add(reporte);
                    IsManager = true;
                }
                return this;
            }
            return null;
        }

        public string NormalizeNTID(string Id)
        {
            if (string.IsNullOrWhiteSpace(Id)) return "";
            return Id.Trim().ToUpper().Replace(@"\", "")
                .Replace("\\", "")
                .Replace("/", "")
                .Replace("//", "")
                .Replace("MS", "")
                .Replace("MS//", "")
                .Replace("MS\\", "");
        }

        public AuthenticationResult SignIn(string ntid, string password)
        {
            var NormalizeNTID = this.NormalizeNTID(ntid);
            bool IsAuthenticated = false;
            IdentityError identityError = new IdentityError();
            ManageDirectoryServices context = null;
            AuthenticationResult authenticationResult = new AuthenticationResult();
            var IsSuccess = Context.ValidateCredentials(NormalizeNTID, password, ContextOptions.Negotiate);
            context = GetEmployeeByNTID(NormalizeNTID);
            if (IsSuccess)
            {
                if (context.User != null)
                {
                    IsAuthenticated = true;
                    this.User = context.User;
                    authenticationResult.Context = context;
                    authenticationResult.IsSuccess = true;
                }
            }
            else
            {
                if (!IsAuthenticated || User == null)
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "InCorrectUserAndPassword",
                        Description = "Username or Password is not correct"
                    });
                }

                if (context.User.IsAccountLockedOut())
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "YourAccountIsLocked",
                        Description = "Your account is locked."
                    });
                }

                if (context.User.Enabled.HasValue && User.Enabled.Value == false)
                {
                    authenticationResult.IdentityError.Add(identityError = new IdentityError
                    {
                        Code = "YourAccountIsDisabled",
                        Description = "Your account is disabled"
                    });
                }
                else
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "InvalidLogin",
                        Description = "In valid login!! Please try again"
                    });
                }
            }
            return authenticationResult;
        }

        #region ************Async Envelope**************

        public async Task<ManageDirectoryServices> GetEmployeeByNTIDAsync(string ntid)
        {
            return await Task.Run(() => GetEmployeeByNTID(ntid));
        }

        public async Task<ManageDirectoryServices> GetEmployeeByEmailAsync(string email)
        {
            return await Task.Run(() => GetEmployeeByEmail(email));
        }

        public async Task<ManageDirectoryServices> GetEmployeeByEmpIdAsync(string employeeId)
        {
            return await Task.Run(() => GetEmployeeByEmpId(employeeId));
        }

        public async Task<ManageDirectoryServices> GetManagerAsync()
        {
            return await Task.Run(() => GetManager());
        }

        public async Task<ManageDirectoryServices> GetDirectReportsAsync()
        {
            return await Task.Run(() => GetDirectReports());
        }

        public async Task<AuthenticationResult> SignInAsync(string ntid, string password)
        {
            return await Task.Run(() => SignIn(ntid, password));
        }

        #endregion

        public void Dispose()
        {
            this.Dispose();
            GC.Collect();
        }

    }
}
</code>```

How To Use

```<code>[TestMethod]
        public void ContractorInitialsSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices(MSID);
            var context = manageDirectoryServices.User;
            Assert.AreEqual(MSID, context.SamAccountName);
        }

        [TestMethod]
        public void SignInSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.SignIn(MSID,MSPASSWORD);
            Assert.AreEqual(EMAIL, context.Context.User.EmailAddress);
        }

        [TestMethod]
        public void GetEmployeeByNTIDSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            Assert.AreEqual(MSID, context.User.SamAccountName);
        }

        [TestMethod]
        public void GetManagerSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            var manager = context.GetManager();
            Assert.AreEqual(MANAGER_NTID, context.Manager.SamAccountName);
        }

        [TestMethod]
        public void GetReportesSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            var repcontext = context.GetDirectReports();
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeByEmailSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByEmail(EMAIL);
            Assert.AreEqual(EMAIL, context.User.EmailAddress);
        }

        [TestMethod]
        public void GetEmployeeByEmployeeIdSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByEmpId(EMPLOYEEID);
            Assert.AreEqual(EMPLOYEEID, context.User.EmployeeId);
        }

        [TestMethod]
        public void IsUserExistSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var IsExist = manageDirectoryServices.IsUserExist(MSID);
            Assert.AreEqual(true, IsExist);
        }

        [TestMethod]
        public void IsUserExistFail()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var IsExist = manageDirectoryServices.IsUserExist("invalidid");
            Assert.AreEqual(false, IsExist);
        }

        [TestMethod]
        public void GetEmployeeSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var searchTemplate = new System.DirectoryServices.AccountManagement.UserPrincipal(manageDirectoryServices.Context) {
                SamAccountName= MSID,
                EmailAddress=EMAIL,
                EmployeeId=EMPLOYEEID
            };
            var context = manageDirectoryServices.GetEmployee(searchTemplate);
            Assert.AreEqual(MSID, context.User.SamAccountName);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess0()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "givenname");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess1()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "name");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess2()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "displayname");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }
</code>```

Body:
I am using System.DirectoryServices.AccountManagement to manage my login user account.

I am able to get information for login user, but not able to get direct reports user id based on manager.

var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);

I have refer to this link: C# - Look up a users manager in active directory

But still didn't get any clue. Anyone can help me on this?

Body:
I have designed class for active directory search.

This class support.

Search Employee By Same Account Name

Search Employee By Employee Id

Search Employee By Employee Code

Search Employee By Employee Email

Search Employee Manage

Search Team Member

CLASS CODE

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace UAT.COMMON
{
    #region RefranceHelpers
    /*
        //https://www.c-sharpcorner.com/article/active-directory-and-net/
        //https://ianatkinson.net/computing/adcsharp.htm
        //https://ianatkinson.net/computing/adcsharp.htm
    */
    #endregion

    public enum SearchBy
    {
        StartNTID=0,
    }
    public class ManageDirectoryServices : IDisposable
    {
        public ContextType contextType = ContextType.Domain;
        public PrincipalContext Context { get; protected set; }
        public UserPrincipal User { get; protected set; }
        public UserPrincipal Manager { get; protected set; }
        public bool IsManager { get; protected set; }
        public List<UserPrincipal> DirectReports { get; protected set; }

        public class AuthenticationResult
        {
            public AuthenticationResult()
            {
                IdentityError = new List<IdentityError>();
                IsSuccess = IdentityError.Count > 0;
            }
            public List<IdentityError> IdentityError { get; private set; }
            public String RoleName { get; private set; }
            public Boolean IsSuccess { get; set; }
            public ManageDirectoryServices Context { get; set; }
        }

        public ManageDirectoryServices()
        {
            Context = new PrincipalContext(contextType);
            DirectReports = new List<UserPrincipal>();
        }

        public ManageDirectoryServices(string ntid)
        {
            Context = new PrincipalContext(contextType);
            DirectReports = new List<UserPrincipal>();
            GetEmployeeByNTID(NormalizeNTID(ntid));
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="ntid">This is SamAccountName</param>
        /// <returns></returns>
        public ManageDirectoryServices GetEmployeeByNTID(string ntid)
        {
            if (string.IsNullOrWhiteSpace(ntid)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                SamAccountName = ntid
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        public ManageDirectoryServices GetEmployee(string strSearch,string prop)
        {
            if (string.IsNullOrWhiteSpace(strSearch)) return this;
            if (string.IsNullOrWhiteSpace(prop)) return this;

            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(cn={0})", strSearch);
            search.PropertiesToLoad.Add(prop);
            var result = search.FindAll();

            if (result != null)
            {
                int directReports = result.Count; //result.Properties["displayname"].Count;
                if (directReports < 0) return null;

                for (int counter = 0; counter < directReports; counter++)
                {
                    var user = (string)result[counter].Properties["givenname"][counter];
                    var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
                    this.DirectReports.Add(reporte);
                    IsManager = true;
                }
                return this;
            }
            return null;
        }

        public ManageDirectoryServices GetEmployee(UserPrincipal searchTemplate)
        {
            if (searchTemplate == null) return null;
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="NTID">This is SamAccountName</param>
        /// <returns></returns>
        public bool IsUserExist(string NTID)
        {
            var data = GetEmployeeByNTID(NormalizeNTID(NTID));
            return !string.IsNullOrWhiteSpace(data?.User?.SamAccountName);
        }

        public bool IsUserExist()
        {
            var data = User;
            return !string.IsNullOrWhiteSpace(data?.SamAccountName);
        }

        public ManageDirectoryServices GetEmployeeByEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                EmailAddress = email
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        public ManageDirectoryServices GetEmployeeByEmpId(string employeeId)
        {
            if (string.IsNullOrWhiteSpace(employeeId)) return null;
            UserPrincipal searchTemplate = new UserPrincipal(Context)
            {
                EmployeeId = employeeId
            };
            PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
            User = (UserPrincipal)ps.FindOne();
            return this;
        }

        public ManageDirectoryServices GetManager()
        {
            if (this.User == null) return null;
            DirectoryEntry ManagerDE = this.User.GetUnderlyingObject() as DirectoryEntry;
            var manager = ManagerDE.Properties["manager"].Value.ToString();
            UserPrincipal oManager = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, manager);
            this.Manager = oManager;
            return this;
        }

        public ManageDirectoryServices GetDirectReports()
        {
            if (this.User == null) return this;
            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(cn={0})", this.User.SamAccountName);
            search.PropertiesToLoad.Add("directReports");
            SearchResult result = search.FindOne();
            if (result != null)
            {
                int directReports = result.Properties["directReports"].Count;
                if (directReports < 0) return null;

                for (int counter = 0; counter < directReports; counter++)
                {
                    var user = (string)result.Properties["directReports"][counter];
                    var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
                    this.DirectReports.Add(reporte);
                    IsManager = true;
                }
                return this;
            }
            return null;
        }

        public string NormalizeNTID(string Id)
        {
            if (string.IsNullOrWhiteSpace(Id)) return "";
            return Id.Trim().ToUpper().Replace(@"\", "")
                .Replace("\\", "")
                .Replace("/", "")
                .Replace("//", "")
                .Replace("MS", "")
                .Replace("MS//", "")
                .Replace("MS\\", "");
        }

        public AuthenticationResult SignIn(string ntid, string password)
        {
            var NormalizeNTID = this.NormalizeNTID(ntid);
            bool IsAuthenticated = false;
            IdentityError identityError = new IdentityError();
            ManageDirectoryServices context = null;
            AuthenticationResult authenticationResult = new AuthenticationResult();
            var IsSuccess = Context.ValidateCredentials(NormalizeNTID, password, ContextOptions.Negotiate);
            context = GetEmployeeByNTID(NormalizeNTID);
            if (IsSuccess)
            {
                if (context.User != null)
                {
                    IsAuthenticated = true;
                    this.User = context.User;
                    authenticationResult.Context = context;
                    authenticationResult.IsSuccess = true;
                }
            }
            else
            {
                if (!IsAuthenticated || User == null)
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "InCorrectUserAndPassword",
                        Description = "Username or Password is not correct"
                    });
                }

                if (context.User.IsAccountLockedOut())
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "YourAccountIsLocked",
                        Description = "Your account is locked."
                    });
                }

                if (context.User.Enabled.HasValue && User.Enabled.Value == false)
                {
                    authenticationResult.IdentityError.Add(identityError = new IdentityError
                    {
                        Code = "YourAccountIsDisabled",
                        Description = "Your account is disabled"
                    });
                }
                else
                {
                    authenticationResult.IdentityError.Add(new IdentityError
                    {
                        Code = "InvalidLogin",
                        Description = "In valid login!! Please try again"
                    });
                }
            }
            return authenticationResult;
        }

        #region ************Async Envelope**************

        public async Task<ManageDirectoryServices> GetEmployeeByNTIDAsync(string ntid)
        {
            return await Task.Run(() => GetEmployeeByNTID(ntid));
        }

        public async Task<ManageDirectoryServices> GetEmployeeByEmailAsync(string email)
        {
            return await Task.Run(() => GetEmployeeByEmail(email));
        }

        public async Task<ManageDirectoryServices> GetEmployeeByEmpIdAsync(string employeeId)
        {
            return await Task.Run(() => GetEmployeeByEmpId(employeeId));
        }

        public async Task<ManageDirectoryServices> GetManagerAsync()
        {
            return await Task.Run(() => GetManager());
        }

        public async Task<ManageDirectoryServices> GetDirectReportsAsync()
        {
            return await Task.Run(() => GetDirectReports());
        }

        public async Task<AuthenticationResult> SignInAsync(string ntid, string password)
        {
            return await Task.Run(() => SignIn(ntid, password));
        }

        #endregion

        public void Dispose()
        {
            this.Dispose();
            GC.Collect();
        }

    }
}

How To Use

[TestMethod]
        public void ContractorInitialsSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices(MSID);
            var context = manageDirectoryServices.User;
            Assert.AreEqual(MSID, context.SamAccountName);
        }

        [TestMethod]
        public void SignInSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.SignIn(MSID,MSPASSWORD);
            Assert.AreEqual(EMAIL, context.Context.User.EmailAddress);
        }

        [TestMethod]
        public void GetEmployeeByNTIDSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            Assert.AreEqual(MSID, context.User.SamAccountName);
        }

        [TestMethod]
        public void GetManagerSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            var manager = context.GetManager();
            Assert.AreEqual(MANAGER_NTID, context.Manager.SamAccountName);
        }

        [TestMethod]
        public void GetReportesSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
            var repcontext = context.GetDirectReports();
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeByEmailSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByEmail(EMAIL);
            Assert.AreEqual(EMAIL, context.User.EmailAddress);
        }

        [TestMethod]
        public void GetEmployeeByEmployeeIdSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var context = manageDirectoryServices.GetEmployeeByEmpId(EMPLOYEEID);
            Assert.AreEqual(EMPLOYEEID, context.User.EmployeeId);
        }

        [TestMethod]
        public void IsUserExistSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var IsExist = manageDirectoryServices.IsUserExist(MSID);
            Assert.AreEqual(true, IsExist);
        }

        [TestMethod]
        public void IsUserExistFail()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var IsExist = manageDirectoryServices.IsUserExist("invalidid");
            Assert.AreEqual(false, IsExist);
        }

        [TestMethod]
        public void GetEmployeeSuccess()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var searchTemplate = new System.DirectoryServices.AccountManagement.UserPrincipal(manageDirectoryServices.Context) {
                SamAccountName= MSID,
                EmailAddress=EMAIL,
                EmployeeId=EMPLOYEEID
            };
            var context = manageDirectoryServices.GetEmployee(searchTemplate);
            Assert.AreEqual(MSID, context.User.SamAccountName);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess0()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "givenname");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess1()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "name");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }

        [TestMethod]
        public void GetEmployeeNameSuccess2()
        {
            ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
            var repcontext = manageDirectoryServices.GetEmployee("abhishek", "displayname");
            var flag = repcontext.DirectReports.Count > 0 ? true : false;
            Assert.AreEqual(true, flag);
        }


来源: stackexchange

问:
Outlook vba problem when sending from a Hotmail account
I have an Outlook VBA program that sends Emails to a list of 500+ recipients contained in a spreadsheet. The program functions, but I notice something odd when the Emails are sent from a Hotmail account.  The Emails don't get sent until the macro ends.  It seems like they are suspended somewhere until the macro ends.

On the other hand, when I send from a GMail account, each Email is sent when the ".send" code is encountered.  I call a delay routine (KillSomeTime) so that the sending server doesn't get overwhelmed and to reduce the chance that the Email's will get treated as spam.  But that delay routine is meaningless when the ".SendUsingAccount" is the hotmail account, since they all process at once.

Here is a subset of the code that sends the Emails:

```<code>With objNewItem
    .Display
    'Store the selected sender into objNewItem.SendUsingAccount
    .SendUsingAccount = objSelectedAccount
    'Store the original body into the new item body.
    'NOTE:  HTMLBody preserves the rich text.
    .HTMLBody = objOriginalItem.HTMLBody
    .Subject = objOriginalItem.Subject
    .To = strEmailAddress
        'Loop through the attachments in objOriginalItem
        'Save them to the user's temp folder.
        'Attach them to objNewItem.
        For Each objAtt In objOriginalItem.Attachments
            strAttFile = strTempPath & objAtt
            objAtt.SaveAsFile strAttFile
            objNewItem.Attachments.Add strAttFile, , , objAtt.DisplayName
            objFSO.DeleteFile strAttFile
        Next
    .Send
    'Set and Start objSyncObject to execute "Send / Receive" for this item
    Set objSyncObject = objSyncObjects(1)
    objSyncObject.Start
    'Call the log_event function
    Call log_event(strSubject, strEmailAddress)
    'Call the kill_some_time function
    Call kill_some_time(lngPauseTime)
End With
</code>```

Is there any way to make adjustments to the code so that it takes into account the cause for Hotmail's delay in executing the ".Send"?

答: You can try using the MailItem.DeferredDeliveryTime property which allows setting a Date indicating the date and time the mail message is to be delivered.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have an Outlook VBA program that sends Emails to a list of 500+ recipients contained in a spreadsheet. The program functions, but I notice something odd when the Emails are sent from a Hotmail account.  The Emails don't get sent until the macro ends.  It seems like they are suspended somewhere until the macro ends.

On the other hand, when I send from a GMail account, each Email is sent when the ".send" code is encountered.  I call a delay routine (KillSomeTime) so that the sending server doesn't get overwhelmed and to reduce the chance that the Email's will get treated as spam.  But that delay routine is meaningless when the ".SendUsingAccount" is the hotmail account, since they all process at once.

Here is a subset of the code that sends the Emails:

With objNewItem
    .Display
    'Store the selected sender into objNewItem.SendUsingAccount
    .SendUsingAccount = objSelectedAccount
    'Store the original body into the new item body.
    'NOTE:  HTMLBody preserves the rich text.
    .HTMLBody = objOriginalItem.HTMLBody
    .Subject = objOriginalItem.Subject
    .To = strEmailAddress
        'Loop through the attachments in objOriginalItem
        'Save them to the user's temp folder.
        'Attach them to objNewItem.
        For Each objAtt In objOriginalItem.Attachments
            strAttFile = strTempPath & objAtt
            objAtt.SaveAsFile strAttFile
            objNewItem.Attachments.Add strAttFile, , , objAtt.DisplayName
            objFSO.DeleteFile strAttFile
        Next
    .Send
    'Set and Start objSyncObject to execute "Send / Receive" for this item
    Set objSyncObject = objSyncObjects(1)
    objSyncObject.Start
    'Call the log_event function
    Call log_event(strSubject, strEmailAddress)
    'Call the kill_some_time function
    Call kill_some_time(lngPauseTime)
End With

Is there any way to make adjustments to the code so that it takes into account the cause for Hotmail's delay in executing the ".Send"?


问:
Is there a callback for when a `RecylerView.ViewHolder` instance should be GC'd?

class MyRecyclerViewHolder : RecyclerView.ViewHolder {

  fun onBind(data: Data) {
    // launching an asynchronous action
  }
}
```

<p>I need to cancel the async action I'm launching when <code>onBind(..)</code> is called again on the same <code>MyRecyclerViewHolder</code> instance, or if <code>MyRecyclerViewHolder</code> is ready to be GC'd for whatever reason.</p>

<p>Obviously I can identify when <code>onBind(..)</code> is called again, but how can I register to be made aware of when the <code>MyRecyclerViewHolder(..)</code> instance is ready for GC so I can cancel the async action?</p>

<p>EDIT: Another way to think about this is that imagine that <code>ViewHolder</code> had the following API:</p>

<pre class="lang-kotlin prettyprint-override"><code>interface ViewHolder {

  // because you have constructor access, there's no need for `onCreate(..)`

  // may be called multiple times
  fun onBind(data: Data)

  fun onDestroy() // called once when it is no longer relevant
}
</code>```

How can I be notified that my ViewHolder should be "destroyed" - aka it is no longer relevant for the UI?

答:
You could try to use Object.finalize method but it's not guaranteed to be called:

Why is finalize not being called?

Body:
class MyRecyclerViewHolder : RecyclerView.ViewHolder {

  fun onBind(data: Data) {
    // launching an asynchronous action
  }
}

I need to cancel the async action I'm launching when onBind(..) is called again on the same MyRecyclerViewHolder instance, or if MyRecyclerViewHolder is ready to be GC'd for whatever reason.

Obviously I can identify when onBind(..) is called again, but how can I register to be made aware of when the MyRecyclerViewHolder(..) instance is ready for GC so I can cancel the async action?

EDIT: Another way to think about this is that imagine that ViewHolder had the following API:

interface ViewHolder {

  // because you have constructor access, there's no need for `onCreate(..)`

  // may be called multiple times
  fun onBind(data: Data)

  fun onDestroy() // called once when it is no longer relevant
}

How can I be notified that my ViewHolder should be "destroyed" - aka it is no longer relevant for the UI?


问:
Is it possible for me to get null values I correlated sub queries?
I got that syntax error:

Msg 102, Level 15, State 1, Line 47

  Incorrect syntax near '('

after running this code:

```<code>select *
from enrollment
where grade = (select null(grade) from enrollment)
</code>```

I was trying to run a correlated subquery to output null values of grade in an enrollment table.

答:
The key issue with the question is that null is not a value.

That's why you can't type a = null or a in (null).

You need to use a is null or a is not null to check if there is or there isn't a value.

Body:
I got that syntax error:

Msg 102, Level 15, State 1, Line 47

  Incorrect syntax near '('

after running this code:

select *
from enrollment
where grade = (select null(grade) from enrollment)

I was trying to run a correlated subquery to output null values of grade in an enrollment table.


问:
Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
I am using the following code to make a knex connection, but frequently the error occurred

Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?

Can anyone please suggest the solution for this issue?

```<code>var knexConn = reqKnex({
        client: pClient,
        native: false,
        connection: pConn,
        searchPath: pSearchPath,
        pool: {
            max: 7,
            min: 3,
            acquireTimeout: 60 * 1000
        }
    });

function getTransactionScope(pKnex, callback) {
    try {
        pKnex.transaction(function(trx) {
            return callback(trx);
        });
    } catch (error) {
        console.log(error);
    }
}

function ExecuteSQLQuery(pTranDB, pTrx, pQuery, pCallback) {
    try {
        var query = pTranDB.raw(pQuery);

        if (pTrx) {
            query = query.transacting(pTrx);
        }
        query.then(function(res, error) {
            try {
                if (error) {
                    console.log(error);
                } else {
                    return pCallback(res, error);
                }
            } catch (error) {
                console.log(error);
            }
        }).catch(function(error) {
            return pCallback(null, error);
        });
    } catch (error) {
        console.log(error);
    }
}

function Commit(pTrx, pIsCommit) {
    try {
        if (pIsCommit) {
            pTrx.commit();
        } else {
            pTrx.rollback();
        }
    } catch (error) {
        console.log(error);
    }
}
</code>```

答:
I had the same issue when deploying a strapi app to heroku.
In my package.json I had the following versions:

"knex": "<0.20.0"

"pg": "^7.18.2"

I also had the following node engine configuration:

```<code>"engines": {
  "node": ">=10.0.0",
  "npm": ">=6.0.0"
},
</code>```

Changing the versions to <0.21.1 and ^8.0.3 (as suggested here: https://stackoverflow.com/a/61482183/4696783 ) and changing node engine to 12.16.x (as suggested here: https://stackoverflow.com/a/61942001/4696783) solved the issue.

ContentLicense: CC BY-SA 3.0

Body:
I am using the following code to make a knex connection, but frequently the error occurred

Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?

Can anyone please suggest the solution for this issue?

var knexConn = reqKnex({
        client: pClient,
        native: false,
        connection: pConn,
        searchPath: pSearchPath,
        pool: {
            max: 7,
            min: 3,
            acquireTimeout: 60 * 1000
        }
    });

function getTransactionScope(pKnex, callback) {
    try {
        pKnex.transaction(function(trx) {
            return callback(trx);
        });
    } catch (error) {
        console.log(error);
    }
}

function ExecuteSQLQuery(pTranDB, pTrx, pQuery, pCallback) {
    try {
        var query = pTranDB.raw(pQuery);

        if (pTrx) {
            query = query.transacting(pTrx);
        }
        query.then(function(res, error) {
            try {
                if (error) {
                    console.log(error);
                } else {
                    return pCallback(res, error);
                }
            } catch (error) {
                console.log(error);
            }
        }).catch(function(error) {
            return pCallback(null, error);
        });
    } catch (error) {
        console.log(error);
    }
}

function Commit(pTrx, pIsCommit) {
    try {
        if (pIsCommit) {
            pTrx.commit();
        } else {
            pTrx.rollback();
        }
    } catch (error) {
        console.log(error);
    }
}

Body:
I had the same issue when deploying a strapi app to heroku.
In my package.json I had the following versions:

"knex": "<0.20.0"

"pg": "^7.18.2"

I also had the following node engine configuration:

"engines": {
  "node": ">=10.0.0",
  "npm": ">=6.0.0"
},

Changing the versions to <0.21.1 and ^8.0.3 (as suggested here: https://stackoverflow.com/a/61482183/4696783 ) and changing node engine to 12.16.x (as suggested here: https://stackoverflow.com/a/61942001/4696783) solved the issue.


问:
How to display only searched results in the browser as response
I have a MongoDB collection that I search through by using a value from an input field using the $search operator and it works, when I console log the result it shows me only those documents that match the search, but I want them to be visible on the endpoint http://localhost:3001/search as well, but currently I get all the documents listed, how can I list the result of the search? I am trying with res.send(result); but it does not work. Here is my attempt:

```<code>// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const BASE_URL = process.env.REACT_APP_BASE_URL;
const itemRoutes = express.Router();
let Comment = require('./comment.model');

app.use(cors());
app.use(bodyParser.json());

mongoose.connect(BASE_URL, { useNewUrlParser: true })

const connection = mongoose.connection;

connection.once('open', function () {
  console.log('Connection to MongoDB established succesfully!');
});

let collection = connection.collection("posts_with_tags_test");
collection.createIndex(
  {
    postContent: 'text',
    title: 'text'
  }
);

itemRoutes.route('/search').post(async (req, res) => {
  let result = await connection.collection("posts_with_tags_test").find({
    $text: {
      $search: req.body.queryString
    }
  }).toArray();
  res.send(result);
  console.log(result)
});

app.use('/search', itemRoutes);

app.listen(PORT, function () {
  console.log('Server is running on' + ' ' + PORT);
})
</code>```

and here is my input field:

```<code>import React, { Component } from "react";
import axios from "axios";

class Search extends Component {

    getSearchQuery = () => {

        const queryString = document.querySelector(
            ".search-input"
        ).value;

        axios.post("http://localhost:3001/search", {
            queryString: queryString,
        });

        console.log(queryString)
    };

    render() {
        return (
            <div>
                <input
                    type="text"
                    className="search-input"
                />
                <button type="submit" onClick={this.getSearchQuery}></button>
            </div>
        );
    }
}

export default Search;
</code>```

答:
If you just access localhost:3001/search from a browser, it won't be visible because you aren't sending the data { queryString: "sample" } to be used in the query as req.body.queryString unless you're using Postman

If you're accessing it from frontend, in your React component's getSearchQuery, try using .then() on your axios.post() to receive the response from your backend

```<code>axios.post("http://localhost:3001/search", {
    queryString: queryString,
}).then(response => {
    console.log(response);
    console.log(response.status);
    console.log(response.data);
});
</code>```

Body:
I have a MongoDB collection that I search through by using a value from an input field using the $search operator and it works, when I console log the result it shows me only those documents that match the search, but I want them to be visible on the endpoint http://localhost:3001/search as well, but currently I get all the documents listed, how can I list the result of the search? I am trying with res.send(result); but it does not work. Here is my attempt:

// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const BASE_URL = process.env.REACT_APP_BASE_URL;
const itemRoutes = express.Router();
let Comment = require('./comment.model');

app.use(cors());
app.use(bodyParser.json());

mongoose.connect(BASE_URL, { useNewUrlParser: true })

const connection = mongoose.connection;

connection.once('open', function () {
  console.log('Connection to MongoDB established succesfully!');
});

let collection = connection.collection("posts_with_tags_test");
collection.createIndex(
  {
    postContent: 'text',
    title: 'text'
  }
);

itemRoutes.route('/search').post(async (req, res) => {
  let result = await connection.collection("posts_with_tags_test").find({
    $text: {
      $search: req.body.queryString
    }
  }).toArray();
  res.send(result);
  console.log(result)
});

app.use('/search', itemRoutes);

app.listen(PORT, function () {
  console.log('Server is running on' + ' ' + PORT);
})

and here is my input field:

import React, { Component } from "react";
import axios from "axios";

class Search extends Component {

    getSearchQuery = () => {

        const queryString = document.querySelector(
            ".search-input"
        ).value;

        axios.post("http://localhost:3001/search", {
            queryString: queryString,
        });

        console.log(queryString)
    };

    render() {
        return (

                <input
                    type="text"
                    className="search-input"
                />
                <button type="submit" onClick={this.getSearchQuery}></button>

        );
    }
}

export default Search;

Body:
If you just access localhost:3001/search from a browser, it won't be visible because you aren't sending the data { queryString: "sample" } to be used in the query as req.body.queryString unless you're using Postman

If you're accessing it from frontend, in your React component's getSearchQuery, try using .then() on your axios.post() to receive the response from your backend

axios.post("http://localhost:3001/search", {
    queryString: queryString,
}).then(response => {
    console.log(response);
    console.log(response.status);
    console.log(response.data);
});


问:
create react app - without typescript , got Error: Failed to load parser '@typescript-eslint/parser'
I have sample installation of react-app and I got the following

```<code>Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc » eslint-config-react-app#overrides[0]': Cannot find module 'typescript'
</code>```

after running

```<code> npm run lint -> eslint .
</code>```

I don't use typescript in this project.
I tried to install it from scratch and got it again.
also tried to remove tslint from vscode plugin

答:
Most likely, you have this in your .eslintrc:

```<code>extends: react-app
</code>```

It means the following rule is applied:

```<code>files: ['**/*.ts?(x)'],
parser: '@typescript-eslint/parser',
</code>```

Which probably means you have *.ts/*.tsx files in your root folder. But maybe it's the vscode-eslint. Did you try to run yarn lint from the terminal?

Body:
I have sample installation of react-app and I got the following

Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc » eslint-config-react-app#overrides[0]': Cannot find module 'typescript'

after running

 npm run lint -> eslint .

I don't use typescript in this project.
I tried to install it from scratch and got it again.
also tried to remove tslint from vscode plugin

Body:
Most likely, you have this in your .eslintrc:

extends: react-app

It means the following rule is applied:

files: ['**/*.ts?(x)'],
parser: '@typescript-eslint/parser',

Which probably means you have *.ts/*.tsx files in your root folder. But maybe it's the vscode-eslint. Did you try to run yarn lint from the terminal?


问:
Python: How to pass a list of iterables to zip when the list is only determined at runtime?
I would like to use zip to iterate in lock step over the elements of various generators. Which generators and how many of them there will be is only known at run time.
However, I can't work out how to pass this into zip as any list will be interpreted as an iterable rather than the list of iterables which must be simultaneously iterated over.

What's the correct way to do this?
Also, what's the correct way to unpack the outputs when their number isn't known until runtime?
Below is what I have tried

```<code>from typing import List

l_1 = [1, 2, 3]
l_10 = [10, 20, 30]
l_100 = [100, 200, 300]

def gen(l_: List):
    for i in l_:
        yield i

# Standard: works fine as expected
for i, j, k in zip(gen(l_1), gen(l_10), gen(l_100)):
    print('i={}, j={} k={}'.format(i,j,k))

# List of generators prepared at run time. Does not work
gens = [gen(l_1), gen(l_100)]
receive = [None] * len(gens)
for receive in zip(gens):
    print(receive)

</code>```

The output is

```<code>i=1, j=10 k=100
i=2, j=20 k=200
i=3, j=30 k=300
(<generator object gen at 0x000001C3DB93C258>,)
(<generator object gen at 0x000001C3DB93C620>,)
</code>```

The desired output is

```<code>i=1, j=10 k=100
i=2, j=20 k=200
i=3, j=30 k=300
[1, 100]
[2, 200]
[3, 300]

</code>```

How can I get zip to recognize that gens is not an iterable to iterate over, but rather the list of iterables which must be iterated over in lock step?

答:
It will be only a small change, to pass a list of iterables to zip you have to unpack it using *

# List of generators prepared at run time. Does not work
gens = [gen(l_1), gen(l_100)]
receive = [None] * len(gens)
for receive in zip(*gens):
    print(list(receive))
```

edit:

since you expected lists in your output I had to explicitly convert receive to a list.

Body:
I would like to use zip to iterate in lock step over the elements of various generators. Which generators and how many of them there will be is only known at run time.
However, I can't work out how to pass this into zip as any list will be interpreted as an iterable rather than the list of iterables which must be simultaneously iterated over.

What's the correct way to do this?
Also, what's the correct way to unpack the outputs when their number isn't known until runtime?
Below is what I have tried

from typing import List

l_1 = [1, 2, 3]
l_10 = [10, 20, 30]
l_100 = [100, 200, 300]

def gen(l_: List):
    for i in l_:
        yield i

# Standard: works fine as expected
for i, j, k in zip(gen(l_1), gen(l_10), gen(l_100)):
    print('i={}, j={} k={}'.format(i,j,k))

# List of generators prepared at run time. Does not work
gens = [gen(l_1), gen(l_100)]
receive = [None] * len(gens)
for receive in zip(gens):
    print(receive)

The output is

i=1, j=10 k=100
i=2, j=20 k=200
i=3, j=30 k=300
(<generator object gen at 0x000001C3DB93C258>,)
(<generator object gen at 0x000001C3DB93C620>,)

The desired output is

i=1, j=10 k=100
i=2, j=20 k=200
i=3, j=30 k=300
[1, 100]
[2, 200]
[3, 300]

How can I get zip to recognize that gens is not an iterable to iterate over, but rather the list of iterables which must be iterated over in lock step?

Body:
It will be only a small change, to pass a list of iterables to zip you have to unpack it using *

# List of generators prepared at run time. Does not work
gens = [gen(l_1), gen(l_100)]
receive = [None] * len(gens)
for receive in zip(*gens):
    print(list(receive))

edit:

since you expected lists in your output I had to explicitly convert receive to a list.


问:
How do I increase the number of default rows per page?
Grails scaffolding defaults to 10 rows per page.  I would like to increase that number without generating the views and changing the 10 in every file.  Where do I change the default?</p>

答:
You have to install scaffold templates with:

grails install-templates

Now, edit in src/templates/scaffolding Controller.groovy and increase the value params.max as you want

OwnerDisplayName: anon

LastEditorDisplayName: anon

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dahernan


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
It's possible to have leaks if unmanaged resources do not get cleaned properly. Classes which implement IDisposable can leak.

However, regular object references do not require explicit memory management the way lower level languages do.

OwnerDisplayName: Joan Venge

Title: Memory Leak in C#

LastEditorDisplayName: strager

OwnerDisplayName: Ben S


问:
google cloud functions default environment variables not set
Are there any conditions to the default environment variables being set on google cloud function?

I have the following code:

func init() {
    projectID := os.Getenv("GCP_PROJECT")
    log.Printf("projectID: %s\n", projectID)

    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)

    region := os.Getenv("FUNCTION_REGION")
    log.Printf("region: %s\n", region)
}
```

<p>and the values are empty.</p>

<p>Even if I do:</p>

<pre class="lang-golang prettyprint-override"><code>func GameUpdate(ctx context.Context, e FirestoreEvent) error {
    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)
}
</code>```

They are still empty.

According to documentation, I would expect them to be set and available. But they are not :|

EDIT:

I am using go 1.13 as runtime and as Armatorix mentioned, these env variables are not available in that runtime...

Why I needed them was to write a wrapper for cloud.google.com/go/logging  to be able to tag the severity of the logs.

I ended up prepending my stdout logs with [INFO]/[ERROR], and creating a tag from it \[([A-Z]+)\].*. Bonus is that I don't have to do a network call in my function to ship the logs.

Still disappointing that these environment variables are not available.

答:
So I've read the same documentation.
Here you've got the info that it works like this with go1.11 (And it works, I tested it out).
BUT for go1.13 these are not set. You can still do it manually.
Also I've checked which envs are set on 1.13 version.

From os.Envrion()

```<code>PATH=/layers/google.go.build/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
FUNCTION_SIGNATURE_TYPE=http
DEBIAN_FRONTEND=noninteractive
HOME=/root
K_REVISION=9
FUNCTION_TARGET=HelloWorld
PORT=8080
GOROOT=/usr/local/go/
CGO_ENABLED=1
PWD=/srv
K_SERVICE=function-1
</code>```

So the env that you probably want to use is K_SERVICE

Body:
Are there any conditions to the default environment variables being set on google cloud function?

I have the following code:

func init() {
    projectID := os.Getenv("GCP_PROJECT")
    log.Printf("projectID: %s\n", projectID)

    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)

    region := os.Getenv("FUNCTION_REGION")
    log.Printf("region: %s\n", region)
}

and the values are empty.

Even if I do:

func GameUpdate(ctx context.Context, e FirestoreEvent) error {
    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)
}

They are still empty.

According to documentation, I would expect them to be set and available. But they are not :|

EDIT:

I am using go 1.13 as runtime and as Armatorix mentioned, these env variables are not available in that runtime...

Why I needed them was to write a wrapper for cloud.google.com/go/logging  to be able to tag the severity of the logs.

I ended up prepending my stdout logs with [INFO]/[ERROR], and creating a tag from it \[([A-Z]+)\].*. Bonus is that I don't have to do a network call in my function to ship the logs.

Still disappointing that these environment variables are not available.

Body:
So I've read the same documentation.
Here you've got the info that it works like this with go1.11 (And it works, I tested it out).
BUT for go1.13 these are not set. You can still do it manually.
Also I've checked which envs are set on 1.13 version.

From os.Envrion()

PATH=/layers/google.go.build/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
FUNCTION_SIGNATURE_TYPE=http
DEBIAN_FRONTEND=noninteractive
HOME=/root
K_REVISION=9
FUNCTION_TARGET=HelloWorld
PORT=8080
GOROOT=/usr/local/go/
CGO_ENABLED=1
PWD=/srv
K_SERVICE=function-1

So the env that you probably want to use is K_SERVICE


问:
jQuery Range Slider with fixed values and associated text output
I´m new here.. sorry for my bad English :D

I´m looking for a range slider with fixed values and additional text output.

Here is a example: http://james2013.batcave.net/s100.htm

```<code><p>
</p><div id="resolution-slider" class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all" aria-disabled="false"><a class="ui-slider-handle ui-state-default ui-corner-all" href="#" style="left: 0%;"></a></div>
<div id="resolution"></div>
<div class="resolution-preview">6</div>

<h4>Slider width is set in css for this page</h4>
<script>
$(document).ready(function(){
    var valMap = [6, 10, 12, 18 , 35, 56];
    $("#resolution-slider").slider({
      value: valMap[0],  // Start slider from first (0th) element
      max: valMap.length-1, // Set "max" attribute to array length minus 1
      min: 0,
      values: [0],
      create: function( event, ui ) {  // Place numeric value on page before slide
      $(".resolution-preview").html(valMap[0]);
      },
      slide: function(event, ui) {
        $("#resolution").val(valMap[ui.values[0]]); // Fetch selected value from array
        $(".resolution-preview").html(valMap[ui.values[0]]);
      }
    });
});
</script>
</code>```

If the number 18 is displayed, a text that applies only to this value must also be displayed.

If a different number is selected, a different text will appear.

Thanks for the help guys <3

答:
As you are not using a Range, you do not need to use values only the 1 value. Consider the following example.

$(document).ready(function() {
  var valMap = ["6 (Six)", "10 (Ten)", "12 (Twelve)", "18 (Eighteen)", "35 (Thirty Five)", "56 (Fifty Six)"];
  $("#resolution-slider").slider({
    value: 0,
    max: valMap.length - 1,
    min: 0,
    create: function(event, ui) {
      $(".resolution-preview").html(valMap[0]);
    },
    slide: function(event, ui) {
      $(".resolution-preview").html(valMap[ui.value]);
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#resolution-slider {
  width: 500px;
  margin-left: 50px;
}

.resolution-preview {
  margin-top: 10px;
  margin-left: 50px;
}</code>```

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

6

Slider width is set in css for this page
```

As the slider is moved from 0 to 5, that value is then used as the Index of the valMap array.

Updated

If you want to display text, you simply need to update the Array so it has text instead of just Numbers.

Body:
I´m new here.. sorry for my bad English :D

I´m looking for a range slider with fixed values and additional text output.

Here is a example: http://james2013.batcave.net/s100.htm

6

Slider width is set in css for this page

If the number 18 is displayed, a text that applies only to this value must also be displayed.

If a different number is selected, a different text will appear.

Thanks for the help guys <3

Body:
As you are not using a Range, you do not need to use values only the 1 value. Consider the following example.

$(document).ready(function() {
  var valMap = ["6 (Six)", "10 (Ten)", "12 (Twelve)", "18 (Eighteen)", "35 (Thirty Five)", "56 (Fifty Six)"];
  $("#resolution-slider").slider({
    value: 0,
    max: valMap.length - 1,
    min: 0,
    create: function(event, ui) {
      $(".resolution-preview").html(valMap[0]);
    },
    slide: function(event, ui) {
      $(".resolution-preview").html(valMap[ui.value]);
    }
  });
});

#resolution-slider {
  width: 500px;
  margin-left: 50px;
}

.resolution-preview {
  margin-top: 10px;
  margin-left: 50px;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p></p>

<div id="resolution-slider"></div>
<div class="resolution-preview">6</div>

<h4>Slider width is set in css for this page</h4>

As the slider is moved from 0 to 5, that value is then used as the Index of the valMap array.

Updated

If you want to display text, you simply need to update the Array so it has text instead of just Numbers.


问:
From a list of many dataframes. How can i get the df with the max and min lenght?
For example, if i have:

```<code>list=[df1,df2,df3,df4]
</code>```

How can python identify and get the df with the maximum number of rows? or len
And if you have 2 dfs with the min or max value, it can take any of these.

答:
You can use max() function with a key that specifies the way you look at the magnitude of your data:

```<code>max_df = max(list_, key=len)
min_df = min(list_, key=len)
</code>```

NOTE there is an implicit mistake in your code that you might wanna correct. you have overwritten the python keyword list. add an underscore for example to the end of it to avoid any unwanted error

UPDATE: the key=lambda x:len(x) replaced by key=len, thanks to @rafaelc comment

Body:
For example, if i have:

list=[df1,df2,df3,df4]

How can python identify and get the df with the maximum number of rows? or len
And if you have 2 dfs with the min or max value, it can take any of these.

Body:
You can use max() function with a key that specifies the way you look at the magnitude of your data:

max_df = max(list_, key=len)
min_df = min(list_, key=len)

NOTE there is an implicit mistake in your code that you might wanna correct. you have overwritten the python keyword list. add an underscore for example to the end of it to avoid any unwanted error

UPDATE: the key=lambda x:len(x) replaced by key=len, thanks to @rafaelc comment


问:
Is it possible to select and upload multiple files at one time in Internet Explorer?
I'm writing a form to select and upload multiple files at one time. This seems to be a pretty straight forward task in FF and Chrome but appears to be a limitation in IE 7.

Are there any suggested workarounds?

This is an internal application for my company's intranet and IE is the default browser. There is now word on upgrading to IE 8 or 9, does anybody know if this would make a difference?

What is happening under the hood which which makes IE different from FF and Chrome in this instance? I know this is a lot but specifically to selecting and uploading files.

Thanks,
Russell

答:
IE 7 currently does not (and probably never will) implement the multiple option for file upload input elements which Chrome/FF/Safari/Opera implement. Therefore there is no script/HTML support for receiving multiple files with a single HTML input.

The only option you have for multiple file upload with a single input object is either a Flash-based solution or an Active X control. Alternatively you can create multiple file input elements using javascript.


问:
python regex re.sub: remove everything before or after a pattern until find a specific condition in both ways
I'm trying to remove everything between the two capital letters if there is a 'year' between them.

Here is what I have:

```<code>import re

string = 'Sep 09 2018*57.10*58.05*Sep 08 2018*56.76*54.91*Sep 07 2018*58.14*55.20*Sep 06 2018*55.07*54.66*Sep 06 2018*0.91 higher than last year, blablabla*Sep 05 2018*54.71*53.70'

string = re.sub(r'([A-Z].*year)(.*?)(?=[A-Z])', '*', string)
</code>```

And, what I expect to get:

```<code>string = 'Sep 09 2018*57.10*58.05*Sep 08 2018*56.76*54.91*Sep 07 2018*58.14*55.20*Sep 06 2018*55.07*54.66*Sep 05 2018*54.71*53.70'
</code>```

So, I "removed" everything up to the first capital letter before 'year' and everything until the next, which means '*Sep 06 2018*0.91 higher than last year, blablabla', but my code is starting from the begining, instead of from 'year' and then look backwards. I solved after 'year' already.

Appreciate if anybody can help me to fix this.

答:
You may use

```<code>[A-Z][^A-Z]*year[^A-Z]*(?=[A-Z])
</code>```

See the regex demo

Details

[A-Z] - an uppercase letter

[^A-Z]* - 0+ chars other than uppercase letters

year - a word

[^A-Z]* - 0+ chars other than uppercase letters

(?=[A-Z]) - immediately to the right of the current location, there should be an uppercase letter.

In Python, use

```<code>string = re.sub(r'[A-Z][^A-Z]*year[^A-Z]*(?=[A-Z])', '', string)
</code>```

Body:
I'm trying to remove everything between the two capital letters if there is a 'year' between them.

Here is what I have:

import re

string = 'Sep 09 2018*57.10*58.05*Sep 08 2018*56.76*54.91*Sep 07 2018*58.14*55.20*Sep 06 2018*55.07*54.66*Sep 06 2018*0.91 higher than last year, blablabla*Sep 05 2018*54.71*53.70'

string = re.sub(r'([A-Z].*year)(.*?)(?=[A-Z])', '*', string)

And, what I expect to get:

string = 'Sep 09 2018*57.10*58.05*Sep 08 2018*56.76*54.91*Sep 07 2018*58.14*55.20*Sep 06 2018*55.07*54.66*Sep 05 2018*54.71*53.70'

So, I "removed" everything up to the first capital letter before 'year' and everything until the next, which means '*Sep 06 2018*0.91 higher than last year, blablabla', but my code is starting from the begining, instead of from 'year' and then look backwards. I solved after 'year' already.

Appreciate if anybody can help me to fix this.

Body:
You may use

[A-Z][^A-Z]*year[^A-Z]*(?=[A-Z])

See the regex demo

Details

[A-Z] - an uppercase letter

[^A-Z]* - 0+ chars other than uppercase letters

year - a word

[^A-Z]* - 0+ chars other than uppercase letters

(?=[A-Z]) - immediately to the right of the current location, there should be an uppercase letter.

In Python, use

string = re.sub(r'[A-Z][^A-Z]*year[^A-Z]*(?=[A-Z])', '', string)


问:
use custom python module in script run from c#
I am trying to run a python script from a c# console application. This c# code works fine until I import our custom python module that in turn imports other modules, e.g. arcpy, keyring, etc within the python script. The script runs fine from the cmd line but once in c# it just hangs. In the end, a system deadlock error pops up. How do I get my python to run? The goal is to get the password from python to c#. I am open to other approaches...

c#

```<code>        private static string getPassword(string database)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:\Python27\ArcGIS10.6\python.exe";
            string script = @"C:\src\xxxx\etw_password.py";
            start.Arguments = $"\"{script}\" \"{database}\"";
            start.UseShellExecute = false;
            start.CreateNoWindow = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            string errors;
            string password;
            Console.WriteLine(start.Arguments);
            using(Process process = Process.Start(start))
            {
                errors = process.StandardError.ReadToEnd();
                password = process.StandardOutput.ReadToEnd();
            }

            return password;
        }
</code>```

python: not working-- I replaced our custom python security calls with "x"

```<code>import sys
import xxxx

database = sys.argv[1]
password = xxxx.xxxx(database, 'xxxx')
print password
</code>```

python: this works fine

```<code>import sys

database = sys.argv[1]
print database
</code>```

I also run the test below to check if it was just our module or if the problem extended to others. I tested with numpy and arcpy. Both failed.

python: not working

```<code>import sys
import numpy

database = sys.argv[1]
print database
</code>```

答:
The issue lies with your script, not C#.  Your C# code is well-formed and working (I tested it out by replacing your script with a hello world script that takes in one argument, and it printed the output correctly).

If you're saying it works on the command line, then it might be important to note what path you are running the script from.  Your script might contain relative path dependencies.  This would, in turn, affect the C# code because you may need to start in that directory first.

If you want my test, here it is:

script.py:

```<code>import sys

database = sys.argv[1]
print("Hello, " + database)
</code>```

Program.cs:

```<code>        static void Main(string[] args)
        {
            var pwd = getPassword("World!");
            Console.WriteLine($"OUTPUT: {pwd}");
        }

        private static string getPassword(string database)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:\Users\<path-to-my>\python.exe";
            string script = @"C:\<path-to-my>\script.py";
            start.Arguments = $"\"{script}\" \"{database}\"";
            start.UseShellExecute = false;
            start.CreateNoWindow = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            string errors;
            string password;
            Console.WriteLine(start.Arguments);
            using (Process process = Process.Start(start))
            {
                errors = process.StandardError.ReadToEnd();
                password = process.StandardOutput.ReadToEnd();
            }

            return password;
        }
</code>```

Output:

Body:
I am trying to run a python script from a c# console application. This c# code works fine until I import our custom python module that in turn imports other modules, e.g. arcpy, keyring, etc within the python script. The script runs fine from the cmd line but once in c# it just hangs. In the end, a system deadlock error pops up. How do I get my python to run? The goal is to get the password from python to c#. I am open to other approaches...

c#

        private static string getPassword(string database)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:\Python27\ArcGIS10.6\python.exe";
            string script = @"C:\src\xxxx\etw_password.py";
            start.Arguments = $"\"{script}\" \"{database}\"";
            start.UseShellExecute = false;
            start.CreateNoWindow = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            string errors;
            string password;
            Console.WriteLine(start.Arguments);
            using(Process process = Process.Start(start))
            {
                errors = process.StandardError.ReadToEnd();
                password = process.StandardOutput.ReadToEnd();
            }

            return password;
        }

python: not working-- I replaced our custom python security calls with "x"

import sys
import xxxx

database = sys.argv[1]
password = xxxx.xxxx(database, 'xxxx')
print password

python: this works fine

import sys

database = sys.argv[1]
print database

I also run the test below to check if it was just our module or if the problem extended to others. I tested with numpy and arcpy. Both failed.

python: not working

import sys
import numpy

database = sys.argv[1]
print database

Body:
The issue lies with your script, not C#.  Your C# code is well-formed and working (I tested it out by replacing your script with a hello world script that takes in one argument, and it printed the output correctly).

If you're saying it works on the command line, then it might be important to note what path you are running the script from.  Your script might contain relative path dependencies.  This would, in turn, affect the C# code because you may need to start in that directory first.

If you want my test, here it is:

script.py:

import sys

database = sys.argv[1]
print("Hello, " + database)

Program.cs:

        static void Main(string[] args)
        {
            var pwd = getPassword("World!");
            Console.WriteLine($"OUTPUT: {pwd}");
        }

        private static string getPassword(string database)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:\Users\<path-to-my>\python.exe";
            string script = @"C:\<path-to-my>\script.py";
            start.Arguments = $"\"{script}\" \"{database}\"";
            start.UseShellExecute = false;
            start.CreateNoWindow = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            string errors;
            string password;
            Console.WriteLine(start.Arguments);
            using (Process process = Process.Start(start))
            {
                errors = process.StandardError.ReadToEnd();
                password = process.StandardOutput.ReadToEnd();
            }

            return password;
        }

Output:


问:
Vue Vuetify. v-model for v-checkbox not taking the correct value when inside a v-for loop
So I have this in my template:

```<code> <v-checkbox v-for="(option,index) in options" :key="option.id" :label="option.checked.toString()" :v-model="options[index].checked"></v-checkbox>
</code>```

And this in my data():

```<code>options: [
        {
          id: '1',
          name: 'Cotton',
          checked : true
        },
        {
          id: '2',
          name: 'Silk',
          checked : false
        }
 ]
</code>```

However, even when the value is true, the checkbox is not checked; why??

I have this in codepen:

https://codepen.io/averied/pen/JjYQLJQ?editable=true&editors=101%3Dhttps%3A%2F%2Fvuetifyjs.com%2Fen%2Fcomponents%2Fselection-controls%2F

答:
Delete : before v-model

Plus
it would be cleaner to use

v-model="option.checked"

instead of v-model="options[index].checked"

then you do not need index in v-for

Body:
So I have this in my template:

 <v-checkbox v-for="(option,index) in options" :key="option.id" :label="option.checked.toString()" :v-model="options[index].checked"></v-checkbox>

And this in my data():

options: [
        {
          id: '1',
          name: 'Cotton',
          checked : true
        },
        {
          id: '2',
          name: 'Silk',
          checked : false
        }
 ]

However, even when the value is true, the checkbox is not checked; why??

I have this in codepen:

https://codepen.io/averied/pen/JjYQLJQ?editable=true&editors=101%3Dhttps%3A%2F%2Fvuetifyjs.com%2Fen%2Fcomponents%2Fselection-controls%2F


问:
SPF Record for Multiple DKIMs (including MX)
I know very little about mail server administration. I'm piecing together user guides. I've bought a domain name, and [paid] Protonmail which allows using a custom domain. I've had this working for a while, but now I'm having trouble extending it for another DKIM record.

Objectives:

Send and receive email using Protonmail from the custom domain

Send-only email from a Postfix server I'm running

In order to send/receive email using Protonmail through my domain name, I've set up the following TXT records:

```<code>Host=@   protonmail-verification=e954fa...
</code>```

```<code>Host=protonmail._domainkey    v=DKIM1; k=rsa; p=MGM0....
</code>```

```<code>Host=@   v=spf1 include:_spf.protonmail.ch mx ~all
</code>```

This has been working for months. Now I'd like to implement objective 2 (above). I created a DKIM key using opendkim:

```<code>sudo opendkim-genkey -b 8192 -h rsa-sha256 -r -v --subdomains -s postfix -d $(hostname --domain) && \
sudo sed -i 's/h=rsa-sha256/h=sha256/' postfix.txt
</code>```

Then I've added the contents from postfix.txt, concatenating the long p string, to my DNS provider with another TXT record:

```<code>Host=[MY DOMAIN NAME]._domainkey      v=DKIM1; h=sha256; k=rsa; s=email; p=MEEij...
</code>```

Where I think I'm struggling is with updating the spf record. How should it look? I thought it should be like so:

```<code>v=spf1 include:[MY DOMAIN NAME] include:_spf.protonmail.ch mx ~all
</code>```

However, when testing sending an email from my Postfix server, some client servers reject the email, with the following log in my Postfix server:

```<code>E543D5E0003: host mail.tutanota.de[81.3.6.165] said: 450 4.7.1 Client host rejected: cannot find your reverse hostname, [MY POSTFIX SERVERS IP] (in reply to RCPT TO command)
</code>```

I'm quite sure there is something wrong in my spf record. Are the arguments correct? And does the order matter? How can I use the Protonmail records for sending and receiving, but restrict my Postfix server to send-only? (does DNS even care about this directionality?)

答:
Ok, let's start debugging this anyways ... (quite frankly, this is not a programming question so superuser would have been the better choice there, but I like that you wanna host your own mail :) )

Your SPF record should look like the following. Your own domain is not needed, cause the SPF record is saved in it's DNS records. Otherwise, that would (but won't) build a loop.

```<code>v=spf1 include:_spf.protonmail.ch mx ~all
</code>```

The error itself you are seeing is related to the PTR lookup of your public IP, but could also be caused by the extra include and be a false positive here.

To make sure it's correct anyway, look it up manually:

On linux

```<code>dig -x <public ip of mail domain>
</code>```

that will (should) print multiple lines, the one you're interested in:

```<code>;; ANSWER SECTION:
XXX.XXX.XXX.XXX.in-addr.arpa. 43200 IN    PTR     my-domain.com.
</code>```

On windows:

```<code>nslookup <public ip of mail domain>
</code>```

prints:

```<code>Server:  some.dns.server.com
Address:  XXX.XXX.XXX.XXX

Name:    my-domain.com
Address:  <public ip of mail domain>
</code>```

crucial here is the "my-domain.com." part - if that is not your mail domain, then your hosting provider will most likely give you a way to change the PTR somewhere.

Try this and then we will look futher into it if necessary, of course it's hard to debug without being able to lookup all the information ;)

Body:
I know very little about mail server administration. I'm piecing together user guides. I've bought a domain name, and [paid] Protonmail which allows using a custom domain. I've had this working for a while, but now I'm having trouble extending it for another DKIM record.

Objectives:

Send and receive email using Protonmail from the custom domain

Send-only email from a Postfix server I'm running

In order to send/receive email using Protonmail through my domain name, I've set up the following TXT records:

Host=@   protonmail-verification=e954fa...

Host=protonmail._domainkey    v=DKIM1; k=rsa; p=MGM0....

Host=@   v=spf1 include:_spf.protonmail.ch mx ~all

This has been working for months. Now I'd like to implement objective 2 (above). I created a DKIM key using opendkim:

sudo opendkim-genkey -b 8192 -h rsa-sha256 -r -v --subdomains -s postfix -d $(hostname --domain) && \
sudo sed -i 's/h=rsa-sha256/h=sha256/' postfix.txt

Then I've added the contents from postfix.txt, concatenating the long p string, to my DNS provider with another TXT record:

Host=[MY DOMAIN NAME]._domainkey      v=DKIM1; h=sha256; k=rsa; s=email; p=MEEij...

Where I think I'm struggling is with updating the spf record. How should it look? I thought it should be like so:

v=spf1 include:[MY DOMAIN NAME] include:_spf.protonmail.ch mx ~all

However, when testing sending an email from my Postfix server, some client servers reject the email, with the following log in my Postfix server:

E543D5E0003: host mail.tutanota.de[81.3.6.165] said: 450 4.7.1 Client host rejected: cannot find your reverse hostname, [MY POSTFIX SERVERS IP] (in reply to RCPT TO command)

I'm quite sure there is something wrong in my spf record. Are the arguments correct? And does the order matter? How can I use the Protonmail records for sending and receiving, but restrict my Postfix server to send-only? (does DNS even care about this directionality?)

Body:
Ok, let's start debugging this anyways ... (quite frankly, this is not a programming question so superuser would have been the better choice there, but I like that you wanna host your own mail :) )

Your SPF record should look like the following. Your own domain is not needed, cause the SPF record is saved in it's DNS records. Otherwise, that would (but won't) build a loop.

v=spf1 include:_spf.protonmail.ch mx ~all

The error itself you are seeing is related to the PTR lookup of your public IP, but could also be caused by the extra include and be a false positive here.

To make sure it's correct anyway, look it up manually:

On linux

dig -x <public ip of mail domain>

that will (should) print multiple lines, the one you're interested in:

;; ANSWER SECTION:
XXX.XXX.XXX.XXX.in-addr.arpa. 43200 IN    PTR     my-domain.com.

On windows:

nslookup <public ip of mail domain>

prints:

Server:  some.dns.server.com
Address:  XXX.XXX.XXX.XXX

Name:    my-domain.com
Address:  <public ip of mail domain>

crucial here is the "my-domain.com." part - if that is not your mail domain, then your hosting provider will most likely give you a way to change the PTR somewhere.

Try this and then we will look futher into it if necessary, of course it's hard to debug without being able to lookup all the information ;)


问:
re.findall() was working but now isn't finding the pattern I need
To preface I am working in Python 3.8.3 on windows 10 and using slate3k to parse through my pdf

I am working on a python program that will parse through a PDF and spit out a certain pattern and make a csv file for me.

However, when I try find the pattern with the parsed text, I am getting nothing.

I've taken an example of some parsed text and assigned it to parsed

```<code>import re

parsed = '7\n\n8\n\n6\n\n1\n\n2\n\nF\n\nNOTES\n\n3\n\n4\n\n5\n\n7\n\n6\n\n5\n\n4\n\n3\n\nA\n\n8\n\nE\n\nD\n\nC\n\nB\n\nR\n\nV\nE\n\n.\n\nR\nD\n\nA\n\nW\n\nI\n\nN\n\nG\n\nN\n\nO\n\n.\n\nP\n\nL\n\nO\n\nT\n\nS\n\nC\n\nA\n\nL\n\nE\n\n:\n\n2\n\n1\n\nA\n\nB\n\nC\n\nD\n\nE\n\nREFERENCE DRAWINGS\n\nDATE\n\nREV.\n\nBY\n\nCHK. ENG. APP.\n\nD\n\nM\n\nY\n\nDESCRIPTION\n\n\n\nTITLE\n\nEQUIP. NO.\n\nSAP NO.\n\nDRAWN BY\n\nAPPROVED\n\nDRAWING NO.\n\nSCALE\n\nCHECKED BY\n\nPLANT AREA\n\nFILE NAME\n\nMICRO. REV.\n\nREV.\n\nG\n\nD\n\n0\n0\n\n-\n\nA\n\n-\n\n0\n4\n0\n1\n\n-\n\n1\n\nR\n\ne\n\nv\n\n5\n\nA\n\n1\n\nS\n\ni\n\nz\n\ne\n\n\n1B\n\nD\nD\n\n6\n8\n\n-\n\nL\n\n-\n\n0\n0\n9\n\n-\n\n1\n\n1\n\nB\n\n\n\nN.T.S.\n\n1\n\n:\n\n2\n\n\n\n-\n\n1A\n\n18\n\n02\n\n22\n\n\n\n\nSCALE - NTS\n\n1.\n2.\n81PEW1002, 81PEW1003 AND 81PEW1004 ARE.\n\n3.\n\n4.\n\n5.\n\nSCALE\n\n6.\n\n7.\n\n8.\n\n9.\n10.\n11.\n12.\n13.\n\n14.\n\n15.\n\n8\n\n1\n\nP\n( E\n\nE\nX I S\n\nW\n\n1\n0\nT I N\n\n0\n\n2 - 4\n\n2 "- C\n\nA\n\nJ\n\nG )\n\n8 1\n\nP\n( E\n\nE\nXI S\n\nW\n\n1 0 0 4-4 2"- C\n\nA J\n\nTI N\n\nG )\n\n3\n\nAREA LIMIT N 252510\nSIPHON C TIE IN DETAIL\n\nPL81-L-147-1\\/1210-1\n\nSCALE - NTS\n\n81PEW1002-42"-CAJ\n(EXISTING)\n\n2\n\nAREA LIMIT N 252497\nSIPHON B TIE IN DETAIL\n\nPL81-L-147-1\n\nSCALE - NTS\n\n81PEW1003-42"-CAJ\n(EXISTNG)\n\n8\n\n1\n\nP\n\nE\nX I S\n\nW\n\n1\n0\nT I N\n\n0\n\n3 - 4\n\n2 "- C\n\nA\n\nJ\n\n( E\n\nG )\n\n81PEW1004-42"-CAJ\n(EXISTING)\n\nDRAIN\n\nA\n\nDRAIN DETAIL\n\n-\n\nSCALE - NTS\n\nA\n\n-\n\nA\n\n-\n\nA\n\n-\n\n81PEW1002-42"-CAJ (SIPHON C)\n81PEW1003-42"-CAJ (SIPHON B)\n81PEW1004-42"-CAJ (SIPHON A)\n\n45°\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nSIP\n\nH\n\nO\n\nN A\n\nSIP\n\nH\n\nO\n\nN B\n\nS I P\n\nH\n\nO\n\nN A\n\nTP\n05\n\nTP\n06\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nTP\n03\n\nTP\n04\n\nTP\n02\n\nTP\n01\n\nS I P\n\nH\n\nO\n\nN B\n\nS I P\n\nH\n\nO\n\nN C\n\n5\n\n\n\n5\n\n\n\n5\n\n\n\nS\n\nI\n\nP\n\nH\n\nO\n\nN\n\nC\n\n4\n\n\n\n4\n\n\n\nE\n\nXI S\nA\n\nTI N\n\nG 4 8"\n\nC\n\nS I N\n\nG ( T\n\nY\n\nP .)\n\n4\n\n\nTEE\nDETAIL\n\nDRAIN\nSPOOL\n\n60°\n\nTYP.\n\nTEE\nDETAIL\n\nDRAIN\nSPOOL\n\n60°\n\nTYP.\n\nNOTE 14\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n5\n8\n0\n8\n4\n1\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n3\n9\n0\n8\n4\n1\n\nAREA LIMIT N 252504\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n0\n9\n0\n8\n4\n1\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n9\n9\n0\n8\n4\n1\n\nAREA LIMIT N 252517\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n0\n2\n1\n8\n4\n1\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n8\n2\n1\n8\n4\n1\n\nAREA LIMIT N 252459\n\nAREA LIMIT N 252467\n\nDRAIN\nSPOOL\n\nTEE\nDETAIL\n\n60°\n\nTYP.\n\nNOTE 15\n\nNOTE 15\n\nNOTE 15\n\nSEE MT81-L-PEW1003-1\n\nSEE MT81-L-PEW1002-1\n\nSEE MT81-L-PEW1004-1\n\nSEE MT86-L-PEW1218-1\n\nSEE MT86-L-PEW1217-1\n\nSEE MT86-L-PEW1216-1\n\nCUT BACK EXISTING INSULATION\nFOR INSTALLATION OF FLANGES\nAND TEE\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\x0c'
rawtags = re.findall(r'[0-9]+[A-Z]+-[0-9]+|[0-9]+[A-Z]+[0-9]{1-5}|[0-9]{3}[A-Z]+[0-9]+', parsed, re.I)
print(rawtags)
</code>```

I had this pattern working in a previous iteration but I am having issues here. Any insight as to why it isn't working for me now would be greatly appreciated.

Edit:

I was expecting a list of ['81PEW1002', '81PEW1003', '81PEW1004'... etc]

There are two distinct patterns I am trying to catch:

##XXX-#####

##XXX#####

答:
You had an extra minus - symbol

```<code>rawtags = re.findall(r'[0-9]+[A-Z-]+[0-9]+|[0-9]+[A-Z-]+[0-9]{1-5}|[0-9]{3}[A-Z-]+[0-9]+', parsed, re.I)
</code>```

I think the above is something you are looking for.
V/R
Steven M

Body:
To preface I am working in Python 3.8.3 on windows 10 and using slate3k to parse through my pdf

I am working on a python program that will parse through a PDF and spit out a certain pattern and make a csv file for me.

However, when I try find the pattern with the parsed text, I am getting nothing.

I've taken an example of some parsed text and assigned it to parsed

import re

parsed = '7\n\n8\n\n6\n\n1\n\n2\n\nF\n\nNOTES\n\n3\n\n4\n\n5\n\n7\n\n6\n\n5\n\n4\n\n3\n\nA\n\n8\n\nE\n\nD\n\nC\n\nB\n\nR\n\nV\nE\n\n.\n\nR\nD\n\nA\n\nW\n\nI\n\nN\n\nG\n\nN\n\nO\n\n.\n\nP\n\nL\n\nO\n\nT\n\nS\n\nC\n\nA\n\nL\n\nE\n\n:\n\n2\n\n1\n\nA\n\nB\n\nC\n\nD\n\nE\n\nREFERENCE DRAWINGS\n\nDATE\n\nREV.\n\nBY\n\nCHK. ENG. APP.\n\nD\n\nM\n\nY\n\nDESCRIPTION\n\n\n\nTITLE\n\nEQUIP. NO.\n\nSAP NO.\n\nDRAWN BY\n\nAPPROVED\n\nDRAWING NO.\n\nSCALE\n\nCHECKED BY\n\nPLANT AREA\n\nFILE NAME\n\nMICRO. REV.\n\nREV.\n\nG\n\nD\n\n0\n0\n\n-\n\nA\n\n-\n\n0\n4\n0\n1\n\n-\n\n1\n\nR\n\ne\n\nv\n\n5\n\nA\n\n1\n\nS\n\ni\n\nz\n\ne\n\n\n1B\n\nD\nD\n\n6\n8\n\n-\n\nL\n\n-\n\n0\n0\n9\n\n-\n\n1\n\n1\n\nB\n\n\n\nN.T.S.\n\n1\n\n:\n\n2\n\n\n\n-\n\n1A\n\n18\n\n02\n\n22\n\n\n\n\nSCALE - NTS\n\n1.\n2.\n81PEW1002, 81PEW1003 AND 81PEW1004 ARE.\n\n3.\n\n4.\n\n5.\n\nSCALE\n\n6.\n\n7.\n\n8.\n\n9.\n10.\n11.\n12.\n13.\n\n14.\n\n15.\n\n8\n\n1\n\nP\n( E\n\nE\nX I S\n\nW\n\n1\n0\nT I N\n\n0\n\n2 - 4\n\n2 "- C\n\nA\n\nJ\n\nG )\n\n8 1\n\nP\n( E\n\nE\nXI S\n\nW\n\n1 0 0 4-4 2"- C\n\nA J\n\nTI N\n\nG )\n\n3\n\nAREA LIMIT N 252510\nSIPHON C TIE IN DETAIL\n\nPL81-L-147-1\\/1210-1\n\nSCALE - NTS\n\n81PEW1002-42"-CAJ\n(EXISTING)\n\n2\n\nAREA LIMIT N 252497\nSIPHON B TIE IN DETAIL\n\nPL81-L-147-1\n\nSCALE - NTS\n\n81PEW1003-42"-CAJ\n(EXISTNG)\n\n8\n\n1\n\nP\n\nE\nX I S\n\nW\n\n1\n0\nT I N\n\n0\n\n3 - 4\n\n2 "- C\n\nA\n\nJ\n\n( E\n\nG )\n\n81PEW1004-42"-CAJ\n(EXISTING)\n\nDRAIN\n\nA\n\nDRAIN DETAIL\n\n-\n\nSCALE - NTS\n\nA\n\n-\n\nA\n\n-\n\nA\n\n-\n\n81PEW1002-42"-CAJ (SIPHON C)\n81PEW1003-42"-CAJ (SIPHON B)\n81PEW1004-42"-CAJ (SIPHON A)\n\n45°\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nSIP\n\nH\n\nO\n\nN A\n\nSIP\n\nH\n\nO\n\nN B\n\nS I P\n\nH\n\nO\n\nN A\n\nTP\n05\n\nTP\n06\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nF\n\nL\n\nO\n\nW\n\nTP\n03\n\nTP\n04\n\nTP\n02\n\nTP\n01\n\nS I P\n\nH\n\nO\n\nN B\n\nS I P\n\nH\n\nO\n\nN C\n\n5\n\n\n\n5\n\n\n\n5\n\n\n\nS\n\nI\n\nP\n\nH\n\nO\n\nN\n\nC\n\n4\n\n\n\n4\n\n\n\nE\n\nXI S\nA\n\nTI N\n\nG 4 8"\n\nC\n\nS I N\n\nG ( T\n\nY\n\nP .)\n\n4\n\n\nTEE\nDETAIL\n\nDRAIN\nSPOOL\n\n60°\n\nTYP.\n\nTEE\nDETAIL\n\nDRAIN\nSPOOL\n\n60°\n\nTYP.\n\nNOTE 14\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n5\n8\n0\n8\n4\n1\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n3\n9\n0\n8\n4\n1\n\nAREA LIMIT N 252504\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n0\n9\n0\n8\n4\n1\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n9\n9\n0\n8\n4\n1\n\nAREA LIMIT N 252517\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n0\n2\n1\n8\n4\n1\n\nA\n\nR\n\nA\nE\n\nL\n\nI\n\nM\n\nI\n\nT\n\nE\n\n8\n2\n1\n8\n4\n1\n\nAREA LIMIT N 252459\n\nAREA LIMIT N 252467\n\nDRAIN\nSPOOL\n\nTEE\nDETAIL\n\n60°\n\nTYP.\n\nNOTE 15\n\nNOTE 15\n\nNOTE 15\n\nSEE MT81-L-PEW1003-1\n\nSEE MT81-L-PEW1002-1\n\nSEE MT81-L-PEW1004-1\n\nSEE MT86-L-PEW1218-1\n\nSEE MT86-L-PEW1217-1\n\nSEE MT86-L-PEW1216-1\n\nCUT BACK EXISTING INSULATION\nFOR INSTALLATION OF FLANGES\nAND TEE\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\x0c'
rawtags = re.findall(r'[0-9]+[A-Z]+-[0-9]+|[0-9]+[A-Z]+[0-9]{1-5}|[0-9]{3}[A-Z]+[0-9]+', parsed, re.I)
print(rawtags)

I had this pattern working in a previous iteration but I am having issues here. Any insight as to why it isn't working for me now would be greatly appreciated.

Edit:

I was expecting a list of ['81PEW1002', '81PEW1003', '81PEW1004'... etc]

There are two distinct patterns I am trying to catch:

##XXX-#####

##XXX#####

Body:
You had an extra minus - symbol

rawtags = re.findall(r'[0-9]+[A-Z-]+[0-9]+|[0-9]+[A-Z-]+[0-9]{1-5}|[0-9]{3}[A-Z-]+[0-9]+', parsed, re.I)

I think the above is something you are looking for.
V/R
Steven M


问:
Multiple time formats using fluentd JSON parser
I'm currently reading container logs as my source in fluentd, and I'm parsing all of our log files which is in JSON format. The JSON parser is working as expected based on our configuration, but the issue is the time format. There are multiple time formats depending on the log file.

As an example, one log file might store time as 2020-05-28T21:00:07Z, but another will store it as 2020-04-28T20:07:52.013557931Z. The time is stored in a key named "time" in all cases, too, so fluentd by default attempts to parse this key.

Is it possible to use the same filter to parse all JSON data but have it handle multiple time formats? Would we need to create different filters for each different time format?

答:
This is more of a 'fluentd' question, than a straight 'Ruby' question.

However, to your specific question about filters, generally speaking it's impossible to tell specific date formats based on the value alone. For example, does '2020-03-04' mean March 4 (yyyy-MM-dd), or April 3 (yyyy-dd-MM)? Unfortunately there's no way to tell from values alone.

The best course of action is generally to verify the format per source (by reading documentation for that source or otherwise), and make sure identifying information is available to tie the date value back to the source. Without that, neither fluentd nor any other program will be able to determine what time it is (although you can do tricks in some situations to determine what time it isn't.)


问:
ZeroTier One Mac change IP
I need your help.

I have had to install the ZeroTier One client to be all together in one serv. But also the idea is to change our IP from ZeroTier to work more comfortably from home. From Windows it is quite easy because you go to system resources and modify it on the network. But in MacOs I have spent several days looking for how to change the private IP only of the ZeroTier. Does anyone know how to do it?

Thanks in advance

答:
A ZeroTier IP address is virtual and is thus assigned from the network controller. In order to change this you need to log into your account at https://my.zerotier.com/, go to the Network tab and navigate to the network in question and edit the assigned addresses. Once edited the changes will propagate to the nodes on the network automatically.

In practice if you are not experienced with this sort of concept it is best to choose a managed routing scheme that works best for your scenario and let ZeroTier automatically assign addresses for you.

Title: ZeroTier One Mac change IP


问:
Why does SwiftUI code run/reloae on iPhone and not on iPad?
I have been looking at this code and other similar code for the last week and have a question.

The app (code link below) is a simple 5 question app in SwiftUI. Using an iPhone 11 simulator, the quiz runs perfectly and when you hit the back nav link and press the Start Quiz button, the quiz runs again. On an iPad however the Start Quiz button does not work to relaunch the Quiz.

I figured since both are running the same IOS, they should both function the same but they do not. Tried it on my physical iPad and the same thing. Runs through the quiz once, and will not run a second time. Anybody have any idea why? Thanks for your help!

https://github.com/albypanz94/Quiz-Game-in-SwiftUI.git

答:
The issue is that the SwiftUI Navigation model is, by default, based on a UISplitview, and that on the iPad, the "Start Quiz" navigation link transfers navigation to its second controller. On an iphone, the second controller is collapsed away.

What this means for the game is that for the iPad (and large iPhones in landscape mode), the game cannot re-start.

You would also find anomalies if you ran the game on a large format iPhone, and then rotated it mid way through the game.

You can change the navigation view style to not use the split view model by using:

```<code>.navigationViewStyle(StackNavigationViewStyle())
</code>```

after the NavigationView closing brace.

Body:
The issue is that the SwiftUI Navigation model is, by default, based on a UISplitview, and that on the iPad, the "Start Quiz" navigation link transfers navigation to its second controller. On an iphone, the second controller is collapsed away.

What this means for the game is that for the iPad (and large iPhones in landscape mode), the game cannot re-start.

You would also find anomalies if you ran the game on a large format iPhone, and then rotated it mid way through the game.

You can change the navigation view style to not use the split view model by using:

.navigationViewStyle(StackNavigationViewStyle())

after the NavigationView closing brace.