问:
npm install fails when package is installed via github
I install a module (electron-window-managerwhich installs melanke-WatchJsfrom its git repository) and npm crashes, only in my Windows 10 Laptop since in my Windows 7 PC everything is okay.

Now I noticed that every module that I try to install via git returns the same error:

```<code>npm ERR! git clone C:\Users\Malés\AppData\Roaming\npm-cache\_git-remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88 C:\Users\MALS~1\AppData\Local\Temp\npm-14036-6a70847d\git-cache-3d25afee\fb3946f4549395b2f0d3a166ef74eb407d11549b:
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "git+https://git@github.com/visionmedia/express.git"
npm ERR! node v6.9.5
npm ERR! npm  v3.10.10
npm ERR! code 128

npm ERR! Command failed: git -c core.longpaths=true clone C:\Users\Malés\AppData\Roaming\npm-cache\_git-remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88 C:\Users\MALS~1\AppData\Local\Temp\npm-14036-6a70847d\git-cache-3d25afee\fb3946f4549395b2f0d3a166ef74eb407d11549b
npm ERR! "git-upload-pack 'C:\Users\Malés\AppData\Roaming\npm-cache\_git_remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88'":git-upload-pack 'C:\Users\Malés\AppData\Roaming\npm-cache\_git-remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88': No such file or directory
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     E:\Programming\Electron\MUVTIME_Electron\npm-debug.log
</code>```

Tried this and did not solve my problem.

I already reinstalled Git, updated Node for the newest stable version (v6.9.5 which includes npm 3.10.10), ran the same commands in administrator mode and nothing solved it.

Please help.

答:
Had the same issue...
Run the git bash or the command line console as an administrator when launching the npm install command
Worked for me ! ;)</p>

Body:
I install a module (electron-window-managerwhich installs melanke-WatchJsfrom its git repository) and npm crashes, only in my Windows 10 Laptop since in my Windows 7 PC everything is okay.

Now I noticed that every module that I try to install via git returns the same error:

npm ERR! git clone C:\Users\Malés\AppData\Roaming\npm-cache\_git-remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88 C:\Users\MALS~1\AppData\Local\Temp\npm-14036-6a70847d\git-cache-3d25afee\fb3946f4549395b2f0d3a166ef74eb407d11549b:
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "git+https://git@github.com/visionmedia/express.git"
npm ERR! node v6.9.5
npm ERR! npm  v3.10.10
npm ERR! code 128

npm ERR! Command failed: git -c core.longpaths=true clone C:\Users\Malés\AppData\Roaming\npm-cache\_git-remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88 C:\Users\MALS~1\AppData\Local\Temp\npm-14036-6a70847d\git-cache-3d25afee\fb3946f4549395b2f0d3a166ef74eb407d11549b
npm ERR! "git-upload-pack 'C:\Users\Malés\AppData\Roaming\npm-cache\_git_remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88'":git-upload-pack 'C:\Users\Malés\AppData\Roaming\npm-cache\_git-remotes\git-https-git-github-com-visionmedia-express-git-d7a03b88': No such file or directory
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     E:\Programming\Electron\MUVTIME_Electron\npm-debug.log

Tried this and did not solve my problem.

I already reinstalled Git, updated Node for the newest stable version (v6.9.5 which includes npm 3.10.10), ran the same commands in administrator mode and nothing solved it.

Please help.


来源: stackexchange

问:
Laravel 5.4 Disable Register Route
I am trying to disable the register route on my application which is running in Laravel 5.4.

In my routes file, I have only the

```<code>Auth::routes();
</code>```

Is there any way to disable the register routes?

答:
You could try this.

```<code>Route::match(['get', 'post'], 'register', function(){
    return redirect('/');
});
</code>```

Add those routes just below the Auth::routes() to override the default registration routes. Any request to the /register route will redirect to the baseUrl.

ContentLicense: CC BY-SA 4.0

Title: Laravel 5.4 Disable Register Route

Body:
I am trying to disable the register route on my application which is running in Laravel 5.4.

In my routes file, I have only the

Auth::routes();

Is there any way to disable the register routes?

Body:
You could try this.

Route::match(['get', 'post'], 'register', function(){
    return redirect('/');
});

Add those routes just below the Auth::routes() to override the default registration routes. Any request to the /register route will redirect to the baseUrl.

ContentLicense: CC BY-SA 3.0


问:
Content script can connect to background script but popup.js cannot connect to content script
In my code, I currently have a content script that sends a message to a background script, and in response creates an alert. This works for example.js and background.js when visiting https://www.google.com. However, when trying to establish communication between popup.js and my content script, I get the error message

```<code>Could not establish connection. Receiving end does not exist.
</code>```

What I currently have is I send a message from popup.js once a button on the popup is clicked on. Then, a console message should be displayed from the content script, example.js, but it doesn't even seem to be reaching the content script's listener. Here's the code,

popup.js:

```<code>window.onload=function(){
    document.getElementById('highlight').addEventListener('click', sendHighlightMessage, false);
}

function sendHighlightMessage() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    console.log("going through tabs " + tabs[0].url); //this actually occurs

      chrome.tabs.sendMessage(tabs[0].id, {highlight: true}, function(response) {
        if (chrome.runtime.lastError) {
          // An error occurred :(
          console.log("ERROR: ", chrome.runtime.lastError);
        }
        else{
          console.log(response.message);
        }
      });
  });
}
</code>```

example.js:

```<code>chrome.runtime.sendMessage('Hello World');
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){
  console.log("received " + response); //never gets to this point
  sendResponse({message : "Response Received"});
});
</code>```

background.js:

```<code>chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
  alert(response);
});
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){
 console.log("received " + response);
 sendResponse({message : "Response Received"});
});
</code>```

I've tried a lot of answers but none have seem to worked so far.

答:
Popups scripts were designed not to be able to talk to content scripts directly, you have to send messages through the background script to accomplish this.

Have your popup send the message to the background page first, have the background page send another message to specific content script. Have your content script listen for the event from the background page.

Body:
In my code, I currently have a content script that sends a message to a background script, and in response creates an alert. This works for example.js and background.js when visiting https://www.google.com. However, when trying to establish communication between popup.js and my content script, I get the error message

Could not establish connection. Receiving end does not exist.

What I currently have is I send a message from popup.js once a button on the popup is clicked on. Then, a console message should be displayed from the content script, example.js, but it doesn't even seem to be reaching the content script's listener. Here's the code,

popup.js:

window.onload=function(){
    document.getElementById('highlight').addEventListener('click', sendHighlightMessage, false);
}

function sendHighlightMessage() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    console.log("going through tabs " + tabs[0].url); //this actually occurs

      chrome.tabs.sendMessage(tabs[0].id, {highlight: true}, function(response) {
        if (chrome.runtime.lastError) {
          // An error occurred :(
          console.log("ERROR: ", chrome.runtime.lastError);
        }
        else{
          console.log(response.message);
        }
      });
  });
}

example.js:

chrome.runtime.sendMessage('Hello World');
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){
  console.log("received " + response); //never gets to this point
  sendResponse({message : "Response Received"});
});

background.js:

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
  alert(response);
});
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){
 console.log("received " + response);
 sendResponse({message : "Response Received"});
});

I've tried a lot of answers but none have seem to worked so far.


问:
C# Multi-form coding practice
My question is, in general is it allowable and maintainable to have a multi-form program. More specifically in C# is it good practice to have a button go to another form(each button would be in a separate class). Here is an example:
(In this example I create a programmers reference application, where I need to go from page to page gathering information from the web and put it on an application for quick reference)

Main form:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
public partial class main : Form
{
    public main()
    {
        InitializeComponent();
    }

    //About button click
    private void btnAbout_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Author: anon \n"
            +"Version Number: 00.00.01 \n"
            ,"Information");    //Version Key quickreference: 00(high profile change).00(Medium profile change).00(low profile change)
    }

    private void btnWebsites_Click(object sender, EventArgs e)
    {
        websiteForm websiteFormObj = new websiteForm();
        websiteFormObj.Show();
    }
 }
}
</code>```

Second form(IN A DIFFERENT CLASS):

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
  public partial class websiteForm : Form
   {
    public websiteForm()
    {
        InitializeComponent();
    }
   }
}
</code>```

If this is not a good way can you answer what is a better way, is tab control a better way, or using panels to show and hide new content in an application?

答:
Look at the big programs. Is steam using new windows for each action. Is Visual Studio using alot of new windows for every single action. The are all using tabs for the diffrent pages. It will get very messy if the do.

The reason why Pop up windows are created is to get some input from the user. For example:

Saving a file

Opening a file

Creating a new class in Visual studio.

Change Settings.

All these popup windows are created when a program want to have some input without disturbing the main layout and the program goal. These windows will also close quickly.

So only create popup windows when they will quickly disapear after the user gave some input. And put the main functions of your program in tabs.

Title: C# Multi-form coding practice

Body:
My question is, in general is it allowable and maintainable to have a multi-form program. More specifically in C# is it good practice to have a button go to another form(each button would be in a separate class). Here is an example:
(In this example I create a programmers reference application, where I need to go from page to page gathering information from the web and put it on an application for quick reference)

Main form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
public partial class main : Form
{
    public main()
    {
        InitializeComponent();
    }

    //About button click
    private void btnAbout_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Author: anon \n"
            +"Version Number: 00.00.01 \n"
            ,"Information");    //Version Key quickreference: 00(high profile change).00(Medium profile change).00(low profile change)
    }

    private void btnWebsites_Click(object sender, EventArgs e)
    {
        websiteForm websiteFormObj = new websiteForm();
        websiteFormObj.Show();
    }
 }
}

Second form(IN A DIFFERENT CLASS):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
  public partial class websiteForm : Form
   {
    public websiteForm()
    {
        InitializeComponent();
    }
   }
}

If this is not a good way can you answer what is a better way, is tab control a better way, or using panels to show and hide new content in an application?


问:
SQL model for flexible and configurable attributes
I'd like to design an application which will eventually fuel a configurable data-driven form.

Each user should be able to customize what fields appear in their own forms, and configure new form types to collect different sets of data.

One user may require:

Name

Contact Number

Email

Another user might want:

Name

Organization

Address

I've heard that the **Entity Attribute Value (EAV) ** design pattern may be appropriate for this, but in my case basically all fields are going to be known initially. New field types may be added later, but it'll be a controlled process.

Is there an advantage of using a EAV design pattern, compared to using a SQL table with ~1000 columns where each user may toggle on/off columns depending on their requirements? Does EAV have query disadvantages compared to the single table?

Is there another approach I should be taking?

答:
You might like my presentation: Extensible Data Modeling with MySQL. It was done with MySQL in mind, but many of the concepts apply to any SQL database.

Or this past answer of mine on Stack Overflow: How to design a product table for many kinds of product where each product has many parameters?

I'm not a fan of the EAV solution for this kind of task. It introduces more problems than it solves. Read the link above for details, or this blog post of mine: EAV FAIL.


问:
PyCharm Professional - type hinting error
I've recently switched from PyCharm Community Edition to PyCharm Professional and I believe there's something wrong with the type hinting system of PyCharm Professional.

For example, if I'm using the function map(), I get the following hint from PyCharm Community Edition, which appears to be reasonable:

And here is what I get from PyCharm Professional, which does not look right:

I don't believe this is the intended behaviour. This issue appears to impact all functions that take iterable inputs.

Has anyone else experienced this issue and if so, has anyone found a way to fix this?

Many thanks!

EDIT:
My PyCharm Professional version: 2017.1

My PyCharm Community Edition version: 2016.3

答:
PyCharm started to show types in parameters hints in 2017.1 version.

Parameter types for builtin functions are taken from pyi-stubs which are available here (Py2) and here (Py3).

map function has signatures which are shown on your screenshot. So there is nothing wrong.


问:
Pointer and reference address
Can anyone explain me why &p have the same address after I allocated memory.
And why p does not have the same address as: &p ?

```<code>#include <iostream>

using namespace std;

int main()
{
   int *p;

   cout << "p value: " << *p << "   p adress: " << p << " &p reference: " << &p;

   p = new int;
   *p = 5;
   cout << endl;
   cout << "p value: " << *p << "   p adress: " << p << " &p reference: " << &p;

   return 0;

}
</code>```

After compilation:

```<code>p value: -462058557   p adress: 0x74af73da &p reference: 0x6fff0c
p value: 5            p adress: 0x1d2978   &p reference: 0x6fff0c
</code>```

答:
Can anyone explain me why &p have the same address after I allocated memory.

You cannot take the address of an object whose memory has not been allocated. The pointer is allocated at the beginning of the block scope. Therefore you never observed the address of the pointer before it was allocated - only after.

You do take the address of the pointer before the dynamic memory is allocated. After you allocate the dynamic memory, you assign the value of the pointer to have the address of the dynamic memory. Assigning the value of a variable has no effect on where that variable is stored. It is expected to remain in the same address.

And why p does not have the same address as: &p ?

You never observe the address of &p. In fact, &p is a temporary, so it has no address.

<< &p gives you the value of &p i.e. the address of p. << p gives you the value of p i.e. an indeterminate value on the first occasion, and the address of the dynamically allocated integer on the second occasion.

Perhaps you meant to ask "why p does not have the same value as &p". That is simply because p doesn't point to itself, but to another object instead.

Also, reading an indeterminate value has undefined behaviour. Your program reads p, and also dereferences it before assigning it a value. Therefore the behaviour of your program is undefined.

reference address

Your program uses no references.

What is a reference then?

Reference is a type similar to a pointer. It is simpler and more restricted: It can not be null, it can not be re-assigned and its address can not be taken. Whenever a reference variable is used, it is indirected implicitly, unlike a pointer that must be dereferenced explicitly. Example:

```<code>int  i;        // non reference, non pointer
int* p = &i;   // a pointer
int& r = i;    // a reference

p = nullptr;   // a pointer can be null (doesn't point to anything)
               // and it can be reassigned
//r = nullptr; // a reference can not. This is ill-formed
r   = 42;      // a reference is implicitly indirected
*p  = 42;      // a pointer must be dereferenced explicitly
               // to acces the pointed object

int** pp = &p;   // you can take the address of a pointer
//int*& pr = &r; // you cannot take the address of a reference
p = &r;          // if you apply address-of operator on a reference,
                 // it is indirected implicitly
</code>```

Title: Pointer and reference address

Body:
Can anyone explain me why &p have the same address after I allocated memory.
And why p does not have the same address as: &p ?

#include <iostream>

using namespace std;

int main()
{
   int *p;

   cout << "p value: " << *p << "   p adress: " << p << " &p reference: " << &p;

   p = new int;
   *p = 5;
   cout << endl;
   cout << "p value: " << *p << "   p adress: " << p << " &p reference: " << &p;

   return 0;

}

After compilation:

p value: -462058557   p adress: 0x74af73da &p reference: 0x6fff0c
p value: 5            p adress: 0x1d2978   &p reference: 0x6fff0c

Body:
Can anyone explain me why &p have the same address after I allocated memory.

You cannot take the address of an object whose memory has not been allocated. The pointer is allocated at the beginning of the block scope. Therefore you never observed the address of the pointer before it was allocated - only after.

You do take the address of the pointer before the dynamic memory is allocated. After you allocate the dynamic memory, you assign the value of the pointer to have the address of the dynamic memory. Assigning the value of a variable has no effect on where that variable is stored. It is expected to remain in the same address.

And why p does not have the same address as: &p ?

You never observe the address of &p. In fact, &p is a temporary, so it has no address.

<< &p gives you the value of &p i.e. the address of p. << p gives you the value of p i.e. an indeterminate value on the first occasion, and the address of the dynamically allocated integer on the second occasion.

Perhaps you meant to ask "why p does not have the same value as &p". That is simply because p doesn't point to itself, but to another object instead.

Also, reading an indeterminate value has undefined behaviour. Your program reads p, and also dereferences it before assigning it a value. Therefore the behaviour of your program is undefined.

reference address

Your program uses no references.

What is a reference then?

Reference is a type similar to a pointer. It is simpler and more restricted: It can not be null, it can not be re-assigned and its address can not be taken. Whenever a reference variable is used, it is indirected implicitly, unlike a pointer that must be dereferenced explicitly. Example:

int  i;        // non reference, non pointer
int* p = &i;   // a pointer
int& r = i;    // a reference

p = nullptr;   // a pointer can be null (doesn't point to anything)
               // and it can be reassigned
//r = nullptr; // a reference can not. This is ill-formed
r   = 42;      // a reference is implicitly indirected
*p  = 42;      // a pointer must be dereferenced explicitly
               // to acces the pointed object

int** pp = &p;   // you can take the address of a pointer
//int*& pr = &r; // you cannot take the address of a reference
p = &r;          // if you apply address-of operator on a reference,
                 // it is indirected implicitly


答:
&p contains the address of p.

p contains the address of the value; this can change when you re-allocate.

*p dereferences the address and reads/writes the value.

Besides your code is not correct; it might compile though.

Title: Pointer and reference address


问:
How to set cookies in phantomjs using selenium with python?

It raise an error message said "Can only set Cookies for the current domain",but all I did is just put the old cookies in.Sometime I add the 'correct' domain,it will raise error Message "Unable to set Cookie".
And I tested it in Firefox,Firefox also cant work.

```<code>from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=phantompath)
driver.get('http://stackoverflow.com/')
driver.get_screenshot_as_file('1.png')
cookies = driver.get_cookies()
driver.delete_all_cookies()
driver.get_cookies()
for cookie in cookies:
    driver.add_cookie(cookie)
</code>```

答:
You need to change the domain parameter for each cookie. The domain field must be formatted like this:</p>

```<code>driver = webdriver.PhantomJS()
driver.get('http://www.baidu.com')
driver.delete_all_cookies()

for item in cookie_dictionary:
    driver.add_cookie({
      'domain': '.baidu.com', # note the dot at the beginning
      'name': item['name'],
      'value': item['value'],
      'path': '/',
      'expires': None
    })

driver.get('http://www.baidu.com')
</code>```

Body:
It raise an error message said "Can only set Cookies for the current domain",but all I did is just put the old cookies in.Sometime I add the 'correct' domain,it will raise error Message "Unable to set Cookie".
And I tested it in Firefox,Firefox also cant work.

from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=phantompath)
driver.get('http://stackoverflow.com/')
driver.get_screenshot_as_file('1.png')
cookies = driver.get_cookies()
driver.delete_all_cookies()
driver.get_cookies()
for cookie in cookies:
    driver.add_cookie(cookie)

Body:
You need to change the domain parameter for each cookie. The domain field must be formatted like this:

driver = webdriver.PhantomJS()
driver.get('http://www.baidu.com')
driver.delete_all_cookies()

for item in cookie_dictionary:
    driver.add_cookie({
      'domain': '.baidu.com', # note the dot at the beginning
      'name': item['name'],
      'value': item['value'],
      'path': '/',
      'expires': None
    })

driver.get('http://www.baidu.com')


答:
variable p holds a pointer to an integer, i.e. the value of p is a pointer, and this value changes when you assign p = new int;

&p, in contrast, means the memory address where p stores this pointer value. The address &p is most likely on the stack, and this address does not change if you assign something to p.

Note further that your first cout-sequence refers to non-initialized variables, which is undefined behaviour.

Title: Pointer and reference address


问:
What is a good design for an interface with optional components?
Suppose I have an interface that supports a few potential operations:

```<code>interface Frobnicator {
    int doFoo(double v);
    int doBar();
}
</code>```

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

```<code>interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}
</code>```

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

答:
How about just adding empty non-implementation methods rather than throwing UnsupportedOperationExceptions? This way, calling an unsupported method will have no side-effects, and won't cause a run-time error.

If you do want to be able to tell if a certain object supports a method or not, I would suggest you split your interface up into two with a common super interface, and then type check whatever object you get handed to determine what methods are supported. This is probably cleaner, and more advisable than my first suggestion.

```<code>interface Frobnicator {}

interface FooFrobnicator extends Frobnicator {
    void doFoo();
}

interface BarFrobnicator extends Frobnicator {
    void doBar();
}
</code>```

Edit:

Another way of doing it would be to add a boolean return type to your methods, and make sure that they only return false if the method is not supported. Hence:

```<code>interface Frobnicator
{
    boolean doFoo();
    boolean doBar();
}

class FooFrobnicator implements Frobnicator
{
    public boolean doFoo() { code, code, code; return true; }
    public boolean doBar() { return false; }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have an interface that supports a few potential operations:

interface Frobnicator {
    int doFoo(double v);
    int doBar();
}

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

Body:
How about just adding empty non-implementation methods rather than throwing UnsupportedOperationExceptions? This way, calling an unsupported method will have no side-effects, and won't cause a run-time error.

If you do want to be able to tell if a certain object supports a method or not, I would suggest you split your interface up into two with a common super interface, and then type check whatever object you get handed to determine what methods are supported. This is probably cleaner, and more advisable than my first suggestion.

interface Frobnicator {}

interface FooFrobnicator extends Frobnicator {
    void doFoo();
}

interface BarFrobnicator extends Frobnicator {
    void doBar();
}

Edit:

Another way of doing it would be to add a boolean return type to your methods, and make sure that they only return false if the method is not supported. Hence:

interface Frobnicator
{
    boolean doFoo();
    boolean doBar();
}

class FooFrobnicator implements Frobnicator
{
    public boolean doFoo() { code, code, code; return true; }
    public boolean doBar() { return false; }
}


问:
Haskell - Couldn't match type ‘PersistEntityBackend record0’ with ‘SqlBackend’
I am trying to get a record by id in Yesod. My code is:

```<code>getEditActorR :: Handler Html
getEditActorR = do
    actorId <- runInputGet $ ireq intField "id"
    actor <- runDB $ get $ Key $ PersistInt64 (fromIntegral actorId)
    defaultLayout $ do
        $(widgetFile "actor-edit")
</code>```

The error I get is:

```<code>• Couldn't match type ‘PersistEntityBackend record0’
                 with ‘SqlBackend’
    arising from a use of ‘get’
  The type variable ‘record0’ is ambiguous
• In the second argument of ‘($)’, namely
    ‘get $ Key $ PersistInt64 (fromIntegral actorId)’
  In a stmt of a 'do' block:
    actor <- runDB $ get $ Key $ PersistInt64 (fromIntegral actorId)
  In the expression:
    do { actorId <- runInputGet $ ireq intField "id";
         actor <- runDB $ get $ Key $ PersistInt64 (fromIntegral actorId);
         defaultLayout $ do { (do { ... }) } }
</code>```

How can I fix that?

答:
First thing I did was to run stack ghci.

Then I run :info Actor, where Actor is the name of my PersistEntity.

Among other things, there was:

```<code>newtype instance Key Actor = ActorKey {unActorKey :: Int}
</code>```

So I wrote:

```<code>maybeActor <- runDB $ get $ ActorKey actorId
case maybeActor of
    Just actor -> defaultLayout $ do
        $(widgetFile "actor-edit")
    Nothing -> defaultLayout $ do
        $(widgetFile "actor-new")
</code>```

Body:
I am trying to get a record by id in Yesod. My code is:

getEditActorR :: Handler Html
getEditActorR = do
    actorId <- runInputGet $ ireq intField "id"
    actor <- runDB $ get $ Key $ PersistInt64 (fromIntegral actorId)
    defaultLayout $ do
        $(widgetFile "actor-edit")

The error I get is:

• Couldn't match type ‘PersistEntityBackend record0’
                 with ‘SqlBackend’
    arising from a use of ‘get’
  The type variable ‘record0’ is ambiguous
• In the second argument of ‘($)’, namely
    ‘get $ Key $ PersistInt64 (fromIntegral actorId)’
  In a stmt of a 'do' block:
    actor <- runDB $ get $ Key $ PersistInt64 (fromIntegral actorId)
  In the expression:
    do { actorId <- runInputGet $ ireq intField "id";
         actor <- runDB $ get $ Key $ PersistInt64 (fromIntegral actorId);
         defaultLayout $ do { (do { ... }) } }

How can I fix that?

Body:
First thing I did was to run stack ghci.

Then I run :info Actor, where Actor is the name of my PersistEntity.

Among other things, there was:

newtype instance Key Actor = ActorKey {unActorKey :: Int}

So I wrote:

maybeActor <- runDB $ get $ ActorKey actorId
case maybeActor of
    Just actor -> defaultLayout $ do
        $(widgetFile "actor-edit")
    Nothing -> defaultLayout $ do
        $(widgetFile "actor-new")


问:
Modify existing object in ASP.NET
I have some problem with my ASP.NET MVC application. How can I modify an existing object created previously in different ActionResult?

I created object in this action:

```<code>public ActionResult getLogin(AccountViewModel accountViewModel)
{
    Account account2 = de.Accounts.FirstOrDefault(a => a.Username == accountViewModel.Account.Username);
    PasswordReminder.PasswordReminder reminder = new PasswordReminder.PasswordReminder();
    reminder.showQuestion(account2.Username);
    return View("Question", reminder);
}
</code>```

And I want to add an attribute to the existing reminder object by this ActionResult

```<code>@model PasswordReminder.PasswordReminder
@{
Layout = null;
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Question</title>
</head>
<body>
<div>
 @Model.questionReminder
    @using (Html.BeginForm("Answer", "Account", FormMethod.Post))
    {
        @Html.TextBoxFor(a => a.reminderAnswer)
        <input type="submit" value="Send" />
    }
</div>
</body>
</html>
</code>```

So in my View "Answer" in attribute "reminderAnswer" I entered value but questionReminder is null, so this must be a new object..  Thanks for all help

答:
If I have understood your question correctly, in order to achieve what you are after, the PasswordReminder object that you are using as your Model, must be persisted in the getLogin action, and then passed back separately as the model from your action that feeds your Answer view (but I recommend to use a ViewModel as an abstraction over the previous PasswordReminder object for security)

This would insure you are referencing the previously instantiated PasswordReminder object in your Answer view, in order to modify the value of reminderAnswer property.

Title: Modify existing object in ASP.NET

Body:
I have some problem with my ASP.NET MVC application. How can I modify an existing object created previously in different ActionResult?

I created object in this action:

public ActionResult getLogin(AccountViewModel accountViewModel)
{
    Account account2 = de.Accounts.FirstOrDefault(a => a.Username == accountViewModel.Account.Username);
    PasswordReminder.PasswordReminder reminder = new PasswordReminder.PasswordReminder();
    reminder.showQuestion(account2.Username);
    return View("Question", reminder);
}

And I want to add an attribute to the existing reminder object by this ActionResult

@model PasswordReminder.PasswordReminder
@{
Layout = null;

<meta name="viewport" content="width=device-width" />
<title>Question</title>

 @Model.questionReminder
    @using (Html.BeginForm("Answer", "Account", FormMethod.Post))
    {
        @Html.TextBoxFor(a => a.reminderAnswer)
        <input type="submit" value="Send" />
    }

So in my View "Answer" in attribute "reminderAnswer" I entered value but questionReminder is null, so this must be a new object..  Thanks for all help


问:
Regular expressions don't work as expected in bash if-else block's condition
My pattern defined to match in if-else block is :

```<code>pat="17[0-1][0-9][0-9][0-9].AUG"
nln=""
</code>```

In my script, I'm taking user input which needs to be matched against the pattern, which if doesn't match, appropriate error messages are to be shown. Pretty simple, but giving me a hard time though. My code block from the script is this:

```<code>echo "How many days' AUDIT Logs need to be searched?"
read days
echo "Enter file name(s)[For multiple files, one file per line]: "
for(( c = 0 ; c < $days ; c++))
do
  read elements
  if [[  $elements =~ $pat ]];
     then
       array[$c]="$elements"
  elif [[  $elements =~ $nln ]];
     then
        echo "No file entered.Run script again. Exiting"
        exit;
  else
      echo "Invalid filename entered: $elements.Run script again. Exiting"
      exit;
  fi
done
</code>```

The format I want from the user for filenames to be entered is this:

```<code>170402.AUG
</code>```

So basically yymmdd.AUG (where y-year,m-month,d-day), with trailing or leading spaces is fine. Anything other than that should throw "Invalid filename entered: $elements.Run script again. Exiting" message. Also I want to check if if it is a blank line with a "Enter" hit, it should give an error saying "No file entered.Run script again. Exiting"

However my code, even if I enter something like "xxx" as filename, which should be throwing "Invalid filename entered: $elements.Run script again. Exiting", is actually checking true against a blank line, and throwing "No file entered.Run script again. Exiting"

Need some help with handling the regular expressions' check with user input, as otherwise rest of my script works just fine.

答:
I would not bug the user with how many days (who want count 15 days or like)? Also, why only one file per line? You should help the users, not bug them like microsoft...

For the start:

```<code>show_help() { cat <<'EOF'
bla bla....
EOF
}

show_files() { echo "${#files[@]} valid files entered: ${files[@]}"; }

while read -r -p 'files? (h-help)> ' line
do
    case "$line" in
        q) echo "quitting..." ; exit 0 ;;
        h) show_help ; continue;;
        '') (( ${#files} )) && show_files; continue ;;
        l) show_files ; continue ;;
        p) (( ${#files} )) && break || { echo "No files enterd.. quitting" ; exit 1; } ;; # go to processing
    esac
    # select (grep) the valid patterns from the entered line
    # and append them into the array
    # using the -P (if your grep know it) you can construct very complex regexes
    files+=( $(grep -oP '17\d{4}.\w{3}' <<< "$line") )
done

echo "processing files ${files[@]}"
</code>```

Using such logic you can build really powerful and user-friendly app. Also, you can use -e for the read enable the readline functions (cursor keys and like)...

But :) Consider just create a simple script, which accepts arguments. Without any dialogs and such. example:

```<code>myscript -h
</code>```

same as above, or some longer help text

```<code>myscript 170402.AUG 170403.AUG 170404.AUG 170405.AUG
</code>```

will do whatever it should do with the files. Main benefit, you could use globbing in the filenames, like

```<code>myscript 1704*
</code>```

and so on...

And if you really want the dialog, it could show it when someone runs the script without any argument, e.g.:

```<code>myscript
</code>```

will run in interactive mode...

Body:
My pattern defined to match in if-else block is :

pat="17[0-1][0-9][0-9][0-9].AUG"
nln=""

In my script, I'm taking user input which needs to be matched against the pattern, which if doesn't match, appropriate error messages are to be shown. Pretty simple, but giving me a hard time though. My code block from the script is this:

echo "How many days' AUDIT Logs need to be searched?"
read days
echo "Enter file name(s)[For multiple files, one file per line]: "
for(( c = 0 ; c < $days ; c++))
do
  read elements
  if [[  $elements =~ $pat ]];
     then
       array[$c]="$elements"
  elif [[  $elements =~ $nln ]];
     then
        echo "No file entered.Run script again. Exiting"
        exit;
  else
      echo "Invalid filename entered: $elements.Run script again. Exiting"
      exit;
  fi
done

The format I want from the user for filenames to be entered is this:

170402.AUG

So basically yymmdd.AUG (where y-year,m-month,d-day), with trailing or leading spaces is fine. Anything other than that should throw "Invalid filename entered: $elements.Run script again. Exiting" message. Also I want to check if if it is a blank line with a "Enter" hit, it should give an error saying "No file entered.Run script again. Exiting"

However my code, even if I enter something like "xxx" as filename, which should be throwing "Invalid filename entered: $elements.Run script again. Exiting", is actually checking true against a blank line, and throwing "No file entered.Run script again. Exiting"

Need some help with handling the regular expressions' check with user input, as otherwise rest of my script works just fine.

Body:
I would not bug the user with how many days (who want count 15 days or like)? Also, why only one file per line? You should help the users, not bug them like microsoft...

For the start:

show_help() { cat <<'EOF'
bla bla....
EOF
}

show_files() { echo "${#files[@]} valid files entered: ${files[@]}"; }

while read -r -p 'files? (h-help)> ' line
do
    case "$line" in
        q) echo "quitting..." ; exit 0 ;;
        h) show_help ; continue;;
        '') (( ${#files} )) && show_files; continue ;;
        l) show_files ; continue ;;
        p) (( ${#files} )) && break || { echo "No files enterd.. quitting" ; exit 1; } ;; # go to processing
    esac
    # select (grep) the valid patterns from the entered line
    # and append them into the array
    # using the -P (if your grep know it) you can construct very complex regexes
    files+=( $(grep -oP '17\d{4}.\w{3}' <<< "$line") )
done

echo "processing files ${files[@]}"

Using such logic you can build really powerful and user-friendly app. Also, you can use -e for the read enable the readline functions (cursor keys and like)...

But :) Consider just create a simple script, which accepts arguments. Without any dialogs and such. example:

myscript -h

same as above, or some longer help text

myscript 170402.AUG 170403.AUG 170404.AUG 170405.AUG

will do whatever it should do with the files. Main benefit, you could use globbing in the filenames, like

myscript 1704*

and so on...

And if you really want the dialog, it could show it when someone runs the script without any argument, e.g.:

myscript

will run in interactive mode...


问:
Pipe stdout to command which itself needs to read from own stdin
I would like to get the stdout from a process into another process not using stdin, as that one is used for another purpose.

In short I want to accomplish something like that:

```<code>echo  "a" >&4
cat | grep -f /dev/fd/4
</code>```

I got it running using an file as source for file descriptor 4, but that is not what I want:

```<code># Variant 1
cat file | grep -f /dev/fd/4 4<pattern

# Variant 2
exec 4<pattern
cat | grep -f /dev/fd/4
exec 4<&-
</code>```

My best try is that, but I got the following error message:

```<code># Variant 3
cat | (
    echo  "a" >&4
    grep -f /dev/fd/4
) <&4
</code>```

Error message:

```<code>test.sh: line 5: 4: Bad file descriptor
</code>```

What is the best way to accomplish that?

答:
For POSIX shells that lack process substitution, (e.g. dash, ash, yash, etc.).

If the command allows string input, (grep allows it), and the input string containing search targets isn't especially large, (i.e. the string doesn't exceed the length limit for the command line), there's always command substitution:

```<code>$ printf '%s\n' foo bar baz | grep $(echo foo)
foo
</code>```

Or if the input file is multi-line, separating quoted search items with '\n' works  the same as grep OR \|:

```<code>$ printf '%s\n' foo bar baz | grep "$(printf "%s\n" foo bar)"
foo
bar
</code>```

Body:
I would like to get the stdout from a process into another process not using stdin, as that one is used for another purpose.

In short I want to accomplish something like that:

echo  "a" >&4
cat | grep -f /dev/fd/4

I got it running using an file as source for file descriptor 4, but that is not what I want:

# Variant 1
cat file | grep -f /dev/fd/4 4<pattern

# Variant 2
exec 4<pattern
cat | grep -f /dev/fd/4
exec 4<&-

My best try is that, but I got the following error message:

# Variant 3
cat | (
    echo  "a" >&4
    grep -f /dev/fd/4
) <&4

Error message:

test.sh: line 5: 4: Bad file descriptor

What is the best way to accomplish that?

Body:
For POSIX shells that lack process substitution, (e.g. dash, ash, yash, etc.).

If the command allows string input, (grep allows it), and the input string containing search targets isn't especially large, (i.e. the string doesn't exceed the length limit for the command line), there's always command substitution:

$ printf '%s\n' foo bar baz | grep $(echo foo)
foo

Or if the input file is multi-line, separating quoted search items with '\n' works  the same as grep OR \|:

$ printf '%s\n' foo bar baz | grep "$(printf "%s\n" foo bar)"
foo
bar


问:
Trying to get my navigation next to my logo
I am trying to get my nav next to my logo and it just keeps putting it below it. My code isn't great, but I want the nav to be next to the logo like I have in the design that I have:

HTML:

```<code><body>
<div class="backgroundofdivgreen">
<header>

<div class="logo"><a href="index.html"><img src="images/logo.jpg"></a></div>

    <nav>
    <a href="index.html">Home</a>
    <a href="services.html">Services</a>
    <a href="offers.html">Offers</a>
    <a href="people.html">People</a>
    <a href="franchises.html">Franchises</a>
    <a href="reviews.html">Reviews</a>
    </div>

</header>
</div>
</code>```

CSS:

```<code>body {
    margin: 0px;
    background-color:blue;
}

.backgroundofdivgreen {
    height: 96px;
    margin: 0px;
    background-color: #39b54a;

}

header {
    width: 980px;
    height: 96px;
    background-color: #39b54a;
    margin: 0px auto;
}

nav {
    float:right;
}
</code>```

答:
Apply float: left; to the .logo class and close your  with  . not with`:

body {
  margin: 0px;
  background-color: blue;
}

.backgroundofdivgreen {
  height: 96px;
  margin: 0px;
  background-color: #39b54a;
}

header {
  width: 980px;
  height: 96px;
  background-color: #39b54a;
  margin: 0px auto;
}

.logo {
  float: left;
}

nav {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="backgroundofdivgreen">
    <header>

      <div class="logo">
        <img src="images/logo.jpg">
      </div>

      <nav>
        Home
        Services
        Offers
        People
        Franchises
        Reviews
      </nav>

    </header>
  </div></code>```

Body:
I am trying to get my nav next to my logo and it just keeps putting it below it. My code isn't great, but I want the nav to be next to the logo like I have in the design that I have:

HTML:

    Home
    Services
    Offers
    People
    Franchises
    Reviews

CSS:

body {
    margin: 0px;
    background-color:blue;
}

.backgroundofdivgreen {
    height: 96px;
    margin: 0px;
    background-color: #39b54a;

}

header {
    width: 980px;
    height: 96px;
    background-color: #39b54a;
    margin: 0px auto;
}

nav {
    float:right;
}

Body:
Apply float: left; to the .logo class and close your <nav> with </nav> . not with`:

body {
  margin: 0px;
  background-color: blue;
}

.backgroundofdivgreen {
  height: 96px;
  margin: 0px;
  background-color: #39b54a;
}

header {
  width: 980px;
  height: 96px;
  background-color: #39b54a;
  margin: 0px auto;
}

.logo {
  float: left;
}

nav {
  float: right;
}

<body>
  <div class="backgroundofdivgreen">
    <header>

      <div class="logo">
        <a href="index.html"><img src="images/logo.jpg"></a>
      </div>

      <nav>
        <a href="index.html">Home</a>
        <a href="services.html">Services</a>
        <a href="offers.html">Offers</a>
        <a href="people.html">People</a>
        <a href="franchises.html">Franchises</a>
        <a href="reviews.html">Reviews</a>
      </nav>

    </header>
  </div>


问:
How can I tell when UITableView has completed ReloadData?
I am trying to scroll to the bottom of a UITableView after it is done performing [self.tableView reloadData].

I originally had

```<code> [self.tableView reloadData]
 NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)];

[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
</code>```

But then I read that reloadData is asynchronous, so the scrolling doesn't happen since the self.tableView, [self.tableView numberOfSections] and [self.tableView numberOfRowsinSection are all 0.

It's weird that I am using:

```<code>[self.tableView reloadData];
NSLog(@"Number of Sections %d", [self.tableView numberOfSections]);
NSLog(@"Number of Rows %d", [self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1);
</code>```

In the console it returns Sections = 1, Row = -1;

When I do the exact same NSLogs in cellForRowAtIndexPath I get Sections = 1 and Row = 8; (8 is right)

答:
As of Xcode 8.2.1, iOS 10, and Swift 3,

You can determine the end of tableView.reloadData() easily by using a CATransaction block:

```<code>CATransaction.begin()
CATransaction.setCompletionBlock({
    print("reload completed")
    // Your completion code here
})
print("reloading")
tableView.reloadData()
CATransaction.commit()
</code>```

The above also works for determining the end of UICollectionView's reloadData() and UIPickerView's reloadAllComponents().

Body:
I am trying to scroll to the bottom of a UITableView after it is done performing [self.tableView reloadData].

I originally had

 [self.tableView reloadData]
 NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)];

[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

But then I read that reloadData is asynchronous, so the scrolling doesn't happen since the self.tableView, [self.tableView numberOfSections] and [self.tableView numberOfRowsinSection are all 0.

It's weird that I am using:

[self.tableView reloadData];
NSLog(@"Number of Sections %d", [self.tableView numberOfSections]);
NSLog(@"Number of Rows %d", [self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1);

In the console it returns Sections = 1, Row = -1;

When I do the exact same NSLogs in cellForRowAtIndexPath I get Sections = 1 and Row = 8; (8 is right)

Body:
As of Xcode 8.2.1, iOS 10, and Swift 3,

You can determine the end of tableView.reloadData() easily by using a CATransaction block:

CATransaction.begin()
CATransaction.setCompletionBlock({
    print("reload completed")
    // Your completion code here
})
print("reloading")
tableView.reloadData()
CATransaction.commit()

The above also works for determining the end of UICollectionView's reloadData() and UIPickerView's reloadAllComponents().


问:
Longest Increasing Cyclic Subsequence
I have a code for finding the longest increasing subsequence, but I'd like to extend this to allow wrap arounds. For example for the sequence (4,5,6,1,2,3) the longest increasing cyclic subsequence is (1,2,3,4,5,6) since once we reach 3, we can go back to the beginning of the sequence (we can only do this once.) Is anyone able to help me?

Here is the code:

```<code>def longest_increasing_subsequence(X):

N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
   lo = 1
   hi = L
   while lo <= hi:
       mid = (lo+hi)//2
       if (X[M[mid]] < X[i]):
           lo = mid+1
       else:
           hi = mid-1

   newL = lo
   P[i] = M[newL-1]
   M[newL] = i

   if (newL > L):
       L = newL

S = []
k = M[L]
for i in range(L-1, -1, -1):
    S.append(X[k])
    k = P[k]
return len(S[::-1])
</code>```

答:
Just check the returned value from the function on each shift:</p>

```<code>max_increasing=longest_increasing_subsequence(X)
for i in range(len(X)-1):
    X=X.append(X.pop(0)) #shift X by 1
    if longest_increasing_subsequence(X)>max_increasing:
         max_increasing=longest_increasing_subsequence(X)
</code>```

Title: Longest Increasing Cyclic Subsequence

Body:
I have a code for finding the longest increasing subsequence, but I'd like to extend this to allow wrap arounds. For example for the sequence (4,5,6,1,2,3) the longest increasing cyclic subsequence is (1,2,3,4,5,6) since once we reach 3, we can go back to the beginning of the sequence (we can only do this once.) Is anyone able to help me?

Here is the code:

def longest_increasing_subsequence(X):

N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
   lo = 1
   hi = L
   while lo <= hi:
       mid = (lo+hi)//2
       if (X[M[mid]] < X[i]):
           lo = mid+1
       else:
           hi = mid-1

   newL = lo
   P[i] = M[newL-1]
   M[newL] = i

   if (newL > L):
       L = newL

S = []
k = M[L]
for i in range(L-1, -1, -1):
    S.append(X[k])
    k = P[k]
return len(S[::-1])

Body:
Just check the returned value from the function on each shift:

max_increasing=longest_increasing_subsequence(X)
for i in range(len(X)-1):
    X=X.append(X.pop(0)) #shift X by 1
    if longest_increasing_subsequence(X)>max_increasing:
         max_increasing=longest_increasing_subsequence(X)


问:
In pyzmq, how do you stop a Proxy?
I have a server behind a firewall and a publicly available web server requesting info from the server.  I am using pyzmq to manage the communication between the backend and the web front end.  This work without a proxy in place, when they are communicating locally.  It works when using the proxy.  I can start up a ThreadProxy, but how do I stop it?

```<code>import zmq
from zmq.devices import ThreadProxy

class MyProxy:
    def __init__(self)
        p = ThreadProxy(zmq.ROUTER, zmq.DEALER) # Not using mon
        p.setsockopt_in(zmq.IDENTITY, b'ROUTER')
        p.setsockopt_out(zmq.IDENTITY, b'DEALER')
        p.bind_in('tcp://*:5550')
        p.connect_out('tcp://localhost:5550')
        self._proxy = p
    def start(self)
        self._proxy.start()
    def stop(self)
        ???
</code>```

How do I actually ask that proxy to stop? .join just waits, because the proxy is blocked or has no reason to stop.  I don't have a context to .term().

I would like to run this inside a linux daemon, so "kill" is not the most elegant solution, nor does it give me the control over the proxy I am looking for.

答:
The answer is that the proxy closes itself.

I think my problem was one of understanding.  The proxy is being started as a daemon (the default) and I did not know what that meant to Python.  When all non-daemon threads finish, the program ends.  What that means in this context is that the proxy stops when the rest of my program stops. I do not need to explicitly stop it.

As I am building an Linux service, this is precisely the functionality I want.  In the main thread, I will kick off the proxy, do something (like monitor the proxy) or nothing, and when I want to the service to stop, the main thread will wrap up, close and the proxy will die on it's own.

Title: In pyzmq, how do you stop a Proxy?

Body:
I have a server behind a firewall and a publicly available web server requesting info from the server.  I am using pyzmq to manage the communication between the backend and the web front end.  This work without a proxy in place, when they are communicating locally.  It works when using the proxy.  I can start up a ThreadProxy, but how do I stop it?

import zmq
from zmq.devices import ThreadProxy

class MyProxy:
    def __init__(self)
        p = ThreadProxy(zmq.ROUTER, zmq.DEALER) # Not using mon
        p.setsockopt_in(zmq.IDENTITY, b'ROUTER')
        p.setsockopt_out(zmq.IDENTITY, b'DEALER')
        p.bind_in('tcp://*:5550')
        p.connect_out('tcp://localhost:5550')
        self._proxy = p
    def start(self)
        self._proxy.start()
    def stop(self)
        ???

How do I actually ask that proxy to stop? .join just waits, because the proxy is blocked or has no reason to stop.  I don't have a context to .term().

I would like to run this inside a linux daemon, so "kill" is not the most elegant solution, nor does it give me the control over the proxy I am looking for.


问:
secure or encrypt smarty plugins
I am working on CMS system using smarty. The one cms system could support multiple websites with multiple websites, multiple templates, multiple plugins and components...

Client can register and create his website using pre existing templates and choose components to display them on that template.

My Question is that How i can make those component secure or encrypted. so if client take his site away from the server to another server, he won't able to use those module, components etc. or atleast these would expire after certain time..

I am going to create these components using smarty plugins.

Is there any solution in php, smarty ?

答:
As before mentioned IONCube do the job well, but if you need some fast solution without crypt or embarrassing the code with such a tool, then you need to code something... I remenber sometime ago I did a kind of tool, I crypt the data, then put it inside a database and after a time I retrieve that data, off course checking the passphrase key. This is the way, but sometimes it can make your server very slow, specialy if you have a lot of users.

good Luck man!

Title: secure or encrypt smarty plugins


问:
Make a camel-case function using a for loop in Javascript
I am brand new to Javascript and trying to figure out how to camel-case any string by using a for loop. This is what I have so far.

```<code>function camelCase(str) {
 var splitStr = "";
 var result = "";

 splitStr = str.split(" ");
 for(var i = 0; i < splitStr.length; i++){
 result += splitStr[i][0].toUpperCase() +
   splitStr[i].slice(1);
  }
  return result;
 }

console.log(camelCase("hello there people"));
</code>```

it returns "HelloTherePeople" - How do you I make the very first index of splitStr (splitStr[0][0]) be excluded from toUpperCase, but still included in the beginning of the string?

答:
What is your delimiter? This method assumes an underscore _. Change it to a space if you want a space. Or make it a variable you can pass to camelize.

```<code>if( !String.prototype.camelize )
    String.prototype.camelize = function(){
        return this.replace(/_+(.)?/g, function(match, chr) {
            return chr ? chr.toUpperCase() : '';
        });
    }

"a_new_string".camelize()
//"aNewString"
</code>```

The regex /_+(.)?/g/ says find 1 or more _ characters followed by any character ., the (.) creates a capturing group, so you are able to get that one character. It's passed to the function as the second paramater chr.  The ? means not greedy so it will stop at the next _. The g means globally, pretty much means find all matches.

String.prototype.replace reference

Body:
I am brand new to Javascript and trying to figure out how to camel-case any string by using a for loop. This is what I have so far.

function camelCase(str) {
 var splitStr = "";
 var result = "";

 splitStr = str.split(" ");
 for(var i = 0; i < splitStr.length; i++){
 result += splitStr[i][0].toUpperCase() +
   splitStr[i].slice(1);
  }
  return result;
 }

console.log(camelCase("hello there people"));

it returns "HelloTherePeople" - How do you I make the very first index of splitStr (splitStr[0][0]) be excluded from toUpperCase, but still included in the beginning of the string?

Body:
What is your delimiter? This method assumes an underscore _. Change it to a space if you want a space. Or make it a variable you can pass to camelize.

if( !String.prototype.camelize )
    String.prototype.camelize = function(){
        return this.replace(/_+(.)?/g, function(match, chr) {
            return chr ? chr.toUpperCase() : '';
        });
    }

"a_new_string".camelize()
//"aNewString"

The regex /_+(.)?/g/ says find 1 or more _ characters followed by any character ., the (.) creates a capturing group, so you are able to get that one character. It's passed to the function as the second paramater chr.  The ? means not greedy so it will stop at the next _. The g means globally, pretty much means find all matches.

String.prototype.replace reference


问:
Excel VBA If Statement to Find Cells That Contain A String
I'm looking to create an IF/Else statment in VBA that when run will return a True or False value based on if a cell contains a certain string of text.  So basically I want a True value returned if the cell contains the specified string or a False value if it does not contain the specified string.  This formula needs to run down a range of cells not just one if that makes a difference.  I'm thinking I need to use the InStr function, but I'm not 100% sure if that is correct or how to implement it.  I am fairly new to VBA so any help I can get would be greatly appreciated as I have been stuck on this for several hours.

Thank You

答:
Why use VBA? An expression in cell can return True/False.

=ISNUMBER(FIND("something",A1))

I tested @3vts code and it runs but the output is wrong. This version works:

```<code>Sub FindString()
Dim rng As Range
Set rng = ActiveSheet.Range("A1:A100")
For Each cell In rng.Cells
    If InStr(1, cell, "text to find") > 0 Then
        cell.Offset(0, 1).Value = True
    Else
        cell.Offset(0, 1).Value = False
    End If
Next
End Sub
</code>```

I certainly hope you learned something in spite of the work was done for you.

Body:
Why use VBA? An expression in cell can return True/False.

=ISNUMBER(FIND("something",A1))

I tested @3vts code and it runs but the output is wrong. This version works:

Sub FindString()
Dim rng As Range
Set rng = ActiveSheet.Range("A1:A100")
For Each cell In rng.Cells
    If InStr(1, cell, "text to find") > 0 Then
        cell.Offset(0, 1).Value = True
    Else
        cell.Offset(0, 1).Value = False
    End If
Next
End Sub

I certainly hope you learned something in spite of the work was done for you.


答:
You can do a check inside the loop to see if you are on the first index.

function camelCase(str) {
  //splitStr will be an array
  var splitStr = [];
  var result = "";

  splitStr = str.split(" ");

  //Capitalize first letter of words starting from the second one
  for(var i = 0; i < splitStr.length; i++){

    //first word
    if (i===0) {
      //Good practice to lowercase the first letter regardless of input
      result += splitStr[i][0].toLowerCase() + splitStr[i].slice(1);
    }

    else {
      //rest can proceed as before
      result += splitStr[i][0].toUpperCase() +
      splitStr[i].slice(1);
    }

  }

  return result;
  }

console.log(camelCase("hello there people"));```

Alternatively, the loop can even start on the second index. However, you will have to check if the length of splitStr before running a loop from the second index

Title: Make a camel-case function using a for loop in Javascript

Body:
You can do a check inside the loop to see if you are on the first index.

function camelCase(str) {
  //splitStr will be an array
  var splitStr = [];
  var result = "";

  splitStr = str.split(" ");

  //Capitalize first letter of words starting from the second one
  for(var i = 0; i < splitStr.length; i++){

    //first word
    if (i===0) {
      //Good practice to lowercase the first letter regardless of input
      result += splitStr[i][0].toLowerCase() + splitStr[i].slice(1);
    }

    else {
      //rest can proceed as before
      result += splitStr[i][0].toUpperCase() +
      splitStr[i].slice(1);
    }

  }

  return result;
  }

console.log(camelCase("hello there people"));

Alternatively, the loop can even start on the second index. However, you will have to check if the length of splitStr before running a loop from the second index


问:
Identify strings inside a vector using R
Can anyone help me in this problem?

I have a vector like this:

```<code>vec1 <- c("10F/I/V", "33F", "36I", "54A/L/M/S/T/V", "62V", "82A/C/F/G", "84V", "90M")
</code>```

And another one like this:

```<code>vec2 <- c("10F", "10L", "10I", "33G", "47A", "54A", "54T", "62V")
</code>```

I want to compute the result equal 3, because vec2 has the strings "10F" and "10I" that belongs to the same string "10F/I/V", it also has the strings "54A" and "54T" that belongs to "54A/L/M/S/T/V" and the "62V".

Thanks!

答:
You can expand your original vector vec1 to explicitly construct strings like 54A, 54L, 54M... Once you have that, you can find any pattern and call "match" as you go.

```<code>vec1 <- c("10F/I/V", "33F", "36I", "54A/L/M/S/T/V", "62V", "82A/C/F/G", "84V", "90M")

vec2 <- c("10F", "10L", "10I", "33G", "47A", "54A", "54T", "62V")

out1 <- mapply(x = gsub("(^\\d+)(.*$)", "\\1", vec1),
               y = strsplit(gsub("\\d+", "", vec1), "/"),
               FUN = function(x, y) {
                 # expands the vector to make comparisons easy using regex
                 xy <- paste(x, y, sep = "")
                 # finds individual combination
                 m <- sapply(xy, FUN = grepl, vec2)
                 # finds if strings appears in original element (element is a column)
                 apply(m, MARGIN = 2, any)
               })

> sapply(out1, any)
   10    33    36    54    62    82    84    90
 TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
> sum(sapply(out1, any))
[1] 3
</code>```

Body:
Can anyone help me in this problem?

I have a vector like this:

vec1 <- c("10F/I/V", "33F", "36I", "54A/L/M/S/T/V", "62V", "82A/C/F/G", "84V", "90M")

And another one like this:

vec2 <- c("10F", "10L", "10I", "33G", "47A", "54A", "54T", "62V")

I want to compute the result equal 3, because vec2 has the strings "10F" and "10I" that belongs to the same string "10F/I/V", it also has the strings "54A" and "54T" that belongs to "54A/L/M/S/T/V" and the "62V".

Thanks!

Body:
You can expand your original vector vec1 to explicitly construct strings like 54A, 54L, 54M... Once you have that, you can find any pattern and call "match" as you go.

vec1 <- c("10F/I/V", "33F", "36I", "54A/L/M/S/T/V", "62V", "82A/C/F/G", "84V", "90M")

vec2 <- c("10F", "10L", "10I", "33G", "47A", "54A", "54T", "62V")

out1 <- mapply(x = gsub("(^\\d+)(.*$)", "\\1", vec1),
               y = strsplit(gsub("\\d+", "", vec1), "/"),
               FUN = function(x, y) {
                 # expands the vector to make comparisons easy using regex
                 xy <- paste(x, y, sep = "")
                 # finds individual combination
                 m <- sapply(xy, FUN = grepl, vec2)
                 # finds if strings appears in original element (element is a column)
                 apply(m, MARGIN = 2, any)
               })

> sapply(out1, any)
   10    33    36    54    62    82    84    90
 TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
> sum(sapply(out1, any))
[1] 3


问:
How to create two views in Android that use 50% height each, unless one is smaller?
Imagine a full Android device screen, I want it split in to two sections:

The upper half has text in it, which may be larger than the space available (or not) and so the text will scroll (i.e. TextView inside a ScrollView)

The lower half contains a MapView control.

Looking specifically at some scenarios:

If the text is small, I want the map to take up more space, i.e. more than 50%. So perhaps 20% text, 80% map.

If the text is larger, it only takes up a MAXIMUM of 50% of the screen space, and then scrolls. So 50% map, 50% text.

At the moment I've assigned weights to the two parts, and that isn't too bad, but if the text is small, the map doesn't expand to take the space, and the layout has a wasted gap that the map could usefully use.

I've tried loads of combinations but can't see how to make this happen. It seems to be a common experience for me that I know what I want, but can't see how to get the available views to deliver it. I'm hoping there's a nice easy way to do this.

Please feel free to make me look like a fool and point out the obvious attribute I've missed :-)

======================================================================

As far as I can see there's no way to do this just in declarative XML and it needs doing in the code. I set the text section height to wrap_content, weight to 0 (no resizing), and have the map set to weight=1 (i.e. take up the remaining space). I then check if the text section (in a ScrollView) is taking up too much space and if so, shrink it back. This code would need changing to support a different layout orientation.

```<code>private void fixLayoutProportions()
{
    float maxPercentageOfScreenForText = 50/100;
    LinearLayout container = (LinearLayout)findViewById(R.id.container);
    ScrollView eventText = (ScrollView)findViewById(R.id.text_scroller);
    int heightAvailable = container.getHeight();
    int scrollerHeight = eventText.getHeight();
    if ( scrollerHeight>(heightAvailable*maxPercentageOfScreenForText) )      // Text section using too much space
    {
        eventText.getLayoutParams().height = (int)(heightAvailable*maxPercentageOfScreenForText) ;
        eventText.invalidate();
    }
}
</code>```

答:
You can do it by putting everything into LinearLayout and changing following parameters:

the sum of weights for LienarLayout

weights for children

Body:
Imagine a full Android device screen, I want it split in to two sections:

The upper half has text in it, which may be larger than the space available (or not) and so the text will scroll (i.e. TextView inside a ScrollView)

The lower half contains a MapView control.

Looking specifically at some scenarios:

If the text is small, I want the map to take up more space, i.e. more than 50%. So perhaps 20% text, 80% map.

If the text is larger, it only takes up a MAXIMUM of 50% of the screen space, and then scrolls. So 50% map, 50% text.

At the moment I've assigned weights to the two parts, and that isn't too bad, but if the text is small, the map doesn't expand to take the space, and the layout has a wasted gap that the map could usefully use.

I've tried loads of combinations but can't see how to make this happen. It seems to be a common experience for me that I know what I want, but can't see how to get the available views to deliver it. I'm hoping there's a nice easy way to do this.

Please feel free to make me look like a fool and point out the obvious attribute I've missed :-)

======================================================================

As far as I can see there's no way to do this just in declarative XML and it needs doing in the code. I set the text section height to wrap_content, weight to 0 (no resizing), and have the map set to weight=1 (i.e. take up the remaining space). I then check if the text section (in a ScrollView) is taking up too much space and if so, shrink it back. This code would need changing to support a different layout orientation.

private void fixLayoutProportions()
{
    float maxPercentageOfScreenForText = 50/100;
    LinearLayout container = (LinearLayout)findViewById(R.id.container);
    ScrollView eventText = (ScrollView)findViewById(R.id.text_scroller);
    int heightAvailable = container.getHeight();
    int scrollerHeight = eventText.getHeight();
    if ( scrollerHeight>(heightAvailable*maxPercentageOfScreenForText) )      // Text section using too much space
    {
        eventText.getLayoutParams().height = (int)(heightAvailable*maxPercentageOfScreenForText) ;
        eventText.invalidate();
    }
}


问:
Take input in arrays of pointers
Can someone please let me know why one can't take an input in arrays of pointer to strings using input stream as in the following code: </p>

```<code>char *names[5];

for(int i=0; i<5; i++)
{
cout<<"enter name "<<i+1;
cin>>names[i];
}
</code>```

答:
Disclaimer:
using char* for reading from std::cin is generally a bad idea and I suggest you learn how to use std::string in future.

Also this question would have been better suited for codereview.SE but I'll ignore that for now.

Here is an example of doing what you want to do, but I strongly insist you avoid doing it in any real code.

```<code>char * names[5];

// Allocate names
for (int i = 0; i < 5; i++)
{
    // Use 256 characters as a buffer
    // any names longer than that might cause errors
    names[i] = new char[256];
}

// Do IO
for (int i = 0; i<5; i++)
{
    // Append std::endl
    std::cout << "enter name " << i + 1 << std::endl;
    // This isn't very robust since the user can give anything as a name,
    // and they can't use spaces because of how cin works in this example.
    std::cin >> names[i];
}

// Use names
for (int i = 0; i < 5; i++)
{
    // Printing names is just an example
    // you could write the names to somewhere more important
    // you could copy them to a smaller location to use less memory
    std::cout << names[i] << std::endl;
}

// Dispose of names when done
for (int i = 0; i < 5; i++)
{
    // Check pointer isn't null
    if (names[i] != nullptr)
    {
        // Never forget to delete
        delete names[i];
    }
}
</code>```

Title: Take input in arrays of pointers

Body:
Can someone please let me know why one can't take an input in arrays of pointer to strings using input stream as in the following code:

char *names[5];

for(int i=0; i<5; i++)
{
cout<<"enter name "<>names[i];
}

Body:
Disclaimer:
using char* for reading from std::cin is generally a bad idea and I suggest you learn how to use std::string in future.

Also this question would have been better suited for codereview.SE but I'll ignore that for now.

Here is an example of doing what you want to do, but I strongly insist you avoid doing it in any real code.

char * names[5];

// Allocate names
for (int i = 0; i < 5; i++)
{
    // Use 256 characters as a buffer
    // any names longer than that might cause errors
    names[i] = new char[256];
}

// Do IO
for (int i = 0; i<5; i++)
{
    // Append std::endl
    std::cout << "enter name " << i + 1 << std::endl;
    // This isn't very robust since the user can give anything as a name,
    // and they can't use spaces because of how cin works in this example.
    std::cin >> names[i];
}

// Use names
for (int i = 0; i < 5; i++)
{
    // Printing names is just an example
    // you could write the names to somewhere more important
    // you could copy them to a smaller location to use less memory
    std::cout << names[i] << std::endl;
}

// Dispose of names when done
for (int i = 0; i < 5; i++)
{
    // Check pointer isn't null
    if (names[i] != nullptr)
    {
        // Never forget to delete
        delete names[i];
    }
}