Title: Using -replace when selecting object to replace using an $array

Body:
I need some help. I am trying to get a script working which uses a text file full of words that need filtering from the pipeline of a command.

This is the $filters text file I have created (NB - The values are server volume names):

('75ab4a4776bc11e09ae1806e6f6e6963','')
('296b67b2c1f111e298d6806e6f6e6963','')
('e3636932b95111e2a4be806e6f6e6963','')
('296b67b2c1f111e298d6806e6f6e6963','')
('3f149289a83911e380b3806e6f6e6963','')
('61aee3ccd72911e4ad8e806e6f6e6963','')
('97c80f3d9b7911e2b24e806e6f6e6963','')
('3f149289a83911e380b3806e6f6e6963','')
('181BCC0400D34ED0BC61CB7B1AC1FB9E','')
('52120b028f8011dfb1bd806e6f6e6963','')
('dfff9b1f76a911e09259806e6f6e6963','')
('d4843b91172311e4ba95806e6f6e6963','')
('668b283173711e4bfdb806e6f6e6963','')
('d68e8a9cc5d211e680b4806e6f6e6963','')
('d68e8a9cc5d211e680b4806e6f6e6963','')
('3f149289a83911e380b3806e6f6e6963','')

What I want to do is parse all those values in the text file into the following command:

Get-BEAgentServer | Where-Object {
    ($_.BackupStatus -eq "BackupSucceeded")
} | Where-Object {
    ($_.BackupStatus -ne "unknown")
}

If I add this, I get the filtered output I want:

Select-Object @{n='Server Name';e={
    $_.Name -replace ('3f149289a83911e380b3806e6f6e6963','') `
        -replace ('61aee3ccd72911e4ad8e806e6f6e6963','') `
        -replace  ('97c80f3d9b7911e2b24e806e6f6e6963','') `
        -replace ('3f149289a83911e380b3806e6f6e6963','') `
        -replace ('181BCC0400D34ED0BC61CB7B1AC1FB9E','') `
        -replace ('52120b028f8011dfb1bd806e6f6e6963','') `
        -replace ('dfff9b1f76a911e09259806e6f6e6963','') `
        -replace ('d4843b91172311e4ba95806e6f6e6963','') `
        -replace ('668b283173711e4bfdb806e6f6e6963','') `
        -replace ('d68e8a9cc5d211e680b4806e6f6e6963','') `
        -replace ('d68e8a9cc5d211e680b4806e6f6e6963','') `
        -replace ('3f149289a83911e380b3806e6f6e6963','') `
        -replace ('Volume', 'SysVol') `
        -replace ('7ECA562AF49C475EB10168CF5C0D302C','') `
        -replace ('e3636932b95111e2a4be806e6f6e6963','') `
        -replace ('296b67b2c1f111e298d6806e6f6e6963','') `
        -replace ('75ab4a4776bc11e09ae1806e6f6e6963','')
}}, starttime, setendtime | Sort-Object "Server Name" -Unique | select -Skip 1

My question is, is it possible to simplfy the command to replace using $filters instead of manually adding each string to filter?
This will make it easier for me to add filter strings in the future.

Body:
Put just the strings you want removed in the input file:

75ab4a4776bc11e09ae1806e6f6e6963
296b67b2c1f111e298d6806e6f6e6963
e3636932b95111e2a4be806e6f6e6963
296b67b2c1f111e298d6806e6f6e6963
3f149289a83911e380b3806e6f6e6963
61aee3ccd72911e4ad8e806e6f6e6963
97c80f3d9b7911e2b24e806e6f6e6963
3f149289a83911e380b3806e6f6e6963
181BCC0400D34ED0BC61CB7B1AC1FB9E
52120b028f8011dfb1bd806e6f6e6963
dfff9b1f76a911e09259806e6f6e6963
d4843b91172311e4ba95806e6f6e6963
668b283173711e4bfdb806e6f6e6963
d68e8a9cc5d211e680b4806e6f6e6963
d68e8a9cc5d211e680b4806e6f6e6963
3f149289a83911e380b3806e6f6e6963

Read the file and build one regular expression from it:

$filter = (Get-Content 'C:\path\to\filters.txt' | ForEach-Object {
    [regex]::Escape($_)
}) -join '|'

Then remove the content with a single replacement:

Select-Object @{n='Server Name';e={$_.Name -replace $filter}}, ...


来源: stackexchange

问:
Programming Language Implementation
In my lecture notes "Language Implementation System" is explained as,

A language implementation system provides an interface fro programs in
  higher level languages to machine instructions.

And after a search Wikipedia gave me,

A programming language implementation is a system for executing
  computer programs.

But I am having a hard time understanding this concept. Is it talking about something like a JVM (Java Virtual Machine)?

Can someone explain this to me in simpler terms?

答:
I'll give it a shot.

Programming Language Implementation describes the method for how your code (such as Java) as an example is converted to a language that the machine (processor etc) understand. We refer to this as machine code.

There are 2 main forms of this, compilation and interpretation.

Technically, as the Wikipedia page points out, a compilation is converting one programming language to another (usually a lower level one). Traditionally, this refers to combining multiple input files into a single file that is runnable on the target system.

In an interpreted language, the program is converted piece by piece while it's running on your machine.

You mention the Java Virtual Machine, so I'm going to use that as an example. In the JVM, the Java code is compiled into  Java bytecode using javac. This bytecode is then interpreted by the Java Virtual Machine and run on the underlying hardware. This is what the java command does. While Java could be described as a compiled and interpreted language, it's probably easier to think of Java itself as a compiled language, and Java bytecode as an interpreted language.

In contrast, other languages such as C and C++ are usually converted (compiled) directly to the machine code of the target hardware platform.

In addition to these, as @kostix pointed out in the comments, there exists transpiling, or source-to-source compiling. Transpiling refers to converting one higher level language into another higher level one. A common example is converting JavaScript ES6 to JavaScript ES5 for backwards compatibility, or C++ into JavaScript

ContentLicense: CC BY-SA 3.0

Title: Programming Language Implementation


问:
Error C# Invoke SetPassword AD
I'm trying to do a work for my final school project and I'm using C#, PHP, MySQL and Active Directory. The accounts will be created by the C# program into the Active Directory database, but I get this error while creating:

```<code>System.Reflection.TargetInvocationException: O destino de uma invocação accionou uma excepção. ---> System.Runtime.InteropServices.COMException: O servidor de RPC não está disponível. (Excepção de HRESULT: 0x800706BA)
   --- Fim do rastreio da pilha de excepção interna ---
   em System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)
   em PAP.ldap_functions.createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, Int32 mobile, String streetAddress, String city, String postalcode, Boolean enabled) em C:\Users\Karbust\source\repos\PAP\PAP\ldap_functions.cs:line 176
</code>```

I'm using this code to do it:

```<code>        public int createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, Int32 mobile, String streetAddress, String city, String postalcode, bool enabled)
        {
            try
            {
                // create new user object and write into AD
                DirectoryEntry user = new DirectoryEntry(connectionstring_membros, adminlogin, adminpass);

                // User name (domain based)
                DirectoryEntry objUser = user.Children.Add("CN=" + username, "user");

                // User name
                objUser.Properties["userPrincipalName"].Add(username + "@" + domain);

                // User name (older systems)
                objUser.Properties["samaccountname"].Add(username);

                // Surname
                objUser.Properties["sn"].Add(last);

                // Forename
                objUser.Properties["givenname"].Add(first);

                // Display name
                objUser.Properties["displayname"].Add(first + " " + last);

                // Description
                objUser.Properties["description"].Add(description);

                // E-mail
                objUser.Properties["mail"].Add(email);

                // Home dir (drive letter)
                //objUser.Properties["homedirectory"].Add(homeDir);

                // Home dir (path)
                //objUser.Properties["homedrive"].Add(homeDrive);

                objUser.CommitChanges();

                // set user's password
                objUser.Invoke("SetPassword", password);
                //objUser.Properties["password"].Add(password);
                //objUser.SetPassword(password);
                //objUser.Invoke("SetPassword", new object[] { password });

                // Mobile Number
                objUser.Properties["mobile"].Add(mobile);

                // Telephone Number
                //objUser.Properties["telephoneNumber"].Add(telephoneNumber);

                // Street
                objUser.Properties["streetAddress"].Add(streetAddress);

                // City
                objUser.Properties["l"].Add(city);

                // State/Province
                //objUser.Properties["st"].Add(stateprovince);

                // Zip/Postal Code
                objUser.Properties["postalCode"].Add(postalcode);

                // enable account if requested (see http://support.microsoft.com/kb/305144 for other codes)
                if (enabled)
                    objUser.Invoke("Put", new object[] { "userAccountControl", "512" });

                // add user to specified groups
                foreach (String thisGroup in groups)
                {
                    DirectoryEntry newGroup = objUser.Parent.Children.Find("CN=" + thisGroup, "group");

                    if (newGroup != null)
                        newGroup.Invoke("Add", new object[] { objUser.Path.ToString() });
                }

                objUser.CommitChanges();

                // make home folder on server
                //Directory.CreateDirectory(homeDir);

                // set permissions on folder, we loop this because if the program
                // tries to set the permissions straight away an exception will be
                // thrown as the brand new user does not seem to be available, it takes
                // a second or so for it to appear and it can then be used in ACLs
                // and set as the owner
                /*bool folderCreated = false;

                while (!folderCreated)
                {
                    try
                    {
                        // get current ACL
                        DirectoryInfo dInfo = new DirectoryInfo(homeDir);
                        DirectorySecurity dSecurity = dInfo.GetAccessControl();

                        // Add full control for the user and set owner to them
                        IdentityReference newUser = new NTAccount(domain + @"\" + username);
                        dSecurity.SetOwner(newUser);
                        FileSystemAccessRule permissions = new FileSystemAccessRule(newUser, FileSystemRights.FullControl, AccessControlType.Allow);
                        dSecurity.AddAccessRule(permissions);

                        // Set the new access settings.
                        dInfo.SetAccessControl(dSecurity);
                        folderCreated = true;
                    }
                    catch (System.Security.Principal.IdentityNotMappedException)
                    {
                        Console.Write(".");
                    }
                    catch (Exception ex)
                    {
                        // other exception caught so not problem with user delay as
                        // commented above
                        Console.WriteLine("Exception caught:" + ex.ToString());
                        return 0;
                    }
                }*/

                return 1;
            }
            catch(Exception ex)
            {
                MessageBox.Show("Exception caught: " + ex.ToString(), "Criar Cliente");

                fncs.ErroToTxt(ex);

                return 0;
            }
        }
</code>```

The account is created but everything after

```<code>objUser.Invoke("SetPassword", password);
</code>```

is not working, the program gives the exception is this line.

I'm using a code I found on the internet that is working 100% and adapted to my needs:

```<code>using System;
using System.Text;
using System.DirectoryServices;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.DirectoryServices.Protocols;
using System.DirectoryServices.AccountManagement;

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            // connect to LDAP
            //DirectoryEntry myLdapConnection = createDirectoryEntry();

            // define vars for user
            String domain = "vm.pap";
            String first = "First name";
            String last = "Last name";
            String description = ".NET Test";
            String password = "xpto001!";
            String[] groups = { "gr_membros" };
            //String username = first.ToLower() + last.Substring(0, 1).ToLower();
            String username = "charparodar";
            String email = "email@mail.com";
            String homeDrive = "H:";
            String homeDir = @"\\vm.pap\data3\USERS\" + username;

            // create user
            try
            {
                if (createUser(domain, first, last, description, password, groups, username, email, homeDrive, homeDir, true) == 0)
                {
                    Console.WriteLine("Account created!");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Problem creating account :(");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
                Console.ReadLine();
            }
        }
        static int createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, String homeDrive, String homeDir, bool enabled)
        {
            // create new user object and write into AD
            //DirectoryEntry user = myLdapConnection.Children.Add("OU=" + first + ",OU= " + last, "user");
            //DirectoryEntry user = myLdapConnection.Children.Add("CN=" + first + " " + last, "user");
            DirectoryEntry user = new DirectoryEntry("LDAP://vmpap/OU=Membros,OU=Utilizadores,DC=vm,DC=pap", "Administrator", "xpto001!");

            // User name (domain based)
            //user.Properties["userprincipalname"].Add(username + "@" + domain);
            //user.Invoke("Add", new object[] { username + "@" + domain });
            //user.Invoke("Add", new object[] { "ansilva15ig@vm.pap" });
            DirectoryEntry objUser = user.Children.Add("CN=ansilva15ig","user");

            // User name
            objUser.Properties["userPrincipalName"].Add(username + "@" + domain);

            // User name (older systems)
            objUser.Properties["samaccountname"].Add(username);

            // Surname
            objUser.Properties["sn"].Add(last);

            // Forename
            objUser.Properties["givenname"].Add(first);

            // Display name
            objUser.Properties["displayname"].Add(first + " " + last);

            // Description
            objUser.Properties["description"].Add(description);

            // E-mail
            objUser.Properties["mail"].Add(email);

            // Home dir (drive letter)
            //objUser.Properties["homedirectory"].Add(homeDir);

            // Home dir (path)
            //objUser.Properties["homedrive"].Add(homeDrive);

            objUser.CommitChanges();

            // set user's password
            objUser.Invoke("SetPassword", password);

            // enable account if requested (see http://support.microsoft.com/kb/305144 for other codes)
            if (enabled)
                objUser.Invoke("Put", new object[] { "userAccountControl", "512" });

            // add user to specified groups
            foreach (String thisGroup in groups)
            {
                DirectoryEntry newGroup = objUser.Parent.Children.Find("CN=" + thisGroup, "group");

                if (newGroup != null)
                    newGroup.Invoke("Add", new object[] { objUser.Path.ToString() });
            }

            objUser.CommitChanges();

            // make home folder on server
            //Directory.CreateDirectory(homeDir);

            // set permissions on folder, we loop this because if the program
            // tries to set the permissions straight away an exception will be
            // thrown as the brand new user does not seem to be available, it takes
            // a second or so for it to appear and it can then be used in ACLs
            // and set as the owner
            /*bool folderCreated = false;

            while (!folderCreated)
            {
                try
                {
                    // get current ACL
                    DirectoryInfo dInfo = new DirectoryInfo(homeDir);
                    DirectorySecurity dSecurity = dInfo.GetAccessControl();

                    // Add full control for the user and set owner to them
                    IdentityReference newUser = new NTAccount(domain + @"\" + username);
                    dSecurity.SetOwner(newUser);
                    FileSystemAccessRule permissions = new FileSystemAccessRule(newUser, FileSystemRights.FullControl, AccessControlType.Allow);
                    dSecurity.AddAccessRule(permissions);

                    // Set the new access settings.
                    dInfo.SetAccessControl(dSecurity);
                    folderCreated = true;
                }
                catch (System.Security.Principal.IdentityNotMappedException)
                {
                    Console.Write(".");
                }
                catch (Exception ex)
                {
                    // other exception caught so not problem with user delay as
                    // commented above
                    Console.WriteLine("Exception caught:" + ex.ToString());
                    return 1;
                }
            }*/
            return 0;
        }
        static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings
            DirectoryEntry ldapConnection = new DirectoryEntry("vm.pap");
            ldapConnection.Path = "LDAP://192.168.1.80/OU=Utilizadores,DC=vm,DC=pap";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;
        }
    }
}
</code>```

Thanks to everyone that tries to help

答:
I tested on my end and affirm that your code works absolutely fine. So, there is nothing wrong with the code.

I was reading something and so as a solution, I would request you to temporarily disable the Firewall on PC where you are testing the software or application. Then test.

If it's a software application, test by running the software as Run as Administrator

Title: Error C# Invoke SetPassword AD

Body:
I'm trying to do a work for my final school project and I'm using C#, PHP, MySQL and Active Directory. The accounts will be created by the C# program into the Active Directory database, but I get this error while creating:

System.Reflection.TargetInvocationException: O destino de uma invocação accionou uma excepção. ---> System.Runtime.InteropServices.COMException: O servidor de RPC não está disponível. (Excepção de HRESULT: 0x800706BA)
   --- Fim do rastreio da pilha de excepção interna ---
   em System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)
   em PAP.ldap_functions.createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, Int32 mobile, String streetAddress, String city, String postalcode, Boolean enabled) em C:\Users\Karbust\source\repos\PAP\PAP\ldap_functions.cs:line 176

I'm using this code to do it:

        public int createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, Int32 mobile, String streetAddress, String city, String postalcode, bool enabled)
        {
            try
            {
                // create new user object and write into AD
                DirectoryEntry user = new DirectoryEntry(connectionstring_membros, adminlogin, adminpass);

                // User name (domain based)
                DirectoryEntry objUser = user.Children.Add("CN=" + username, "user");

                // User name
                objUser.Properties["userPrincipalName"].Add(username + "@" + domain);

                // User name (older systems)
                objUser.Properties["samaccountname"].Add(username);

                // Surname
                objUser.Properties["sn"].Add(last);

                // Forename
                objUser.Properties["givenname"].Add(first);

                // Display name
                objUser.Properties["displayname"].Add(first + " " + last);

                // Description
                objUser.Properties["description"].Add(description);

                // E-mail
                objUser.Properties["mail"].Add(email);

                // Home dir (drive letter)
                //objUser.Properties["homedirectory"].Add(homeDir);

                // Home dir (path)
                //objUser.Properties["homedrive"].Add(homeDrive);

                objUser.CommitChanges();

                // set user's password
                objUser.Invoke("SetPassword", password);
                //objUser.Properties["password"].Add(password);
                //objUser.SetPassword(password);
                //objUser.Invoke("SetPassword", new object[] { password });

                // Mobile Number
                objUser.Properties["mobile"].Add(mobile);

                // Telephone Number
                //objUser.Properties["telephoneNumber"].Add(telephoneNumber);

                // Street
                objUser.Properties["streetAddress"].Add(streetAddress);

                // City
                objUser.Properties["l"].Add(city);

                // State/Province
                //objUser.Properties["st"].Add(stateprovince);

                // Zip/Postal Code
                objUser.Properties["postalCode"].Add(postalcode);

                // enable account if requested (see http://support.microsoft.com/kb/305144 for other codes)
                if (enabled)
                    objUser.Invoke("Put", new object[] { "userAccountControl", "512" });

                // add user to specified groups
                foreach (String thisGroup in groups)
                {
                    DirectoryEntry newGroup = objUser.Parent.Children.Find("CN=" + thisGroup, "group");

                    if (newGroup != null)
                        newGroup.Invoke("Add", new object[] { objUser.Path.ToString() });
                }

                objUser.CommitChanges();

                // make home folder on server
                //Directory.CreateDirectory(homeDir);

                // set permissions on folder, we loop this because if the program
                // tries to set the permissions straight away an exception will be
                // thrown as the brand new user does not seem to be available, it takes
                // a second or so for it to appear and it can then be used in ACLs
                // and set as the owner
                /*bool folderCreated = false;

                while (!folderCreated)
                {
                    try
                    {
                        // get current ACL
                        DirectoryInfo dInfo = new DirectoryInfo(homeDir);
                        DirectorySecurity dSecurity = dInfo.GetAccessControl();

                        // Add full control for the user and set owner to them
                        IdentityReference newUser = new NTAccount(domain + @"\" + username);
                        dSecurity.SetOwner(newUser);
                        FileSystemAccessRule permissions = new FileSystemAccessRule(newUser, FileSystemRights.FullControl, AccessControlType.Allow);
                        dSecurity.AddAccessRule(permissions);

                        // Set the new access settings.
                        dInfo.SetAccessControl(dSecurity);
                        folderCreated = true;
                    }
                    catch (System.Security.Principal.IdentityNotMappedException)
                    {
                        Console.Write(".");
                    }
                    catch (Exception ex)
                    {
                        // other exception caught so not problem with user delay as
                        // commented above
                        Console.WriteLine("Exception caught:" + ex.ToString());
                        return 0;
                    }
                }*/

                return 1;
            }
            catch(Exception ex)
            {
                MessageBox.Show("Exception caught: " + ex.ToString(), "Criar Cliente");

                fncs.ErroToTxt(ex);

                return 0;
            }
        }

The account is created but everything after

objUser.Invoke("SetPassword", password);

is not working, the program gives the exception is this line.

I'm using a code I found on the internet that is working 100% and adapted to my needs:

using System;
using System.Text;
using System.DirectoryServices;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.DirectoryServices.Protocols;
using System.DirectoryServices.AccountManagement;

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            // connect to LDAP
            //DirectoryEntry myLdapConnection = createDirectoryEntry();

            // define vars for user
            String domain = "vm.pap";
            String first = "First name";
            String last = "Last name";
            String description = ".NET Test";
            String password = "xpto001!";
            String[] groups = { "gr_membros" };
            //String username = first.ToLower() + last.Substring(0, 1).ToLower();
            String username = "charparodar";
            String email = "email@mail.com";
            String homeDrive = "H:";
            String homeDir = @"\\vm.pap\data3\USERS\" + username;

            // create user
            try
            {
                if (createUser(domain, first, last, description, password, groups, username, email, homeDrive, homeDir, true) == 0)
                {
                    Console.WriteLine("Account created!");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Problem creating account :(");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
                Console.ReadLine();
            }
        }
        static int createUser(String domain, String first, String last, String description, String password, String[] groups, String username, String email, String homeDrive, String homeDir, bool enabled)
        {
            // create new user object and write into AD
            //DirectoryEntry user = myLdapConnection.Children.Add("OU=" + first + ",OU= " + last, "user");
            //DirectoryEntry user = myLdapConnection.Children.Add("CN=" + first + " " + last, "user");
            DirectoryEntry user = new DirectoryEntry("LDAP://vmpap/OU=Membros,OU=Utilizadores,DC=vm,DC=pap", "Administrator", "xpto001!");

            // User name (domain based)
            //user.Properties["userprincipalname"].Add(username + "@" + domain);
            //user.Invoke("Add", new object[] { username + "@" + domain });
            //user.Invoke("Add", new object[] { "ansilva15ig@vm.pap" });
            DirectoryEntry objUser = user.Children.Add("CN=ansilva15ig","user");

            // User name
            objUser.Properties["userPrincipalName"].Add(username + "@" + domain);

            // User name (older systems)
            objUser.Properties["samaccountname"].Add(username);

            // Surname
            objUser.Properties["sn"].Add(last);

            // Forename
            objUser.Properties["givenname"].Add(first);

            // Display name
            objUser.Properties["displayname"].Add(first + " " + last);

            // Description
            objUser.Properties["description"].Add(description);

            // E-mail
            objUser.Properties["mail"].Add(email);

            // Home dir (drive letter)
            //objUser.Properties["homedirectory"].Add(homeDir);

            // Home dir (path)
            //objUser.Properties["homedrive"].Add(homeDrive);

            objUser.CommitChanges();

            // set user's password
            objUser.Invoke("SetPassword", password);

            // enable account if requested (see http://support.microsoft.com/kb/305144 for other codes)
            if (enabled)
                objUser.Invoke("Put", new object[] { "userAccountControl", "512" });

            // add user to specified groups
            foreach (String thisGroup in groups)
            {
                DirectoryEntry newGroup = objUser.Parent.Children.Find("CN=" + thisGroup, "group");

                if (newGroup != null)
                    newGroup.Invoke("Add", new object[] { objUser.Path.ToString() });
            }

            objUser.CommitChanges();

            // make home folder on server
            //Directory.CreateDirectory(homeDir);

            // set permissions on folder, we loop this because if the program
            // tries to set the permissions straight away an exception will be
            // thrown as the brand new user does not seem to be available, it takes
            // a second or so for it to appear and it can then be used in ACLs
            // and set as the owner
            /*bool folderCreated = false;

            while (!folderCreated)
            {
                try
                {
                    // get current ACL
                    DirectoryInfo dInfo = new DirectoryInfo(homeDir);
                    DirectorySecurity dSecurity = dInfo.GetAccessControl();

                    // Add full control for the user and set owner to them
                    IdentityReference newUser = new NTAccount(domain + @"\" + username);
                    dSecurity.SetOwner(newUser);
                    FileSystemAccessRule permissions = new FileSystemAccessRule(newUser, FileSystemRights.FullControl, AccessControlType.Allow);
                    dSecurity.AddAccessRule(permissions);

                    // Set the new access settings.
                    dInfo.SetAccessControl(dSecurity);
                    folderCreated = true;
                }
                catch (System.Security.Principal.IdentityNotMappedException)
                {
                    Console.Write(".");
                }
                catch (Exception ex)
                {
                    // other exception caught so not problem with user delay as
                    // commented above
                    Console.WriteLine("Exception caught:" + ex.ToString());
                    return 1;
                }
            }*/
            return 0;
        }
        static DirectoryEntry createDirectoryEntry()
        {
            // create and return new LDAP connection with desired settings
            DirectoryEntry ldapConnection = new DirectoryEntry("vm.pap");
            ldapConnection.Path = "LDAP://192.168.1.80/OU=Utilizadores,DC=vm,DC=pap";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;
        }
    }
}

Thanks to everyone that tries to help


问:
Understanding SimpleRNN process
I have created the following SimpleRNN using Keras:

```<code>X = X.reshape((X.shape[0], X.shape[1], 1))
tr_X, ts_X, tr_y, ts_y = train_test_split(X, y, train_size=.8)
batch_size = 1000

print('RNN model...')
model = Sequential()
model.add(SimpleRNN(64, activation='relu', batch_input_shape=(batch_size, X.shape[1], 1)))
model.add(Dense(1, activation='relu'))

print('Training...')
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print (model.summary())
print ('\n')

model.fit(tr_X, tr_y,
          batch_size=batch_size, epochs=1,
          shuffle=True, validation_data=(ts_X, ts_y))
</code>```

For the model summary, I get the following:

```<code>Layer (type)                 Output Shape              Param #
=================================================================
simple_rnn_1 (SimpleRNN)     (1000, 64)                4224
_________________________________________________________________
dense_1 (Dense)              (1000, 1)                 65
=================================================================
Total params: 4,289
Trainable params: 4,289
Non-trainable params: 0
_________________________________________________________________
</code>```

Given that I have a dataset of 10,000 samples and 64 features. My goal is to generate a classification model by training it using this dataset (class labels are binary 0 and 1). Now, I am trying to understand what is going on here. As seen in 'Output Shape' column, the simple_rnn_1 has (1000, 64). I interpret it as 1000 rows (which is the batch) and 64 features. Assuming the code above is logically correct, my questions is:

How does RNN handle this matrix (i.e., (1000,64))? Does it input
each column something like this figure?

Should SimpleRNN() units always be equal to the number of features?

Thank you

答:
In the code, you defined batch_input_shape to be with shape: (batch_size, X.shape[1], 1)

which means that you will insert to the RNN, batch_size examples, each example contains X.shape[1] time-stamps (number of pink boxes in your image) and each time-stamp is shape 1 (scalar).

So yes, input shape of (1000,64,1) will be exactly like you said - each column will be input to the RNN.

No! units will be your output dim. Usually more units means more complex network (just like in regular neural network) -> more parameters to learn.

Units will be the shape of the RNN's internal state.
(So, in your example, if you declare units=2000 your output will be (1000,2000).)

Title: Understanding SimpleRNN process

Body:
I have created the following SimpleRNN using Keras:

X = X.reshape((X.shape[0], X.shape[1], 1))
tr_X, ts_X, tr_y, ts_y = train_test_split(X, y, train_size=.8)
batch_size = 1000

print('RNN model...')
model = Sequential()
model.add(SimpleRNN(64, activation='relu', batch_input_shape=(batch_size, X.shape[1], 1)))
model.add(Dense(1, activation='relu'))

print('Training...')
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print (model.summary())
print ('\n')

model.fit(tr_X, tr_y,
          batch_size=batch_size, epochs=1,
          shuffle=True, validation_data=(ts_X, ts_y))

For the model summary, I get the following:

Layer (type)                 Output Shape              Param #
=================================================================
simple_rnn_1 (SimpleRNN)     (1000, 64)                4224
_________________________________________________________________
dense_1 (Dense)              (1000, 1)                 65
=================================================================
Total params: 4,289
Trainable params: 4,289
Non-trainable params: 0
_________________________________________________________________

Given that I have a dataset of 10,000 samples and 64 features. My goal is to generate a classification model by training it using this dataset (class labels are binary 0 and 1). Now, I am trying to understand what is going on here. As seen in 'Output Shape' column, the simple_rnn_1 has (1000, 64). I interpret it as 1000 rows (which is the batch) and 64 features. Assuming the code above is logically correct, my questions is:

How does RNN handle this matrix (i.e., (1000,64))? Does it input
each column something like this figure?

Should SimpleRNN() units always be equal to the number of features?

Thank you


问:
java streams in Java 7
My question may be too broad and probably the answer is a simple NO, but I have to ask.

Is there any equivalent implementation of (Java 8) streams* in Java 7?

I am familiar with (Java 8) streams but my project requirement is to use Java 7.

*Not to be confused with inputStream and outputStream.

答:
An another choice is here for Java 6+

interfaces:

```<code>interface TransformRule<In, Out> {
    Out extract(In obj);
}

interface FilterRule<T> {
    boolean apply(T obj);
}
</code>```

And Java8Stream-like container class for Collection/Map:

```<code>import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

class FPMapContainer<KeyType, ValueType> extends FPContainer<Map<KeyType, ValueType>, Map.Entry<KeyType, ValueType>, ValueType> {
    FPMapContainer(Map<KeyType, ValueType> container) {
        super(container);
    }

    @Override
    public <Out> FPMapContainer<KeyType, Out> map(TransformRule<Map.Entry<KeyType, ValueType>, Out> rule) {
        return new FPMapContainer<>(handleContainer(getMapMapRule(rule)));
    }

    @Override
    public FPMapContainer<KeyType, ValueType> filter(FilterRule<Map.Entry<KeyType, ValueType>> rule) {
        return new FPMapContainer<>(handleContainer(getMapFilterRule(rule)));
    }

    @Override
    public FPMapContainer<KeyType, ValueType> concat(Map<KeyType, ValueType> another) {
        HashMap newOne = new HashMap(container);
        newOne.putAll(another);
        return new FPMapContainer<>(newOne);
    }

    @Override
    public FPMapContainer<KeyType, ValueType> concat(FPContainer<Map<KeyType, ValueType>, Map.Entry<KeyType, ValueType>, ValueType> another) {
        return concat(another.get());
    }

    protected <Out> TransformRule<Map<KeyType, ValueType>, Map<KeyType, Out>> getMapMapRule(final TransformRule<Map.Entry<KeyType, ValueType>, Out> rule) {
        return new TransformRule<Map<KeyType, ValueType>, Map<KeyType, Out>>() {
            @Override
            public Map<KeyType, Out> extract(Map<KeyType, ValueType> obj) {
                Map<KeyType, Out> newOne = new HashMap<>();
                for (Map.Entry<KeyType, ValueType> entry : obj.entrySet()) {
                    newOne.put(entry.getKey(), rule.extract(entry));
                }
                return newOne;
            }
        };
    }

    protected TransformRule<Map<KeyType, ValueType>, Map<KeyType, ValueType>> getMapFilterRule(final FilterRule<Map.Entry<KeyType, ValueType>> rule) {
        return new TransformRule<Map<KeyType, ValueType>, Map<KeyType, ValueType>>() {
            @Override
            public Map<KeyType, ValueType> extract(Map<KeyType, ValueType> obj) {
                Map<KeyType, ValueType> newOne = new HashMap<>();
                for (Map.Entry<KeyType, ValueType> entry : obj.entrySet()) {
                    KeyType key = entry.getKey();
                    ValueType value = entry.getValue();
                    boolean isValid = rule.apply(entry);

                    if (isValid) {
                        newOne.put(key, value);
                    }
                }
                return newOne;
            }
        };
    }
}

class FPCollectionContainer<ValueType> extends FPContainer<Collection<ValueType>, ValueType, ValueType> {
    FPCollectionContainer(Collection<ValueType> container) {
        super(container);
    }

    @Override
    public <Out> FPCollectionContainer<Out> map(TransformRule<ValueType, Out> rule) {
        return new FPCollectionContainer<>(handleContainer(getCollectionMapRule(rule)));
    }

    @Override
    public FPCollectionContainer<ValueType> filter(FilterRule<ValueType> rule) {
        return new FPCollectionContainer<>(handleContainer(getCollectionFilterRule(rule)));
    }

    @Override
    public FPCollectionContainer<ValueType> concat(Collection<ValueType> another) {
        ArrayList<ValueType> newOne = new ArrayList<>(container);
        newOne.addAll(another);
        return new FPCollectionContainer<>(newOne);
    }

    @Override
    public FPCollectionContainer<ValueType> concat(FPContainer<Collection<ValueType>, ValueType, ValueType> another) {
        return concat(another.get());
    }

    protected <Out> TransformRule<Collection<ValueType>, Collection<Out>> getCollectionMapRule(final TransformRule<ValueType, Out> rule) {
        return new TransformRule<Collection<ValueType>, Collection<Out>>() {
            @Override
            public Collection<Out> extract(Collection<ValueType> obj) {
                Collection<Out> newOne = new ArrayList<>();
                for (ValueType entry : obj) {
                    newOne.add(rule.extract(entry));
                }
                return newOne;
            }
        };
    }

    protected TransformRule<Collection<ValueType>, Collection<ValueType>> getCollectionFilterRule(final FilterRule<ValueType> rule) {
        return new TransformRule<Collection<ValueType>, Collection<ValueType>>() {
            @Override
            public Collection<ValueType> extract(Collection<ValueType> obj) {
                Collection<ValueType> newOne = new ArrayList<>();
                for (ValueType entry : obj) {
                    if (rule.apply(entry)) {
                        newOne.add(entry);
                    }
                }
                return newOne;
            }
        };
    }
}

abstract class FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> {

    protected ContainerTypeWithValueType container;

    protected FPContainer(ContainerTypeWithValueType container) {
        this.container = container;
    }

    public static <KeyType, ValueType> FPMapContainer<KeyType, ValueType> from(Map<KeyType, ValueType> container) {
        return new FPMapContainer<>(container);
    }

    public static <ValueType> FPCollectionContainer<ValueType> from(Collection<ValueType> container) {
        return new FPCollectionContainer<>(container);
    }

    public abstract <Out> Object map(TransformRule<ContainerIterableItemType, Out> rule);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> filter(FilterRule<ContainerIterableItemType> rule);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> concat(FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> another);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> concat(ContainerTypeWithValueType another);

    public <Out> Out reduce(TransformRule<ContainerTypeWithValueType, Out> rule) {
        return rule.extract(container);
    }

    public ContainerTypeWithValueType get() {
        return container;
    }

    protected <ContainerTargetType> ContainerTargetType handleContainer(TransformRule<ContainerTypeWithValueType, ContainerTargetType> collectionMapRule) {
        if (collectionMapRule != null) {
            return collectionMapRule.extract(container);
        }

        return (ContainerTargetType) container;
    }
}
</code>```

Now you can use it like Java8Stream in this way:

```<code>TransformRule<Integer, String> integerStringTransform = new TransformRule<Integer, String>() {
    @Override
    public String extract(Integer obj) {
        return "" + obj;
    }
};

TransformRule<Collection<String>, String> collectionStringTransform = new TransformRule<Collection<String>, String>() {
    @Override
    public String extract(Collection<String> obj) {
        String result = "";
        for (String item : obj) {
            result += item;
        }

        return result;
    }
};

FilterRule<Integer> ltFourFilter = new FilterRule<Integer>() {
    @Override
    public boolean apply(Integer obj) {
        return obj != null && obj < 4;
    }
};

// ==============================================

String reduced;

// Collection case:
// `reduced` would be "123"
reduced = FPContainer.from(Arrays.asList(1, 4))
        .concat(FPContainer.from(Arrays.asList(2)))
        .concat(Arrays.asList(3))
        .filter(ltFourFilter)
        .map(integerStringTransform).reduce(collectionStringTransform);

// Map case:
reduced = FPContainer.from(stringIntegerHashMap)
        .filter(new FilterRule<Map.Entry<String, Integer>>() {
            @Override
            public boolean apply(Map.Entry<String, Integer> obj) {
                return obj.getKey().charAt(0) < 'c' && obj.getValue() < 4;
            }
        })
        .map(new TransformRule<Map.Entry<String,Integer>, String>() {
            @Override
            public String extract(Map.Entry<String, Integer> obj) {
                return ""+obj.getValue();
            }
        }).reduce(new TransformRule<Map<String, String>, String>() {
            @Override
            public String extract(Map<String, String> obj) {
                String result = "";

                Map<String, String> objectStringMap = sortByValue(obj);
                for (Map.Entry<String, String> entry : objectStringMap.entrySet()) {
                    result += entry.getKey().toString() + entry.getValue();
                }

                return result;
            }
        });
</code>```

P.S.

sortByValue(map) is here: (credit: https://stackoverflow.com/a/109389/2293635)

```<code>public static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Object>() {
        @SuppressWarnings("unchecked")
        public int compare(Object o1, Object o2) {
            return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext();) {
        Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}
</code>```

Title: java streams in Java 7

Body:
An another choice is here for Java 6+

interfaces:

interface TransformRule<In, Out> {
    Out extract(In obj);
}

interface FilterRule<T> {
    boolean apply(T obj);
}

And Java8Stream-like container class for Collection/Map:

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

class FPMapContainer<KeyType, ValueType> extends FPContainer<Map<KeyType, ValueType>, Map.Entry<KeyType, ValueType>, ValueType> {
    FPMapContainer(Map<KeyType, ValueType> container) {
        super(container);
    }

    @Override
    public <Out> FPMapContainer<KeyType, Out> map(TransformRule<Map.Entry<KeyType, ValueType>, Out> rule) {
        return new FPMapContainer<>(handleContainer(getMapMapRule(rule)));
    }

    @Override
    public FPMapContainer<KeyType, ValueType> filter(FilterRule<Map.Entry<KeyType, ValueType>> rule) {
        return new FPMapContainer<>(handleContainer(getMapFilterRule(rule)));
    }

    @Override
    public FPMapContainer<KeyType, ValueType> concat(Map<KeyType, ValueType> another) {
        HashMap newOne = new HashMap(container);
        newOne.putAll(another);
        return new FPMapContainer<>(newOne);
    }

    @Override
    public FPMapContainer<KeyType, ValueType> concat(FPContainer<Map<KeyType, ValueType>, Map.Entry<KeyType, ValueType>, ValueType> another) {
        return concat(another.get());
    }

    protected <Out> TransformRule<Map<KeyType, ValueType>, Map<KeyType, Out>> getMapMapRule(final TransformRule<Map.Entry<KeyType, ValueType>, Out> rule) {
        return new TransformRule<Map<KeyType, ValueType>, Map<KeyType, Out>>() {
            @Override
            public Map<KeyType, Out> extract(Map<KeyType, ValueType> obj) {
                Map<KeyType, Out> newOne = new HashMap<>();
                for (Map.Entry<KeyType, ValueType> entry : obj.entrySet()) {
                    newOne.put(entry.getKey(), rule.extract(entry));
                }
                return newOne;
            }
        };
    }

    protected TransformRule<Map<KeyType, ValueType>, Map<KeyType, ValueType>> getMapFilterRule(final FilterRule<Map.Entry<KeyType, ValueType>> rule) {
        return new TransformRule<Map<KeyType, ValueType>, Map<KeyType, ValueType>>() {
            @Override
            public Map<KeyType, ValueType> extract(Map<KeyType, ValueType> obj) {
                Map<KeyType, ValueType> newOne = new HashMap<>();
                for (Map.Entry<KeyType, ValueType> entry : obj.entrySet()) {
                    KeyType key = entry.getKey();
                    ValueType value = entry.getValue();
                    boolean isValid = rule.apply(entry);

                    if (isValid) {
                        newOne.put(key, value);
                    }
                }
                return newOne;
            }
        };
    }
}

class FPCollectionContainer<ValueType> extends FPContainer<Collection<ValueType>, ValueType, ValueType> {
    FPCollectionContainer(Collection<ValueType> container) {
        super(container);
    }

    @Override
    public <Out> FPCollectionContainer<Out> map(TransformRule<ValueType, Out> rule) {
        return new FPCollectionContainer<>(handleContainer(getCollectionMapRule(rule)));
    }

    @Override
    public FPCollectionContainer<ValueType> filter(FilterRule<ValueType> rule) {
        return new FPCollectionContainer<>(handleContainer(getCollectionFilterRule(rule)));
    }

    @Override
    public FPCollectionContainer<ValueType> concat(Collection<ValueType> another) {
        ArrayList<ValueType> newOne = new ArrayList<>(container);
        newOne.addAll(another);
        return new FPCollectionContainer<>(newOne);
    }

    @Override
    public FPCollectionContainer<ValueType> concat(FPContainer<Collection<ValueType>, ValueType, ValueType> another) {
        return concat(another.get());
    }

    protected <Out> TransformRule<Collection<ValueType>, Collection<Out>> getCollectionMapRule(final TransformRule<ValueType, Out> rule) {
        return new TransformRule<Collection<ValueType>, Collection<Out>>() {
            @Override
            public Collection<Out> extract(Collection<ValueType> obj) {
                Collection<Out> newOne = new ArrayList<>();
                for (ValueType entry : obj) {
                    newOne.add(rule.extract(entry));
                }
                return newOne;
            }
        };
    }

    protected TransformRule<Collection<ValueType>, Collection<ValueType>> getCollectionFilterRule(final FilterRule<ValueType> rule) {
        return new TransformRule<Collection<ValueType>, Collection<ValueType>>() {
            @Override
            public Collection<ValueType> extract(Collection<ValueType> obj) {
                Collection<ValueType> newOne = new ArrayList<>();
                for (ValueType entry : obj) {
                    if (rule.apply(entry)) {
                        newOne.add(entry);
                    }
                }
                return newOne;
            }
        };
    }
}

abstract class FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> {

    protected ContainerTypeWithValueType container;

    protected FPContainer(ContainerTypeWithValueType container) {
        this.container = container;
    }

    public static <KeyType, ValueType> FPMapContainer<KeyType, ValueType> from(Map<KeyType, ValueType> container) {
        return new FPMapContainer<>(container);
    }

    public static <ValueType> FPCollectionContainer<ValueType> from(Collection<ValueType> container) {
        return new FPCollectionContainer<>(container);
    }

    public abstract <Out> Object map(TransformRule<ContainerIterableItemType, Out> rule);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> filter(FilterRule<ContainerIterableItemType> rule);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> concat(FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> another);

    public abstract FPContainer<ContainerTypeWithValueType, ContainerIterableItemType, ValueType> concat(ContainerTypeWithValueType another);

    public <Out> Out reduce(TransformRule<ContainerTypeWithValueType, Out> rule) {
        return rule.extract(container);
    }

    public ContainerTypeWithValueType get() {
        return container;
    }

    protected <ContainerTargetType> ContainerTargetType handleContainer(TransformRule<ContainerTypeWithValueType, ContainerTargetType> collectionMapRule) {
        if (collectionMapRule != null) {
            return collectionMapRule.extract(container);
        }

        return (ContainerTargetType) container;
    }
}

Now you can use it like Java8Stream in this way:

TransformRule<Integer, String> integerStringTransform = new TransformRule<Integer, String>() {
    @Override
    public String extract(Integer obj) {
        return "" + obj;
    }
};

TransformRule<Collection<String>, String> collectionStringTransform = new TransformRule<Collection<String>, String>() {
    @Override
    public String extract(Collection<String> obj) {
        String result = "";
        for (String item : obj) {
            result += item;
        }

        return result;
    }
};

FilterRule<Integer> ltFourFilter = new FilterRule<Integer>() {
    @Override
    public boolean apply(Integer obj) {
        return obj != null && obj < 4;
    }
};

// ==============================================

String reduced;

// Collection case:
// `reduced` would be "123"
reduced = FPContainer.from(Arrays.asList(1, 4))
        .concat(FPContainer.from(Arrays.asList(2)))
        .concat(Arrays.asList(3))
        .filter(ltFourFilter)
        .map(integerStringTransform).reduce(collectionStringTransform);

// Map case:
reduced = FPContainer.from(stringIntegerHashMap)
        .filter(new FilterRule<Map.Entry<String, Integer>>() {
            @Override
            public boolean apply(Map.Entry<String, Integer> obj) {
                return obj.getKey().charAt(0) < 'c' && obj.getValue() < 4;
            }
        })
        .map(new TransformRule<Map.Entry<String,Integer>, String>() {
            @Override
            public String extract(Map.Entry<String, Integer> obj) {
                return ""+obj.getValue();
            }
        }).reduce(new TransformRule<Map<String, String>, String>() {
            @Override
            public String extract(Map<String, String> obj) {
                String result = "";

                Map<String, String> objectStringMap = sortByValue(obj);
                for (Map.Entry<String, String> entry : objectStringMap.entrySet()) {
                    result += entry.getKey().toString() + entry.getValue();
                }

                return result;
            }
        });

P.S.

sortByValue(map) is here: (credit: https://stackoverflow.com/a/109389/2293635)

public static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Object>() {
        @SuppressWarnings("unchecked")
        public int compare(Object o1, Object o2) {
            return ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()).compareTo(((Map.Entry<K, V>) (o2)).getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext();) {
        Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next();
        result.put(entry.getKey(), entry.getValue());
    }

    return result;
}


问:
Magento 1.9 categories not loading after import
I'm currently stuck at my magento shop and I can't find a solution. I want to import almost 600.000 products. The process of it is really slow. The more product are in the system, the slower the import of new products works. I also can't open some category pages. Its simply not loading.

Any idea what could be the problem?

答:
If your indexes are set to auto-update you should switch them to manual mode before importing. this is a common reason for decreasing performance (and db locks)

```<code>$collection = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach ($collection as $process) {
  $process->setMode(Mage_Index_Model_Process::MODE_MANUAL)->save();
}
</code>```

after import you could switch back to

```<code>  $process->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->save();
</code>```

Body:
If your indexes are set to auto-update you should switch them to manual mode before importing. this is a common reason for decreasing performance (and db locks)

$collection = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach ($collection as $process) {
  $process->setMode(Mage_Index_Model_Process::MODE_MANUAL)->save();
}

after import you could switch back to

  $process->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->save();


问:
How I can call function with params in function in VUE.js methods?
Coud you help me with my trouble:
I used Vue.js.
My task was: to convert image in base64 and next send to server. So I wrote code below, but got an error.
When I call function readfile I got an error back:
enter image description here

The error is

"this.bufferToBase64 is not a function"

My HTML code is:

```<code>     <div>
      <button class="btn">Upload</button>
      <input type="file" id="fileItem" @change="readfile('fileItem')">
    </div>
</code>```

And my methods are:

```<code>  readfile(id) {
   let f = document.getElementById(id).files[0];
   console.log(f);
    let r = new FileReader();
    r.readAsArrayBuffer(f);
    r.onload = function (e) {
      console.log(e);
      let data = r.result;
      console.log('data: ' + data);
      let bytes = new Uint8Array(data);
      console.log('bytes: ' + bytes);
      let b64encoded = this.bufferToBase641(bytes);
      console.log(b64encoded);
    };
  },
  bufferToBase641(buf) {
    let binstr = Array.prototype.map.call(buf, function (ch) {
      return String.fromCharCode(ch);
    }).join('');
    return btoa(binstr);
  }
</code>```

And next I will be use upload component in Element.io. But now I have the same error.
My HTML:

```<code>      <el-upload
               :file-list="fileList"
               :auto-upload="false"
               :before-upload="readfile"
               accept="image/*">
      <el-button type="primary" style="padding: 10px 40px;">
        <span class="glyphicon glyphicon-picture"></span> Attach</el-button>
    </el-upload>
</code>```

And my Methods:

```<code>  setAtrbt(){
   let input = document.querySelector('.el-upload__input');
   console.log(input);
   input.setAttribute('onchange', 'vm.readfile(this.files[0])')
 },
  readfile(id) {
   let f = document.getElementById(id).files[0];
   console.log(f);
    let r = new FileReader();
    r.readAsArrayBuffer(f);
    r.onload = function (e) {
      console.log(e);
      let data = r.result;
      console.log('data: ' + data);
      let bytes = new Uint8Array(data);
      console.log('bytes: ' + bytes);
      let b64encoded = this.bufferToBase641(bytes);
      console.log(b64encoded);
    };
  },
  bufferToBase641(buf) {
    let binstr = Array.prototype.map.call(buf, function (ch) {
      return String.fromCharCode(ch);
    }).join('');
    return btoa(binstr);
  }
},
mounted(){
  this.setAtrbt();
}
</code>```

Can someone tell me, please, how shoud I use function bufferToBase641 right?
And maybe my actions with Element.io is not good?

答:
You have scope problem. You lost reference for this, as you are in nested function, which have own this object. Improve your code:

```<code>eadfile(id) {
  let f = document.getElementById(id).files[0];
  console.log(f);
  let r = new FileReader();
  r.readAsArrayBuffer(f);
  var self = this // ADD THIS
  r.onload = function (e) {
    console.log(e);
    let data = r.result;
    console.log('data: ' + data);
    let bytes = new Uint8Array(data);
    console.log('bytes: ' + bytes);
    let b64encoded = self.bufferToBase641(bytes); // CHANGE THIS
    console.log(b64encoded);
  };
},
</code>```

You can also use the arrow function for you r.onload callback:

```<code>eadfile(id) {
  let f = document.getElementById(id).files[0];
  console.log(f);
  let r = new FileReader();
  r.readAsArrayBuffer(f);
  r.onload = e => { // CHANGE JUST THIS LINE
    console.log(e);
    let data = r.result;
    console.log('data: ' + data);
    let bytes = new Uint8Array(data);
    console.log('bytes: ' + bytes);
    let b64encoded = this.bufferToBase641(bytes);
    console.log(b64encoded);
  };
},
</code>```

Body:
Coud you help me with my trouble:
I used Vue.js.
My task was: to convert image in base64 and next send to server. So I wrote code below, but got an error.
When I call function readfile I got an error back:
enter image description here

The error is

"this.bufferToBase64 is not a function"

My HTML code is:

      <button class="btn">Upload</button>
      <input type="file" id="fileItem" @change="readfile('fileItem')">

And my methods are:

  readfile(id) {
   let f = document.getElementById(id).files[0];
   console.log(f);
    let r = new FileReader();
    r.readAsArrayBuffer(f);
    r.onload = function (e) {
      console.log(e);
      let data = r.result;
      console.log('data: ' + data);
      let bytes = new Uint8Array(data);
      console.log('bytes: ' + bytes);
      let b64encoded = this.bufferToBase641(bytes);
      console.log(b64encoded);
    };
  },
  bufferToBase641(buf) {
    let binstr = Array.prototype.map.call(buf, function (ch) {
      return String.fromCharCode(ch);
    }).join('');
    return btoa(binstr);
  }

And next I will be use upload component in Element.io. But now I have the same error.
My HTML:

      <el-upload
               :file-list="fileList"
               :auto-upload="false"
               :before-upload="readfile"
               accept="image/*">
      <el-button type="primary" style="padding: 10px 40px;">
         Attach</el-button>
    </el-upload>

And my Methods:

  setAtrbt(){
   let input = document.querySelector('.el-upload__input');
   console.log(input);
   input.setAttribute('onchange', 'vm.readfile(this.files[0])')
 },
  readfile(id) {
   let f = document.getElementById(id).files[0];
   console.log(f);
    let r = new FileReader();
    r.readAsArrayBuffer(f);
    r.onload = function (e) {
      console.log(e);
      let data = r.result;
      console.log('data: ' + data);
      let bytes = new Uint8Array(data);
      console.log('bytes: ' + bytes);
      let b64encoded = this.bufferToBase641(bytes);
      console.log(b64encoded);
    };
  },
  bufferToBase641(buf) {
    let binstr = Array.prototype.map.call(buf, function (ch) {
      return String.fromCharCode(ch);
    }).join('');
    return btoa(binstr);
  }
},
mounted(){
  this.setAtrbt();
}

Can someone tell me, please, how shoud I use function bufferToBase641 right?
And maybe my actions with Element.io is not good?

Body:
You have scope problem. You lost reference for this, as you are in nested function, which have own this object. Improve your code:

eadfile(id) {
  let f = document.getElementById(id).files[0];
  console.log(f);
  let r = new FileReader();
  r.readAsArrayBuffer(f);
  var self = this // ADD THIS
  r.onload = function (e) {
    console.log(e);
    let data = r.result;
    console.log('data: ' + data);
    let bytes = new Uint8Array(data);
    console.log('bytes: ' + bytes);
    let b64encoded = self.bufferToBase641(bytes); // CHANGE THIS
    console.log(b64encoded);
  };
},

You can also use the arrow function for you r.onload callback:

eadfile(id) {
  let f = document.getElementById(id).files[0];
  console.log(f);
  let r = new FileReader();
  r.readAsArrayBuffer(f);
  r.onload = e => { // CHANGE JUST THIS LINE
    console.log(e);
    let data = r.result;
    console.log('data: ' + data);
    let bytes = new Uint8Array(data);
    console.log('bytes: ' + bytes);
    let b64encoded = this.bufferToBase641(bytes);
    console.log(b64encoded);
  };
},


问:
How to recover history commands?
I have ran certain commands in korn shell script as follows:

```<code>324 pwd
325 list
326 cd mpiomp
327 list
328 cd C
329 list
330 history
</code>```

How can I retrieve the pwd command by using r ?
Currently I am using r -324 but its not working.

答:
The documentation of the r commands shows that you are using it wrong. here are the relevant parts:

The r command (a built-in KornShell alias) re-executes a command you ran previously, possibly editing it first. Commands are obtained from your command history file.

The specifier tells which command you want to re-execute. It can have
  any of the following forms:

An unsigned number (n)

  Run the command with that number.

A negative number (-n)

  Runs the command that came n commands before the current one.

As you can see, calling the command r 324 will execute the command with that history number.

Title: How to recover history commands?

Body:
I have ran certain commands in korn shell script as follows:

324 pwd
325 list
326 cd mpiomp
327 list
328 cd C
329 list
330 history

How can I retrieve the pwd command by using r ?
Currently I am using r -324 but its not working.


问:
WAMP server Icon is red but it shows that it is online, could not open the localhost
I use wampserver 2.4 with php 5.4 , for 64bits in windows platform.

I have a problem with wampserver. It shows a red icon but it tell me that it online,
when I tried to open the localhost it doesn't show the localhost for the wampserver , "Unable to connect" that what shows in Firefox.

I tested the port 80 and the result was " your port 80 is not actually used "
Then,I uninstall the Skype to make sure there is no conflicting between them.
I reinstall the Apache but nothings changed.

I opened start>control panel>administration tool> services, and check the proprieties for the server and it was stop, and the icon 'start' was gray so i couldn't change it.

So I  reinstall the wampserve and the localhost worked but the icon still read.

I want to connect the MSsql data , so i install the drive files '.dll' then added the needed ones in wamp\php\ext. then added the extension in the php.ini, then restart the wampserver. when i restarted it, the problem came back again and the localhost doesn't work. i tried to remove the extensions that i added in php.ini and restart the wampserver again, but nothing solved.

i've been looking for a solution for three days and tried almost every thing i found in the internet. but it still not working. so i register to stack over flow to present my problem to you.

pleas help me.

Leanah

答:
Solution that worked for me:

Access services.msc (Control Panel -> Administrative Tools -> Services);

Find all the services that start with "wamp". In my case: wampapache64 and wampmysqld64;

Double click on each of them and set the start-up type as: "automatic";

Restart all services of wamp, by clicking once on its tray icon and selecting the option "Restart All Services".

I don't know why, but, somehow, the services start-up types where marked as "Disabled". Maybe some other software made it without my consent. Because of that, the Wamp was with a red icon, but showing online when hoovering the mouse over it.


问:
Outlook Interop Exception (E_NOINTERFACE) in Release mode
I'm trying to make a program that would open a new Outlook 2013 message.
I've referenced Microsoft.Office.Interop.Outlook 15.0.0.0.

When running in Debug mode everything works fine but crashes in Release mode with Exception:

Unable to cast COM object of type
  'Microsoft.Office.Interop.Outlook.ApplicationClass' to interface type
  'Microsoft.Office.Interop.Outlook._Application'. This operation failed
  because the QueryInterface call on the COM component for the interface
  with IID '{00063001-0000-0000-C000-000000000046}' failed due to the
  following error: No such interface supported (Exception from HRESULT:
  0x80004002 (E_NOINTERFACE)).

Code:

```<code> var _Outlook = new MSOutlook.Application();
 var _MailItem = _Outlook.CreateItem(MSOutlook.OlItemType.olMailItem) as MSOutlook.MailItem;
 var _Recip = _MailItem.Recipients.Add("xxx@yyy.com");
 Recip.Type = (int)MSOutlook.OlMailRecipientType.olTo;

 _MailItem.Recipients.ResolveAll();
 _MailItem.Subject = "xxx";

 _MailItem.Display(false);
</code>```

where MSOutlook = Microsoft.Office.Interop.Outlook namespace.

I am using .NET Framework 4.5 and Outlook 2013.

How can Release mode affect this? Strangely Debug mode works fine..

I'll be grateful for any ideas how to solve it. Thanks!

答:
I solved this issue by enabling "Prefer 32-bit" in Project Settings -> Build -> General.

It's probably also possible to resolve the recipients object at runtime via dynamic:

```<code>var _Recip = ((dynamic)_MailItem.Recipients).Add("xxx@yyy.com");
</code>```

Body:
I'm trying to make a program that would open a new Outlook 2013 message.
I've referenced Microsoft.Office.Interop.Outlook 15.0.0.0.

When running in Debug mode everything works fine but crashes in Release mode with Exception:

Unable to cast COM object of type
  'Microsoft.Office.Interop.Outlook.ApplicationClass' to interface type
  'Microsoft.Office.Interop.Outlook._Application'. This operation failed
  because the QueryInterface call on the COM component for the interface
  with IID '{00063001-0000-0000-C000-000000000046}' failed due to the
  following error: No such interface supported (Exception from HRESULT:
  0x80004002 (E_NOINTERFACE)).

Code:

 var _Outlook = new MSOutlook.Application();
 var _MailItem = _Outlook.CreateItem(MSOutlook.OlItemType.olMailItem) as MSOutlook.MailItem;
 var _Recip = _MailItem.Recipients.Add("xxx@yyy.com");
 Recip.Type = (int)MSOutlook.OlMailRecipientType.olTo;

 _MailItem.Recipients.ResolveAll();
 _MailItem.Subject = "xxx";

 _MailItem.Display(false);

where MSOutlook = Microsoft.Office.Interop.Outlook namespace.

I am using .NET Framework 4.5 and Outlook 2013.

How can Release mode affect this? Strangely Debug mode works fine..

I'll be grateful for any ideas how to solve it. Thanks!

Body:
I solved this issue by enabling "Prefer 32-bit" in Project Settings -> Build -> General.

It's probably also possible to resolve the recipients object at runtime via dynamic:

var _Recip = ((dynamic)_MailItem.Recipients).Add("xxx@yyy.com");


问:
Command only reads first line of text file
I have to make a program in which one of the functions is retrieval of usernames and results from  a text file. (All on the same line)
For some reason, when I run it, only the first line is printed out. Why is this ? Also, this only happens when I try to run the program at school (part of an assignment), it prints everything it needs to on my laptop at home. (Python versions are also the same)

Here is my code :

```<code>def results():
       username = input("Enter username :")
       for line in open("resultsfile.txt","r"):
             if username in line:
                  print (line)
             elif username not in line:
                   ("No such user")
</code>```

Also, this is what the text file looks like (without bullet points) :

tud16 CS Easy 2points

ser23 CH Med 4points

tud16 CS Hard 1points

答:
You are iterating over a file but you are printing No such user for every line that does not match the username.

What you should do is evaluate after the loop if one of the lines in the file contained the username. To implement this you could introduce a boolean (found) indicating if a user has been found or not:

```<code>def results():
   found = False
   username = input("Enter username :")
   for line in open("resultsfile.txt","r"):
       if username in line:
           print (line)
           found = True
   if not found:
       print("No such user")
</code>```

Body:
I have to make a program in which one of the functions is retrieval of usernames and results from  a text file. (All on the same line)
For some reason, when I run it, only the first line is printed out. Why is this ? Also, this only happens when I try to run the program at school (part of an assignment), it prints everything it needs to on my laptop at home. (Python versions are also the same)

Here is my code :

def results():
       username = input("Enter username :")
       for line in open("resultsfile.txt","r"):
             if username in line:
                  print (line)
             elif username not in line:
                   ("No such user")

Also, this is what the text file looks like (without bullet points) :

tud16 CS Easy 2points

ser23 CH Med 4points

tud16 CS Hard 1points

Body:
You are iterating over a file but you are printing No such user for every line that does not match the username.

What you should do is evaluate after the loop if one of the lines in the file contained the username. To implement this you could introduce a boolean (found) indicating if a user has been found or not:

def results():
   found = False
   username = input("Enter username :")
   for line in open("resultsfile.txt","r"):
       if username in line:
           print (line)
           found = True
   if not found:
       print("No such user")


问:
Return struct type confirming to protocols
Here is my piece of code,

```<code>protocol Configuration {

    static var url: String { get }
    static var username: String { get }
    static var password: String { get }
}

protocol Server {

    associatedtype Profile: Configuration
    associatedtype Payment: Configuration
    associatedtype Images: Configuration
}

struct Development: Server {

    struct Profile: Configuration {

        static var url: String { return "http://google.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://bing.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://duckduckgo.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }
}

struct Production: Server {

    struct Profile: Configuration {

        static var url: String { return "http://amazon.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://facebook.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://orkut.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }
}
</code>```

Question is I would like to fetch my 'struct' (depending on my environment). I need something like,

```<code>struct Environment {

    static func current() -> Any:Server {

        if #DEBUG
            return Development
        #endif

        return Production
    }
}
</code>```

But returning a specific type confirming to my protocol is not possible.

Any suggestion on this or a different approach will be helpful.

答:
You can return a generic type or you can simply do something like this:</p>

```<code>struct Config {

  static var BaseURL: URL {
    switch Environment.current {
      case .debug:
        return URL(string: "https://...dev.com")!
      case .staging:
        return URL(string: "https://...staging.com")!
      case .release:
        return URL(string: "https://...production.com")!
      }
  }

}
</code>```

Body:
Here is my piece of code,

protocol Configuration {

    static var url: String { get }
    static var username: String { get }
    static var password: String { get }
}

protocol Server {

    associatedtype Profile: Configuration
    associatedtype Payment: Configuration
    associatedtype Images: Configuration
}

struct Development: Server {

    struct Profile: Configuration {

        static var url: String { return "http://google.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://bing.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://duckduckgo.com" }
        static var username: String { return "abc" }
        static var password: String { return "xyz" }
    }
}

struct Production: Server {

    struct Profile: Configuration {

        static var url: String { return "http://amazon.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Payment: Configuration {

        static var url: String { return "http://facebook.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }

    struct Images: Configuration {

        static var url: String { return "http://orkut.com" }
        static var username: String { return "pqr" }
        static var password: String { return "xyz" }
    }
}

Question is I would like to fetch my 'struct' (depending on my environment). I need something like,

struct Environment {

    static func current() -> Any:Server {

        if #DEBUG
            return Development
        #endif

        return Production
    }
}

But returning a specific type confirming to my protocol is not possible.

Any suggestion on this or a different approach will be helpful.

Body:
You can return a generic type or you can simply do something like this:

struct Config {

  static var BaseURL: URL {
    switch Environment.current {
      case .debug:
        return URL(string: "https://...dev.com")!
      case .staging:
        return URL(string: "https://...staging.com")!
      case .release:
        return URL(string: "https://...production.com")!
      }
  }

}


问:
Using a CASE or IF..ELSE within WHERE clause's AND part - SQL Server
I have a stored procedure in SQL Server.
The SELECT part for this SP is as follows :

```<code>SELECT * FROM demoTable dt
INNER JOIN demoTable2 dt2
WHERE
      (@StartDate IS NULL OR dt.StartDate = @StartDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
      AND (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
</code>```

Now I want to modify the above WHERE clause part after the AND condition.
I have added 3 new parameters/variables which are being passed to this SP.

```<code>@ID int , @isAdmin int and @Date varchar(50)
</code>```

Using the values of these variables I'm trying to manipulate the above WHERE clause as follows :

```<code> WHERE
   @StartDate IS NULL OR dt.StartDate = @StartDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
    -- Logic change below
    AND(
    CASE WHEN (@ID != 100 AND @isAdmin != 1)
    THEN (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
    ELSE (dt.EndDate>sysdatetime())
    END)
</code>```

But after this modification I'm receiving an error.

Error statement :

```<code>Incorrect syntax near the keyword 'IS'.
</code>```

This error is pointing to the line where I've used IS NULL from the modified logic part.

Basically what I want to do is to apply the original logic for AND  i.e.

```<code>(@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
</code>```

only when the

```<code>(@ID != 100 AND isAdmin != 1)
</code>```

holds true or else I want to apply the new logic i.e.

```<code>(dt.EndDate>sysdatetime()
</code>```

How can I achieve this?

答:
If you want a special condition for @ID !=100 AND isAdmin !=1

You don't need case/when, you need just a valid boolean expression

change :

```<code>AND(
    CASE WHEN (@ID != 100 AND isAdmin != 1)
    THEN (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >=
@StartDate and dt.EndDate <= @EndDate))
    ELSE (dt.EndDate>sysdatetime())
    END
)
</code>```

to

```<code>AND(
    ((@ID != 100 AND isAdmin != 1) AND (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate)))
    OR
    ((@ID == 100 OR isAdmin == 1)  AND (dt.EndDate>sysdatetime()) )
)
</code>```

Body:
I have a stored procedure in SQL Server.
The SELECT part for this SP is as follows :

SELECT * FROM demoTable dt
INNER JOIN demoTable2 dt2
WHERE
      (@StartDate IS NULL OR dt.StartDate = @StartDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
      AND (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))

Now I want to modify the above WHERE clause part after the AND condition.
I have added 3 new parameters/variables which are being passed to this SP.

@ID int , @isAdmin int and @Date varchar(50)

Using the values of these variables I'm trying to manipulate the above WHERE clause as follows :

 WHERE
   @StartDate IS NULL OR dt.StartDate = @StartDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
    -- Logic change below
    AND(
    CASE WHEN (@ID != 100 AND @isAdmin != 1)
    THEN (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))
    ELSE (dt.EndDate>sysdatetime())
    END)

But after this modification I'm receiving an error.

Error statement :

Incorrect syntax near the keyword 'IS'.

This error is pointing to the line where I've used IS NULL from the modified logic part.

Basically what I want to do is to apply the original logic for AND  i.e.

(@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate))

only when the

(@ID != 100 AND isAdmin != 1)

holds true or else I want to apply the new logic i.e.

(dt.EndDate>sysdatetime()

How can I achieve this?

Body:
If you want a special condition for @ID !=100 AND isAdmin !=1

You don't need case/when, you need just a valid boolean expression

change :

AND(
    CASE WHEN (@ID != 100 AND isAdmin != 1)
    THEN (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >=
@StartDate and dt.EndDate <= @EndDate))
    ELSE (dt.EndDate>sysdatetime())
    END
)

to

AND(
    ((@ID != 100 AND isAdmin != 1) AND (@EndDate IS NULL OR dt.EndDate = @EndDate OR (dt.StartDate >= @StartDate and dt.EndDate <= @EndDate)))
    OR
    ((@ID == 100 OR isAdmin == 1)  AND (dt.EndDate>sysdatetime()) )
)


问:
Does Flutter support cascading grids?
Does Flutter support cascading grid style layouts such as:

答: You can use a CustomScrollView or a SliderGrid with a custom gridDelegate

Title: Does Flutter support cascading grids?


问:
Increment number with Delay (C#)
i have a button when i click on it it increases the number in a text block by one.
But i want to show increment with few millisecond wait.

XAML

```<code><TextBlock Name="DisplayTextBlock" FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Top"/>

<Button Name="CountingButton" Height="80" Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="CountingButton_Click"/>
</code>```

C#

```<code>int i = 0;

private void CountingButton_Click(object sender, RoutedEventArgs e)
{
    do
    {
        i++;

        DisplayTextBlock.Text = i.ToString();
    }
    while(//something is on)
}
</code>```

so how can i add wait...

答:
Seeing as you want to update it indefinitely, I've changed my previous answer to use a timer. My solution is toggling the enabled state with a subsequent click of the button for illustration purposes. Consider the following:

```<code>DispatcherTimer _timer;

private int i = 0;

public bool SomethingIsOn { get; private set; } = true;

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (_timer == null && SomethingIsOn)
    {
        _timer = new DispatcherTimer()
        {
            Interval = TimeSpan.FromMilliseconds(300)
        };
        _timer.Tick += _timer_Tick;
        _timer.Start();
    }
  else if(_timer != null)
    {
        _timer.Stop();
        ((Button)sender).IsEnabled = false;
    }
}

private void _timer_Tick(object sender, object e)
{
    if (SomethingIsOn)
    {
        i++;
        DisplayTextBlock.Text = i.ToString();
    }
}
</code>```

In your proper solution, you might want to disable the button when it is clicked the first time to avoid having the user click it multiple times.

Update
I'm now using the DispatcherTimer which is available in UWP and easier to work with.

Title: Increment number with Delay (C#)

Body:
i have a button when i click on it it increases the number in a text block by one.
But i want to show increment with few millisecond wait.

XAML

<TextBlock Name="DisplayTextBlock" FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Top"/>

<Button Name="CountingButton" Height="80" Width="150" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="CountingButton_Click"/>

C#

int i = 0;

private void CountingButton_Click(object sender, RoutedEventArgs e)
{
    do
    {
        i++;

        DisplayTextBlock.Text = i.ToString();
    }
    while(//something is on)
}

so how can i add wait...

Body:
Seeing as you want to update it indefinitely, I've changed my previous answer to use a timer. My solution is toggling the enabled state with a subsequent click of the button for illustration purposes. Consider the following:

DispatcherTimer _timer;

private int i = 0;

public bool SomethingIsOn { get; private set; } = true;

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (_timer == null && SomethingIsOn)
    {
        _timer = new DispatcherTimer()
        {
            Interval = TimeSpan.FromMilliseconds(300)
        };
        _timer.Tick += _timer_Tick;
        _timer.Start();
    }
  else if(_timer != null)
    {
        _timer.Stop();
        ((Button)sender).IsEnabled = false;
    }
}

private void _timer_Tick(object sender, object e)
{
    if (SomethingIsOn)
    {
        i++;
        DisplayTextBlock.Text = i.ToString();
    }
}

In your proper solution, you might want to disable the button when it is clicked the first time to avoid having the user click it multiple times.

Update
I'm now using the DispatcherTimer which is available in UWP and easier to work with.


问:
How can I add a badge to a standard UIButton?
Is it possible to add a standard-looking badge to a standard UIButton?

If it's not supported semi-natively, what would be the simplest way to achieve this?

Example image:

答:
I'd go a similar way as @Björn Kaiser: Use the button as you like it, and then add a custom view with that badge as a subview to it - I've done it and it works well.

As for the view, you can draw it as you like. You can draw it manually or use CoreAnimation and let it make the main part, i.e. theBadge.layer.cornerRadius = ...; to give it a round shape, draw the text/number in drawRect: or add it as a label etc.

ContentLicense: CC BY-SA 2.5


问:
update database date values format using MY-SQL
i have date stored in database on date column in dd-mm-yyyy format. This column data type is VARCHAR. i wanted to convert those stored dates in yyy-mm-dd format. i tried using this MYSQL query:

```<code>UPDATE status SET new_time_creation = STR_TO_DATE(date, '%Y-%m-%d');
</code>```

but this does not convert the dates properly (eg. 30-05-2016 => 2030-05-20).
please help me with this query or suggest best on even using php to update the date format. Thanks!

答:
UPDATE transaction SET new_time_creation = STR_TO_DATE(time_creation, '%Y-%m-%d');

STR_TO_DATE documentation.

Body:
i have date stored in database on date column in dd-mm-yyyy format. This column data type is VARCHAR. i wanted to convert those stored dates in yyy-mm-dd format. i tried using this MYSQL query:

UPDATE status SET new_time_creation = STR_TO_DATE(date, '%Y-%m-%d');

but this does not convert the dates properly (eg. 30-05-2016 => 2030-05-20).
please help me with this query or suggest best on even using php to update the date format. Thanks!


问:
Search product data not working in codeigniter
I tried to make a search bar so users will be able to search products by searching on the product name but its not working and I'm not able to search a product.

This is my controller function:

```<code><?php
class SearchController extends CI_Controller {
  function __construct(){
     parent::__construct();
     $this->load->model('Search_model');
  }

  public function index(){
     $data = array();
  }

  function search_keyword(){
    $keyword = $this->input->post('keyword');
    $data['results'] = $this->Search_model->search($keyword);
    //laad de view
    $this->load->view('result_view',$data);
  }
}
?>
</code>```

This is my model function:

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search_model extends CI_Model  {
    function __construct(){
        parent::__construct();
    }

    function search($keyword) {
        $this->db->select('product_naam');
        $this->db->like('product_naam',$keyword);
        $query  =   $this->db->get('products');
        return $query->result_array();
    }
}
?>
</code>```

And this is my view file with searchbar:

```<code><?php include_once('templates/header.php');  ?>
  <center>
    <h2>Zoek een cadeau</h2><br>
      <form class="navbar-form" role="search" action="<?php echo base_url(); ?>SearchController/search_keyword" method="POST">
          <div class="input-group">
              <input type="text" class="form-control" placeholder="Search" name="keyword" size="30px; ">
              <div class="input-group-btn">
                  <button class="btn btn-default " type="submit" value = "Search"><i class="glyphicon glyphicon-search"></i></button>
              </div>
          </div>
      </form>
  </center>
    <div class="clearfix"></div>
  <table>
    <?php foreach($results as $row){ ?>
      <tr>
        <td><?php echo $row->product_naam?></td>
      </tr>
    <?php } ?>
  </table>
<?php include_once('templates/footer.php'); ?>
</code>```

I hope someone can help me with this problem!,
thanks

答:
Because you use $query->result_array();, items should be taken by

```<code><td><?php echo $row['product_naam']?></td>
</code>```

result_array()

This method returns the query result as a pure array, or an empty
  array when no result is produced

CI documentation

Body:
I tried to make a search bar so users will be able to search products by searching on the product name but its not working and I'm not able to search a product.

This is my controller function:

<?php
class SearchController extends CI_Controller {
  function __construct(){
     parent::__construct();
     $this->load->model('Search_model');
  }

  public function index(){
     $data = array();
  }

  function search_keyword(){
    $keyword = $this->input->post('keyword');
    $data['results'] = $this->Search_model->search($keyword);
    //laad de view
    $this->load->view('result_view',$data);
  }
}
?>

This is my model function:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search_model extends CI_Model  {
    function __construct(){
        parent::__construct();
    }

    function search($keyword) {
        $this->db->select('product_naam');
        $this->db->like('product_naam',$keyword);
        $query  =   $this->db->get('products');
        return $query->result_array();
    }
}
?>

And this is my view file with searchbar:

<?php include_once('templates/header.php');  ?>

Zoek een cadeau

      <form class="navbar-form" role="search" action="<?php echo base_url(); ?>SearchController/search_keyword" method="POST">

              <input type="text" class="form-control" placeholder="Search" name="keyword" size="30px; ">

                  <button class="btn btn-default " type="submit" value = "Search"></button>

      </form>

    <?php foreach($results as $row){ ?>

        <?php echo $row->product_naam?>

    <?php } ?>

<?php include_once('templates/footer.php'); ?>

I hope someone can help me with this problem!,
thanks

Body:
Because you use $query->result_array();, items should be taken by

<td><?php echo $row['product_naam']?></td>

result_array()

This method returns the query result as a pure array, or an empty
  array when no result is produced

CI documentation


问:
Deciphering text in python 3
I am trying to take a text as input, count the number of occurrences of each alphabetic letter in the string, so for example in "hello" h =1 , e =1 , l =2, o =1 . and then replace the highest occurring letter with E and second highest with T and so on from here (http://www.counton.org/explorer/codebreaking/frequency-analysis.php)
So am trying to do this in python 3 , and so far I made a code the takes the text as input and counts the number of occurrences of each alphabet, but my problem is in the replacing part. Can any one help me in doing this, how do I replace the highest occurring alphabet with the highest occurring one according to that website?

Here is my code (sorry about that):

```<code>def break_cipher(OriginalText = input()):
a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0
i=0
j=0
k=0
l=0
m=0
n=0
o=0
p=0
q=0
r=0
s=0
t=0
u=0
v=0
w=0
x=0
y=0
z=0
for charr in OriginalText:
    if charr  == 'a' :
        a +=1
    if charr  == 'b' :
        b +=1
    if charr  == 'c' :
        c +=1
    if charr  == 'd' :
        d +=1
    if charr  == 'e' :
        e +=1
    if charr  == 'f' :
        f +=1
    if charr  == 'g' :
        g +=1
    if charr  == 'h' :
        h +=1
    if charr  == 'i' :
        i +=1
    if charr  == 'j' :
        j +=1
    if charr  == 'k' :
        k +=1
    if charr  == 'l' :
        l +=1
    if charr  == 'm' :
        m +=1
    if charr  == 'n' :
        n +=1
    if charr  == 'o' :
        o +=1
    if charr  == 'p' :
        p +=1
    if charr  == 'q' :
        q +=1
    if charr  == 'r' :
        r +=1
    if charr  == 's' :
        s +=1
    if charr  == 't' :
        t +=1
    if charr  == 'u' :
        u +=1
    if charr  == 'v' :
        v +=1
    if charr  == 'w' :
        w +=1
    if charr  == 'x' :
        x +=1
    if charr  == 'y' :
        y +=1
    if charr  == 'z' :
        z +=1
mylist = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v]
mylist.sort()
print(mylist)
print(mylist[-1])
str(OriginalText)
print("a = " + str(a))
print("b = " +str(b))
print("c = " +str(c))
print("d = " +str(d))
print("e = " +str(e))
print("f = " +str(f))
print("g = " +str(g))
print("h = " +str(h))
print("i = " +str(i))
print("j = " +str(j))
print("k = " +str(k))
print("l = " +str(l))
print("m = " +str(m))
print("n = " +str(n))
print("o = " +str(o))
print("p = " +str(p))
print("q = " +str(q))
print("r = " +str(r))
print("s = " +str(s))
print("t = " +str(t))
print("u = " +str(u))
print("v = " +str(v))
print("w = " +str(w))
print("x = " +str(x))
print("y = " +str(y))
print("z = " +str(z))
</code>```

break_cipher()

答:
Here is an example:

```<code>from collections import Counter

def break_cipher(text):
    letters = sorted(Counter(text).items(), key=lambda x: x[1], reverse=True)
    text = text.replace(letters[0][0],'E').replace(letters[1][0],'T')
    return text

break_cipher('hello')
</code>```

Returns:

```<code>'TeEEo'
</code>```

This works because Counter(text) equals:

```<code>Counter({'e': 1, 'h': 1, 'l': 2, 'o': 1})
</code>```

And the variable letters is a list with these sorted:

```<code>[('l', 2), ('h', 1), ('e', 1), ('o', 1)]
</code>```

the 'l' becomes 'E' and the 'h' becomes 'T'

Title: Deciphering text in python 3

Body:
I am trying to take a text as input, count the number of occurrences of each alphabetic letter in the string, so for example in "hello" h =1 , e =1 , l =2, o =1 . and then replace the highest occurring letter with E and second highest with T and so on from here (http://www.counton.org/explorer/codebreaking/frequency-analysis.php)
So am trying to do this in python 3 , and so far I made a code the takes the text as input and counts the number of occurrences of each alphabet, but my problem is in the replacing part. Can any one help me in doing this, how do I replace the highest occurring alphabet with the highest occurring one according to that website?

Here is my code (sorry about that):

def break_cipher(OriginalText = input()):
a=0
b=0
c=0
d=0
e=0
f=0
g=0
h=0
i=0
j=0
k=0
l=0
m=0
n=0
o=0
p=0
q=0
r=0
s=0
t=0
u=0
v=0
w=0
x=0
y=0
z=0
for charr in OriginalText:
    if charr  == 'a' :
        a +=1
    if charr  == 'b' :
        b +=1
    if charr  == 'c' :
        c +=1
    if charr  == 'd' :
        d +=1
    if charr  == 'e' :
        e +=1
    if charr  == 'f' :
        f +=1
    if charr  == 'g' :
        g +=1
    if charr  == 'h' :
        h +=1
    if charr  == 'i' :
        i +=1
    if charr  == 'j' :
        j +=1
    if charr  == 'k' :
        k +=1
    if charr  == 'l' :
        l +=1
    if charr  == 'm' :
        m +=1
    if charr  == 'n' :
        n +=1
    if charr  == 'o' :
        o +=1
    if charr  == 'p' :
        p +=1
    if charr  == 'q' :
        q +=1
    if charr  == 'r' :
        r +=1
    if charr  == 's' :
        s +=1
    if charr  == 't' :
        t +=1
    if charr  == 'u' :
        u +=1
    if charr  == 'v' :
        v +=1
    if charr  == 'w' :
        w +=1
    if charr  == 'x' :
        x +=1
    if charr  == 'y' :
        y +=1
    if charr  == 'z' :
        z +=1
mylist = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v]
mylist.sort()
print(mylist)
print(mylist[-1])
str(OriginalText)
print("a = " + str(a))
print("b = " +str(b))
print("c = " +str(c))
print("d = " +str(d))
print("e = " +str(e))
print("f = " +str(f))
print("g = " +str(g))
print("h = " +str(h))
print("i = " +str(i))
print("j = " +str(j))
print("k = " +str(k))
print("l = " +str(l))
print("m = " +str(m))
print("n = " +str(n))
print("o = " +str(o))
print("p = " +str(p))
print("q = " +str(q))
print("r = " +str(r))
print("s = " +str(s))
print("t = " +str(t))
print("u = " +str(u))
print("v = " +str(v))
print("w = " +str(w))
print("x = " +str(x))
print("y = " +str(y))
print("z = " +str(z))

break_cipher()

Body:
Here is an example:

from collections import Counter

def break_cipher(text):
    letters = sorted(Counter(text).items(), key=lambda x: x[1], reverse=True)
    text = text.replace(letters[0][0],'E').replace(letters[1][0],'T')
    return text

break_cipher('hello')

Returns:

'TeEEo'

This works because Counter(text) equals:

Counter({'e': 1, 'h': 1, 'l': 2, 'o': 1})

And the variable letters is a list with these sorted:

[('l', 2), ('h', 1), ('e', 1), ('o', 1)]

the 'l' becomes 'E' and the 'h' becomes 'T'