问:
EF6 - Correct SQL output but data does not populate
I am attempting to populate a child entity of a reference table entity using a many-to-many relationship.

I have 3 tables: Addresses, Members, and MemberAddresses. Addresses and Members have a collection of MemberAddresses each. MemberAddresses has a single Address and Member object with a composite key. Here are the related mappings:

Addresses

```<code>HasMany(x => x.MemberAddresses).WithRequired(x => x.Address).HasForeignKey(x => x.AddressId);
</code>```

Members

```<code>HasMany(x => x.MemberAddresses).WithRequired(x => x.Member).HasForeignKey(x => x.MemberId);
</code>```

MemberAddresses

```<code>HasRequired(rp => rp.Member).WithMany(x => x.MemberAddresses).HasForeignKey(rp => rp.MemberId);
</code>```

When I attmempt to do the following, I am not getting any of the child objects loaded into the Local extension (i.e. both Address and Member are null):

```<code>_context.MemberAddresses.Include(rp => rp.Address).Where(rp => rp.MemberId == member.MemberId).Load();
</code>```

What's interesting is that the output SQL from EF is doing the correct fetch (I checked this against SQL Server). If I attempt to use a linq query with ToList(), it works as intended. It seems to be loading specifically will not work, and doesn't populate the child objects.

EDIT
For some added clarity, I attempted to use a simple linq query syntax to accomplish the same result:

```<code>            var results = (from ma in _context.MemberAddresses
                       where ma.MemberId == parentMember.MemberId
                       select ma).Include(x => x.Address).Include(x => x.Member).ToList();
</code>```

This was able to populate results with the fully populated list of MemberAddresses. However, it was NOT being added to the _context.MemberAddresses.Local instance.

What is even stranger, if I first use the linq query, then perform the load lineI have above, the results now remove the child objects from memory. That is, it will still have the ID's for both child tables, but loses the child object instances.

答:
I can't repro any difference in using Load() and enumerating the results.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;

namespace Ef6Test
{

    public class Address
    {
        public int Id { get; set; }
        public virtual ICollection<MemberAddress> MemberAddresses { get; } = new HashSet<MemberAddress>();
    }
    public class Member
    {
        public int Id { get; set; }
        public virtual ICollection<MemberAddress> MemberAddresses { get; } = new HashSet<MemberAddress>();
    }
    public class MemberAddress

    {
        public Address Address { get; set; }
        [Key( ), Column(Order =0)]
        public int AddressId { get; set; }
        public Member  Member{ get; set; }

        [Key(), Column(Order = 1)]
        public int MemberId{ get; set; }

    }
    class Db : DbContext
    {
        public DbSet<Address> Address { get; set; }
        public DbSet<Member> Member{ get; set; }
        public DbSet<MemberAddress> MemberAddresses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {
                db.Database.Initialize(true);

                var m = new Member();

                for (int i = 0; i < 10; i++)
                {
                    var a = new Address();
                    var ma = new MemberAddress();
                    ma.Address = a;
                    ma.Member = m;
                    db.Address.Add(a);
                    db.MemberAddresses.Add(ma);
                }

                db.Member.Add(m);
                db.SaveChanges();

            }

            Console.WriteLine("Enumerating Include Query");
            using (var db = new Db())
            {

                db.Database.Log = m => Console.WriteLine(m);

                var list = db.MemberAddresses.Include(rp => rp.Address).Where(rp => rp.MemberId < 10).ToList();

                foreach (var e in db.ChangeTracker.Entries())
                {
                    Console.WriteLine(e.Entity.GetType().Name);
                }
                var a = db.ChangeTracker.Entries<MemberAddress>().First();
                Console.WriteLine($"Address IsLoaded: {a.Reference<Address>("Address").IsLoaded}");

                Console.WriteLine($"Member Local {db.Member.Local.Count} items");
                foreach (var member in db.Member.Local)
                {
                    Console.WriteLine($"Member {member.Id}");
                }
                Console.WriteLine($"MemberAddress Local {db.MemberAddresses.Local.Count} items");
                foreach (var ma in db.MemberAddresses.Local)
                {
                    Console.WriteLine($"MemberAddress {ma.MemberId},{ma.AddressId}");
                }
                Console.WriteLine($"Address Local {db.Address.Local.Count} items");
                foreach (var ad in db.Address.Local)
                {
                    Console.WriteLine($"Address {ad.Id}");
                }

            }

            Console.WriteLine("Using Load()");
            using (var db = new Db())
            {

                db.Database.Log = m => Console.WriteLine(m);

                db.MemberAddresses.Include(rp => rp.Address).Where(rp => rp.MemberId < 10).Load();

                foreach (var e in db.ChangeTracker.Entries())
                {
                    Console.WriteLine(e.Entity.GetType().Name);
                }
                var a = db.ChangeTracker.Entries<MemberAddress>().First();
                Console.WriteLine($"Address IsLoaded: {a.Reference<Address>("Address").IsLoaded}");

                Console.WriteLine($"Member Local {db.Member.Local.Count} items");
                foreach (var member in db.Member.Local)
                {
                    Console.WriteLine($"Member {member.Id}");
                }
                Console.WriteLine($"MemberAddress Local {db.MemberAddresses.Local.Count} items");
                foreach (var ma in db.MemberAddresses.Local)
                {
                    Console.WriteLine($"MemberAddress {ma.MemberId},{ma.AddressId}");
                }
                Console.WriteLine($"Address Local {db.Address.Local.Count} items");
                foreach (var ad in db.Address.Local)
                {
                    Console.WriteLine($"Address {ad.Id}");
                }

            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}
</code>```

outputs

```<code>Enumerating Include Query
Opened connection at 12/6/2017 8:33:59 AM -06:00

SELECT
    [Extent1].[AddressId] AS [AddressId],
    [Extent1].[MemberId] AS [MemberId]
    FROM [dbo].[MemberAddresses] AS [Extent1]
    WHERE [Extent1].[MemberId] < 10

-- Executing at 12/6/2017 8:34:00 AM -06:00

-- Completed in 15 ms with result: SqlDataReader

Closed connection at 12/6/2017 8:34:00 AM -06:00

MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
Address IsLoaded: True
Member Local 0 items
MemberAddress Local 10 items
MemberAddress 1,1
MemberAddress 1,2
MemberAddress 1,3
MemberAddress 1,4
MemberAddress 1,5
MemberAddress 1,6
MemberAddress 1,7
MemberAddress 1,8
MemberAddress 1,9
MemberAddress 1,10
Address Local 10 items
Address 1
Address 2
Address 3
Address 4
Address 5
Address 6
Address 7
Address 8
Address 9
Address 10
Using Load()
Opened connection at 12/6/2017 8:34:00 AM -06:00

SELECT
    [Extent1].[AddressId] AS [AddressId],
    [Extent1].[MemberId] AS [MemberId]
    FROM [dbo].[MemberAddresses] AS [Extent1]
    WHERE [Extent1].[MemberId] < 10

-- Executing at 12/6/2017 8:34:00 AM -06:00

-- Completed in 8 ms with result: SqlDataReader

Closed connection at 12/6/2017 8:34:00 AM -06:00

MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
Address IsLoaded: True
Member Local 0 items
MemberAddress Local 10 items
MemberAddress 1,1
MemberAddress 1,2
MemberAddress 1,3
MemberAddress 1,4
MemberAddress 1,5
MemberAddress 1,6
MemberAddress 1,7
MemberAddress 1,8
MemberAddress 1,9
MemberAddress 1,10
Address Local 10 items
Address 1
Address 2
Address 3
Address 4
Address 5
Address 6
Address 7
Address 8
Address 9
Address 10
Hit any key to exit
</code>```

Body:
I am attempting to populate a child entity of a reference table entity using a many-to-many relationship.

I have 3 tables: Addresses, Members, and MemberAddresses. Addresses and Members have a collection of MemberAddresses each. MemberAddresses has a single Address and Member object with a composite key. Here are the related mappings:

Addresses

HasMany(x => x.MemberAddresses).WithRequired(x => x.Address).HasForeignKey(x => x.AddressId);

Members

HasMany(x => x.MemberAddresses).WithRequired(x => x.Member).HasForeignKey(x => x.MemberId);

MemberAddresses

HasRequired(rp => rp.Member).WithMany(x => x.MemberAddresses).HasForeignKey(rp => rp.MemberId);

When I attmempt to do the following, I am not getting any of the child objects loaded into the Local extension (i.e. both Address and Member are null):

_context.MemberAddresses.Include(rp => rp.Address).Where(rp => rp.MemberId == member.MemberId).Load();

What's interesting is that the output SQL from EF is doing the correct fetch (I checked this against SQL Server). If I attempt to use a linq query with ToList(), it works as intended. It seems to be loading specifically will not work, and doesn't populate the child objects.

EDIT
For some added clarity, I attempted to use a simple linq query syntax to accomplish the same result:

            var results = (from ma in _context.MemberAddresses
                       where ma.MemberId == parentMember.MemberId
                       select ma).Include(x => x.Address).Include(x => x.Member).ToList();

This was able to populate results with the fully populated list of MemberAddresses. However, it was NOT being added to the _context.MemberAddresses.Local instance.

What is even stranger, if I first use the linq query, then perform the load lineI have above, the results now remove the child objects from memory. That is, it will still have the ID's for both child tables, but loses the child object instances.

Body:
I can't repro any difference in using Load() and enumerating the results.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;

namespace Ef6Test
{

    public class Address
    {
        public int Id { get; set; }
        public virtual ICollection<MemberAddress> MemberAddresses { get; } = new HashSet<MemberAddress>();
    }
    public class Member
    {
        public int Id { get; set; }
        public virtual ICollection<MemberAddress> MemberAddresses { get; } = new HashSet<MemberAddress>();
    }
    public class MemberAddress

    {
        public Address Address { get; set; }
        [Key( ), Column(Order =0)]
        public int AddressId { get; set; }
        public Member  Member{ get; set; }

        [Key(), Column(Order = 1)]
        public int MemberId{ get; set; }

    }
    class Db : DbContext
    {
        public DbSet<Address> Address { get; set; }
        public DbSet<Member> Member{ get; set; }
        public DbSet<MemberAddress> MemberAddresses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            Database.SetInitializer(new DropCreateDatabaseAlways<Db>());

            using (var db = new Db())
            {
                db.Database.Initialize(true);

                var m = new Member();

                for (int i = 0; i < 10; i++)
                {
                    var a = new Address();
                    var ma = new MemberAddress();
                    ma.Address = a;
                    ma.Member = m;
                    db.Address.Add(a);
                    db.MemberAddresses.Add(ma);
                }

                db.Member.Add(m);
                db.SaveChanges();

            }

            Console.WriteLine("Enumerating Include Query");
            using (var db = new Db())
            {

                db.Database.Log = m => Console.WriteLine(m);

                var list = db.MemberAddresses.Include(rp => rp.Address).Where(rp => rp.MemberId < 10).ToList();

                foreach (var e in db.ChangeTracker.Entries())
                {
                    Console.WriteLine(e.Entity.GetType().Name);
                }
                var a = db.ChangeTracker.Entries<MemberAddress>().First();
                Console.WriteLine($"Address IsLoaded: {a.Reference<Address>("Address").IsLoaded}");

                Console.WriteLine($"Member Local {db.Member.Local.Count} items");
                foreach (var member in db.Member.Local)
                {
                    Console.WriteLine($"Member {member.Id}");
                }
                Console.WriteLine($"MemberAddress Local {db.MemberAddresses.Local.Count} items");
                foreach (var ma in db.MemberAddresses.Local)
                {
                    Console.WriteLine($"MemberAddress {ma.MemberId},{ma.AddressId}");
                }
                Console.WriteLine($"Address Local {db.Address.Local.Count} items");
                foreach (var ad in db.Address.Local)
                {
                    Console.WriteLine($"Address {ad.Id}");
                }

            }

            Console.WriteLine("Using Load()");
            using (var db = new Db())
            {

                db.Database.Log = m => Console.WriteLine(m);

                db.MemberAddresses.Include(rp => rp.Address).Where(rp => rp.MemberId < 10).Load();

                foreach (var e in db.ChangeTracker.Entries())
                {
                    Console.WriteLine(e.Entity.GetType().Name);
                }
                var a = db.ChangeTracker.Entries<MemberAddress>().First();
                Console.WriteLine($"Address IsLoaded: {a.Reference<Address>("Address").IsLoaded}");

                Console.WriteLine($"Member Local {db.Member.Local.Count} items");
                foreach (var member in db.Member.Local)
                {
                    Console.WriteLine($"Member {member.Id}");
                }
                Console.WriteLine($"MemberAddress Local {db.MemberAddresses.Local.Count} items");
                foreach (var ma in db.MemberAddresses.Local)
                {
                    Console.WriteLine($"MemberAddress {ma.MemberId},{ma.AddressId}");
                }
                Console.WriteLine($"Address Local {db.Address.Local.Count} items");
                foreach (var ad in db.Address.Local)
                {
                    Console.WriteLine($"Address {ad.Id}");
                }

            }

            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}

outputs

Enumerating Include Query
Opened connection at 12/6/2017 8:33:59 AM -06:00

SELECT
    [Extent1].[AddressId] AS [AddressId],
    [Extent1].[MemberId] AS [MemberId]
    FROM [dbo].[MemberAddresses] AS [Extent1]
    WHERE [Extent1].[MemberId] < 10

-- Executing at 12/6/2017 8:34:00 AM -06:00

-- Completed in 15 ms with result: SqlDataReader

Closed connection at 12/6/2017 8:34:00 AM -06:00

MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
Address IsLoaded: True
Member Local 0 items
MemberAddress Local 10 items
MemberAddress 1,1
MemberAddress 1,2
MemberAddress 1,3
MemberAddress 1,4
MemberAddress 1,5
MemberAddress 1,6
MemberAddress 1,7
MemberAddress 1,8
MemberAddress 1,9
MemberAddress 1,10
Address Local 10 items
Address 1
Address 2
Address 3
Address 4
Address 5
Address 6
Address 7
Address 8
Address 9
Address 10
Using Load()
Opened connection at 12/6/2017 8:34:00 AM -06:00

SELECT
    [Extent1].[AddressId] AS [AddressId],
    [Extent1].[MemberId] AS [MemberId]
    FROM [dbo].[MemberAddresses] AS [Extent1]
    WHERE [Extent1].[MemberId] < 10

-- Executing at 12/6/2017 8:34:00 AM -06:00

-- Completed in 8 ms with result: SqlDataReader

Closed connection at 12/6/2017 8:34:00 AM -06:00

MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
MemberAddress
Address_B9AEC76E2DAA985CBBFB722E4D5F60354D0FC4633617474BEE39DD928330C226
Address IsLoaded: True
Member Local 0 items
MemberAddress Local 10 items
MemberAddress 1,1
MemberAddress 1,2
MemberAddress 1,3
MemberAddress 1,4
MemberAddress 1,5
MemberAddress 1,6
MemberAddress 1,7
MemberAddress 1,8
MemberAddress 1,9
MemberAddress 1,10
Address Local 10 items
Address 1
Address 2
Address 3
Address 4
Address 5
Address 6
Address 7
Address 8
Address 9
Address 10
Hit any key to exit


来源: stackexchange

问:
Make Google App Engine as Load Balancing Server
I'm wondering if anyone knows any script in Python or Java to setup Google App Engine as Load Balancer server?

I choose GAE, because of 100% uptime and free, so it would be the best to setup as Load balancer.

So what I want to do is set up a GAE app (a load balancer application) in "www.domain.com" - using Google Apps, it will share the load to all my servers (with round-robin, or any technique), but when all servers are down, show maintenance page which is host in GAE.

Is this possible?

答:
You could do it, but you'd

incur extra latency by requiring an extra hop from google app engine to your servers

have all your servers public to the web, since otherwise google app engine won't be able to redirect to them Edit: apparently this is incorrect.  See Nick Johnson's comment below!

have to implement something in google app engine to keep track of what servers you have up and how and when to route to them

Seems like it might not be worth it, but it'd be cool if you did it and posted some numbers about how it works!

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
How make prod and dev envs using git
I’d like to improve my workflow so I decided myself use git.

Till now for my projects, on my web server, I had 2 folders which are prod and dev.

Once modifications are over I sync both of my folders.

I tried to use git like this way :

```<code>// on my prod folder
$ git init
$ git add *
$ git commit -a
</code>```

Then on parent folder

```<code>$ git clone prod dev
</code>```

Works like a charm I got my dev folder as perfect cot of prod
But now once my modifications are ok I can’t commit to prod. How can I achieve that ?! Thx

EDIT

Here is my organization tree on my web server :

```<code>home
|--git
   |--.ssh
   |--repositories
      |-- myfirstrepo.git
          |-- index.html
</code>```

What I'm trying to achieve is from /var/www

```<code>$ git clone /home/git/repositories/myfirstrepo.git
Initialized empty Git repository in /var/www/myfirstrepo_wc/.git/
</code>```

I got the clone of my repo in

```<code>var
|--www
   |--myfirstrepo_wc
      |--index.html
</code>```

So now I make change to my index.html file in /var/www/myfirstrepo_wc then

```<code>$ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   www/index.html
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Make commit

```<code>$ git commit -a
[master d19749d] first commit from working copy
Committer: root <root@localhost.localdomain>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email you@example.com

If the identity used for this commit is wrong, you can fix it with:

git commit --amend --author='Your Name <you@example.com>'

1 files changed, 1 insertions(+), 0 deletions(-)
</code>```

then want to pull to my repo who is in /home/git/repositories/myfirstrepo.git

```<code>$ git pull origin master
Counting objects: 7, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (4/4), 358 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To /git/myfirstrepo.git
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '/git/myfirstrepo.git'
</code>```

答:
Two folders with two .git folders means you have two git repositories, what you want is one folder with one .git folder and two branches, "prod" for production and "dev" for development, and to change between both you "checkout " the branch you want to see. Once you have this you can pull changes from dev to prod once you have finished making changes in dev and they are ready for prod, whilst this is not ideal it's a start.
In your case you could:

We have 2 folders, each one with .git, let's delete the .git folder from dev

Open your git console on the prod folder, you will notice you are in branch master.

Type git branch dev , this will create a new branch called dev based on master (let's say that master = prod)

Type git checkout dev to move to the dev branch

Now copy the contents of the dev folder into the prod folder.

Type git status in the console and you will notice the files that were changed are marked as such.

Type git add -a to add all the changes to your development branch

Type git commit -m ""

now you have two branches in one repository.

Now let's assume you are happy with the changes in dev and want to add them to master,

Change your branch to master with git checkout master

Type git pull dev

and assuming no conflicts arise now master is in sync with develop.

Please bear in mind that this is just to get you started with git, try experimenting with toy repositories and using supplementary tools.

Title: How make prod and dev envs using git

Body:
I’d like to improve my workflow so I decided myself use git.

Till now for my projects, on my web server, I had 2 folders which are prod and dev.

Once modifications are over I sync both of my folders.

I tried to use git like this way :

// on my prod folder
$ git init
$ git add *
$ git commit -a

Then on parent folder

$ git clone prod dev

Works like a charm I got my dev folder as perfect cot of prod
But now once my modifications are ok I can’t commit to prod. How can I achieve that ?! Thx

EDIT

Here is my organization tree on my web server :

home
|--git
   |--.ssh
   |--repositories
      |-- myfirstrepo.git
          |-- index.html

What I'm trying to achieve is from /var/www

$ git clone /home/git/repositories/myfirstrepo.git
Initialized empty Git repository in /var/www/myfirstrepo_wc/.git/

I got the clone of my repo in

var
|--www
   |--myfirstrepo_wc
      |--index.html

So now I make change to my index.html file in /var/www/myfirstrepo_wc then

$ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   www/index.html
#
no changes added to commit (use "git add" and/or "git commit -a")

Make commit

$ git commit -a
[master d19749d] first commit from working copy
Committer: root <root@localhost.localdomain>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email you@example.com

If the identity used for this commit is wrong, you can fix it with:

git commit --amend --author='Your Name <you@example.com>'

1 files changed, 1 insertions(+), 0 deletions(-)

then want to pull to my repo who is in /home/git/repositories/myfirstrepo.git

$ git pull origin master
Counting objects: 7, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (4/4), 358 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To /git/myfirstrepo.git
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '/git/myfirstrepo.git'


问:
Trying to display object properties stored within an array onto a
 element
I've just started learning JS and I'm trying to do some basic projects to cement what I've learned from reading and courses and tutorials and whatnot. I'm trying to make a contact list which takes 4 inputs: first name, last name, email and phone number. I wrote this part already and passed the arguments into an object within an array. What I can't figure out is how to display the contact object. I want to try and print each property into a list item within an unordered list but I'm stuck here, either because I don't know enough about DOM manipulation or just because I'm not looking in the right direction

//this passes the text input as an object to the list array
var contactList = {
  list: [],

  addNew: function() {
    this.list.push({
      firstName: document.getElementById('firstname').value,
      lastName: document.getElementById('lastname').value,
      email: document.getElementById('emailAdd').value,
      phoneNumber: document.getElementById('phoneNumber').value
    });
  },
};

// this runs the addNew() function and clears the input fields afterwards
var handlers = {
  addContact: function() {
    contactList.addNew();

    document.getElementById('firstname').value = '';
    document.getElementById('lastname').value = '';
    document.getElementById('emailAdd').value = '';
    document.getElementById('phoneNumber').value = '';

    //      view.displayContact();
  },

};
//this is where i'm trying to display the contacts array
var view = {
  displayContact: function() {
    var contacts = document.getElementById('contactul');
    for (var i = 0; i < contactList.list.length; i++) {
      var li = document.createElement('li');

      contacts.appendChild(li);
      li.innerHTML += contactList.list[i];
    };
  },
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  First name:<br>
  <input id="firstname" type="text" name="firstname">
  <br> Last name:<br>
  <input id="lastname" type="text" name="lastname">
  <br> Email Address:<br>
  <input id="emailAdd" type="text">
  <br> Phone number:<br>
  <input id="phoneNumber" type="text">
  <br>
</form>
<button onclick='handlers.addContact()'>Submit</button>

<div id='displayContacts'>
  <ul id='contactul'>

  </ul>
</div></code>```

This is the desired result. I just can't figure out how to write it.

答:
Well, you're close. The problem you have here is that when you go to display your items, you have to get the values for each individual element (first name, last name, etc). You can do that through another loop, or just hard-code each one since there are only 4. Here is an example:

//this passes the text input as an object to the list array
var contactList = {
  list: [],

  addNew: function() {
    this.list.push({
      firstName: document.getElementById('firstname').value,
      lastName: document.getElementById('lastname').value,
      email: document.getElementById('emailAdd').value,
      phoneNumber: document.getElementById('phoneNumber').value
    });
  },
};

// this runs the addNew() function and clears the input fields afterwards
var handlers = {
  addContact: function() {
    contactList.addNew();

    document.getElementById('firstname').value = '';
    document.getElementById('lastname').value = '';
    document.getElementById('emailAdd').value = '';
    document.getElementById('phoneNumber').value = '';

    view.displayContact();
  },

};
//this is where i'm trying to display the contacts array
var view = {
  displayContact: function() {
    var contacts = document.getElementById('contactul');
    while(contacts.firstChild ){
      contacts.removeChild(contacts.firstChild );
    }
    for (var i = 0; i < contactList.list.length; i++) {
      var liForFirstName = document.createElement('li');
      contacts.appendChild(liForFirstName);
      liForFirstName.innerHTML += "First Name: " + contactList.list[i].firstName;
      var liForLastName = document.createElement('li');
      contacts.appendChild(liForLastName);
      liForLastName.innerHTML += "Last Name: " + contactList.list[i].lastName;
      var liForEmail = document.createElement('li');
      contacts.appendChild(liForEmail);
      liForEmail.innerHTML += "Email: " + contactList.list[i].email;
      var liForPhoneNumber = document.createElement('li');
      contacts.appendChild(liForPhoneNumber);
      liForPhoneNumber.innerHTML += "Phone Number: " + contactList.list[i].phoneNumber;
    };
  },
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  First name:<br>
  <input id="firstname" type="text" name="firstname">
  <br> Last name:<br>
  <input id="lastname" type="text" name="lastname">
  <br> Email Address:<br>
  <input id="emailAdd" type="text">
  <br> Phone number:<br>
  <input id="phoneNumber" type="text">
  <br>
</form>
<button onclick='handlers.addContact()'>Submit</button>

<div id='displayContacts'>
  <ul id='contactul'>

  </ul>
</div></code>```

Title: Trying to display object properties stored within an array onto a <ul> element

Body:
I've just started learning JS and I'm trying to do some basic projects to cement what I've learned from reading and courses and tutorials and whatnot. I'm trying to make a contact list which takes 4 inputs: first name, last name, email and phone number. I wrote this part already and passed the arguments into an object within an array. What I can't figure out is how to display the contact object. I want to try and print each property into a list item within an unordered list but I'm stuck here, either because I don't know enough about DOM manipulation or just because I'm not looking in the right direction

//this passes the text input as an object to the list array
var contactList = {
  list: [],

  addNew: function() {
    this.list.push({
      firstName: document.getElementById('firstname').value,
      lastName: document.getElementById('lastname').value,
      email: document.getElementById('emailAdd').value,
      phoneNumber: document.getElementById('phoneNumber').value
    });
  },
};

// this runs the addNew() function and clears the input fields afterwards
var handlers = {
  addContact: function() {
    contactList.addNew();

    document.getElementById('firstname').value = '';
    document.getElementById('lastname').value = '';
    document.getElementById('emailAdd').value = '';
    document.getElementById('phoneNumber').value = '';

    //      view.displayContact();
  },

};
//this is where i'm trying to display the contacts array
var view = {
  displayContact: function() {
    var contacts = document.getElementById('contactul');
    for (var i = 0; i < contactList.list.length; i++) {
      var li = document.createElement('li');

      contacts.appendChild(li);
      li.innerHTML += contactList.list[i];
    };
  },
};

<form>
  First name:

  <input id="firstname" type="text" name="firstname">

 Last name:

  <input id="lastname" type="text" name="lastname">

 Email Address:

  <input id="emailAdd" type="text">

 Phone number:

  <input id="phoneNumber" type="text">

</form>
<button onclick='handlers.addContact()'>Submit</button>

This is the desired result. I just can't figure out how to write it.

Body:
Well, you're close. The problem you have here is that when you go to display your items, you have to get the values for each individual element (first name, last name, etc). You can do that through another loop, or just hard-code each one since there are only 4. Here is an example:

//this passes the text input as an object to the list array
var contactList = {
  list: [],

  addNew: function() {
    this.list.push({
      firstName: document.getElementById('firstname').value,
      lastName: document.getElementById('lastname').value,
      email: document.getElementById('emailAdd').value,
      phoneNumber: document.getElementById('phoneNumber').value
    });
  },
};

// this runs the addNew() function and clears the input fields afterwards
var handlers = {
  addContact: function() {
    contactList.addNew();

    document.getElementById('firstname').value = '';
    document.getElementById('lastname').value = '';
    document.getElementById('emailAdd').value = '';
    document.getElementById('phoneNumber').value = '';

    view.displayContact();
  },

};
//this is where i'm trying to display the contacts array
var view = {
  displayContact: function() {
    var contacts = document.getElementById('contactul');
    while(contacts.firstChild ){
      contacts.removeChild(contacts.firstChild );
    }
    for (var i = 0; i < contactList.list.length; i++) {
      var liForFirstName = document.createElement('li');
      contacts.appendChild(liForFirstName);
      liForFirstName.innerHTML += "First Name: " + contactList.list[i].firstName;
      var liForLastName = document.createElement('li');
      contacts.appendChild(liForLastName);
      liForLastName.innerHTML += "Last Name: " + contactList.list[i].lastName;
      var liForEmail = document.createElement('li');
      contacts.appendChild(liForEmail);
      liForEmail.innerHTML += "Email: " + contactList.list[i].email;
      var liForPhoneNumber = document.createElement('li');
      contacts.appendChild(liForPhoneNumber);
      liForPhoneNumber.innerHTML += "Phone Number: " + contactList.list[i].phoneNumber;
    };
  },
};

<form>
  First name:<br>
  <input id="firstname" type="text" name="firstname">
  <br> Last name:<br>
  <input id="lastname" type="text" name="lastname">
  <br> Email Address:<br>
  <input id="emailAdd" type="text">
  <br> Phone number:<br>
  <input id="phoneNumber" type="text">
  <br>
</form>
<button onclick='handlers.addContact()'>Submit</button>

<div id='displayContacts'>
  <ul id='contactul'>

  </ul>
</div>


问:
AWSCognito in Angular4 (SpaceFinder) Example
I'd like to understand the difference between

AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);

vs

new AmazonCognitoIdentity.CognitoUserPool(poolData);

Since most examples I've found use AWSCognito, and AWS declared similar to:

```<code>declare let AWS: any;
declare let AWSCognito: any;
</code>```

or

```<code>declare const AWS: any;
declare const AWSCognito: any;
</code>```

yet the answer found here and the document documentation propose a different approach.

答:
For script usage, the different objects are available on the AWSCognito object. And with webpack you can get them on the AWS object, similar to what the main AWS SDK does.

I think this solution works. 'AWSCognito' is not defined

Body:
I'd like to understand the difference between

AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);

vs

new AmazonCognitoIdentity.CognitoUserPool(poolData);

Since most examples I've found use AWSCognito, and AWS declared similar to:

declare let AWS: any;
declare let AWSCognito: any;

or

declare const AWS: any;
declare const AWSCognito: any;

yet the answer found here and the document documentation propose a different approach.


问:
Jersey mangles data from JSON?
We have a REST web service implemented with the Jersey framework that allows users to save configuration info from the UI. There is a GET (to get current config info) and a corresponding POST to save settings. That data is saved in a JSON file. The GET works perfectly, as does the POST exept for one value:

```<code>"modulation": 2,
</code>```

No matter what this value is set to, when getting the data from the UI in the POST, it's always the default. Every other value is perfect.

This value used to be an enum and since everything in the file is saved as an int or String, I thought that might be confusing it. So I changed it to an int. That didn't help. On the bright side, it didn't make anything worse either.

Using good ol' Postman, I send a JSON structure with the POST:

```<code>{
    "customers": {
        "max": 20,
        "current": 2
    },
    "window": {
        "x": 10,
        "y": 10,
        "width": 20,
        "height": 20
    },
    "modulation": 2,    // always just the default, 1
    "pointsOfConsternation": 20
}
</code>```

It gets automagically converted into an object that we use for configuration. All the values come across correctly except that pesky mode. Here is what the receiving method signature looks like:

```<code>@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces(MediaType.TEXT_PLAIN)
@Path("/config")
public String setConfiguration( ConsternationConfig config ) {
    ...
    // do magic
    ...
}
</code>```

I've debugged the crap out of it to no avail. The mangling happens in code that I don't have any control over. It comes into the POST method mangled.

Any idea on what might be going on?

UPDATE
Per @Aleh Maksimovich, here is the source for ConsternationConfig:

```<code>@XmlRootElement
public class ConsternationConfig {

    // Data members
    private Customers customers;
//  private ConsternationModulation modulation; // how modulation used to be defined, changed to the int below
    private int modulation;
    private int pointsOfConsternation;

    @XmlJavaTypeAdapter(RectangleStandInAdapter.class)
    private Rectangle window;

    /**
     * Default constructor
    */
    public ConsternationConfig() {
        customers = new Customers();
//      modulation = DEFAULT_MODULATION;  // how modulation used to be defined
        modulation = DEFAULT_MODULATION.ordinal();
        pointsOfConsternation= DEFAULT_POINTS_OF_CONSTERNATION;
        window = new Rectangle(DEFAULT_WINDOW_X, DEFAULT_WINDOW_Y, DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT);
    }

    public ConsternationModulation getModulation() {
        return ConsternationModulation.values()[modulation];
    }

    public void setModulation(int modulation) {
        this.modulation = modulation;
    }

    public void setModulation(ConsternationModulation modulation) {
        this.modulation = modulation.ordinal();
    }

...a whole bunch of other getters and setters that do nothing but set individual members...
}
</code>```

And here's ConsternationModulation just for good measure:

```<code>public enum ConsternationModulation {

    INVALID,
    FIRST_CONSTERNATION,
    SECOND_CONSTERNATION,
    THIRD_CONSTERNATION,
    FOURTH_CONSTERNATION
}
</code>```

答:
The problem was the fact that I had two setModulation() methods. One allows the modulation to set with an int, the other with an enum. I thought the conversation would be smart enough to call the appropriate setter (the int setter). I was wrong. Apparently, having two setters confused the converter, so it didn't call either. That explains why it was always at the default value (which is set in the constructor).

Removing the enum version of the setter fixed the problem, and it worked fine afterwards. The setter is shown above, but for convenience, here it is again. There is nothing special or magical about it:

```<code>public void setModulation(int modulation) {
    this.modulation = modulation;
}
</code>```

Thanks for all the input, especially peeskillet!

Title: Jersey mangles data from JSON?

Body:
We have a REST web service implemented with the Jersey framework that allows users to save configuration info from the UI. There is a GET (to get current config info) and a corresponding POST to save settings. That data is saved in a JSON file. The GET works perfectly, as does the POST exept for one value:

"modulation": 2,

No matter what this value is set to, when getting the data from the UI in the POST, it's always the default. Every other value is perfect.

This value used to be an enum and since everything in the file is saved as an int or String, I thought that might be confusing it. So I changed it to an int. That didn't help. On the bright side, it didn't make anything worse either.

Using good ol' Postman, I send a JSON structure with the POST:

{
    "customers": {
        "max": 20,
        "current": 2
    },
    "window": {
        "x": 10,
        "y": 10,
        "width": 20,
        "height": 20
    },
    "modulation": 2,    // always just the default, 1
    "pointsOfConsternation": 20
}

It gets automagically converted into an object that we use for configuration. All the values come across correctly except that pesky mode. Here is what the receiving method signature looks like:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces(MediaType.TEXT_PLAIN)
@Path("/config")
public String setConfiguration( ConsternationConfig config ) {
    ...
    // do magic
    ...
}

I've debugged the crap out of it to no avail. The mangling happens in code that I don't have any control over. It comes into the POST method mangled.

Any idea on what might be going on?

UPDATE
Per @Aleh Maksimovich, here is the source for ConsternationConfig:

@XmlRootElement
public class ConsternationConfig {

    // Data members
    private Customers customers;
//  private ConsternationModulation modulation; // how modulation used to be defined, changed to the int below
    private int modulation;
    private int pointsOfConsternation;

    @XmlJavaTypeAdapter(RectangleStandInAdapter.class)
    private Rectangle window;

    /**
     * Default constructor
    */
    public ConsternationConfig() {
        customers = new Customers();
//      modulation = DEFAULT_MODULATION;  // how modulation used to be defined
        modulation = DEFAULT_MODULATION.ordinal();
        pointsOfConsternation= DEFAULT_POINTS_OF_CONSTERNATION;
        window = new Rectangle(DEFAULT_WINDOW_X, DEFAULT_WINDOW_Y, DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT);
    }

    public ConsternationModulation getModulation() {
        return ConsternationModulation.values()[modulation];
    }

    public void setModulation(int modulation) {
        this.modulation = modulation;
    }

    public void setModulation(ConsternationModulation modulation) {
        this.modulation = modulation.ordinal();
    }

...a whole bunch of other getters and setters that do nothing but set individual members...
}

And here's ConsternationModulation just for good measure:

public enum ConsternationModulation {

    INVALID,
    FIRST_CONSTERNATION,
    SECOND_CONSTERNATION,
    THIRD_CONSTERNATION,
    FOURTH_CONSTERNATION
}

Body:
The problem was the fact that I had two setModulation() methods. One allows the modulation to set with an int, the other with an enum. I thought the conversation would be smart enough to call the appropriate setter (the int setter). I was wrong. Apparently, having two setters confused the converter, so it didn't call either. That explains why it was always at the default value (which is set in the constructor).

Removing the enum version of the setter fixed the problem, and it worked fine afterwards. The setter is shown above, but for convenience, here it is again. There is nothing special or magical about it:

public void setModulation(int modulation) {
    this.modulation = modulation;
}

Thanks for all the input, especially peeskillet!


问:
Unable to access vue data in basic modal
I am trying to loop and reference vue data values within a modal and am getting an error that the field needs to be reactive, despite the values being provided in the component initialization. Any idea why this is?

Fiddle:
https://jsfiddle.net/mwLbw11k/2618/

JS

```<code>// register modal component
Vue.component('modal', {
  template: '#modal-template'
})

// start app
new Vue({
  el: '#app',
  data: {
    myData: [{'first': 'Matt', 'last': 'Smith'}, {'first': 'Tom', 'last': 'Brady'}],
    showModal: false
  }
})
</code>```

HTML

```<code><script type="text/x-template" id="modal-template">
  <transition name="modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header">
              default header
            </slot>
          </div>

          <div class="modal-body">
            <slot name="body">
              <ul>
                <li v-for="user in myData"> {{ user.first }} {{ user.last }}</li>
              </ul>
            </slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              default footer
              <button class="modal-default-button" @click="$emit('close')">
                OK
              </button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</script>

<!-- app -->
<div id="app">
  <button id="show-modal" @click="showModal = true">Show Modal</button>
  <!-- use the modal component, pass in the prop -->
  <modal v-if="showModal" @close="showModal = false">
  </modal>
</div>
</code>```

Vue Warning

```<code>[Vue warn]: Property or method "myData" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
</code>```

答:
Yous should add myData to modal component props

```<code>Vue.component('modal', {
  template: '#modal-template',
  props: ['myData']
})
</code>```

and then pass it from parent like this:

```<code>  <modal v-if="showModal" :my-data="myData" @close="showModal = false">
  </modal>
</code>```

Body:
I am trying to loop and reference vue data values within a modal and am getting an error that the field needs to be reactive, despite the values being provided in the component initialization. Any idea why this is?

Fiddle:
https://jsfiddle.net/mwLbw11k/2618/

JS

// register modal component
Vue.component('modal', {
  template: '#modal-template'
})

// start app
new Vue({
  el: '#app',
  data: {
    myData: [{'first': 'Matt', 'last': 'Smith'}, {'first': 'Tom', 'last': 'Brady'}],
    showModal: false
  }
})

HTML

  <button id="show-modal" @click="showModal = true">Show Modal</button>

  <modal v-if="showModal" @close="showModal = false">
  </modal>

Vue Warning

[Vue warn]: Property or method "myData" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Body:
Yous should add myData to modal component props

Vue.component('modal', {
  template: '#modal-template',
  props: ['myData']
})

and then pass it from parent like this:

  <modal v-if="showModal" :my-data="myData" @close="showModal = false">
  </modal>


问:
STArray indexing gives a type error
I'm trying to solve this year's Advent of Code using Haskell, and ran into an issue on day 5 which asks us to jump around instructions in a list of jumps and count how many steps it takes until you exit the instruction set. I implemented this correctly with IArrays, but it seems like a waste to re-initialize this huge array over and over so I'm trying to re-implement with MArray instead, which is throwing me into the scary world of the ST monad.

Here is my correctly working code:

```<code>import qualified Data.Array as A

-- sample input
day5Input :: [Int]
day5Input = [0, -1, 1032] ++ replicate 1030 [1]  -- to fill the array

day5Array :: A.Array Int Int
day5Array = A.listArray (0, 1032) day5Input

p1Day5Result :: Integer
p1Day5Result = go 0 0 day5Array where
  go :: Integer -> Int -> A.Array Int Int -> Integer
  go c i a | i > ubound || i < lbound = c
           | otherwise                = let n = a A.! i
                                            i' = i+n
                                            n' = n+1
                                            a' = a A.// [(i, n')]
                                        in  go (c+1) i' a'
  (lbound, ubound) = A.bounds day5Array
</code>```

which I attempted to re-create using an STArray with:

```<code>import Data.Array.MArray as MA
import Data.Array.ST (STArray, runSTArray)
import Control.Monad.ST

-- sample input
day5Input :: [Int]
day5Input = [0, -1, 1032] ++ replicate 1030 [1]  -- to fill the array

testMArray :: ST s (STArray s Int Int)
testMArray = MA.newListArray (0, 1032) day5Input

mStep :: ST s Integer
mStep = go 0 0 testMArray where
  go :: Integer -> Int -> ST s (STArray s Int Int) -> ST s Integer
  go c i arr | i > ubound || i < lbound = return c
             | otherwise                = do
                     n <- MA.readArray arr i
                     let i' = i+n
                         n' = n+1
                     MA.writeArray arr i n'
                     go (c+1) i' arr
  (lbound, ubound) = (0, 1032)  -- sub-question, how do I query for this
                                -- like I did with A.bounds above?
</code>```

However I get the error:

```<code>day5.hs:1091:44: error:
    * Couldn't match expected type `s1' with actual type `Int'
      `s1' is a rigid type variable bound by
        the type signature for:
          go :: forall s1.
                Integer -> Int -> ST s1 (STArray s1 Int Int) -> ST s1 Integer
</code>```

I'm not seeing how my code differs from this example code that works. Please advise.

答:
You simply seem to be mixing up ST actions which produce arrays with the arrays themselves. The fix is pretty easy: run such actions to get their arrays. Here's the minimal fix I needed to make to get this to compile (no idea if it is "correct" -- just that it type-checks).

Run the ST action.

```<code>mStep = testMArray >>= go 0 0 where
</code>```

Give go a type that expects an array, not an ST action.

```<code>go :: Integer -> Int -> STArray s Int Int -> ST s Integer
</code>```

Define day5Input. (Presumably you need not backport this fix.)

```<code>day5Input = undefined
</code>```

For your subquestion, you can use

```<code>getBounds :: (Ix i, MArray a e m) => a i e -> m (i, i)
</code>```

to get the bounds dynamically. So:

```<code>mStep = do
    arr <- testMArray
    (lbound, ubound) <- MA.getBounds arr
    go lbound ubound 0 0 arr
    where
    go :: Int -> Int -> Integer -> Int -> STArray s Int Int -> ST s Integer
    go lbound ubound c i arr | -- same as before
        -- until the very last line
        go lbound ubound (c+1) i' arr
</code>```

Title: STArray indexing gives a type error

Body:
I'm trying to solve this year's Advent of Code using Haskell, and ran into an issue on day 5 which asks us to jump around instructions in a list of jumps and count how many steps it takes until you exit the instruction set. I implemented this correctly with IArrays, but it seems like a waste to re-initialize this huge array over and over so I'm trying to re-implement with MArray instead, which is throwing me into the scary world of the ST monad.

Here is my correctly working code:

import qualified Data.Array as A

-- sample input
day5Input :: [Int]
day5Input = [0, -1, 1032] ++ replicate 1030 [1]  -- to fill the array

day5Array :: A.Array Int Int
day5Array = A.listArray (0, 1032) day5Input

p1Day5Result :: Integer
p1Day5Result = go 0 0 day5Array where
  go :: Integer -> Int -> A.Array Int Int -> Integer
  go c i a | i > ubound || i < lbound = c
           | otherwise                = let n = a A.! i
                                            i' = i+n
                                            n' = n+1
                                            a' = a A.// [(i, n')]
                                        in  go (c+1) i' a'
  (lbound, ubound) = A.bounds day5Array

which I attempted to re-create using an STArray with:

import Data.Array.MArray as MA
import Data.Array.ST (STArray, runSTArray)
import Control.Monad.ST

-- sample input
day5Input :: [Int]
day5Input = [0, -1, 1032] ++ replicate 1030 [1]  -- to fill the array

testMArray :: ST s (STArray s Int Int)
testMArray = MA.newListArray (0, 1032) day5Input

mStep :: ST s Integer
mStep = go 0 0 testMArray where
  go :: Integer -> Int -> ST s (STArray s Int Int) -> ST s Integer
  go c i arr | i > ubound || i < lbound = return c
             | otherwise                = do
                     n <- MA.readArray arr i
                     let i' = i+n
                         n' = n+1
                     MA.writeArray arr i n'
                     go (c+1) i' arr
  (lbound, ubound) = (0, 1032)  -- sub-question, how do I query for this
                                -- like I did with A.bounds above?

However I get the error:

day5.hs:1091:44: error:
    * Couldn't match expected type `s1' with actual type `Int'
      `s1' is a rigid type variable bound by
        the type signature for:
          go :: forall s1.
                Integer -> Int -> ST s1 (STArray s1 Int Int) -> ST s1 Integer

I'm not seeing how my code differs from this example code that works. Please advise.

Body:
You simply seem to be mixing up ST actions which produce arrays with the arrays themselves. The fix is pretty easy: run such actions to get their arrays. Here's the minimal fix I needed to make to get this to compile (no idea if it is "correct" -- just that it type-checks).

Run the ST action.

mStep = testMArray >>= go 0 0 where

Give go a type that expects an array, not an ST action.

go :: Integer -> Int -> STArray s Int Int -> ST s Integer

Define day5Input. (Presumably you need not backport this fix.)

day5Input = undefined

For your subquestion, you can use

getBounds :: (Ix i, MArray a e m) => a i e -> m (i, i)

to get the bounds dynamically. So:

mStep = do
    arr <- testMArray
    (lbound, ubound) <- MA.getBounds arr
    go lbound ubound 0 0 arr
    where
    go :: Int -> Int -> Integer -> Int -> STArray s Int Int -> ST s Integer
    go lbound ubound c i arr | -- same as before
        -- until the very last line
        go lbound ubound (c+1) i' arr


问:
How do I tell playframework to use my corporate proxy?
I'm trying to get started with the play web framework and its scala support,

unfortunately "install scala" fails because play can't fetch the module site.

I've got my system settings correct for the corporate proxy, however play doesn't seem to use them.

Is there a config file somewhere or some environment properties I need to set for play to pick them up?

答:
I would strongly recommend using software such as Proxifier to deal with corporate proxy servers, not dealing with it on the application level.  That will allow you to control all of your proxy configuration in one place, and will also work much more seamlessly than trying to update individual software packages.

http://www.proxifier.com/

If you are on U*nx, try CNTLM instead.

http://cntlm.sourceforge.net/


问:
How to create a custom square in a-frame
How can I create a custom square registering a new component in a-frame?

I am trying to update the example found here https://github.com/aframevr/aframe/blob/master/docs/components/geometry.md
under the heading "Register a Custom Geometry"

Below is what I have tried - first the js

```<code>AFRAME.registerGeometry('example', {
      schema: {
        vertices: {
          default: ['-10 10 0', '-10 -10 0', '10 -10 0', '10 -10 0'], //added a 4th set of dimensions here
        }
      },

      init: function (data) {
        var geometry = new THREE.Geometry();
        geometry.vertices = data.vertices.map(function (vertex) {
            var points = vertex.split(' ').map(function(x){return parseInt(x);});
            return new THREE.Vector3(points[0], points[1], points[2], points[3]); //added a 4th 'points' here
        });
        geometry.computeBoundingBox();
        geometry.faces.push(new THREE.Face3(0, 1, 2, 3)); //added a 4th number here
        geometry.mergeVertices();
        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
        this.geometry = geometry;
      }
    });
</code>```

I have made comments where I have made changes, essentially just adding 4 elements where there were previously three

I then add this into the html

```<code><a-entity geometry="primitive: example; vertices: 1 1 -3, 3 1 -3, 2 2 -3, 1 2 -3"></a-entity>
</code>```

But it seems to just ignore my new vertice and just creates a triangle. I suspect there is something about the three.js code that I do not understand and I don't seem to be able to solve it by looking at their documentation - any help would be much appreciated.

答:
This seems to work;

```<code>AFRAME.registerGeometry('example', {
      schema: {
        vertices: {
          default: ['-10 10 0', '-10 -10 0', '10 -10 0', '10 -10 0'],
        }
      },

      init: function (data) {
        var geometry = new THREE.Geometry();
        geometry.vertices = data.vertices.map(function (vertex) {
            var points = vertex.split(' ').map(function(x){return parseInt(x);});
            return new THREE.Vector3(points[0], points[1], points[2]);
        });
        geometry.computeBoundingBox();
        geometry.faces.push(new THREE.Face3(0, 1, 2));
        geometry.faces.push(new THREE.Face3(0, 2, 3));
        geometry.mergeVertices();
        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
        this.geometry = geometry;
      }
    });
</code>```

again followed by this in the html

```<code><a-entity geometry="primitive: example; vertices: 1 1 -3, 3 1 -3, 2 2 -3, 1 2 -3"></a-entity>
</code>```

Body:
How can I create a custom square registering a new component in a-frame?

I am trying to update the example found here https://github.com/aframevr/aframe/blob/master/docs/components/geometry.md
under the heading "Register a Custom Geometry"

Below is what I have tried - first the js

AFRAME.registerGeometry('example', {
      schema: {
        vertices: {
          default: ['-10 10 0', '-10 -10 0', '10 -10 0', '10 -10 0'], //added a 4th set of dimensions here
        }
      },

      init: function (data) {
        var geometry = new THREE.Geometry();
        geometry.vertices = data.vertices.map(function (vertex) {
            var points = vertex.split(' ').map(function(x){return parseInt(x);});
            return new THREE.Vector3(points[0], points[1], points[2], points[3]); //added a 4th 'points' here
        });
        geometry.computeBoundingBox();
        geometry.faces.push(new THREE.Face3(0, 1, 2, 3)); //added a 4th number here
        geometry.mergeVertices();
        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
        this.geometry = geometry;
      }
    });

I have made comments where I have made changes, essentially just adding 4 elements where there were previously three

I then add this into the html

But it seems to just ignore my new vertice and just creates a triangle. I suspect there is something about the three.js code that I do not understand and I don't seem to be able to solve it by looking at their documentation - any help would be much appreciated.

Body:
This seems to work;

AFRAME.registerGeometry('example', {
      schema: {
        vertices: {
          default: ['-10 10 0', '-10 -10 0', '10 -10 0', '10 -10 0'],
        }
      },

      init: function (data) {
        var geometry = new THREE.Geometry();
        geometry.vertices = data.vertices.map(function (vertex) {
            var points = vertex.split(' ').map(function(x){return parseInt(x);});
            return new THREE.Vector3(points[0], points[1], points[2]);
        });
        geometry.computeBoundingBox();
        geometry.faces.push(new THREE.Face3(0, 1, 2));
        geometry.faces.push(new THREE.Face3(0, 2, 3));
        geometry.mergeVertices();
        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
        this.geometry = geometry;
      }
    });

again followed by this in the html

<a-entity geometry="primitive: example; vertices: 1 1 -3, 3 1 -3, 2 2 -3, 1 2 -3"></a-entity>


问:
Installing latest version of Dancer2 on Debian
OK, got myself a clean virtual machine running Debian 9 (Stretch). I installed Dancer2 from the Debian package system. It's running version 0.204002. The Dancer2 software is telling me that the latest version is 0.205002.

I want to finally, once and for all, learn the proper way to upgrade Perl modules on a Debian machine to the latest and greatest versions without ruining the Debian dpkg dependencies. How do I achieve this?

EDIT
Yes, this is a development machine I'm just playing with. But what if I wanted to run the latest version of Dancer 2 on a production machine? How would I do it?

答:
I can't tell that the following is the answer for the I want to finally, once and for all, learn the proper way... , but this is how me doing it in all my deployments.

Install anyenv sudo git clone https://github.com/riywo/anyenv /opt/anyenv - you could deploy it into your $HOME as git clone https://github.com/riywo/anyenv ~/.anyenv but myself prefering some commonly accessible place. This step isn't mandatory, but for me help managing other local installations as node and such.

change ownership: sudo chown -R jm666 /opt/anyenv - you will manage the content

add into the .profile:

```<code>export ANYENV_ROOT=/opt/anyenv
export PATH="$ANYENV_ROOT/bin:$PATH"
eval "$(anyenv init -)"
</code>```

Relog, or run exec $SHELL -l. Now you have installed an helper for all commonly needed environments.

Now install the perl env. helper, called plenv.

```<code>anyenv install plenv
</code>```

Or follow the guide in the repo if you don't want the previous anyenv step.

And finally install fresh perl using plenv:

```<code>plenv install -l #will display all available perl versions
plenv install 5.26.1 -j 8 # number of proc cores or less. :)
</code>```

This will take some time - on my notebook 4m23,186s - just tested :).

```<code>plenv global 5.26.1 # now all `perl script.pl` will use the freshly installed perl
plenv install-cpanm
plenv rehash #needed if you install some commands which should be accesible from `bash`
</code>```

And you're ready to install any perl modules using cpanm - without compromising the system-wide installed perl. Everything will be installed into the plenv's directory tree. Even, you never need be root.

This way I could manage to have the same development and deployment environment. Maybe here is a better way - but for me the above works.

In short, read:

https://github.com/riywo/anyenv

https://github.com/tokuhirom/plenv

Body:
I can't tell that the following is the answer for the I want to finally, once and for all, learn the proper way... , but this is how me doing it in all my deployments.

Install anyenv sudo git clone https://github.com/riywo/anyenv /opt/anyenv - you could deploy it into your $HOME as git clone https://github.com/riywo/anyenv ~/.anyenv but myself prefering some commonly accessible place. This step isn't mandatory, but for me help managing other local installations as node and such.

change ownership: sudo chown -R jm666 /opt/anyenv - you will manage the content

add into the .profile:

export ANYENV_ROOT=/opt/anyenv
export PATH="$ANYENV_ROOT/bin:$PATH"
eval "$(anyenv init -)"

Relog, or run exec $SHELL -l. Now you have installed an helper for all commonly needed environments.

Now install the perl env. helper, called plenv.

anyenv install plenv

Or follow the guide in the repo if you don't want the previous anyenv step.

And finally install fresh perl using plenv:

plenv install -l #will display all available perl versions
plenv install 5.26.1 -j 8 # number of proc cores or less. :)

This will take some time - on my notebook 4m23,186s - just tested :).

plenv global 5.26.1 # now all `perl script.pl` will use the freshly installed perl
plenv install-cpanm
plenv rehash #needed if you install some commands which should be accesible from `bash`

And you're ready to install any perl modules using cpanm - without compromising the system-wide installed perl. Everything will be installed into the plenv's directory tree. Even, you never need be root.

This way I could manage to have the same development and deployment environment. Maybe here is a better way - but for me the above works.

In short, read:

https://github.com/riywo/anyenv

https://github.com/tokuhirom/plenv


问:
Environment variable is too large on Windows 10
I have recently upgraded to Windows 10 from Windows 8.1.

Now I wanted to set an environment variable for my new installation of Apache Maven.

Each time I created the user variable, things were fine. However, I also need to create the system variable where I will need to append the bin directory to the variable that I already create in the user variable to be "path".

Now, each time I do this, I get an error that says "This environment variable is too large". As a result of this, I am unable to create the path.

I have attached an image of this error.

答:
There are a few ways to clean up your path variable. The easiest is to use Rapid Environment Editor. This free utility will,

Remove the duplicate paths (right click → Cleanup Paths)

Remove non-existent folders (shown in red which you need to manually delete)

Replace long paths with short paths (right click → long to short path).

I do the above steps in order and use the third step only for the longest paths until the Path variable size is under control again.

If you want to go more advanced, here's a little C# tool that you can modify to whatever other logic you want to implement.

ContentLicense: CC BY-SA 4.0


问:
How can we compute solar position at a given place on a given day and time?
I have UTC time (hours, minutes, seconds), longitude(deg E), latitude (deg N) and date. Can anyone provide me with a code to calculate solar zenith angle in Python 2.7? </p>

答:
It is an interesting problem and I think I have a good answer - well, at least starting points.

Check out the awesome astropy package. I believe you need to use the coordinates module.

Something along these lines:

```<code>import astropy.coordinates as coord
from astropy.time import Time
import astropy.units as u

loc = coord.EarthLocation(lon=0.1 * u.deg,
                          lat=51.5 * u.deg)
now = Time.now()

altaz = coord.AltAz(location=loc, obstime=now)
sun = coord.get_sun(now)

print(sun.transform_to(altaz).alt)
</code>```

Here, we are getting the angle of the sun above the horizon for the 0.1 degrees longitude and 51.5 latitude location at the current time.

FYI, .zen would give you the zenith angle.

Body:
It is an interesting problem and I think I have a good answer - well, at least starting points.

Check out the awesome astropy package. I believe you need to use the coordinates module.

Something along these lines:

import astropy.coordinates as coord
from astropy.time import Time
import astropy.units as u

loc = coord.EarthLocation(lon=0.1 * u.deg,
                          lat=51.5 * u.deg)
now = Time.now()

altaz = coord.AltAz(location=loc, obstime=now)
sun = coord.get_sun(now)

print(sun.transform_to(altaz).alt)

Here, we are getting the angle of the sun above the horizon for the 0.1 degrees longitude and 51.5 latitude location at the current time.

FYI, .zen would give you the zenith angle.


问:
Do I have to use JavaScript?
When does it become unavoidable and when would you want to choose JavaScript over server side when you have a choice?</p>

答: JavaScript is not a necessity but, coupled with the DOM API, it provides a very useful medium for gradually improving the user experience of your site. Obviously the extent to which this is true is dependent on how well you execute these enhancements, don't just use JavaScript for the sake of it; it's a design decision, and should not be taken lightly.</p>

OwnerDisplayName: zsharp

Title: Do I have to use JavaScript?


问:
How does the web server locate a file on server through URL?
Has anyone ever tried to implement a web server? Or know something about the underhood of a working web server program? I am wondering what happens exactly from when a URL is received by the web server to a file on the web server is located and sent back as response.

Does the server just keep an internal table to remember the mapping between the URLs it supports and the corresponding local paths? Or is there anything more tricky?

Thanks!

Update

Thanks for your replies. Here's my understanding for now.

I checked with the Microsoft IIS (Internet Information Service), I noticed that IIS can host multiple sites, and foreach site IIS memorize its root path on the local file system. Different sites on the same host share the same host name or IP, and they are differentiated by separate ports. For example:

```<code>http://www.myServer.com:1111/folderA/pageA.htm
</code>```

The web server will use www.myServer.com:1111 part of the URL string to locate which path on its local file system will be used, and then in that local path, it searches for subfolder folderA and then the file pageA.htm.

The web server only need to memorize the following mapping between 2 plain strings:

```<code>"http://www.myServer.com:1111/" <---> "D:\myWebRoot"
</code>```

I don't know where this kind of mapping info is stored, maybe some config files for the Web Server Program in question.

But the result of this mapping granularity is that we could only access content within that mapped local folder. We couldn't do arbitray mapping.

Update - 2 -

I found where the IIS keep the mapping, here's some quotes from applicationHost.config:

```<code><sites>
    <site name="Default Web Site" id="1" serverAutoStart="false">
        <application path="/">
            <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:80:" />
            <binding protocol="net.tcp" bindingInformation="808:*" />
            <binding protocol="net.pipe" bindingInformation="*" />
            <binding protocol="net.msmq" bindingInformation="localhost" />
            <binding protocol="msmq.formatname" bindingInformation="localhost" />
        </bindings>
    </site>
    <site name="myIISService" id="2" serverAutoStart="true">
        <application path="/" applicationPool="myIISService">
            <virtualDirectory path="/" physicalPath="D:\MySites\MyIISService" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:8022:" />
        </bindings>
    </site>
    <siteDefaults>
        <logFile logFormat="W3C" directory="%SystemDrive%\inetpub\logs\LogFiles" />
        <traceFailedRequestsLogging directory="%SystemDrive%\inetpub\logs\FailedReqLogFiles" />
    </siteDefaults>
    <applicationDefaults applicationPool="DefaultAppPool" />
    <virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>
</code>```

Update - 3 -

After I read foo's reply, my undersanding of a "server" is enlarged. I want to make some comment based on my recent learning of WCF.

No matter what kind of server it is, we could always send messages to them by specifying the protocol, URL, port. For example:

```<code>[http://www.myserver.com:1111/]page.htm

[net.tcp://www.myserver.com/]someService.svc/someMethod

[net.msmq://www.myserver.com/]someService.svc

[net.pipe://localhost/]
</code>```

After the messages arrives at the server program using the parts in square bracket of above URLs, the rest part of the url will send to the server program as input for further processing. And the following behaviour could be as simple as static content feeding or as complex as dynamic content generating.

答:
Depends on the webserver and what its focus is.

(For all items, checking access rights, remapping and such steps apply of course.)

General-purpose webservers like Apache start out with files and directories, so they split up the URL into a hierarchical path description, try to find a file at the given location, and serve it if it exists. (This gets more complex with modules and filetypes; some filetypes imply processing the file as a script and returning the script output rather than just piping out the file contents, and so on).

Application servers like Tomcat do a mapping to servlets; if they have found a servlet that will handle the URL, they call it and pass any leftover URL parts/parameters to it for further handling.

Embedded webservers may even use hardcoded lookup tables for available URL patterns, directly mapping to functions to be called.

Special-purpose webservers will do whatever is required; some won't even parse the URL but just the other headers (like some streaming servers do).

It all depends on what you want to achieve. In most cases, you will be best off with nginx or Apache and maybe some modules and/or finetuning.

Be aware that any HTTP header can be used for mapping the request to whatever means of producing output you have. Hostname, port and URL are used most often, but you may as well take language or client IP or other header data and use them in the mapping.

So for your question: Yes, it can be as simple as that; and yes, it can be substantially more tricky (with mapping, rewriting, and complex processing).

Body:
Has anyone ever tried to implement a web server? Or know something about the underhood of a working web server program? I am wondering what happens exactly from when a URL is received by the web server to a file on the web server is located and sent back as response.

Does the server just keep an internal table to remember the mapping between the URLs it supports and the corresponding local paths? Or is there anything more tricky?

Thanks!

Update

Thanks for your replies. Here's my understanding for now.

I checked with the Microsoft IIS (Internet Information Service), I noticed that IIS can host multiple sites, and foreach site IIS memorize its root path on the local file system. Different sites on the same host share the same host name or IP, and they are differentiated by separate ports. For example:

http://www.myServer.com:1111/folderA/pageA.htm

The web server will use www.myServer.com:1111 part of the URL string to locate which path on its local file system will be used, and then in that local path, it searches for subfolder folderA and then the file pageA.htm.

The web server only need to memorize the following mapping between 2 plain strings:

"http://www.myServer.com:1111/" <---> "D:\myWebRoot"

I don't know where this kind of mapping info is stored, maybe some config files for the Web Server Program in question.

But the result of this mapping granularity is that we could only access content within that mapped local folder. We couldn't do arbitray mapping.

Update - 2 -

I found where the IIS keep the mapping, here's some quotes from applicationHost.config:

<sites>
    <site name="Default Web Site" id="1" serverAutoStart="false">
        <application path="/">
            <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:80:" />
            <binding protocol="net.tcp" bindingInformation="808:*" />
            <binding protocol="net.pipe" bindingInformation="*" />
            <binding protocol="net.msmq" bindingInformation="localhost" />
            <binding protocol="msmq.formatname" bindingInformation="localhost" />
        </bindings>
    </site>
    <site name="myIISService" id="2" serverAutoStart="true">
        <application path="/" applicationPool="myIISService">
            <virtualDirectory path="/" physicalPath="D:\MySites\MyIISService" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:8022:" />
        </bindings>
    </site>
    <siteDefaults>
        <logFile logFormat="W3C" directory="%SystemDrive%\inetpub\logs\LogFiles" />
        <traceFailedRequestsLogging directory="%SystemDrive%\inetpub\logs\FailedReqLogFiles" />
    </siteDefaults>
    <applicationDefaults applicationPool="DefaultAppPool" />
    <virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>

Update - 3 -

After I read foo's reply, my undersanding of a "server" is enlarged. I want to make some comment based on my recent learning of WCF.

No matter what kind of server it is, we could always send messages to them by specifying the protocol, URL, port. For example:

[http://www.myserver.com:1111/]page.htm

[net.tcp://www.myserver.com/]someService.svc/someMethod

[net.msmq://www.myserver.com/]someService.svc

[net.pipe://localhost/]

After the messages arrives at the server program using the parts in square bracket of above URLs, the rest part of the url will send to the server program as input for further processing. And the following behaviour could be as simple as static content feeding or as complex as dynamic content generating.


问:
How do you make a Discord bot delete the message and it says what you said after the prefix like ".say <text>" in Python?
I'm just wondering, how do you make a Discord bot say something using a command like ".say " it deletes the message and then says the "" part. How do you do that in Python? I know how to do this in JavaScript, this is the code I use in Discord.JS:

```<code>const args = message.content.split(" ").slice(1);
if(message.content.startsWith(prefix + 'say')) {
    message.delete()
    var saytext = args.join(" ");
    message.channel.send(saytext)
    fs.appendFile("fbkbotlog.txt", `\n${ts} ${message.author.username} in ${message.guild.id} or ${message.guild.name} used say with text " ${saytext} "`)
}
</code>```

I want to know how to do it in discord.py. I'm not really familiar with Discord.PY or even Python in general.

Note: I'm trying to use the Just-Some-Bots MusicBot code

答:
Basically the same thing:

Using the message event listener (very similar to your JS example)

```<code>import discord
from discord.ext import commands

bot = discord.Client()
prefix = "/"

@bot.event
async def on_ready():
    print("Online")

@bot.event
async def on_message(message):
    args = message.content.split(" ")[1:]
    if message.content.startswith(prefix + "say"):
        await bot.delete_message(message)
        await bot.send_message(message.channel, " ".join(args))

bot.run("token")
</code>```

Using the in-built command handler

```<code>import discord
from discord.ext import commands

prefix = "/"
bot = commands.Bot(prefix)

@bot.event
async def on_ready():
    print("Online")

@bot.command(pass_context = True)
async def say(ctx, *, mg = None):
    await bot.delete_message(ctx.message)

    if not mg: await bot.say("Please specify a message to send")
    else: await bot.say(mg)

bot.run("token")
</code>```

Body:
I'm just wondering, how do you make a Discord bot say something using a command like ".say " it deletes the message and then says the "" part. How do you do that in Python? I know how to do this in JavaScript, this is the code I use in Discord.JS:

const args = message.content.split(" ").slice(1);
if(message.content.startsWith(prefix + 'say')) {
    message.delete()
    var saytext = args.join(" ");
    message.channel.send(saytext)
    fs.appendFile("fbkbotlog.txt", `\n${ts} ${message.author.username} in ${message.guild.id} or ${message.guild.name} used say with text " ${saytext} "`)
}

I want to know how to do it in discord.py. I'm not really familiar with Discord.PY or even Python in general.

Note: I'm trying to use the Just-Some-Bots MusicBot code

Body:
Basically the same thing:

Using the message event listener (very similar to your JS example)

import discord
from discord.ext import commands

bot = discord.Client()
prefix = "/"

@bot.event
async def on_ready():
    print("Online")

@bot.event
async def on_message(message):
    args = message.content.split(" ")[1:]
    if message.content.startswith(prefix + "say"):
        await bot.delete_message(message)
        await bot.send_message(message.channel, " ".join(args))

bot.run("token")

Using the in-built command handler

import discord
from discord.ext import commands

prefix = "/"
bot = commands.Bot(prefix)

@bot.event
async def on_ready():
    print("Online")

@bot.command(pass_context = True)
async def say(ctx, *, mg = None):
    await bot.delete_message(ctx.message)

    if not mg: await bot.say("Please specify a message to send")
    else: await bot.say(mg)

bot.run("token")


问:
Searching for a Key in Multivalue Dictionaries in C#
I want to set up a lookup table like so:

```<code> Key           Value
 -----         ------------------
 Cat           Lion, Tiger, Cheetah
 Fish          Dolphin, Whale
 Dog .         Pitbull, Doberman
</code>```

An input of "Lion" would return the key "Cat"

I have set up 3 possible ways to initialize the data:

A Dictionary:

```<code>var map = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};
</code>```

A HashSet:

```<code>var data = new Dictionary<string, HashSet<string>>
{
    {"cat", new HashSet<string> {"Lion", "Tiger", "Cheetah"}},
    {"fish", new HashSet<string> {"Dolphin", "Whale"}},
    {"Dog", new HashSet<string> {"Pitbull", "Doberman"}}
};
</code>```

A tuple:

```<code>var data = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" }),
    Tuple.Create<string,List<string>> ("Dog", new List<string> { "Doberman", "Pitbull" }),
    Tuple.Create<string,List<string>> ("Fish", new List<string> { "Dolphin", "Whale" }),

};
</code>```

Given an animal, I want to return its type.
I know for the dictionary I can call the ContainsKey method.

Is there something similar for the other two options?

The data set isn't that big, (~15 keys that have 10 or so values), so I'm also wondering if one option would be better than the other in terms of performance.

答:
Personally, this architecture is a bit tricky... I mean, normally the lookup is based on keys, not on values, but I understand that sometimes you need to reverse the common logics and retrieve what you need within a data structure that is adequate in many other situations, except that one!

Anyway, if I was given the choice I would go for the HashSet approach, since it can grant a uniqueness of its values and also an immediate aggregation of the subtypes. But you can eventually run a benchmark and find out the fastest lookup solution in a few minutes.

Using the aforementioned approach (the HashSet one I mean), you can retrieve your type as follows:

```<code>String animalType = data.Where(kvp => kvp.Value.Contains("Dolphin")).Select(p => p.Key).FirstOrDefault();

// Animal type found: Fish!
if (animalType != null)
    Console.WriteLine("Animal type found: " + animalType + "!");
else
    Console.WriteLine("No animal type found!");
</code>```

Body:
I want to set up a lookup table like so:

 Key           Value
 -----         ------------------
 Cat           Lion, Tiger, Cheetah
 Fish          Dolphin, Whale
 Dog .         Pitbull, Doberman

An input of "Lion" would return the key "Cat"

I have set up 3 possible ways to initialize the data:

A Dictionary:

var map = new Dictionary<string,string>
{
    ["Dolphin"] = "Fish",
    ["Lion"] = "Cat",
    //....
};

A HashSet:

var data = new Dictionary<string, HashSet<string>>
{
    {"cat", new HashSet<string> {"Lion", "Tiger", "Cheetah"}},
    {"fish", new HashSet<string> {"Dolphin", "Whale"}},
    {"Dog", new HashSet<string> {"Pitbull", "Doberman"}}
};

A tuple:

var data = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" }),
    Tuple.Create<string,List<string>> ("Dog", new List<string> { "Doberman", "Pitbull" }),
    Tuple.Create<string,List<string>> ("Fish", new List<string> { "Dolphin", "Whale" }),

};

Given an animal, I want to return its type.
I know for the dictionary I can call the ContainsKey method.

Is there something similar for the other two options?

The data set isn't that big, (~15 keys that have 10 or so values), so I'm also wondering if one option would be better than the other in terms of performance.

Body:
Personally, this architecture is a bit tricky... I mean, normally the lookup is based on keys, not on values, but I understand that sometimes you need to reverse the common logics and retrieve what you need within a data structure that is adequate in many other situations, except that one!

Anyway, if I was given the choice I would go for the HashSet approach, since it can grant a uniqueness of its values and also an immediate aggregation of the subtypes. But you can eventually run a benchmark and find out the fastest lookup solution in a few minutes.

Using the aforementioned approach (the HashSet one I mean), you can retrieve your type as follows:

String animalType = data.Where(kvp => kvp.Value.Contains("Dolphin")).Select(p => p.Key).FirstOrDefault();

// Animal type found: Fish!
if (animalType != null)
    Console.WriteLine("Animal type found: " + animalType + "!");
else
    Console.WriteLine("No animal type found!");