问:
How to use the sequence in Server Template and Inline Template Docusign
I saw the example in docusign to do it like so:

Both Server Template and Inline Template have the same sequence number per composite template
Notice:

```<code>CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 1
CompositeTemplate: ServerTemplate Sequence = 2
                   InlineTemplate Sequence = 2

{
    "emailSubject": "DocuSign API - Composite Templates",
    "emailBlurb": "Composite Templates Sample 1",
    "status": "sent",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": "1",
            "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
        }],
        "inlineTemplates": [{
            "sequence": "1",
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "roleName": "Buyer"
                }]
            }
        }]
    }, {
        "serverTemplates": [{
            "sequence": "2",
            "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
        }],
        "inlineTemplates": [{
            "sequence": "2",
            "recipients": {
                "signers": [{
                    "email": "sallydoe@email.com",
                    "name": "Sally Doe",
                    "recipientId": "1",
                    "roleName": "Seller"
                }]
            }
        }]
    }]
}
</code>```

But I also saw in some stack overflow to use it this way:

Multiple Server Templates have the same sequence number, and the inline Templates are the difference

```<code>CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
    {
        "emailSubject": "DocuSign API - Composite Templates",
        "emailBlurb": "Composite Templates Sample 1",
        "status": "sent",
        "compositeTemplates": [{
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "johndoe@email.com",
                        "name": "John Doe",
                        "recipientId": "1",
                        "roleName": "Buyer"
                    }]
                }
            }]
        }, {
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "sallydoe@email.com",
                        "name": "Sally Doe",
                        "recipientId": "1",
                        "roleName": "Seller"
                    }]
                }
            }]
        }]
    }
</code>```

I tried to read the docusign api doc, but still not sure when to use each scenario

答:
Based on my experience, you're correct in suggesting that DocuSign API documentation about the sequence property is somewhat lacking. That said, here's a link to an (older) API documentation page that describes it as good as I've seen it described anywhere:  https://www.docusign.com/p/APIGuide/Content/Sending%20Group/Rules%20for%20CompositeTemplate%20Usage.htm.

As this documentation describes, the purpose of the sequence property in the composite templates structure is to specify the order in which you want DocuSign to apply the templates you specify (ServerTemplates, InlineTemplates, etc.) as it creates the Envelope. Personally, I've always done as the example in the documentation shows, and specified incremental values for sequence throughout the templates that are present in the request body.  In your example, this would mean using the following values:

```<code>CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
CompositeTemplate: ServerTemplate Sequence = 3
                   InlineTemplate Sequence = 4
</code>```

Body:
I saw the example in docusign to do it like so:

Both Server Template and Inline Template have the same sequence number per composite template
Notice:

CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 1
CompositeTemplate: ServerTemplate Sequence = 2
                   InlineTemplate Sequence = 2

{
    "emailSubject": "DocuSign API - Composite Templates",
    "emailBlurb": "Composite Templates Sample 1",
    "status": "sent",
    "compositeTemplates": [{
        "serverTemplates": [{
            "sequence": "1",
            "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
        }],
        "inlineTemplates": [{
            "sequence": "1",
            "recipients": {
                "signers": [{
                    "email": "johndoe@email.com",
                    "name": "John Doe",
                    "recipientId": "1",
                    "roleName": "Buyer"
                }]
            }
        }]
    }, {
        "serverTemplates": [{
            "sequence": "2",
            "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
        }],
        "inlineTemplates": [{
            "sequence": "2",
            "recipients": {
                "signers": [{
                    "email": "sallydoe@email.com",
                    "name": "Sally Doe",
                    "recipientId": "1",
                    "roleName": "Seller"
                }]
            }
        }]
    }]
}

But I also saw in some stack overflow to use it this way:

Multiple Server Templates have the same sequence number, and the inline Templates are the difference

CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
    {
        "emailSubject": "DocuSign API - Composite Templates",
        "emailBlurb": "Composite Templates Sample 1",
        "status": "sent",
        "compositeTemplates": [{
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "55A80182-2E9F-435D-9B16-FD1E1C0F9D74"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "johndoe@email.com",
                        "name": "John Doe",
                        "recipientId": "1",
                        "roleName": "Buyer"
                    }]
                }
            }]
        }, {
            "serverTemplates": [{
                "sequence": "1",
                "templateId": "44D9E888-3D86-4186-8EE9-7071BC87A0DA"
            }],
            "inlineTemplates": [{
                "sequence": "2",
                "recipients": {
                    "signers": [{
                        "email": "sallydoe@email.com",
                        "name": "Sally Doe",
                        "recipientId": "1",
                        "roleName": "Seller"
                    }]
                }
            }]
        }]
    }

I tried to read the docusign api doc, but still not sure when to use each scenario

Body:
Based on my experience, you're correct in suggesting that DocuSign API documentation about the sequence property is somewhat lacking. That said, here's a link to an (older) API documentation page that describes it as good as I've seen it described anywhere:  https://www.docusign.com/p/APIGuide/Content/Sending%20Group/Rules%20for%20CompositeTemplate%20Usage.htm.

As this documentation describes, the purpose of the sequence property in the composite templates structure is to specify the order in which you want DocuSign to apply the templates you specify (ServerTemplates, InlineTemplates, etc.) as it creates the Envelope. Personally, I've always done as the example in the documentation shows, and specified incremental values for sequence throughout the templates that are present in the request body.  In your example, this would mean using the following values:

CompositeTemplate: ServerTemplate Sequence = 1
                   InlineTemplate Sequence = 2
CompositeTemplate: ServerTemplate Sequence = 3
                   InlineTemplate Sequence = 4


来源: stackexchange

问:
Problem pushing to Heroku with dm-migrations
I couldn't find anyone else having this error, so I hope it's not something specific to my machine or something.

```<code>-----> Heroku receiving push
-----> Sinatra app detected

-----> Installing gem data_mapper 1.0.0 from http://rubygems.org
      ERROR:  Error installing data_mapper:
       dm-migrations requires dm-core (~> 1.0.2, runtime)
!     Heroku push rejected, failed to install gem

error: hooks/pre-receive exited with error code 1
To git@heroku.com:episodes.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:episodes.git'
</code>```

I'm using bundler 1.0.7 to manage my dependencies.

Here is my Gemfile:

```<code>source :rubygems
gem 'sinatra', '>= 1.0'
gem 'rake'
gem 'rspec', :require => 'spec'
gem 'data_mapper'
gem 'rack-test'
gem 'dm-core'
gem 'dm-sqlite-adapter'
gem 'dm-timestamps'
gem 'dm-validations'
gem 'dm-aggregates'
gem 'dm-migrations'
gem 'haml'
</code>```

With Gemfile.lock (up-to-date)

```<code>GEM
  remote: http://rubygems.org/
  specs:
    addressable (2.2.3)
    data_mapper (1.0.2)
      dm-aggregates (= 1.0.2)
      dm-constraints (= 1.0.2)
      dm-core (= 1.0.2)
      dm-migrations (= 1.0.2)
      dm-serializer (= 1.0.2)
      dm-timestamps (= 1.0.2)
      dm-transactions (= 1.0.2)
      dm-types (= 1.0.2)
      dm-validations (= 1.0.2)
    data_objects (0.10.2)
      addressable (~> 2.1)
    diff-lcs (1.1.2)
    dm-aggregates (1.0.2)
      dm-core (~> 1.0.2)
    dm-constraints (1.0.2)
      dm-core (~> 1.0.2)
      dm-migrations (~> 1.0.2)
    dm-core (1.0.2)
      addressable (~> 2.2)
      extlib (~> 0.9.15)
    dm-do-adapter (1.0.2)
      data_objects (~> 0.10.2)
      dm-core (~> 1.0.2)
    dm-migrations (1.0.2)
      dm-core (~> 1.0.2)
    dm-serializer (1.0.2)
      dm-core (~> 1.0.2)
      fastercsv (~> 1.5.3)
      json_pure (~> 1.4)
    dm-sqlite-adapter (1.0.2)
      dm-do-adapter (~> 1.0.2)
      do_sqlite3 (~> 0.10.2)
    dm-timestamps (1.0.2)
      dm-core (~> 1.0.2)
    dm-transactions (1.0.2)
      dm-core (~> 1.0.2)
    dm-types (1.0.2)
      dm-core (~> 1.0.2)
      fastercsv (~> 1.5.3)
      json_pure (~> 1.4)
      stringex (~> 1.1.0)
      uuidtools (~> 2.1.1)
    dm-validations (1.0.2)
      dm-core (~> 1.0.2)
    do_sqlite3 (0.10.2)
      data_objects (= 0.10.2)
    do_sqlite3 (0.10.2-x86-mingw32)
      data_objects (= 0.10.2)
    extlib (0.9.15)
    fastercsv (1.5.4)
    haml (3.0.25)
    json_pure (1.4.6)
    rack (1.2.1)
    rack-test (0.5.7)
      rack (>= 1.0)
    rake (0.8.7)
    rspec (2.4.0)
      rspec-core (~> 2.4.0)
      rspec-expectations (~> 2.4.0)
      rspec-mocks (~> 2.4.0)
    rspec-core (2.4.0)
    rspec-expectations (2.4.0)
      diff-lcs (~> 1.1.2)
    rspec-mocks (2.4.0)
    sinatra (1.1.2)
      rack (~> 1.1)
      tilt (~> 1.2)
    stringex (1.1.0)
    tilt (1.2.2)
    uuidtools (2.1.1)

PLATFORMS
  ruby
  x86-mingw32

DEPENDENCIES
  data_mapper
  dm-aggregates
  dm-core
  dm-migrations
  dm-sqlite-adapter
  dm-timestamps
  dm-validations
  haml
  rack-test
  rake
  rspec
  sinatra (>= 1.0)
</code>```

In my actual application, my requires are in this order:

```<code>require 'rubygems'
require 'bundler/setup'
require 'dm-core'
require 'dm-validations'
require 'dm-timestamps'
require 'dm-migrations'
require 'dm-types'
require 'haml'
require 'yaml'
require 'json'
require 'ostruct'
require 'sinatra'
</code>```

Is there anything out of the ordinary that would have Heroku throw this error at me?

答: I think, and I may be wrong, gem 'data_mapper' is like a meta gem. Remove that from list and try</p>

ContentLicense: CC BY-SA 2.5

Body:
I couldn't find anyone else having this error, so I hope it's not something specific to my machine or something.

-----> Heroku receiving push
-----> Sinatra app detected

-----> Installing gem data_mapper 1.0.0 from http://rubygems.org
      ERROR:  Error installing data_mapper:
       dm-migrations requires dm-core (~> 1.0.2, runtime)
!     Heroku push rejected, failed to install gem

error: hooks/pre-receive exited with error code 1
To git@heroku.com:episodes.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:episodes.git'

I'm using bundler 1.0.7 to manage my dependencies.

Here is my Gemfile:

source :rubygems
gem 'sinatra', '>= 1.0'
gem 'rake'
gem 'rspec', :require => 'spec'
gem 'data_mapper'
gem 'rack-test'
gem 'dm-core'
gem 'dm-sqlite-adapter'
gem 'dm-timestamps'
gem 'dm-validations'
gem 'dm-aggregates'
gem 'dm-migrations'
gem 'haml'

With Gemfile.lock (up-to-date)

GEM
  remote: http://rubygems.org/
  specs:
    addressable (2.2.3)
    data_mapper (1.0.2)
      dm-aggregates (= 1.0.2)
      dm-constraints (= 1.0.2)
      dm-core (= 1.0.2)
      dm-migrations (= 1.0.2)
      dm-serializer (= 1.0.2)
      dm-timestamps (= 1.0.2)
      dm-transactions (= 1.0.2)
      dm-types (= 1.0.2)
      dm-validations (= 1.0.2)
    data_objects (0.10.2)
      addressable (~> 2.1)
    diff-lcs (1.1.2)
    dm-aggregates (1.0.2)
      dm-core (~> 1.0.2)
    dm-constraints (1.0.2)
      dm-core (~> 1.0.2)
      dm-migrations (~> 1.0.2)
    dm-core (1.0.2)
      addressable (~> 2.2)
      extlib (~> 0.9.15)
    dm-do-adapter (1.0.2)
      data_objects (~> 0.10.2)
      dm-core (~> 1.0.2)
    dm-migrations (1.0.2)
      dm-core (~> 1.0.2)
    dm-serializer (1.0.2)
      dm-core (~> 1.0.2)
      fastercsv (~> 1.5.3)
      json_pure (~> 1.4)
    dm-sqlite-adapter (1.0.2)
      dm-do-adapter (~> 1.0.2)
      do_sqlite3 (~> 0.10.2)
    dm-timestamps (1.0.2)
      dm-core (~> 1.0.2)
    dm-transactions (1.0.2)
      dm-core (~> 1.0.2)
    dm-types (1.0.2)
      dm-core (~> 1.0.2)
      fastercsv (~> 1.5.3)
      json_pure (~> 1.4)
      stringex (~> 1.1.0)
      uuidtools (~> 2.1.1)
    dm-validations (1.0.2)
      dm-core (~> 1.0.2)
    do_sqlite3 (0.10.2)
      data_objects (= 0.10.2)
    do_sqlite3 (0.10.2-x86-mingw32)
      data_objects (= 0.10.2)
    extlib (0.9.15)
    fastercsv (1.5.4)
    haml (3.0.25)
    json_pure (1.4.6)
    rack (1.2.1)
    rack-test (0.5.7)
      rack (>= 1.0)
    rake (0.8.7)
    rspec (2.4.0)
      rspec-core (~> 2.4.0)
      rspec-expectations (~> 2.4.0)
      rspec-mocks (~> 2.4.0)
    rspec-core (2.4.0)
    rspec-expectations (2.4.0)
      diff-lcs (~> 1.1.2)
    rspec-mocks (2.4.0)
    sinatra (1.1.2)
      rack (~> 1.1)
      tilt (~> 1.2)
    stringex (1.1.0)
    tilt (1.2.2)
    uuidtools (2.1.1)

PLATFORMS
  ruby
  x86-mingw32

DEPENDENCIES
  data_mapper
  dm-aggregates
  dm-core
  dm-migrations
  dm-sqlite-adapter
  dm-timestamps
  dm-validations
  haml
  rack-test
  rake
  rspec
  sinatra (>= 1.0)

In my actual application, my requires are in this order:

require 'rubygems'
require 'bundler/setup'
require 'dm-core'
require 'dm-validations'
require 'dm-timestamps'
require 'dm-migrations'
require 'dm-types'
require 'haml'
require 'yaml'
require 'json'
require 'ostruct'
require 'sinatra'

Is there anything out of the ordinary that would have Heroku throw this error at me?


问:
CozyRoc SSIS, reading email attachment filename?
In a package where I harvest all mail attachments (example found here:cozyroc documentation), I would like to read the attachment filename and according to that, store attachments in different folders.

Anyone knows if and how can I do this using Cozyroc?

答: It doesn't look like there's an easy way to extract the attachment file names from the CozyRoc email object. What I would do is save all attachments to a single "staging" folder, then create a For Each Loop to loop through all the files in that staging folder, and then use File System tasks to move the files.</p>

ContentLicense: CC BY-SA 3.0


问:
create unique links to send to users
I have been tasked with sending out a google forms link to a set of email addresses. I need each link to be unique so that a user can only answer the form once.

Is this possible with google forms?

The emails I send to will not necessarily have google accounts so the "limit to one response" will not be suitable as users will not be able to login to a google account to answer the form.

Many thanks for any pointers

答:
No, its not possible to create unique links to prevent that a user without a Google account submit more than one answer.

Regarding official documentation to support this, there isn't as usually Google only include the supported features. The close that you could find are feature requests on the Google Issue Tracker, posts on the Google Docs Help Forum.

Title: create unique links to send to users


问:
NLTK and PYTHON GRAMMAR
I already have python 2.7 and nltk installed on my system
please and please, how can I make my python program use the below cfg to be attaching part of speech to my sentences??

```<code>N -> 'ọnẹkẹlẹ'|'igbẹlẹ'|'ọma-ọnẹkẹlẹ'
Pr -> 'Omi'|'uwẹ'|'awa'|'ama'|'oñwu'|'I'
Dart -> 'lẹ'
Adj -> 'kẹkẹ'|'nya'|'kpa'
Adv -> 'ọgboolo'|'nyọnyọ'|'lile'
Ord -> 'ejodudu'|'ẹkeji'|'ẹkẹta'
Card -> 'ka'|'meji'|'mẹta'
Quant -> 'wewe'|'gwẹẹ'|'Uchẹkibọ'|'uchẹkibọ'
Dem -> 'dẹi'|'i'|'lẹi'
Poss -> 'mi'|'wa'|'wẹ'|'ñw'|'ma'
</code>```

答:
You can check this sample code from the NLTK book, chapter 8.

```<code>import nltk

grammar1 = nltk.CFG.fromstring("""
S -> NP VP
VP -> V NP | V NP PP
PP -> P NP
V -> "saw" | "ate" | "walked"
NP -> "John" | "Mary" | "Bob" | Det N | Det N PP
Det -> "a" | "an" | "the" | "my"
N -> "man" | "dog" | "cat" | "telescope" | "park"
P -> "in" | "on" | "by" | "with"
""")

sent = "Mary saw Bob".split()
rd_parser = nltk.RecursiveDescentParser(grammar1)
for tree in rd_parser.parse(sent):
    print(tree)
</code>```

output:

(S (NP Mary) (VP (V saw) (NP Bob)))

Title: NLTK and PYTHON GRAMMAR

Body:
I already have python 2.7 and nltk installed on my system
please and please, how can I make my python program use the below cfg to be attaching part of speech to my sentences??

N -> 'ọnẹkẹlẹ'|'igbẹlẹ'|'ọma-ọnẹkẹlẹ'
Pr -> 'Omi'|'uwẹ'|'awa'|'ama'|'oñwu'|'I'
Dart -> 'lẹ'
Adj -> 'kẹkẹ'|'nya'|'kpa'
Adv -> 'ọgboolo'|'nyọnyọ'|'lile'
Ord -> 'ejodudu'|'ẹkeji'|'ẹkẹta'
Card -> 'ka'|'meji'|'mẹta'
Quant -> 'wewe'|'gwẹẹ'|'Uchẹkibọ'|'uchẹkibọ'
Dem -> 'dẹi'|'i'|'lẹi'
Poss -> 'mi'|'wa'|'wẹ'|'ñw'|'ma'

Body:
You can check this sample code from the NLTK book, chapter 8.

import nltk

grammar1 = nltk.CFG.fromstring("""
S -> NP VP
VP -> V NP | V NP PP
PP -> P NP
V -> "saw" | "ate" | "walked"
NP -> "John" | "Mary" | "Bob" | Det N | Det N PP
Det -> "a" | "an" | "the" | "my"
N -> "man" | "dog" | "cat" | "telescope" | "park"
P -> "in" | "on" | "by" | "with"
""")

sent = "Mary saw Bob".split()
rd_parser = nltk.RecursiveDescentParser(grammar1)
for tree in rd_parser.parse(sent):
    print(tree)

output:

(S (NP Mary) (VP (V saw) (NP Bob)))


问:
Simple script running on server and app communicating with it
new to web development and i need some help to figure out the basics.I have a website right now,which is working fine,on a VPS with Ubuntu 16.04 and Apache.Say i would like a converter in my site or in a mobile application and have a python script in my server doing all the work.How can i send the python program the request and how can the page/application receive the data back(like download link,or info like JSON).

A simple information would suffice,i don't need a thorough explanation,mostly names like protocols,etc.. maybe some sample code for Hello World.

I should add that my website runs with Wordpress and i am not looking to change that yet.I want to create a web app within wordpress,with the app written in Python.

答: You could use something like Django or Flask. Both are used for building back end of web apps. </p>


问:
How can I add my seed data to my test database using rake db:seed?
I'm using Factory Girl to populate my seed data and adding it to the db in seed.rb.

I'm then running my tests using Cucumber.

I have a price table that contains seed data that I want in all my environments.

I want rake db:seed to add it to my dev and test db's and for cucumber to be able to use that test seed. Then I'll add that seed data in prod also.

How can I ensure that my seed data is added to both dev and test db's?

```<code>rake db:seed #only adds it only to my dev database
</code>```

答:
You can try something like this:</p>

```<code>rake db:seed RAILS_ENV=test --trace
rake db:seed RAILS_ENV=production --trace
</code>```

Body:
I'm using Factory Girl to populate my seed data and adding it to the db in seed.rb.

I'm then running my tests using Cucumber.

I have a price table that contains seed data that I want in all my environments.

I want rake db:seed to add it to my dev and test db's and for cucumber to be able to use that test seed. Then I'll add that seed data in prod also.

How can I ensure that my seed data is added to both dev and test db's?

rake db:seed #only adds it only to my dev database

Body:
You can try something like this:

rake db:seed RAILS_ENV=test --trace
rake db:seed RAILS_ENV=production --trace


问:
How could I rename the first 5 files in a folder with a different extension while keeping the old ones the same?
I have about 20 files in a folder. I want to rename the extension of the first 5 from .txt to .html. I want to keep the first 5 files with the .txt extension though. Here is what I have so far. It is a bash script</p>

```<code>cp 'ls | head -5 "files would go here I think"
</code>```

答:
```<code>files=(*.txt)
for ((i=0; i<5; i++)); do
    cp -v "${files[i]}" "${files[i]%.txt}.html"
done
</code>```

Body:
I have about 20 files in a folder. I want to rename the extension of the first 5 from .txt to .html. I want to keep the first 5 files with the .txt extension though. Here is what I have so far. It is a bash script

cp 'ls | head -5 "files would go here I think"


问:
Existing website on ubuntu that want to change to deploy using gitosis - process?
I have an existing directory on my webserver, currently deployed to by file copy, that I'd like to change to deploying with gitosis. How can I create a new gitosis repository to point to this web directory and then clone it down to my local machine?</p>

答:
while Arrowmaster is correct in saying that Gitosis has been depreciated in favour of Gitolite there is nothing to say that you cant use git for web deployment, there are loads of people doing it including me. What you need to do is the following, get Gitolite setup and have a working installation whereby you can clone, push and pull into the repositories that Gitolite will create for you. Then it is just a matter of running git init in you existing web directory and then git add . to add all files to it. You then add a gitolite repo as a git remote and git push master into it so you can git clone it to your local machine make allowing you to make changes and push back to the live site.

Essentially you would have a hub repository (gitolite) and prime repository (web directory) these would be lined by means of hooks with within git. I have to point out though that I don't use hooks and manually pull from Gitolite (sudo git pull hub master) on the live machine as I'm not comfortable pushing to a live site in case I think of something I've forgotten.

I take no credit for this setup and owe all knowledge to Joe Maller for his very instructional guide here I have although obviously swapped git for Gitolite.

After a long time messing around and having some success with Gitosis I switched to Gitolite and haven't looked back. I have found it a lot less buggy and more stable in the push/pull permissions department.

I did however have some issues setting Gitolite up and I owe this tutorial a world of thanks for showing me the way forward. It is however for Centos but should be easily ported to Ubuntu.

If you do decide to go the gitosis route then maybe this tutorial will help you with the installation.

Good luck.

seanl


问:
How can I use the hide/show toggle when clicking on text?
I would like to click on the first line of text, which will then expand the rest of the paragraph. But I also want to be able to close the text by clicking on that same first line again. I have written some code for it, but I am very elementary in JS. I would appreciate getting help on this. Thank you.

Here's my JSFiddle: http://jsfiddle.net/JUtcX/868/

$('.expand').each(function() {
  var reducedHeight = $(this).height();
  $(this).css('height', 'auto');
  var fullHeight = $(this).height();
  $(this).height(reducedHeight);

  $(this).data('reducedHeight', reducedHeight);
  $(this).data('fullHeight', fullHeight);
}).click(function() {
  $(this).animate({
    height: $(this).height() ==
      $(this).data('reducedHeight') ? $(this).data('fullHeight') : $(this).data('reducedHeight')
  }, 500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.expand {
  height: 14pt;
  padding: 2px;
  overflow: hidden
}</code>```

  The day after his forty-eighth birthday was the same day Theo Bitner’s seventy-five-year-old mother Friended him on Facebook. It was also the same day his wife told him he needed to see a doctor. Or a therapist. “It’s your mood,” she said. “It sucks.”

```

答:
You can try toggle()
http://jsfiddle.net/JUtcX/870/

jQuery

```<code>$('.firstLine').click(function (){
$('.secondLine').toggle();
});
</code>```

HTML

```<code><div class="firstLine">
The day after his forty-eighth birthday was the same day Theo Bitner’s
seventy-five-year-old mother Friended him on Facebook.

<div class="secondLine">
It was also the same day his wife told him he needed to see a doctor. Or a
therapist. “It’s your mood,” she said. “It sucks.” </div>
</div>
</code>```

CSS

```<code>.secondLine {display: none;}
</code>```

Body:
I would like to click on the first line of text, which will then expand the rest of the paragraph. But I also want to be able to close the text by clicking on that same first line again. I have written some code for it, but I am very elementary in JS. I would appreciate getting help on this. Thank you.

Here's my JSFiddle: http://jsfiddle.net/JUtcX/868/

$('.expand').each(function() {
  var reducedHeight = $(this).height();
  $(this).css('height', 'auto');
  var fullHeight = $(this).height();
  $(this).height(reducedHeight);

  $(this).data('reducedHeight', reducedHeight);
  $(this).data('fullHeight', fullHeight);
}).click(function() {
  $(this).animate({
    height: $(this).height() ==
      $(this).data('reducedHeight') ? $(this).data('fullHeight') : $(this).data('reducedHeight')
  }, 500);
});

.expand {
  height: 14pt;
  padding: 2px;
  overflow: hidden
}

  The day after his forty-eighth birthday was the same day Theo Bitner’s seventy-five-year-old mother Friended him on Facebook. It was also the same day his wife told him he needed to see a doctor. Or a therapist. “It’s your mood,” she said. “It sucks.”

Body:
You can try toggle()
http://jsfiddle.net/JUtcX/870/

jQuery

$('.firstLine').click(function (){
$('.secondLine').toggle();
});

HTML

<div class="firstLine">
The day after his forty-eighth birthday was the same day Theo Bitner’s
seventy-five-year-old mother Friended him on Facebook.

<div class="secondLine">
It was also the same day his wife told him he needed to see a doctor. Or a
therapist. “It’s your mood,” she said. “It sucks.” </div>
</div>

CSS

.secondLine {display: none;}


问:
Neo4j-shell not working on Mac Community edition 3.3.0
I'm new to Neo4j and have installed the Community Edition (3.3.0).  I'm working through tutorials that reference neo4j-shell.  However, every time I try to run it I get:

```<code>-bash: /usr/local/bin/neo4j-shell: No such file or directory
</code>```

I tried to run the Desktop version and use its terminal, but get the same thing.  I even installed it with Homebrew (have since uninstalled) and it seemed to respond but could not connect to anything even when I used the appropriate switches.  I've also tried things I've found searching here and within the Google Group to no avail.

Could anyone please let me know how to get this running with Community Edition, or if not possible, please let me know how to otherwise.  I'm running on a Mac and installed using the .dmg file.

Thanks in advance for your help.

Greg

答:
neo4j-shell is deprecated since version 3.0, and you should use the cypher-shell instead.

You can still use neo4j-shell if you want, but you need to add the following key into neo4.conf file : dbms.shell.enabled=true.

All the Neo4j's console tools are located under the NEO4J_HOME/bin folder.

If you use the Desktop edition, as you have seen, there a tab to have a console, and you are directly under the NEO4J_HOME.

I'm not an expert on MacOS, but normally the dmg package should unpack Neo4j somewhere on your filesystem.

You can also use the unix version on MacOS

Body:
I'm new to Neo4j and have installed the Community Edition (3.3.0).  I'm working through tutorials that reference neo4j-shell.  However, every time I try to run it I get:

-bash: /usr/local/bin/neo4j-shell: No such file or directory

I tried to run the Desktop version and use its terminal, but get the same thing.  I even installed it with Homebrew (have since uninstalled) and it seemed to respond but could not connect to anything even when I used the appropriate switches.  I've also tried things I've found searching here and within the Google Group to no avail.

Could anyone please let me know how to get this running with Community Edition, or if not possible, please let me know how to otherwise.  I'm running on a Mac and installed using the .dmg file.

Thanks in advance for your help.

Greg


问:
How to extend a module from npm using TypeScript?
I'm using joi and @types/joi with TypeScript. Joi has an extend method which allows extending joi by returning a new instance without modifying original joi library. I created an extended instance with it.

To create definition for this extended instance, I tried Module Augmentation as described here using code below:

```<code>declare module 'joi' {
  // Add a new Schema type which has noChildren() method.
  interface CustomSchema extends ObjectSchema {
    noChildren(): this;
  }
}
</code>```

However, as expected, this modifies original definition by augmenting it. What I want is to create definitions for the extended instance which inherits everything from original without modifying it.

Also extended Joi is created as below:

```<code>import * as Joi from 'joi';
const JoiExtended = Joi.extend({...some implementation...})
// How to export?
// export * from 'Joi' ---> In this case, original non-extended Joi is exported
// export default JoiExtended ---> Imported `Joi` reports: Cannot find namespace 'Joi'
</code>```

How can I create extended definitions?

How to export extended Joi?

P.S. I'm learning TypeScript and searched for an answer for this question but couldn't find an answer, maybe, because I'm not accustomed to typescript terminology and search for wrong terms.

答:
Joi.extend returns a new instance of the joi module for which you can use the exported Root type.

You'll need to create an interface that extends Joi.Root and another that extends the base joi type that you're extending. You can simply export your custom joi instance like you would any other object.

Below is an example using the round() and dividable() rules from the API Documentation examples on extend().

```<code>import * as Joi from 'joi';

interface ExtendedNumberSchema extends Joi.NumberSchema {
    round(): this;
    dividable(num: number): this;
}

interface ExtendedJoi extends Joi.Root {
    number(): ExtendedNumberSchema;
}

const customJoi: ExtendedJoi = Joi.extend((joi) => ({
    base: joi.number(),
    name: 'number',
    language: {
        round: 'needs to be a rounded number', // Used below as 'number.round'
        dividable: 'needs to be dividable by {{q}}'
    },
    pre(value, state, options) {

        if (options.convert && this._flags.round) {
            return Math.round(value); // Change the value
        }

        return value; // Keep the value as it was
    },
    rules: [
        {
            name: 'round',
            setup(params) {

                this._flags.round = true; // Set a flag for later use
            },
            validate(params, value, state, options) {

                if (value % 1 !== 0) {
                    // Generate an error, state and options need to be passed
                    return this.createError('number.round', {v: value}, state, options);
                }

                return value; // Everything is OK
            }
        },
        {
            name: 'dividable',
            params: {
                q: joi.alternatives([joi.number().required(), joi.func().ref()])
            },
            validate(params, value, state, options) {

                if (value % params.q !== 0) {
                    // Generate an error, state and options need to be passed, q is used in the language
                    return this.createError('number.dividable', {v: value, q: params.q}, state, options);
                }

                return value; // Everything is OK
            }
        }
    ]
}));

const schema = {
    a: customJoi.number().round().dividable(3)
};

const result = customJoi.validate({a: 4.1}, schema); // will fail because 4 is no divisible by 3

console.log(result);

export = customJoi;
</code>```

Body:
I'm using joi and @types/joi with TypeScript. Joi has an extend method which allows extending joi by returning a new instance without modifying original joi library. I created an extended instance with it.

To create definition for this extended instance, I tried Module Augmentation as described here using code below:

declare module 'joi' {
  // Add a new Schema type which has noChildren() method.
  interface CustomSchema extends ObjectSchema {
    noChildren(): this;
  }
}

However, as expected, this modifies original definition by augmenting it. What I want is to create definitions for the extended instance which inherits everything from original without modifying it.

Also extended Joi is created as below:

import * as Joi from 'joi';
const JoiExtended = Joi.extend({...some implementation...})
// How to export?
// export * from 'Joi' ---> In this case, original non-extended Joi is exported
// export default JoiExtended ---> Imported `Joi` reports: Cannot find namespace 'Joi'

How can I create extended definitions?

How to export extended Joi?

P.S. I'm learning TypeScript and searched for an answer for this question but couldn't find an answer, maybe, because I'm not accustomed to typescript terminology and search for wrong terms.

Body:
Joi.extend returns a new instance of the joi module for which you can use the exported Root type.

You'll need to create an interface that extends Joi.Root and another that extends the base joi type that you're extending. You can simply export your custom joi instance like you would any other object.

Below is an example using the round() and dividable() rules from the API Documentation examples on extend().

import * as Joi from 'joi';

interface ExtendedNumberSchema extends Joi.NumberSchema {
    round(): this;
    dividable(num: number): this;
}

interface ExtendedJoi extends Joi.Root {
    number(): ExtendedNumberSchema;
}

const customJoi: ExtendedJoi = Joi.extend((joi) => ({
    base: joi.number(),
    name: 'number',
    language: {
        round: 'needs to be a rounded number', // Used below as 'number.round'
        dividable: 'needs to be dividable by {{q}}'
    },
    pre(value, state, options) {

        if (options.convert && this._flags.round) {
            return Math.round(value); // Change the value
        }

        return value; // Keep the value as it was
    },
    rules: [
        {
            name: 'round',
            setup(params) {

                this._flags.round = true; // Set a flag for later use
            },
            validate(params, value, state, options) {

                if (value % 1 !== 0) {
                    // Generate an error, state and options need to be passed
                    return this.createError('number.round', {v: value}, state, options);
                }

                return value; // Everything is OK
            }
        },
        {
            name: 'dividable',
            params: {
                q: joi.alternatives([joi.number().required(), joi.func().ref()])
            },
            validate(params, value, state, options) {

                if (value % params.q !== 0) {
                    // Generate an error, state and options need to be passed, q is used in the language
                    return this.createError('number.dividable', {v: value, q: params.q}, state, options);
                }

                return value; // Everything is OK
            }
        }
    ]
}));

const schema = {
    a: customJoi.number().round().dividable(3)
};

const result = customJoi.validate({a: 4.1}, schema); // will fail because 4 is no divisible by 3

console.log(result);

export = customJoi;


问:
Canvas - Isometric view by transform, determine which tile is mouse on
I'm trying to make actual hover on tiles when the canvas is transformed.

Problem image

What is working

The render function:

```<code>ctx.save()
ctx.transform(1, 0.5, -1, 0.5, 250, 150)
// ctx.setTransform(1, 0.5, -1, 0.5, 250, 150)

Terrain.forEach((line, lineNumber) => {
  line.forEach((tile, blockNumber) => {
    const block = new Block({
      ...resolveBlock(tile),
      position: {
        x: blockNumber * 32 + 250,
        y: lineNumber * 32
      },
      size: {
        width: 32,
        height: 32
      }
    })

    // check if the mouse position is on tile
    block.mousePos(frameNow)
    block.render()
  })
})

ctx.restore()
</code>```

The mousePos function which is working on

```<code>ctx.rotate(Math.PI / 4)
</code>```

but not on the full ctx.transform(...) or even ctx.scale(1, 0.5)

```<code>function mousePos() {
  let currentX =
    mousePos.x * Math.cos(-(Math.PI / 4)) -
    mousePos.y * Math.sin(-(Math.PI / 4))

  let currentY =
    mousePos.x * Math.sin(-(Math.PI / 4)) +
    mousePos.y * Math.cos(-(Math.PI / 4))

  if (
    currentX >= this.position.x &&
    currentX <= this.position.x + this.size.width - 1 &&
    currentY >= this.position.y &&
    currentY <= this.position.y + this.size.height - 1
  ) { // change color of hovered tile... }
}
</code>```

Thanks for your time.

答:
Found the solution after some brainstorming; find the mouse position after transform</p>

```<code>const invertedTransform = ctx.mozCurrentTransformInverse()
// sadly there is no currentTransformInverse in all browsers yet

const wX =
  mousePos.x * invertedTransform.a +
  mousePos.y +
  invertedTransform.c +
  invertedTransform.e

const wY =
  mousePos.x * invertedTransform.b +
  mousePos.y +
  invertedTransform.d +
  invertedTransform.f
</code>```

Body:
I'm trying to make actual hover on tiles when the canvas is transformed.

Problem image

What is working

The render function:

ctx.save()
ctx.transform(1, 0.5, -1, 0.5, 250, 150)
// ctx.setTransform(1, 0.5, -1, 0.5, 250, 150)

Terrain.forEach((line, lineNumber) => {
  line.forEach((tile, blockNumber) => {
    const block = new Block({
      ...resolveBlock(tile),
      position: {
        x: blockNumber * 32 + 250,
        y: lineNumber * 32
      },
      size: {
        width: 32,
        height: 32
      }
    })

    // check if the mouse position is on tile
    block.mousePos(frameNow)
    block.render()
  })
})

ctx.restore()

The mousePos function which is working on

ctx.rotate(Math.PI / 4)

but not on the full ctx.transform(...) or even ctx.scale(1, 0.5)

function mousePos() {
  let currentX =
    mousePos.x * Math.cos(-(Math.PI / 4)) -
    mousePos.y * Math.sin(-(Math.PI / 4))

  let currentY =
    mousePos.x * Math.sin(-(Math.PI / 4)) +
    mousePos.y * Math.cos(-(Math.PI / 4))

  if (
    currentX >= this.position.x &&
    currentX <= this.position.x + this.size.width - 1 &&
    currentY >= this.position.y &&
    currentY <= this.position.y + this.size.height - 1
  ) { // change color of hovered tile... }
}

Thanks for your time.

Body:
Found the solution after some brainstorming; find the mouse position after transform

const invertedTransform = ctx.mozCurrentTransformInverse()
// sadly there is no currentTransformInverse in all browsers yet

const wX =
  mousePos.x * invertedTransform.a +
  mousePos.y +
  invertedTransform.c +
  invertedTransform.e

const wY =
  mousePos.x * invertedTransform.b +
  mousePos.y +
  invertedTransform.d +
  invertedTransform.f


问:
Interactive Report Varchar2 Limit? (APEX 5.0)
I have 2 interactive reports that display on a page, a report that shows the data of forms submitted, and a file report that shows the files inserted. The main report has 9 columns, the majority being VARCHAR2(4000). The longest value we have in there though is 1110 characters. But we keep getting the ORA-06502: PL/SQL Numeric or Value Error: Character string too small. If we don't display these columns, everything is fine. From what I can gather, an Interactive Report row has a limit of 32k, but we shouldn't be close to breaking 8k per row.

What are the actual limits for Interactive Reports, because I can't find anything solid.

答: Limit is 32K per row and it includes column values and HTML text that gets generated for each row of interactive report.  Try removing links or custom HTML, if any.</p>


问:
Java maven project building with clean, install, run as
Many times I find that for my changes to take effect while working on a Maven/java project I need to Maven clean -> Maven install -> run as ..

How can I automate this in Eclipse?
So every time Im running the application it would clean, install then run

答: If you select option 5 "Maven build...", you will get a window where you can specify different goals. Put in clean install and click Run. This will create a new menu item (which you can also name) in the "Run As..." menu.


问:
Huge number of files generated for every Angular project
I wanted to start a simple hello world app for Angular.

When I followed the instructions in the official quickstart the installation created 32,000 files in my project.

I figured this is some mistake or I missed something, so I decided to use angular-cli, but after setting up the project I counted 41,000 files.

Where did I go wrong? Am I missing something really really obvious?

答:
if you use Angular CLI you can always use --minimal flag when you create a project

```<code>ng new name --minimal
</code>```

I've just run it with the flag and it creates 24 600 files and ng build --prod produces 212 KB dist folder

So if you don't need water fountains in your project or just want to quickly test something out this I think is pretty useful

Body:
if you use Angular CLI you can always use --minimal flag when you create a project

ng new name --minimal

I've just run it with the flag and it creates 24 600 files and ng build --prod produces 212 KB dist folder

So if you don't need water fountains in your project or just want to quickly test something out this I think is pretty useful


问:
What's the correct data design for recording the results of generic two player game?
Assume the game has two players.  Each player has a score and highest score wins.  A user table is self evident.  The first design I thought of is as follows:

match_id, user1_id, user2_id, score1, score2

The problem is suppose I want a quick way of ranking users by win %.  In the above table a single userid would be scattered between user1_id and user2_id.  It would seem to require multiple queries and seems messy.  The other way is to keep a separate stats table

user_id, winloss

This makes queries easy but doesn't seem theoretically correct because the stats table stores derive data.  Is there a way to solve this which involves a nice, clean theoretically correct data structure which is easy to query?

答:
How about have one record for each user in a match? The primary key is then the combination of match_id and user_id. Also include a boolean winner field.

match_id, user_id, score, winner

Though not part of your requirement, this also easily scales up to more players.

Querying win % is simply a matter of:

```<code>SELECT winner, count(winner) FROM match_results
WHERE user_id = (some_user) GROUP BY winner;
</code>```

Body:
How about have one record for each user in a match? The primary key is then the combination of match_id and user_id. Also include a boolean winner field.

match_id, user_id, score, winner

Though not part of your requirement, this also easily scales up to more players.

Querying win % is simply a matter of:

SELECT winner, count(winner) FROM match_results
WHERE user_id = (some_user) GROUP BY winner;


问:
Optional deconstruction function parameter
How do you modify the function below to make the second parameter optional?

TypeScript:

```<code>function getName(name: string, {
    lastName
  }: {
    lastName: string
  }) {
  // ...
}

getName('John'); // error
</code>```

Update:

The solution I've found so far is to take out the deconstruction into the function body:

```<code>function getName(name: string, options: {
    lastName: string
  } = {} as any) {
    const { lastName } = options;
    // ...
}

getName('John'); // OK
</code>```

However, I still cannot find how to make it work in this context:

```<code>const getName = Bluebird.coroutine(function* co(name: string,
  {
    lastName
  }: {
    lastName: string
  }) {
    // ...
});

getName('John'); // error

/* -------- DECLARATIONS -------- */

declare namespace Bluebird {
    interface CoroutineOptions {
        yieldHandler(value: any): any;
    }
}

declare class Bluebird<R> {
    static coroutine<T, A1, A2>(
        generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
        options?: Bluebird.CoroutineOptions
    ): (a1: A1, a2: A2) => Bluebird<T>;
}
</code>```

Moving the deconstruction to the function body still gives an error:

```<code>const getName = Bluebird.coroutine(function* co(name: string, options: {
    lastName: string
  } = {} as any) {
    // ...
});

getName('John'); // error: Expected 2 arguments but got 1.
</code>```

答:
options = {} should work?

function getName(name: string, options = {}) {}

Body:
How do you modify the function below to make the second parameter optional?

TypeScript:

function getName(name: string, {
    lastName
  }: {
    lastName: string
  }) {
  // ...
}

getName('John'); // error

Update:

The solution I've found so far is to take out the deconstruction into the function body:

function getName(name: string, options: {
    lastName: string
  } = {} as any) {
    const { lastName } = options;
    // ...
}

getName('John'); // OK

However, I still cannot find how to make it work in this context:

const getName = Bluebird.coroutine(function* co(name: string,
  {
    lastName
  }: {
    lastName: string
  }) {
    // ...
});

getName('John'); // error

/* -------- DECLARATIONS -------- */

declare namespace Bluebird {
    interface CoroutineOptions {
        yieldHandler(value: any): any;
    }
}

declare class Bluebird<R> {
    static coroutine<T, A1, A2>(
        generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
        options?: Bluebird.CoroutineOptions
    ): (a1: A1, a2: A2) => Bluebird<T>;
}

Moving the deconstruction to the function body still gives an error:

const getName = Bluebird.coroutine(function* co(name: string, options: {
    lastName: string
  } = {} as any) {
    // ...
});

getName('John'); // error: Expected 2 arguments but got 1.


问:
print value shown as none
I'm wondering why the variable lengthOfList can store len(l) but the variable reverseOfList cannot store a method being called on a list.
If I call l.reverse() and print(l) I can see the reverse but why can't the reversed list be stored in a variable?

Please see example code below.

```<code>    l = [1,2,3]

    lengthOfList = len(l) #3

    reverseOfList = l.reverse() # Global frame None

    print(reverseOfList) #None
</code>```

答:
From Python documentation:

list.reverse()

    Reverse the elements of the list in place.

This means the list is reversed in place, and the function returns None

You should try

```<code>>>> l = [1, 2, 3]
>>> l.reverse()
>>> print(l)
[3, 2, 1]
</code>```

Title: print value shown as none

Body:
I'm wondering why the variable lengthOfList can store len(l) but the variable reverseOfList cannot store a method being called on a list.
If I call l.reverse() and print(l) I can see the reverse but why can't the reversed list be stored in a variable?

Please see example code below.

    l = [1,2,3]

    lengthOfList = len(l) #3

    reverseOfList = l.reverse() # Global frame None

    print(reverseOfList) #None

Body:
From Python documentation:

list.reverse()

    Reverse the elements of the list in place.

This means the list is reversed in place, and the function returns None

You should try

>>> l = [1, 2, 3]
>>> l.reverse()
>>> print(l)
[3, 2, 1]


问:
How do you split data from a textfile on an array list?
I am trying to code an array list that contains information from a text file that should add all the characters of the names together to give me a total. I have done it but it adds the spaces to, i have tried using .split(" "); but it still didnt work.
here is my code so far

```<code>    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        tempLatinName.split(" ");
        latinLength = tempLatinName;
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);
</code>```

any suggestions?

答:
based from here

have you tried the following:

tempLatinName.split(' ');

or

tempLatinName.split();

Body:
I am trying to code an array list that contains information from a text file that should add all the characters of the names together to give me a total. I have done it but it adds the spaces to, i have tried using .split(" "); but it still didnt work.
here is my code so far

    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        tempLatinName.split(" ");
        latinLength = tempLatinName;
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);

any suggestions?


问:
Ember Expected property shorthand object-shorthand
I have an action in one of my Ember controllers where I am making a call to my backend, and ESLint is giving me an error

Ember Expected property shorthand  object-shorthand

in the AJAX data for 'preserve': preserve

I'm new to Ember, and somewhat new to ES6 syntax, so I'm not entirely sure how this chunk of code could be made any more 'shorthand'.

Controller

```<code>merge(preserve) {
      let experienceIdList = [];

      // To-Do Make this a computed property
      get(this, 'model.experiences').forEach(function(experience) {
        experienceIdList.pushObject(experience.id);
      });

      $.ajax({
        url: `${config.EmberENV.API_HOST}/api/v0.1/experiences/merge/`,
        type: 'POST',
        data: {
          'experience_ids': experienceIdList,
          'name': get(this, 'model.newExperience.name'),
          'preserve': preserve,
          'moduleExperience': get(this, 'moduleExperience')
        }
      }).then(() => {
        this.transitionToRoute('authenticated.experiences');
      }).catch(function(error) {
        this.set('errorMessage', error.error || error);
      });
    }
</code>```

答:
Following the ESLint documentation on object-shorthand change

```<code>'preserve': preserve,
</code>```

to

```<code> preserve,
</code>```

so the full object declaration of data should be:

```<code> data: {
      'experience_ids': experienceIdList,
      'name': get(this, 'model.newExperience.name'),
      preserve,
      'moduleExperience': get(this, 'moduleExperience')
}
</code>```

Note, that you can change this behavior in the es-lint options which you will find in this file: .eslintrc.js (in ember-root)

Body:
I have an action in one of my Ember controllers where I am making a call to my backend, and ESLint is giving me an error

Ember Expected property shorthand  object-shorthand

in the AJAX data for 'preserve': preserve

I'm new to Ember, and somewhat new to ES6 syntax, so I'm not entirely sure how this chunk of code could be made any more 'shorthand'.

Controller

merge(preserve) {
      let experienceIdList = [];

      // To-Do Make this a computed property
      get(this, 'model.experiences').forEach(function(experience) {
        experienceIdList.pushObject(experience.id);
      });

      $.ajax({
        url: `${config.EmberENV.API_HOST}/api/v0.1/experiences/merge/`,
        type: 'POST',
        data: {
          'experience_ids': experienceIdList,
          'name': get(this, 'model.newExperience.name'),
          'preserve': preserve,
          'moduleExperience': get(this, 'moduleExperience')
        }
      }).then(() => {
        this.transitionToRoute('authenticated.experiences');
      }).catch(function(error) {
        this.set('errorMessage', error.error || error);
      });
    }

Body:
Following the ESLint documentation on object-shorthand change

'preserve': preserve,

to

 preserve,

so the full object declaration of data should be:

 data: {
      'experience_ids': experienceIdList,
      'name': get(this, 'model.newExperience.name'),
      preserve,
      'moduleExperience': get(this, 'moduleExperience')
}

Note, that you can change this behavior in the es-lint options which you will find in this file: .eslintrc.js (in ember-root)


问:
Spark: StringIndexer on sentences
I am trying to do something StringIndexer on a column of sentences, i.e. transforming list of words to list of integers.

For example:

input dataset:

```<code>  (1, ["I", "like", "Spark"])
  (2, ["I", "hate", "Spark"])
</code>```

I expected the output after StringIndexer to be like:

```<code>  (1, [0, 2, 1])
  (2, [0, 3, 1])
</code>```

Ideally, I would like to make such transformation as part of Pipeline, so that I can chain couple transformer together and serialize for online serving.

Is this something Spark support natively?

Thank you!

答:
Standard Transformers used for converting text to features are CountVectorizer

CountVectorizer and CountVectorizerModel aim to help convert a collection of text documents to vectors of token counts.

or HashingTF:

Maps a sequence of terms to their term frequencies using the hashing trick. Currently we use Austin Appleby's MurmurHash 3 algorithm (MurmurHash3_x86_32) to calculate the hash code value for the term object. Since a simple modulo is used to transform the hash function to a column index, it is advisable to use a power of two as the numFeatures parameter; otherwise the features will not be mapped evenly to the columns.

Both have binary option which can used to switch from count to binary vector.

There is no builtin Transfomer that can give exact result you want (it wouldn't be useful for ML algorithms) buy you can explode apply StringIndexer,  and collect_list / collect_set:

```<code>import org.apache.spark.ml.feature._
import org.apache.spark.ml.Pipeline

val df = Seq(
  (1, Array("I", "like", "Spark")), (2, Array("I", "hate", "Spark"))
).toDF("id", "words")

val pipeline = new Pipeline().setStages(Array(
  new SQLTransformer()
    .setStatement("SELECT id, explode(words) as word FROM __THIS__"),
  new StringIndexer().setInputCol("word").setOutputCol("index"),
  new SQLTransformer()
    .setStatement("""SELECT id, COLLECT_SET(index) AS values
                     FROM __THIS__ GROUP BY id""")
))

pipeline.fit(df).transform(df).show

// +---+---------------+
// | id|         values|
// +---+---------------+
// |  1|[0.0, 1.0, 3.0]|
// |  2|[2.0, 0.0, 1.0]|
// +---+---------------+
</code>```

With CountVectorizer and udf:

```<code>import org.apache.spark.ml.linalg._

spark.udf.register("indices", (v: Vector) => v.toSparse.indices)

val pipeline = new Pipeline().setStages(Array(
  new CountVectorizer().setInputCol("words").setOutputCol("vector"),
  new SQLTransformer()
    .setStatement("SELECT *, indices(vector) FROM __THIS__")
))

pipeline.fit(df).transform(df).show

// +---+----------------+--------------------+-------------------+
// | id|           words|              vector|UDF:indices(vector)|
// +---+----------------+--------------------+-------------------+
// |  1|[I, like, Spark]|(4,[0,1,3],[1.0,1...|          [0, 1, 3]|
// |  2|[I, hate, Spark]|(4,[0,1,2],[1.0,1...|          [0, 1, 2]|
// +---+----------------+--------------------+-------------------+
</code>```

Title: Spark: StringIndexer on sentences

Body:
I am trying to do something StringIndexer on a column of sentences, i.e. transforming list of words to list of integers.

For example:

input dataset:

  (1, ["I", "like", "Spark"])
  (2, ["I", "hate", "Spark"])

I expected the output after StringIndexer to be like:

  (1, [0, 2, 1])
  (2, [0, 3, 1])

Ideally, I would like to make such transformation as part of Pipeline, so that I can chain couple transformer together and serialize for online serving.

Is this something Spark support natively?

Thank you!

Body:
Standard Transformers used for converting text to features are CountVectorizer

CountVectorizer and CountVectorizerModel aim to help convert a collection of text documents to vectors of token counts.

or HashingTF:

Maps a sequence of terms to their term frequencies using the hashing trick. Currently we use Austin Appleby's MurmurHash 3 algorithm (MurmurHash3_x86_32) to calculate the hash code value for the term object. Since a simple modulo is used to transform the hash function to a column index, it is advisable to use a power of two as the numFeatures parameter; otherwise the features will not be mapped evenly to the columns.

Both have binary option which can used to switch from count to binary vector.

There is no builtin Transfomer that can give exact result you want (it wouldn't be useful for ML algorithms) buy you can explode apply StringIndexer,  and collect_list / collect_set:

import org.apache.spark.ml.feature._
import org.apache.spark.ml.Pipeline

val df = Seq(
  (1, Array("I", "like", "Spark")), (2, Array("I", "hate", "Spark"))
).toDF("id", "words")

val pipeline = new Pipeline().setStages(Array(
  new SQLTransformer()
    .setStatement("SELECT id, explode(words) as word FROM __THIS__"),
  new StringIndexer().setInputCol("word").setOutputCol("index"),
  new SQLTransformer()
    .setStatement("""SELECT id, COLLECT_SET(index) AS values
                     FROM __THIS__ GROUP BY id""")
))

pipeline.fit(df).transform(df).show

// +---+---------------+
// | id|         values|
// +---+---------------+
// |  1|[0.0, 1.0, 3.0]|
// |  2|[2.0, 0.0, 1.0]|
// +---+---------------+

With CountVectorizer and udf:

import org.apache.spark.ml.linalg._

spark.udf.register("indices", (v: Vector) => v.toSparse.indices)

val pipeline = new Pipeline().setStages(Array(
  new CountVectorizer().setInputCol("words").setOutputCol("vector"),
  new SQLTransformer()
    .setStatement("SELECT *, indices(vector) FROM __THIS__")
))

pipeline.fit(df).transform(df).show

// +---+----------------+--------------------+-------------------+
// | id|           words|              vector|UDF:indices(vector)|
// +---+----------------+--------------------+-------------------+
// |  1|[I, like, Spark]|(4,[0,1,3],[1.0,1...|          [0, 1, 3]|
// |  2|[I, hate, Spark]|(4,[0,1,2],[1.0,1...|          [0, 1, 2]|
// +---+----------------+--------------------+-------------------+


问:
Error: Method “props” is only meant to be run on a single node. 2 found instead
```<code>it('should call setCampaignDate on click', function () {
    let spySetCampaign = sinon.spy(wrapper.instance(), 'setCampaignDate');
    let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker);
    assert.equal(datePickers.length, 2);
    console.log(datePickers);
    var date = new Date();

    for (let index = 0; index < datePickers.length; index++) {
      datePickers.simulate('change');
      sinon.assert.calledOnce(spySetCampaign.withArgs(date, 'startDate'));
    }

  });
</code>```

I am trying to simulate my 'change' function and trying to test whether 'setCampaignDate' is called or not. The problem here is that the length of my shallow component returned by find is 2:

```<code>let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker);
</code>```

When trying to call simulate on 'datepickers', it gives an error as below:

'Error: Method “props” is only meant to be run on a single node. 2 found instead.'.

Not sure how to simulate on components having nodes greater than 1.

答:
The answer for multiple components without changing your code is to use the enzyme API to get the correct index of the button you want.

```<code>wrapper.find(Component).at(index).simulate('click');
</code>```

With component being the name of whatever you're testing and index being the number you want.

Body:
it('should call setCampaignDate on click', function () {
    let spySetCampaign = sinon.spy(wrapper.instance(), 'setCampaignDate');
    let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker);
    assert.equal(datePickers.length, 2);
    console.log(datePickers);
    var date = new Date();

    for (let index = 0; index < datePickers.length; index++) {
      datePickers.simulate('change');
      sinon.assert.calledOnce(spySetCampaign.withArgs(date, 'startDate'));
    }

  });

I am trying to simulate my 'change' function and trying to test whether 'setCampaignDate' is called or not. The problem here is that the length of my shallow component returned by find is 2:

let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker);

When trying to call simulate on 'datepickers', it gives an error as below:

'Error: Method “props” is only meant to be run on a single node. 2 found instead.'.

Not sure how to simulate on components having nodes greater than 1.

Body:
The answer for multiple components without changing your code is to use the enzyme API to get the correct index of the button you want.

wrapper.find(Component).at(index).simulate('click');

With component being the name of whatever you're testing and index being the number you want.


问:
What's the de facto practice on ampersand encoding in HTML?
By the HTML specification, an ampersand should be encoded as

```<code>&
</code>```

But of course a lot on the web doesn't do that. Here's an example of an ad widget from Amazon.com:

```<code><iframe
    src="http://rcm.amazon.com/e/cm?t=xyzxyz-20&o=1&p=11&l=ur1&category=textbooks&banner=17P1AE8RQ1T7ZFC62V82&f=ifr"
    width="120"
    height="600"
    scrolling="no"
    border="0"
    marginwidth="0"
    style="border:none;"
    frameborder="0">
</iframe>
</code>```

Note that the ampersand is not encoded.

For those work a lot with commercial sites, work in a company, or work with many widget codes, do most of these sites actually encode the ampersand?

(In other words, what percentage of top 1k sites try to encode ampersand properly when it is in the URL?)

Stress: this is not about whether it should or should not be encoded. I just want to ask those who work in companies: if you have seen a lot CGI based URL that has an ampersand in it, and this URL is inside an HTML page, in your experience, are they encoded?

答:
My personal experience:

The most common usage is using no practice at all; just put it in the code and see if it works in the browser that they happen to have installed.

More seasoned developers will at least check it in several dfferent browsers.

Those who care enough about robustness will validate the code and encode the characters correctly (which means encoding characters inside URLs also).

ContentLicense: CC BY-SA 4.0

Body:
By the HTML specification, an ampersand should be encoded as

&

But of course a lot on the web doesn't do that. Here's an example of an ad widget from Amazon.com:

Note that the ampersand is not encoded.

For those work a lot with commercial sites, work in a company, or work with many widget codes, do most of these sites actually encode the ampersand?

(In other words, what percentage of top 1k sites try to encode ampersand properly when it is in the URL?)

Stress: this is not about whether it should or should not be encoded. I just want to ask those who work in companies: if you have seen a lot CGI based URL that has an ampersand in it, and this URL is inside an HTML page, in your experience, are they encoded?


问:
HTTP Authentication request always returns 401

I want to do a request to a server but always get a 401. What could it be?

If I try it in Postman everything works fine.

```<code>request({url: 'https://' + username + ':' + password + '@api.fastspring.com/accounts/'}, function (error, response, body) {
    if(response.statusCode == 200){
        console.log('it worked!')
       res.writeHead(200, { "Content-Type": "text/html" });
       res.write("it worked", 'utf-8');
       res.end();
    } else {
        console.log('error: '+ response.statusCode)
        console.log('error Text: '+ error)
        console.log(body)
        res.writeHead(500, { "Content-Type": "text/html" });
        res.write("Error!", 'utf-8');
        res.end();
    }
});
</code>```

答:
401 is 'no access'.  So, the authentication is working, your credentials are correct (else you would have had a 403), but the server is denying you access to this resource under these conditions.

The easiest way to find out why this should be is to check the server logs, but this may not be possible.  Here is a list of possible reasons why you may get denied when you have successfully accessed the URL with these credentials from elsewhere.

You are using a different request type - e.g. POST vs GET.  Maybe only one is permitted.

You are accessing from a different IP address.  Possibly the server is also restricting access via IP as well as credentials.

Your URL is subtly different.  Some servers are picky about trailing /, or explicitly adding /index.html or similar.

The server requires https in this situation but you are using http

The server requires a Host header which is added by one client but not by another.  This can happen on a server with multiple vhosts, or some Java apps

Some other access rule you are not aware of

Your best way to find out for certain is to check the server logs.

Body:
I want to do a request to a server but always get a 401. What could it be?

If I try it in Postman everything works fine.

request({url: 'https://' + username + ':' + password + '@api.fastspring.com/accounts/'}, function (error, response, body) {
    if(response.statusCode == 200){
        console.log('it worked!')
       res.writeHead(200, { "Content-Type": "text/html" });
       res.write("it worked", 'utf-8');
       res.end();
    } else {
        console.log('error: '+ response.statusCode)
        console.log('error Text: '+ error)
        console.log(body)
        res.writeHead(500, { "Content-Type": "text/html" });
        res.write("Error!", 'utf-8');
        res.end();
    }
});


问:
Convert XML Type to VARCHAR
I am trying to convert the data extracted from XMLTYPE column to varchar but it gives me error:

```<code>SELECT TO_CHAR(EXTRACT (XML_DATA, '/root/MYData/text()'))
  FROM TBL_DATA
</code>```

Gives error "Inconsistent datatypes: expected NUMBER got - "

My motive is to put the extracted value into a variable and use it further in stored proc and the node can contain number or alphabets:

```<code>SELECT TO_CHAR(EXTRACT (XML_DATA, '/root/MYData/text()')) INTO TEMP_VAR
  FROM TBL_DATA
</code>```

答:
Use EXTRACTVALUE rather than EXTRACT:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE TBL_DATA ( XML_DATA ) AS
SELECT XMLTYPE( '<root><MYData>test string</MYData></root>' ) FROM DUAL;
</code>```

Query 1:

```<code>SELECT EXTRACTVALUE(XML_DATA, '/root/MYData/text()')
  FROM TBL_DATA
</code>```

Results:

```<code>| EXTRACTVALUE(XML_DATA,'/ROOT/MYDATA/TEXT()') |
|----------------------------------------------|
|                                  test string |
</code>```

Query 2:

However, EXTRACT and EXTRACTVALUE are deprecated and oracle recommends using XMLTABLE instead:

```<code>SELECT value
FROM   TBL_DATA t
       CROSS JOIN
       XMLTABLE(
         '/root/MYData'
         PASSING t.XML_DATA
         COLUMNS value VARCHAR2(200) PATH 'text()'
       )
</code>```

Results:

```<code>|       VALUE |
|-------------|
| test string |
</code>```

Title: Convert XML Type to VARCHAR

Body:
I am trying to convert the data extracted from XMLTYPE column to varchar but it gives me error:

SELECT TO_CHAR(EXTRACT (XML_DATA, '/root/MYData/text()'))
  FROM TBL_DATA

Gives error "Inconsistent datatypes: expected NUMBER got - "

My motive is to put the extracted value into a variable and use it further in stored proc and the node can contain number or alphabets:

SELECT TO_CHAR(EXTRACT (XML_DATA, '/root/MYData/text()')) INTO TEMP_VAR
  FROM TBL_DATA

Body:
Use EXTRACTVALUE rather than EXTRACT:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE TBL_DATA ( XML_DATA ) AS
SELECT XMLTYPE( '<root><MYData>test string</MYData></root>' ) FROM DUAL;

Query 1:

SELECT EXTRACTVALUE(XML_DATA, '/root/MYData/text()')
  FROM TBL_DATA

Results:

| EXTRACTVALUE(XML_DATA,'/ROOT/MYDATA/TEXT()') |
|----------------------------------------------|
|                                  test string |

Query 2:

However, EXTRACT and EXTRACTVALUE are deprecated and oracle recommends using XMLTABLE instead:

SELECT value
FROM   TBL_DATA t
       CROSS JOIN
       XMLTABLE(
         '/root/MYData'
         PASSING t.XML_DATA
         COLUMNS value VARCHAR2(200) PATH 'text()'
       )

Results:

|       VALUE |
|-------------|
| test string |


问:
Java 8, Lambda: Sorting within grouped Lists and merging all groups to a list
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

```<code>Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
</code>```

I need the Grouping based on the order of the Elements in the origin List.

```<code>First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"
</code>```

The result would then look like the following:

```<code>List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"
</code>```

I have tried the following:

```<code>studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
</code>```

But this doesn't work.

答:
If I get you right, you want a List<Student> (not a map) where students are grouped by their locations and sorted by ids inside groups and where groups are also sorted by ids, not by location names. This is possible, but requires one grouping and two sortings:

```<code>//first, use your function to group students
Map<String, List<Student>> studlistGrouped = students.stream()
        .collect(Collectors.groupingBy(Student::getLocation, Collectors.toList()));

//then sort groups by minimum id in each of them
List<Student> sorted = studlistGrouped.entrySet().stream()
        .sorted(Comparator.comparing(e -> e.getValue().stream().map(Student::getId).min(Comparator.naturalOrder()).orElse(0)))
        //and also sort each group before collecting them in one list
        .flatMap(e -> e.getValue().stream().sorted(Comparator.comparing(Student::getId))).collect(Collectors.toList());
</code>```

This will produce following:

```<code>Student{id='1726', name='John', location='New York'}
Student{id='3442', name='Mark', location='New York'}
Student{id='5223', name='Michael', location='New York'}
Student{id='2234', name='Andrew', location='Los Angeles'}
Student{id='4321', name='Max', location='California'}
Student{id='7765', name='Sam', location='California'}
</code>```

Maybe this can be done more elegantly, suggestions are welcome

EDIT: At the time this answer was written there was no mention about Grouping based on the order of the Elements in the origin List in the OPs question. So my assumption was to sort both list and groups by ids. For solutions based on the order in the original list see other answers, for example, the Holgers one

Body:
Based on the following answer: https://stackoverflow.com/a/30202075/8760211

How to sort each group by stud_id and then return a List with all Students as result of the grouping by stud_location and then sorting by stud_id)?

It would be great to have this as extension to the existing Lambda Expression:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

I need the Grouping based on the order of the Elements in the origin List.

First group: "New York"
Second group: "California"
Third group: "Los Angeles"

1726, "John", "New York"
4321, "Max", "California"
2234, "Andrew", "Los Angeles"
5223, "Michael", "New York"
7765, "Sam", "California"
3442, "Mark", "New York"

The result would then look like the following:

List<Student> groupedAndSorted = ....

    1726, "John", "New York"
    3442, "Mark", "New York"
    5223, "Michael", "New York"
    4321, "Max", "California"
    7765, "Sam", "California"
    2234, "Andrew", "Los Angeles"

I have tried the following:

studlistGrouped.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))

But this doesn't work.

Body:
If I get you right, you want a List<Student> (not a map) where students are grouped by their locations and sorted by ids inside groups and where groups are also sorted by ids, not by location names. This is possible, but requires one grouping and two sortings:

//first, use your function to group students
Map<String, List<Student>> studlistGrouped = students.stream()
        .collect(Collectors.groupingBy(Student::getLocation, Collectors.toList()));

//then sort groups by minimum id in each of them
List<Student> sorted = studlistGrouped.entrySet().stream()
        .sorted(Comparator.comparing(e -> e.getValue().stream().map(Student::getId).min(Comparator.naturalOrder()).orElse(0)))
        //and also sort each group before collecting them in one list
        .flatMap(e -> e.getValue().stream().sorted(Comparator.comparing(Student::getId))).collect(Collectors.toList());

This will produce following:

Student{id='1726', name='John', location='New York'}
Student{id='3442', name='Mark', location='New York'}
Student{id='5223', name='Michael', location='New York'}
Student{id='2234', name='Andrew', location='Los Angeles'}
Student{id='4321', name='Max', location='California'}
Student{id='7765', name='Sam', location='California'}

Maybe this can be done more elegantly, suggestions are welcome

EDIT: At the time this answer was written there was no mention about Grouping based on the order of the Elements in the origin List in the OPs question. So my assumption was to sort both list and groups by ids. For solutions based on the order in the original list see other answers, for example, the Holgers one


问:
How to remove Backbone views with require.js?
I have a backbone app that uses require.js.

Prior to using require my Backbone router looked something like this.

```<code>APP.views = {};

APP.Router = Backbone.Router.extend({

routes: {

    '(/)' : 'index',
    'about(/)' : 'about'

},

initialize : function(){
    Backbone.history.start({ pushState: true });
},

index: function() {
    this.showView( new APP.Views.IndexView() );
},

about: function() {
    this.showView( new APP.Views.AboutView() );
},

showView : function( view ) {

        if ( APP.views.current ) {
            APP.views.current.remove();
        }
        APP.views.current = view;
        $( '#page' ).html( view.render().$el );

}
});
</code>```

I would stash the 'current' view in a global variable and kill the existing view each time a route was changed and life was good.

But, how do I achieve this with require.js ?

My requirejs router currently looks like the following but I'm not sure how to remove the existing views. Although, I have not noticed any of the typical "zombie view" symptoms I feel like I should be removing the existing views.

```<code>define( function( require ){

    // DEPS
    var $           = require('jquery'),
        _           = require('underscore'),
        Backbone    = require('backbone');

    // ROUTER
    var Router = Backbone.Router.extend({

        routes: {

            '(/)' : 'index',
            'about(/)' : 'about'

        },
        initialize : function(){

            Backbone.history.start({ pushState: true });

        },
        index: function(){

            this.showPage('index');

        },
        about: function() {

            this.showPage('about');

        },
        showPage : function( pageName ) {

            var view = 'views/pages/' + pageName;

            require( [ view ] , function( Page ) {

                var page = new Page();

                $('#page').html( page.render().el );

            });

        }

    });

    return Router ;

});
</code>```

答:
Even before using require.js, a global wasn't needed.

Just put the current view into a router property.

```<code>initialize : function() {
    this.$page = $('#page');
    Backbone.history.start({ pushState: true });
},
showView : function(view) {
    if (this.current) this.current.remove();
    this.$page.html((this.current = view).render().el);
}
</code>```

Then, same thing applies to your async require case:

```<code>showPage : function(pageName) {
    if (this.current) this.current.remove();

    var view = 'views/pages/' + pageName,
        self = this;
    require([view], function(Page) {
        self.$page.html((self.current = new Page()).render().el);
    });
}
</code>```

But even then, I don't feel like requiring each view with an async require is worth it. You're just slowing down your application with a lot of extra requests.

Just define the dependencies for each module.

```<code>define([
    'jquery',
    'backbone',
    'views/index',
    'views/about'
], function($, Backbone, IndexView, AboutView){
    // ...
});
</code>```

While in development, you'll see a lot of request each time you refresh, but when ready for production, build a minified bundle of all the js files with require optimizer.

Also note that you can have module scope global, which are just local variable declared at the root of a module scope (IIFE or with require.js).

```<code>(function() {
    var currentView;

    var Router = Backbone.Router.extend({
        // ...snip...
        showView: function(view) {
            if (currentView) currentView.remove();
            this.$page.html((currentView = view).render().el);
        }
    });
})();
</code>```

Body:
I have a backbone app that uses require.js.

Prior to using require my Backbone router looked something like this.

APP.views = {};

APP.Router = Backbone.Router.extend({

routes: {

    '(/)' : 'index',
    'about(/)' : 'about'

},

initialize : function(){
    Backbone.history.start({ pushState: true });
},

index: function() {
    this.showView( new APP.Views.IndexView() );
},

about: function() {
    this.showView( new APP.Views.AboutView() );
},

showView : function( view ) {

        if ( APP.views.current ) {
            APP.views.current.remove();
        }
        APP.views.current = view;
        $( '#page' ).html( view.render().$el );

}
});

I would stash the 'current' view in a global variable and kill the existing view each time a route was changed and life was good.

But, how do I achieve this with require.js ?

My requirejs router currently looks like the following but I'm not sure how to remove the existing views. Although, I have not noticed any of the typical "zombie view" symptoms I feel like I should be removing the existing views.

define( function( require ){

    // DEPS
    var $           = require('jquery'),
        _           = require('underscore'),
        Backbone    = require('backbone');

    // ROUTER
    var Router = Backbone.Router.extend({

        routes: {

            '(/)' : 'index',
            'about(/)' : 'about'

        },
        initialize : function(){

            Backbone.history.start({ pushState: true });

        },
        index: function(){

            this.showPage('index');

        },
        about: function() {

            this.showPage('about');

        },
        showPage : function( pageName ) {

            var view = 'views/pages/' + pageName;

            require( [ view ] , function( Page ) {

                var page = new Page();

                $('#page').html( page.render().el );

            });

        }

    });

    return Router ;

});

Body:
Even before using require.js, a global wasn't needed.

Just put the current view into a router property.

initialize : function() {
    this.$page = $('#page');
    Backbone.history.start({ pushState: true });
},
showView : function(view) {
    if (this.current) this.current.remove();
    this.$page.html((this.current = view).render().el);
}

Then, same thing applies to your async require case:

showPage : function(pageName) {
    if (this.current) this.current.remove();

    var view = 'views/pages/' + pageName,
        self = this;
    require([view], function(Page) {
        self.$page.html((self.current = new Page()).render().el);
    });
}

But even then, I don't feel like requiring each view with an async require is worth it. You're just slowing down your application with a lot of extra requests.

Just define the dependencies for each module.

define([
    'jquery',
    'backbone',
    'views/index',
    'views/about'
], function($, Backbone, IndexView, AboutView){
    // ...
});

While in development, you'll see a lot of request each time you refresh, but when ready for production, build a minified bundle of all the js files with require optimizer.

Also note that you can have module scope global, which are just local variable declared at the root of a module scope (IIFE or with require.js).

(function() {
    var currentView;

    var Router = Backbone.Router.extend({
        // ...snip...
        showView: function(view) {
            if (currentView) currentView.remove();
            this.$page.html((currentView = view).render().el);
        }
    });
})();


问:
SQL Design: need ability to add custom "columns" to a table using a fixed schema
Using: SQL Server 2008, Entity Framework, WCF 4 REST

I have a table for holding the measurement data generated by monitoring system (aka the app).  There are currently about 10 different well-known pieces of data being monitored within the app - and each corresponds to a column in the table.  Each customer can "customize" each of their apps to capture from 1 to 10 pieces of data - they only need to capture those pieces of info they are interested in analyzing. Everything's working great (and performance is good) with this straight-forward fixed schema.  This schema is designed to be multi-tenant, so multiple applications across multiple customers in multiple locations could be pumping data into the same DB - millions and millions of rows of measurement data (I wouldn't be surprised if we go to Azure before too long).

I have now been told that the measurement application will soon be able to monitor additional "things".  This new list (so far I'm told is at around 150 items) could wind up being about 1000 items being measured.  Add on top of that, the user could specify their own criteria for items to monitor/measure (i.e. custom measurements equating to custom columns.)  The good news is that all the measurement data will be integers.

Now the fun - how do I design the schema for this situation?  I would really like to keep the schema fixed.  I would also like to keep it as performant as possible given the high volumes of data.

Any help is appreciated.

Current Schema:

```<code>CREATE TABLE MeasurementData (
    DataId bigint IDENTITY(1,1) NOT NULL PRIMARY KEY,
    ApplicationId int NOT NULL,    -- FK to Application table
    DateCollected datetime NOT NULL,
    Length int NULL,
    Width int NULL,
    Height int NULL,
    Color int NULL,
    Shape int NULL,
    Mass int NULL
)
CREATE TABLE Application (
    ApplicationId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyId int NOT NULL,    -- FK to Company table
    SerialNumber nvarchar(50) NOT NULL
)
CREATE TABLE Company (
    CompanyId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyName nvarchar(50) NOT NULL
)
</code>```

And then we have the user table, the roles table, etc, where there's a 1-n relationship btw company and user.

FYI, the web app will then present the data with tables, graphs, etc (communicating via the REST web service layer)

答: Take a look at these SO examples: one, two, three.

Body:
Using: SQL Server 2008, Entity Framework, WCF 4 REST

I have a table for holding the measurement data generated by monitoring system (aka the app).  There are currently about 10 different well-known pieces of data being monitored within the app - and each corresponds to a column in the table.  Each customer can "customize" each of their apps to capture from 1 to 10 pieces of data - they only need to capture those pieces of info they are interested in analyzing. Everything's working great (and performance is good) with this straight-forward fixed schema.  This schema is designed to be multi-tenant, so multiple applications across multiple customers in multiple locations could be pumping data into the same DB - millions and millions of rows of measurement data (I wouldn't be surprised if we go to Azure before too long).

I have now been told that the measurement application will soon be able to monitor additional "things".  This new list (so far I'm told is at around 150 items) could wind up being about 1000 items being measured.  Add on top of that, the user could specify their own criteria for items to monitor/measure (i.e. custom measurements equating to custom columns.)  The good news is that all the measurement data will be integers.

Now the fun - how do I design the schema for this situation?  I would really like to keep the schema fixed.  I would also like to keep it as performant as possible given the high volumes of data.

Any help is appreciated.

Current Schema:

CREATE TABLE MeasurementData (
    DataId bigint IDENTITY(1,1) NOT NULL PRIMARY KEY,
    ApplicationId int NOT NULL,    -- FK to Application table
    DateCollected datetime NOT NULL,
    Length int NULL,
    Width int NULL,
    Height int NULL,
    Color int NULL,
    Shape int NULL,
    Mass int NULL
)
CREATE TABLE Application (
    ApplicationId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyId int NOT NULL,    -- FK to Company table
    SerialNumber nvarchar(50) NOT NULL
)
CREATE TABLE Company (
    CompanyId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CompanyName nvarchar(50) NOT NULL
)

And then we have the user table, the roles table, etc, where there's a 1-n relationship btw company and user.

FYI, the web app will then present the data with tables, graphs, etc (communicating via the REST web service layer)


问:
Parsing command line arguments in Haskell
I am currently working on a project that requires parsing command line arguments. So far I have been following this tutorial, which has been incredibly helpful, but I can't figure out how to return a variable (--author=example) in the arguments. I also can't figure out why parse [] = getContents causes an error (I had to uncomment it).

Here is my code:

```<code>module Main where

import qualified System.Environment as SE
import qualified System.Exit as E
import qualified Lib as Lib

main = do
  args <- SE.getArgs
  rem <- parse args
  Lib.someFunc
  putStrLn rem
  putStrLn "Hello"

tac  = unlines . reverse . lines

parse ["--help"]    = usage   >> exit
parse ["--version"] = version >> exit
parse ["--author=xyz"] = return "xyz"
-- parse ["--author=?"] = ?
{-
this is the code I am trying to figure out... how do I get parse the passed in variable name?
-}

-- parse []            = getContents
{-
the above line generates this error when I run 'main' in GHCi:

  *Main> <stdin>: hIsEOF: illegal operation (handle is semi-closed)
  Process intero exited abnormally with code 1

-}
parse fs            = concat `fmap` mapM readFile fs

usage   = putStrLn "Usage: gc2"
version = putStrLn "gc2 -- git-cal in Haskell2010 - 0.1"
exit    = E.exitWith E.ExitSuccess
die     = E.exitWith (E.ExitFailure 1)
</code>```

答:
To follow up on @ThomasM.DuBuisson comment optparse-applicative is a great package for cli and arguments parsing. There is also another package optparse-simple that is built on top of the previous one and has a few helpers that simplify things a bit.

Just so you can get started with optparse-applicative here is an implementation of your example:

```<code>data Options = Options
  { author :: String
  }

main :: IO ()
main = do
  let ver = "gc2 -- git-cal in Haskell2010 - 0.1"
  args <-
    execParser $
    info
      (Options <$>
       strOption (long "author" <>
                  short 'a' <>
                  help "Name of the author.") <*
       infoOption ver (long "version" <>
                       short 'v' <>
                       help "Display version and exit.") <*
       abortOption ShowHelpText (long "help" <>
                                 short 'h' <>
                                 help "Display this message."))
      (progDesc "Very powerful tool." <> fullDesc)
  putStrLn $ author args
</code>```

And usage example from GHCi:

```<code>λ> :main
Missing: (-a|--author ARG)

Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help]
  Very powerful tool.
*** Exception: ExitFailure 1
λ> :main --version
gc2 -- git-cal in Haskell2010 - 0.1
*** Exception: ExitSuccess
λ> :main --help
Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help]
  Very powerful tool.

Available options:
  -a,--author ARG          Name of the author.
  -v,--version             Display version and exit.
  -h,--help                Display this message.
*** Exception: ExitSuccess
λ> :main --author Me
Me
</code>```

Body:
I am currently working on a project that requires parsing command line arguments. So far I have been following this tutorial, which has been incredibly helpful, but I can't figure out how to return a variable (--author=example) in the arguments. I also can't figure out why parse [] = getContents causes an error (I had to uncomment it).

Here is my code:

module Main where

import qualified System.Environment as SE
import qualified System.Exit as E
import qualified Lib as Lib

main = do
  args <- SE.getArgs
  rem <- parse args
  Lib.someFunc
  putStrLn rem
  putStrLn "Hello"

tac  = unlines . reverse . lines

parse ["--help"]    = usage   >> exit
parse ["--version"] = version >> exit
parse ["--author=xyz"] = return "xyz"
-- parse ["--author=?"] = ?
{-
this is the code I am trying to figure out... how do I get parse the passed in variable name?
-}

-- parse []            = getContents
{-
the above line generates this error when I run 'main' in GHCi:

  *Main> <stdin>: hIsEOF: illegal operation (handle is semi-closed)
  Process intero exited abnormally with code 1

-}
parse fs            = concat `fmap` mapM readFile fs

usage   = putStrLn "Usage: gc2"
version = putStrLn "gc2 -- git-cal in Haskell2010 - 0.1"
exit    = E.exitWith E.ExitSuccess
die     = E.exitWith (E.ExitFailure 1)

Body:
To follow up on @ThomasM.DuBuisson comment optparse-applicative is a great package for cli and arguments parsing. There is also another package optparse-simple that is built on top of the previous one and has a few helpers that simplify things a bit.

Just so you can get started with optparse-applicative here is an implementation of your example:

data Options = Options
  { author :: String
  }

main :: IO ()
main = do
  let ver = "gc2 -- git-cal in Haskell2010 - 0.1"
  args <-
    execParser $
    info
      (Options <$>
       strOption (long "author" <>
                  short 'a' <>
                  help "Name of the author.") <*
       infoOption ver (long "version" <>
                       short 'v' <>
                       help "Display version and exit.") <*
       abortOption ShowHelpText (long "help" <>
                                 short 'h' <>
                                 help "Display this message."))
      (progDesc "Very powerful tool." <> fullDesc)
  putStrLn $ author args

And usage example from GHCi:

λ> :main
Missing: (-a|--author ARG)

Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help]
  Very powerful tool.
*** Exception: ExitFailure 1
λ> :main --version
gc2 -- git-cal in Haskell2010 - 0.1
*** Exception: ExitSuccess
λ> :main --help
Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help]
  Very powerful tool.

Available options:
  -a,--author ARG          Name of the author.
  -v,--version             Display version and exit.
  -h,--help                Display this message.
*** Exception: ExitSuccess
λ> :main --author Me
Me


问:
what is the "editId" in Coq's XML Protocol document?
In Coq's XML Protocol document (for the Add operation), a line reads <int>${editId}</int>. What is the editID here?

I asked this because I failed to interact with coqtop in the ideslave mode. Using coq-8.6.1/theories/FSets/FSetCompat.v as an example, I inputted

```<code><call val="Init"><option val="none"/></call>
</code>```

,

```<code><call val="Add"><pair><pair><string>Require Import FSetInterface FSetFacts MSetInterface MSetFacts.</string><int>1</int></pair><pair><state_id val="1"/><bool val="true"/></pair></pair></call>
</code>```

,

```<code><call val="Add"><pair><pair><string>Set Implicit Arguments.</string><int>1</int></pair><pair><state_id val="2"/><bool val="true"/></pair></pair></call>
</code>```

, and then

```<code><call val="Add"><pair><pair><string>Unset Strict Implicit.</string><int>1</int></pair><pair><state_id val="3"/><bool val="true"/></pair></pair></call>
</code>```

They all generated correct outputs. However, at this time when I typed

```<code><call val="Add"><pair><pair><string>Module Backport_WSets
    (E:DecidableType.DecidableType)
    (M:MSetInterface.WSets with Definition E.t := E.t
                           with Definition E.eq := E.eq)
<: FSetInterface.WSfun E.</string><int>1</int></pair><pair><state_id val="4"/><bool val="true"/></pair></pair></call>
</code>```

I got the following error:

```<code>[pid 48519] XML syntax error: Attribute value expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <int>1</int>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <pair>
  <state_id val="4"/>
  <bool val="true"/>
</pair>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected
</code>```

I suspect that this error is because of the multi-line string, and maybe if I change editId, I should get the correct answer. Am I right? If no, what does editID do, and how should I deal with this error? Thanks for helping!

答:
It doesn't seem to hurt to send an editid for an Add, even in 8.7, even if it's unused on the Coq side.

My XML-based fork of Proof General includes an editid for Add with 8.7, and no error occurs as a result.

Body:
In Coq's XML Protocol document (for the Add operation), a line reads <int>${editId}</int>. What is the editID here?

I asked this because I failed to interact with coqtop in the ideslave mode. Using coq-8.6.1/theories/FSets/FSetCompat.v as an example, I inputted

<call val="Init"><option val="none"/></call>

,

<call val="Add"><pair><pair><string>Require Import FSetInterface FSetFacts MSetInterface MSetFacts.</string><int>1</int></pair><pair><state_id val="1"/><bool val="true"/></pair></pair></call>

,

<call val="Add"><pair><pair><string>Set Implicit Arguments.</string><int>1</int></pair><pair><state_id val="2"/><bool val="true"/></pair></pair></call>

, and then

<call val="Add"><pair><pair><string>Unset Strict Implicit.</string><int>1</int></pair><pair><state_id val="3"/><bool val="true"/></pair></pair></call>

They all generated correct outputs. However, at this time when I typed

<call val="Add"><pair><pair><string>Module Backport_WSets
    (E:DecidableType.DecidableType)
    (M:MSetInterface.WSets with Definition E.t := E.t
                           with Definition E.eq := E.eq)
<: FSetInterface.WSfun E.</string><int>1</int></pair><pair><state_id val="4"/><bool val="true"/></pair></pair></call>

I got the following error:

[pid 48519] XML syntax error: Attribute value expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <int>1</int>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] Unexpected XML message
[pid 48519] Expected XML node: call
[pid 48519] XML tree received: <pair>
  <state_id val="4"/>
  <bool val="true"/>
</pair>
[pid 48519] XML syntax error: Xml node expected
[pid 48519] XML syntax error: Xml node expected

I suspect that this error is because of the multi-line string, and maybe if I change editId, I should get the correct answer. Am I right? If no, what does editID do, and how should I deal with this error? Thanks for helping!