问:
Can't use CAIDA Dataset with tcpreplay to simulate network traffic in network
I have a server and I need to simulate real network traffic. I've been asked to do this using a CAIDA Dataset. I have downloaded the public Dataset which can be found here:
CAIDA Public Dataset

I also need to rewrite the source ip address in the .pcap file to be the one of the server. I tried doing it the way it's described at the end of this page: tcprewrite wiki

I run:

```<code>tcprewrite --infile=oc48-mfn.dirA.20020814-160000.UTC.anon.pcap --outfile=oc48-mfn.dirA.20020814-160000.UTC.anon_rewrite.pcap --dstipmap=0.0.0.0/0:10.101.30.60 --enet-dmac=00:0c:29:00:b1:bd
</code>```

And I get:

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

Fatal Error: From ./plugins/dlt_hdlc/hdlc.c:dlt_hdlc_encode() line 255:
  Non-HDLC packet requires --hdlc-address

So after some tries like this I finally run these to get an error free tcprewrite:

```<code>tcpprep --auto=bridge --pcap=oc48-mfn.dirA.20020814-160000.UTC.anon.pcap --cachefile=cache1.cache
</code>```

Which gives:

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

And then I run:

```<code>tcprewrite --infile=oc48-mfn.dirA.20020814-160000.UTC.anon.pcap --outfile=oc48-mfn.dirA.20020814-160000.UTC.anon_rewrite.pcap --dstipmap=0.0.0.0/0:10.101.30.60 --enet-dmac=00:0c:29:00:b1:bd --cachefile=cache1.cache --hdlc-control=0 --hdlc-address=0xBF
</code>```

And I get:

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

So it seems like a success, except the warning that shows up in every command.
I open the new .pcap file with tcpdump to check that the destination IP addresses have changed to the one of the server and it has been done.

So then I run tcpreplay:

```<code>tcpreplay -i ens160 --loop 5  --unique-ip oc48-mfn.dirA.20020814-160000.UTC.anon.pcap
</code>```

And I run tcpdump on the server to see the traffic from the .pcap file, but the traffic looks like this:

13:30:50.194780 05:8c:55:6f:40:00 (oui Unknown) > 0f:00:08:00:45:00 (oui

Unknown), ethertype Unknown (0x3406), length 60:

0x0000:  ed11 f484 7785 f477 0d79 0050 0487 007c  ....w..w.y.P...|

0x0010:  e7d5 d203 c32b 5010 27f7 aa51 0000 4854  .....+P.'..Q..HT

0x0020:  5450 0000 0000 0000 0000 0000 0000       TP............

I have tried the smallFlow.pcap from the sample captures of tcpreplay: Sample Captures

and it worked just fine.

So any suggestions on how to properly use the CAIDA .pcap files?

答:
Your stated goal is "I need to simulate real network traffic", but you're using pcaps where "the payload has been removed from all packets" (per the CAIDA web page you linked to).

These two statements are in conflict with each other.  All your packets are literally no larger then 48bytes which is merely enough for the TCP/IP header (and then even so, may not be sufficient in all cases).  This is what the warning is telling you.  You can't put the data back.

You'll need to find a new source of pcaps.

Body:
I have a server and I need to simulate real network traffic. I've been asked to do this using a CAIDA Dataset. I have downloaded the public Dataset which can be found here:
CAIDA Public Dataset

I also need to rewrite the source ip address in the .pcap file to be the one of the server. I tried doing it the way it's described at the end of this page: tcprewrite wiki

I run:

tcprewrite --infile=oc48-mfn.dirA.20020814-160000.UTC.anon.pcap --outfile=oc48-mfn.dirA.20020814-160000.UTC.anon_rewrite.pcap --dstipmap=0.0.0.0/0:10.101.30.60 --enet-dmac=00:0c:29:00:b1:bd

And I get:

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

Fatal Error: From ./plugins/dlt_hdlc/hdlc.c:dlt_hdlc_encode() line 255:
  Non-HDLC packet requires --hdlc-address

So after some tries like this I finally run these to get an error free tcprewrite:

tcpprep --auto=bridge --pcap=oc48-mfn.dirA.20020814-160000.UTC.anon.pcap --cachefile=cache1.cache

Which gives:

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

And then I run:

tcprewrite --infile=oc48-mfn.dirA.20020814-160000.UTC.anon.pcap --outfile=oc48-mfn.dirA.20020814-160000.UTC.anon_rewrite.pcap --dstipmap=0.0.0.0/0:10.101.30.60 --enet-dmac=00:0c:29:00:b1:bd --cachefile=cache1.cache --hdlc-control=0 --hdlc-address=0xBF

And I get:

Warning: oc48-mfn.dirA.20020814-160000.UTC.anon.pcap was captured using a snaplen of 48 bytes.  This may mean you have truncated packets.

So it seems like a success, except the warning that shows up in every command.
I open the new .pcap file with tcpdump to check that the destination IP addresses have changed to the one of the server and it has been done.

So then I run tcpreplay:

tcpreplay -i ens160 --loop 5  --unique-ip oc48-mfn.dirA.20020814-160000.UTC.anon.pcap

And I run tcpdump on the server to see the traffic from the .pcap file, but the traffic looks like this:

13:30:50.194780 05:8c:55:6f:40:00 (oui Unknown) > 0f:00:08:00:45:00 (oui

Unknown), ethertype Unknown (0x3406), length 60:

0x0000:  ed11 f484 7785 f477 0d79 0050 0487 007c  ....w..w.y.P...|

0x0010:  e7d5 d203 c32b 5010 27f7 aa51 0000 4854  .....+P.'..Q..HT

0x0020:  5450 0000 0000 0000 0000 0000 0000       TP............

I have tried the smallFlow.pcap from the sample captures of tcpreplay: Sample Captures

and it worked just fine.

So any suggestions on how to properly use the CAIDA .pcap files?


来源: stackexchange

问:
A robust solution for FileSystemWatcher firing events multiple times
FileSystemWatcher events can fire multiple times. Not good if I need predictable behaviour from my code.

This is described in the MSDN documentation:

Common file system operations might raise more than one event. For
  example, when a file is moved from one directory to another, several
  OnChanged and some OnCreated and OnDeleted events might be raised.
  Moving a file is a complex operation that consists of multiple simple
  operations, therefore raising multiple events. Likewise, some
  applications (for example, antivirus software) might cause additional
  file system events that are detected by FileSystemWatcher.

Good use of NotifyFilters with particular events has helped but won't give me 100% confidence in the consistency.

Here's an example, recreating a Notepad write example (but I have experienced this with other write actions too):

```<code> public ExampleAttributesChangedFiringTwice(string demoFolderPath)
 {
     var watcher = new FileSystemWatcher()
     {
          Path = @"c:\temp",
          NotifyFilter = NotifyFilters.LastWrite,
          Filter = "*.txt"
      };

      watcher.Changed += OnChanged;
      watcher.EnableRaisingEvents = true;
  }

  private static void OnChanged(object source, FileSystemEventArgs e)
  {
      // This will fire twice if I edit a file in Notepad
  }
</code>```

Any suggestions for making this more resilient?

EDIT: meaning not repeating multiple actions when multiple events are triggered.

答:
I use a FileSystemWatcher to check for MP4 files being uploaded that I ultimately have to do something with. The process doing the upload doesn't seem to establish any lock on the file, so I formerly struggled with starting the processing of them too early.

The technique I adopted in the end, which has been entirely successful for my case, was to consume the event and add the filepath to a Dictionary<string, long> of potentially interesting files, and start a timer. Periodically (60 seconds) I check the file size. The long dictionary value holds the file size from the last check, and if the current size is greater I deem it still being written to, store the new size and go back to sleep for another 60 seconds.

Upon there being a period of 60 seconds where no write activity has occurred, I can start processing.

If this isn't suitable for you, there are a few other things you could consider; hash the file every minute and store the hash instead, re-hash it periodically until the content hasn't changed. Keep tabs on the Last Modified date in the file system, perhaps

Ultimately, consider that FileSYstemWatcher might be a useful device not for notifying you which files you have to act on, but instead for files that are potentially interesting, and a separate process with more refined in-house logic can decide if a potentially interesting file should be acted on

ContentLicense: CC BY-SA 3.0

Body:
FileSystemWatcher events can fire multiple times. Not good if I need predictable behaviour from my code.

This is described in the MSDN documentation:

Common file system operations might raise more than one event. For
  example, when a file is moved from one directory to another, several
  OnChanged and some OnCreated and OnDeleted events might be raised.
  Moving a file is a complex operation that consists of multiple simple
  operations, therefore raising multiple events. Likewise, some
  applications (for example, antivirus software) might cause additional
  file system events that are detected by FileSystemWatcher.

Good use of NotifyFilters with particular events has helped but won't give me 100% confidence in the consistency.

Here's an example, recreating a Notepad write example (but I have experienced this with other write actions too):

 public ExampleAttributesChangedFiringTwice(string demoFolderPath)
 {
     var watcher = new FileSystemWatcher()
     {
          Path = @"c:\temp",
          NotifyFilter = NotifyFilters.LastWrite,
          Filter = "*.txt"
      };

      watcher.Changed += OnChanged;
      watcher.EnableRaisingEvents = true;
  }

  private static void OnChanged(object source, FileSystemEventArgs e)
  {
      // This will fire twice if I edit a file in Notepad
  }

Any suggestions for making this more resilient?

EDIT: meaning not repeating multiple actions when multiple events are triggered.


问:
Why can struct change their own fields?
Consider the Foo struct as follows:

```<code>struct Foo
{
  public float X;
  public float Y;

  public Foo(float x, float y)
  {
    this.X = x;
    this.Y = y;
  }

  public void Change(float x)
  {
    this.X = x;
  }
}
</code>```

I understand modifying the field in the constructor, that's perfectly logical to me and my understanding of structs as value, number-like immutable types.

However, since one can't do:

```<code>Foo bar = new Foo(1, 2);
bar.X = 5;
</code>```

Why can one use:

```<code>Foo bar = new Foo(1, 2);
bar.Change(5);
</code>```

EDIT: If structs are mutable, then why can't they be modified when in a list or returned from a property?

Cannot modify expression because it is not a variable

答:
Since one cannot do

```<code>Foo bar = new Foo(1, 2);
bar.X = 5;
</code>```

Why can one use:

```<code>Foo bar = new Foo(1, 2);
bar.Change(5);
</code>```

Your original question actually cannot be answered because it is predicated on a completely false assumption. Both code samples are perfectly legal, and so the question about why one is illegal is nonsensical. Let's move on to your follow-up question:

If structs are mutable, then why can't they be modified when in a list or returned from a property?

Because variables are mutable and values are immutable.

That's why they're called "variables", after all, because they can change.

When you say "bar.X = 5", "bar" is a local variable. Variables are allowed to change.

When you say "bar.Change(5)", "bar" is a local variable. Variables are allowed to change.

When you say "myArray[123].X = 5", "myArray[123]" is an array element and an array element is a variable. Variables are allowed to change.

When you say "myDictionary[123].X = 5", "myDictionary[123]" is not a variable. The value is returned from the dictionary, not a reference to the storage location. Since that is a value, not a variable, there is nothing there that can change, so the compiler does not allow it to change.

A subtle point is that when you attempt to change a field, the receiver must be a variable. If it is not a variable, it makes no sense; you are clearly attempting to mutate a variable and there's nothing there to mutate. When you call a method, the receiver must be a variable but what if you have a value? The method might not attempt to mutate anything, and so should be allowed to succeed. What the compiler actually does if the receiver of a method call on a struct is not a variable, then it makes a new temporary local variable and calls the method with that variable. So if you say: "myDictionary[123].Change(5);" that is the same as saying

```<code>var temp = myDictionary[123];
temp.Change(5);
</code>```

Here "temp" is a variable, and the mutating method is allowed to change the temporary copy.

Is that now clear?  The key takeaway here is variables can change.

ContentLicense: CC BY-SA 2.5

Title: Why can struct change their own fields?

Body:
Consider the Foo struct as follows:

struct Foo
{
  public float X;
  public float Y;

  public Foo(float x, float y)
  {
    this.X = x;
    this.Y = y;
  }

  public void Change(float x)
  {
    this.X = x;
  }
}

I understand modifying the field in the constructor, that's perfectly logical to me and my understanding of structs as value, number-like immutable types.

However, since one can't do:

Foo bar = new Foo(1, 2);
bar.X = 5;

Why can one use:

Foo bar = new Foo(1, 2);
bar.Change(5);

EDIT: If structs are mutable, then why can't they be modified when in a list or returned from a property?

Cannot modify expression because it is not a variable

Body:
Since one cannot do

Foo bar = new Foo(1, 2);
bar.X = 5;

Why can one use:

Foo bar = new Foo(1, 2);
bar.Change(5);

Your original question actually cannot be answered because it is predicated on a completely false assumption. Both code samples are perfectly legal, and so the question about why one is illegal is nonsensical. Let's move on to your follow-up question:

If structs are mutable, then why can't they be modified when in a list or returned from a property?

Because variables are mutable and values are immutable.

That's why they're called "variables", after all, because they can change.

When you say "bar.X = 5", "bar" is a local variable. Variables are allowed to change.

When you say "bar.Change(5)", "bar" is a local variable. Variables are allowed to change.

When you say "myArray[123].X = 5", "myArray[123]" is an array element and an array element is a variable. Variables are allowed to change.

When you say "myDictionary[123].X = 5", "myDictionary[123]" is not a variable. The value is returned from the dictionary, not a reference to the storage location. Since that is a value, not a variable, there is nothing there that can change, so the compiler does not allow it to change.

A subtle point is that when you attempt to change a field, the receiver must be a variable. If it is not a variable, it makes no sense; you are clearly attempting to mutate a variable and there's nothing there to mutate. When you call a method, the receiver must be a variable but what if you have a value? The method might not attempt to mutate anything, and so should be allowed to succeed. What the compiler actually does if the receiver of a method call on a struct is not a variable, then it makes a new temporary local variable and calls the method with that variable. So if you say: "myDictionary[123].Change(5);" that is the same as saying

var temp = myDictionary[123];
temp.Change(5);

Here "temp" is a variable, and the mutating method is allowed to change the temporary copy.

Is that now clear?  The key takeaway here is variables can change.


问:
Removing a number from a listed created by given numbers
so here's the details.
I'm coding using java - BlueJ, and currently have a main class Auction, and a few other classes: Lot, Person, Bid

The purpose of the program is to enter items into the auction, along with their prices, where the information will be stored according to whether it's price, person, or item name/description.

This is the code for my getLot method - user inputs lot number, and it shows info for the lot, which I assume should also be the starting point for the removeLot method since it should still check if the lot number given is valid first.

I'm trying to figure out how to add a removeLot method so that I can remove an item from the lot by typing in its lot number.

This is the code I have for that section.

```<code>public Lot removeLot(int number)
 {
    if((number >= 1) && (number < nextLotNumber)) {
        // The number seems to be reasonable.
        Lot selectedLot = lots.get(number - 1);
        // Include a confidence check to be sure we have the
        // right lot.
        if(selectedLot.getNumber() != number) {
            System.out.println("Internal error: Lot number " +
                selectedLot.getNumber() +
                " was returned instead of " +
                number);
            // Don't return an invalid lot.
            selectedLot = null;
        }
        **else {
        Lot.removeIf(selectedLot.getNumber() = number);**
        }
        return selectedLot;
</code>```

The else block with the "**" is what I added, wanting to remove the given number. But it's clearly wrong, and I'm not sure what to do.

答:
Lot.removeIf(selectedLot.getNumber() = number) is not correct

you can try:

```<code>} else if(selectedLot.getNumber() == number) {
   Lot.removeIf(selectedLot.getNumber());
}
</code>```

Body:
so here's the details.
I'm coding using java - BlueJ, and currently have a main class Auction, and a few other classes: Lot, Person, Bid

The purpose of the program is to enter items into the auction, along with their prices, where the information will be stored according to whether it's price, person, or item name/description.

This is the code for my getLot method - user inputs lot number, and it shows info for the lot, which I assume should also be the starting point for the removeLot method since it should still check if the lot number given is valid first.

I'm trying to figure out how to add a removeLot method so that I can remove an item from the lot by typing in its lot number.

This is the code I have for that section.

public Lot removeLot(int number)
 {
    if((number >= 1) && (number < nextLotNumber)) {
        // The number seems to be reasonable.
        Lot selectedLot = lots.get(number - 1);
        // Include a confidence check to be sure we have the
        // right lot.
        if(selectedLot.getNumber() != number) {
            System.out.println("Internal error: Lot number " +
                selectedLot.getNumber() +
                " was returned instead of " +
                number);
            // Don't return an invalid lot.
            selectedLot = null;
        }
        **else {
        Lot.removeIf(selectedLot.getNumber() = number);**
        }
        return selectedLot;

The else block with the "**" is what I added, wanting to remove the given number. But it's clearly wrong, and I'm not sure what to do.

Body:
Lot.removeIf(selectedLot.getNumber() = number) is not correct

you can try:

} else if(selectedLot.getNumber() == number) {
   Lot.removeIf(selectedLot.getNumber());
}


问:
TypeError: modules[moduleId] is undefined
I am trying to run jasmine unit testing with Jenkins using Firefox browser on Linux and I keep having this behavior:

```<code>[32m02 08 2017 08:16:26.443:INFO [Firefox 50.0.0 (Windows 8.1 0.0.0)]:  [39mConnected on socket /#KYlvgi9JYtXnD1jZAAAB with id manual-931
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
  TypeError: modules[moduleId] is undefined
  at http://52.5.4.155:9876/_karma_webpack_/inline.bundle.js:55
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
  TypeError: modules[moduleId] is undefined
  at http://52.5.4.155:9876/_karma_webpack_/inline.bundle.js:55

[33m02 08 2017 08:21:27.750:WARN [Firefox 50.0.0 (Windows 8.1 0.0.0)]:  [39mDisconnected (1 times)
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
Disconnectedundefined
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
Disconnectedundefined
</code>```

The exception is on this Line of code:

```<code>// Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
</code>```

I research a lot about the issue, but I couldn't find any solution. Is there anyone that can help me to solve it.

答:
I faced same issue and found that in Karma.conf.js, I was using wrong configuration for "files" as

```<code>module.exports = function (config) {
config.set({
    basePath: '.',
    frameworks: ['jasmine'],
    files: [
        '../../ClientApp/dist/vendor.js',
        './boot-tests.ts'
    ],
</code>```

Modified this to target only files which contain unit tests as

```<code>module.exports = function (config) {
config.set({
    basePath: '.',
    frameworks: ['jasmine'],
    files: [
        '../../ClientApp/**/*.spec.ts'
    ],
</code>```

and now I don't get this error. Though something else going wrong in my tests so getting other errors but seems this specific issue resolved.

Body:
I am trying to run jasmine unit testing with Jenkins using Firefox browser on Linux and I keep having this behavior:

[32m02 08 2017 08:16:26.443:INFO [Firefox 50.0.0 (Windows 8.1 0.0.0)]:  [39mConnected on socket /#KYlvgi9JYtXnD1jZAAAB with id manual-931
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
  TypeError: modules[moduleId] is undefined
  at http://52.5.4.155:9876/_karma_webpack_/inline.bundle.js:55
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
  TypeError: modules[moduleId] is undefined
  at http://52.5.4.155:9876/_karma_webpack_/inline.bundle.js:55

[33m02 08 2017 08:21:27.750:WARN [Firefox 50.0.0 (Windows 8.1 0.0.0)]:  [39mDisconnected (1 times)
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
Disconnectedundefined
Firefox 50.0.0 (Windows 8.1 0.0.0) ERROR
Disconnectedundefined

The exception is on this Line of code:

// Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

I research a lot about the issue, but I couldn't find any solution. Is there anyone that can help me to solve it.

Body:
I faced same issue and found that in Karma.conf.js, I was using wrong configuration for "files" as

module.exports = function (config) {
config.set({
    basePath: '.',
    frameworks: ['jasmine'],
    files: [
        '../../ClientApp/dist/vendor.js',
        './boot-tests.ts'
    ],

Modified this to target only files which contain unit tests as

module.exports = function (config) {
config.set({
    basePath: '.',
    frameworks: ['jasmine'],
    files: [
        '../../ClientApp/**/*.spec.ts'
    ],

and now I don't get this error. Though something else going wrong in my tests so getting other errors but seems this specific issue resolved.


问:
Create a list of all classes in namespace using reflection and cast to their real type
I have an abstract class Device. A number of classes derive from it, which represent specific devices. So we have, e.g. class RedDevice : Device, class BlueDevice : Device, etc. They are all stored under the Foo.Devices namespace. Here's an overview of the structure:

```<code>- Foo
|  ↳ Devices (folder)
|  |   ↳ RedDevice
|  |   ↳ BlueDevice
|  ↳ Device
</code>```

Device.cs:

```<code>internal abstract class Device
{
    internal string Path { get; set; }
}
</code>```

RedDevice.cs:

```<code>class RedDevice
{
    internal RedDevice()
    {
        this.Path = "/path";
    }
}
</code>```

I want to create a list with all devices under Foo.Devices, cast to their parent class Device. I can get a list of Types using the following code:

```<code>List<System.Type> deviceTypes =
    Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace ==
    typeof(RedDevice).Namespace).ToList();
</code>```

But how can I cast them to Device? Direct cast isn't allowed by the compiler and everything else throws wrong type exceptions. Thanks!

答: SOLVED: The issue was I had internal constructors and the System.Activator couldn't create an instance of the class.

Body:
I have an abstract class Device. A number of classes derive from it, which represent specific devices. So we have, e.g. class RedDevice : Device, class BlueDevice : Device, etc. They are all stored under the Foo.Devices namespace. Here's an overview of the structure:

- Foo
|  ↳ Devices (folder)
|  |   ↳ RedDevice
|  |   ↳ BlueDevice
|  ↳ Device

Device.cs:

internal abstract class Device
{
    internal string Path { get; set; }
}

RedDevice.cs:

class RedDevice
{
    internal RedDevice()
    {
        this.Path = "/path";
    }
}

I want to create a list with all devices under Foo.Devices, cast to their parent class Device. I can get a list of Types using the following code:

List<System.Type> deviceTypes =
    Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace ==
    typeof(RedDevice).Namespace).ToList();

But how can I cast them to Device? Direct cast isn't allowed by the compiler and everything else throws wrong type exceptions. Thanks!


问:
Bind dynamic choices to ModelForm in Django
I'm trying to bind a dynamic list of choices to a ModelForm. The form is rendered correctly. However, when using the form with a POST Request, I get an empty form back. My goal is to save that form into the database (form.save()). Any help would be much appreciated.

Model

I'm using a multiple choice select field ( https://github.com/goinnn/django-multiselectfield )

```<code>from django.db import models
from multiselectfield import MultiSelectField

class VizInfoModel(models.Model):

     tog = MultiSelectField()
     vis = MultiSelectField()
</code>```

Forms

```<code>class VizInfoForm(forms.ModelForm):

    class Meta:
        model = VizInfoModel
        fields = '__all__'

    def __init__(self,choice,*args,**kwargs):
        super(VizInfoForm, self).__init__(*args,**kwargs)
        self.fields['tog'].choices = choice
        self.fields['vis'].choices = choice
</code>```

View

Choices are passed from the view when instantiating the form.

```<code>def viz_details(request):

    options = []
    headers = request.session['headers']
    for header in headers :
        options.append((header, header))

    if request.method == 'POST':
        form = VizInfoForm(options, request.POST)
        #doesnt' get into the if statement since form is empty!
        #choices are not bounded to the model although the form is perfectly rendered
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/upload')
    else:
        #this works just fine
        form = VizInfoForm(options)
        return render(request, 'uploads/details.html', {'form': form})
</code>```

Template

```<code>  <form method="post" enctype="multipart/form-data">
        {% csrf_token %}

         <p>Choose variables to toggle between</p>
        {{ form.tog }}

        <br></br>
        <p>Choose variable to be visualized</p>
        {{ form.vis }}

        <br></br>

        <button type="submit">Submit</button>
    </form>
</code>```

答:
You're saying Django doesn't get into your if request.method == 'POST' block.

This tells us that you're not sending your request through the POST method. Your template probably has an error in it, maybe you haven't specified the method on your form, or you made your button to just be a link instead of a submit ?

Show your template so we can say more, unless this was enough to solve your question !

Body:
I'm trying to bind a dynamic list of choices to a ModelForm. The form is rendered correctly. However, when using the form with a POST Request, I get an empty form back. My goal is to save that form into the database (form.save()). Any help would be much appreciated.

Model

I'm using a multiple choice select field ( https://github.com/goinnn/django-multiselectfield )

from django.db import models
from multiselectfield import MultiSelectField

class VizInfoModel(models.Model):

     tog = MultiSelectField()
     vis = MultiSelectField()

Forms

class VizInfoForm(forms.ModelForm):

    class Meta:
        model = VizInfoModel
        fields = '__all__'

    def __init__(self,choice,*args,**kwargs):
        super(VizInfoForm, self).__init__(*args,**kwargs)
        self.fields['tog'].choices = choice
        self.fields['vis'].choices = choice

View

Choices are passed from the view when instantiating the form.

def viz_details(request):

    options = []
    headers = request.session['headers']
    for header in headers :
        options.append((header, header))

    if request.method == 'POST':
        form = VizInfoForm(options, request.POST)
        #doesnt' get into the if statement since form is empty!
        #choices are not bounded to the model although the form is perfectly rendered
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/upload')
    else:
        #this works just fine
        form = VizInfoForm(options)
        return render(request, 'uploads/details.html', {'form': form})

Template

  <form method="post" enctype="multipart/form-data">
        {% csrf_token %}

Choose variables to toggle between

        {{ form.tog }}

Choose variable to be visualized

        {{ form.vis }}

        <button type="submit">Submit</button>
    </form>


问:
AJAX timing in IE
Chrome has its developer tools that times ajax latency, firefox has firebug, but what do you do in IE? I would have thought firebug lite, but apparently it doesn't time ajax calls (at least not in IE6). How do you do it?</p>

答: Fiddler is a great tool to add to your toolbox</p>

Title: AJAX timing in IE


问:
Runs for the first iteration and fails in the second
This particular code of mine, runs for the first iteration, however, as it continues it shows the following error:

```<code>Traceback (most recent call last):

  File "test1.py", line 7, in <module>

    if len((hex(s)[2:])) == 1:

TypeError: 'str' object is not callable
</code>```

The code is as follows:

```<code>import turtle

t = turtle.Turtle()

s = 0

z = 30

for i in range(s,16777217):[enter image description here][1]

    if len((hex(s)[2:])) == 1:

        hex = '#' + '00000' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 2:

        hex = '#' + '0000' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 3:

        hex = '#' + '000' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 4:

        hex = '#' + '00' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 5:

        hex = '#' + '0' + hex(s)[2:].upper()

    else:

        hex = '#' + hex(s)[2:].upper()

    t.color(hex)

    t.circle(z)

    s += 1

    z += 1
</code>```

答:
Besides the hex vs. hex() issue that @Kevin nicely points out (+1), I don't believe your code will achieve it's goal for several reasons:

Your end target should be 16777216, not 16777217 as that value - 1 doesn't fit into a 6 digit hex string; your circle is askew relative to the origin; your window isn't large enough for the number of colors you generate -- you need a step in your for loop that's significantly larger than 1; your code will take a very long time to complete and will mostly be drawing off screen during that time.

Below is my rework of your code addressing the above issues:

```<code>from turtle import Turtle, Screen

SIZE = 1000
LIMIT = 2 ** 24
INCREMENT = int(LIMIT / (2 ** 0.5 * SIZE / 2))  # fill to corners

screen = Screen()
screen.setup(SIZE, SIZE)
screen.tracer(0)

yertle = Turtle(visible=False)
yertle.speed('fastest')

for radius, n in enumerate(range(0, LIMIT, INCREMENT)):

    my_hex = '#' + format(n, "06X")

    yertle.color(my_hex)

    yertle.penup()
    yertle.sety(yertle.ycor() - 1)
    yertle.pendown()

    yertle.circle(radius)
    screen.update()  # only show completed circles

screen.exitonclick()
</code>```

If we want to maximize colors on a typical screen, we switch to a 1024 x 1024 window; allocate the 10 bits of color unevenly but always as the highest bits in the color values; only draw one quadrant of the circle:

```<code>from turtle import Turtle, Screen

SIZE = 2 ** 10
MASK_3 = 2 ** 3 - 1  # divide our 10 bits into three uneven
MASK_4 = 2 ** 4 - 1  # groups of r=3, g=3, b=4

screen = Screen()
screen.setup(SIZE + 8, SIZE + 8)  # rough adjustment for borders
screen.tracer(0)

yertle = Turtle(visible=False)
yertle.speed('fastest')

yertle.penup()
yertle.goto(-SIZE // 2, -SIZE // 2)  # center of circle is LL corner of window
yertle.pendown()

for radius in range(SIZE):

    my_hex = "#{:01X}0{:01X}0{:01X}0".format(2 * ((radius // 2 ** 7) & MASK_3), 2 * ((radius // 2 ** 4) & MASK_3), radius & MASK_4)

    yertle.color(my_hex)

    yertle.penup()
    yertle.sety(yertle.ycor() - 1)
    yertle.pendown()

    yertle.circle(radius)
    screen.update()  # only show completed arcs

screen.exitonclick()
</code>```

We're still only showing 10 bits of the 24 bit color range.

Body:
This particular code of mine, runs for the first iteration, however, as it continues it shows the following error:

Traceback (most recent call last):

  File "test1.py", line 7, in <module>

    if len((hex(s)[2:])) == 1:

TypeError: 'str' object is not callable

The code is as follows:

import turtle

t = turtle.Turtle()

s = 0

z = 30

for i in range(s,16777217):[enter image description here][1]

    if len((hex(s)[2:])) == 1:

        hex = '#' + '00000' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 2:

        hex = '#' + '0000' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 3:

        hex = '#' + '000' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 4:

        hex = '#' + '00' + hex(s)[2:].upper()

    elif len((hex(s)[2:])) == 5:

        hex = '#' + '0' + hex(s)[2:].upper()

    else:

        hex = '#' + hex(s)[2:].upper()

    t.color(hex)

    t.circle(z)

    s += 1

    z += 1

Body:
Besides the hex vs. hex() issue that @Kevin nicely points out (+1), I don't believe your code will achieve it's goal for several reasons:

Your end target should be 16777216, not 16777217 as that value - 1 doesn't fit into a 6 digit hex string; your circle is askew relative to the origin; your window isn't large enough for the number of colors you generate -- you need a step in your for loop that's significantly larger than 1; your code will take a very long time to complete and will mostly be drawing off screen during that time.

Below is my rework of your code addressing the above issues:

from turtle import Turtle, Screen

SIZE = 1000
LIMIT = 2 ** 24
INCREMENT = int(LIMIT / (2 ** 0.5 * SIZE / 2))  # fill to corners

screen = Screen()
screen.setup(SIZE, SIZE)
screen.tracer(0)

yertle = Turtle(visible=False)
yertle.speed('fastest')

for radius, n in enumerate(range(0, LIMIT, INCREMENT)):

    my_hex = '#' + format(n, "06X")

    yertle.color(my_hex)

    yertle.penup()
    yertle.sety(yertle.ycor() - 1)
    yertle.pendown()

    yertle.circle(radius)
    screen.update()  # only show completed circles

screen.exitonclick()

If we want to maximize colors on a typical screen, we switch to a 1024 x 1024 window; allocate the 10 bits of color unevenly but always as the highest bits in the color values; only draw one quadrant of the circle:

from turtle import Turtle, Screen

SIZE = 2 ** 10
MASK_3 = 2 ** 3 - 1  # divide our 10 bits into three uneven
MASK_4 = 2 ** 4 - 1  # groups of r=3, g=3, b=4

screen = Screen()
screen.setup(SIZE + 8, SIZE + 8)  # rough adjustment for borders
screen.tracer(0)

yertle = Turtle(visible=False)
yertle.speed('fastest')

yertle.penup()
yertle.goto(-SIZE // 2, -SIZE // 2)  # center of circle is LL corner of window
yertle.pendown()

for radius in range(SIZE):

    my_hex = "#{:01X}0{:01X}0{:01X}0".format(2 * ((radius // 2 ** 7) & MASK_3), 2 * ((radius // 2 ** 4) & MASK_3), radius & MASK_4)

    yertle.color(my_hex)

    yertle.penup()
    yertle.sety(yertle.ycor() - 1)
    yertle.pendown()

    yertle.circle(radius)
    screen.update()  # only show completed arcs

screen.exitonclick()

We're still only showing 10 bits of the 24 bit color range.


问:
Way to Use C++ 11's for-range Syntax for Sequential Pairs?
Is there a way to use for-range loop syntax to process two sequential elements in an array?

Example...

```<code>func( std::vector< vec2 > &points )
{
std::vector< float > distances;
for( int i = 0; i < (int)points.size() - 1; i++ )
   {
   auto from = points.at( i );
   auto to   = points.at( i + 1 );

   distances.push_back( magnitude( to - from ) );
   }
}
</code>```

答:
Is there a way to use for-range loop syntax to process two sequential elements in an array?

Not out of the box.

However, you can roll your own wrapper class and an iterator class to get what you need.

The begin() and end() member functions of the wrapper class must return an iterator which evaluates to a std::pair when it is dereferenced with the * operator.

Here's a demonstrative program:

```<code>#include <iostream>
#include <vector>

struct VectorWrapper;

struct MyIterator
{
   MyIterator(VectorWrapper const& wrapper, size_t index) : wrapper_(wrapper), index_(index) {}

   std::pair<float, float> operator*();

   MyIterator& operator++()
   {
      ++index_;
      return *this;
   }

   bool operator==(MyIterator const& rhs) const
   {
      return (this->index_ == rhs.index_);
   }

   bool operator!=(MyIterator const& rhs) const
   {
      return (this->index_ != rhs.index_);
   }

   VectorWrapper const& wrapper_;
   size_t index_;
};

struct VectorWrapper
{
   explicit VectorWrapper(std::vector<float>& distances) : distances_(distances) {}

   MyIterator begin() const
   {
      return MyIterator(*this, 0);
   }

   MyIterator end() const
   {
      return MyIterator(*this, distances_.size()-1);
   }

   std::vector<float>& distances_;
};

std::pair<float, float> MyIterator::operator*()
{
   return std::make_pair(wrapper_.distances_[index_], wrapper_.distances_[index_+1]);
}

int main()
{
   std::vector<float> dist = {1, 2, 3, 4, 5, 6};
   VectorWrapper wrapper(dist);
   for ( auto item : wrapper )
   {
      std::cout << item.first << ", " << item.second << std::endl;
   }
}
</code>```

and its output:

1, 2
2, 3
3, 4
4, 5
5, 6
```

Body:
Is there a way to use for-range loop syntax to process two sequential elements in an array?

Example...

func( std::vector< vec2 > &points )
{
std::vector< float > distances;
for( int i = 0; i < (int)points.size() - 1; i++ )
   {
   auto from = points.at( i );
   auto to   = points.at( i + 1 );

   distances.push_back( magnitude( to - from ) );
   }
}

Body:
Is there a way to use for-range loop syntax to process two sequential elements in an array?

Not out of the box.

However, you can roll your own wrapper class and an iterator class to get what you need.

The begin() and end() member functions of the wrapper class must return an iterator which evaluates to a std::pair when it is dereferenced with the * operator.

Here's a demonstrative program:

#include <iostream>
#include <vector>

struct VectorWrapper;

struct MyIterator
{
   MyIterator(VectorWrapper const& wrapper, size_t index) : wrapper_(wrapper), index_(index) {}

   std::pair<float, float> operator*();

   MyIterator& operator++()
   {
      ++index_;
      return *this;
   }

   bool operator==(MyIterator const& rhs) const
   {
      return (this->index_ == rhs.index_);
   }

   bool operator!=(MyIterator const& rhs) const
   {
      return (this->index_ != rhs.index_);
   }

   VectorWrapper const& wrapper_;
   size_t index_;
};

struct VectorWrapper
{
   explicit VectorWrapper(std::vector<float>& distances) : distances_(distances) {}

   MyIterator begin() const
   {
      return MyIterator(*this, 0);
   }

   MyIterator end() const
   {
      return MyIterator(*this, distances_.size()-1);
   }

   std::vector<float>& distances_;
};

std::pair<float, float> MyIterator::operator*()
{
   return std::make_pair(wrapper_.distances_[index_], wrapper_.distances_[index_+1]);
}

int main()
{
   std::vector<float> dist = {1, 2, 3, 4, 5, 6};
   VectorWrapper wrapper(dist);
   for ( auto item : wrapper )
   {
      std::cout << item.first << ", " << item.second << std::endl;
   }
}

and its output:

1, 2
2, 3
3, 4
4, 5
5, 6


问:
Change value recycleview.adapter and save it to textview in mainactivity?
When I change the value from recycleview.adapter, i want to set it the value to textview in mainactivity, how to do it?

it will be like this,

the recycle data retreive from my json, so it will be random and many data,
when I change or add the value of "total win" to more than "0", the textview  at bottom will be appear, and "total all" will count from data I add, when its done, I want to send the "result" value to next activity or post and save it to mysql dbase,

here my code of MainActivity :

```<code>    ...

private List<Details> listDetails = new ArrayList<>();
private RecyclerAdapter viewAdapter;

@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view);
    ButterKnife.bind(this);

    viewAdapter = new RecyclerAdapter(this, listDetails);
   RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
   recyclerView.setLayoutManager(mLayoutManager);
   recyclerView.setItemAnimator(new DefaultItemAnimator());
   recyclerView.setAdapter(viewAdapter);

    getMyData();

}
    ...

private void getMyData() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(AppConfig.URL_MAIN)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
        ...
    });

    ...
</code>```

My RecycleAdapter code :

```<code>    ...

private Context context;
private List<Details> listDetails;

public RecyclerAdapter(Context context, List<Details> listDetails) {
    this.context = context;
    this.listDetails = listDetails;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
    ViewHolder holder = new ViewHolder(v);
    return holder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final Details getSet = listDetails.get(position);

    holder.tvName.setText(getSet.getName());
    holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
        @Override
        public void valueChanged(int value, ActionEnum action) {

             Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();

        }
    });

}

@Override
public int getItemCount() {
    return listDetails.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    @BindView((R.id.nP))
    NumberPicker numberPickerTotalWin;

    @BindView(R.id.tvName)
    TextView tvName;

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        itemView.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        ...
    }
}
</code>```

答:
Check the code

YourActivity   ... implements RecyclerViewItemClick

```<code>     private List<Details> listDetails = new ArrayList<>();
        private RecyclerAdapter viewAdapter;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        ButterKnife.bind(this);

        viewAdapter = new RecyclerAdapter(this, listDetails, this);
       RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
       recyclerView.setLayoutManager(mLayoutManager);
       recyclerView.setItemAnimator(new DefaultItemAnimator());
       recyclerView.setAdapter(viewAdapter);

        getMyData();

    }
        ...

    private void getMyData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.URL_MAIN)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
            ...
        });
</code>```

RecyclerViewAdapter

```<code>private RecyclerViewItemClick mListener;

    public RecyclerAdapter(Context context, List<Details> listDetails, RecyclerViewItemClick listener) {
        this.context = context;
        this.listDetails = listDetails;
        this.mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
        ViewHolder holder = new ViewHolder(v, mListener);
        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Details getSet = listDetails.get(position);

        holder.tvName.setText(getSet.getName());
        holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
            @Override
            public void valueChanged(int value, ActionEnum action) {

                 Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public int getItemCount() {
        return listDetails.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView((R.id.nP))
        NumberPicker numberPickerTotalWin;

        @BindView(R.id.tvName)
        TextView tvName;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View view) {
            if (mListener != null){
//you can access to the current position if you want -> getLayoutPosition()
              mListener.yourMethod();

}
        }

public interface RecyclerViewItemClick {
   void yourMethod();

}
    }
</code>```

Body:
When I change the value from recycleview.adapter, i want to set it the value to textview in mainactivity, how to do it?

it will be like this,

the recycle data retreive from my json, so it will be random and many data,
when I change or add the value of "total win" to more than "0", the textview  at bottom will be appear, and "total all" will count from data I add, when its done, I want to send the "result" value to next activity or post and save it to mysql dbase,

here my code of MainActivity :

    ...

private List listDetails = new ArrayList<>();
private RecyclerAdapter viewAdapter;

@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view);
    ButterKnife.bind(this);

    viewAdapter = new RecyclerAdapter(this, listDetails);
   RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
   recyclerView.setLayoutManager(mLayoutManager);
   recyclerView.setItemAnimator(new DefaultItemAnimator());
   recyclerView.setAdapter(viewAdapter);

    getMyData();

}
    ...

private void getMyData() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(AppConfig.URL_MAIN)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
        ...
    });

    ...

My RecycleAdapter code :

    ...

private Context context;
private List listDetails;

public RecyclerAdapter(Context context, List listDetails) {
    this.context = context;
    this.listDetails = listDetails;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
    ViewHolder holder = new ViewHolder(v);
    return holder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final Details getSet = listDetails.get(position);

    holder.tvName.setText(getSet.getName());
    holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
        @Override
        public void valueChanged(int value, ActionEnum action) {

             Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();

        }
    });

}

@Override
public int getItemCount() {
    return listDetails.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    @BindView((R.id.nP))
    NumberPicker numberPickerTotalWin;

    @BindView(R.id.tvName)
    TextView tvName;

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        itemView.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        ...
    }
}

Body:
Check the code

YourActivity   ... implements RecyclerViewItemClick

     private List<Details> listDetails = new ArrayList<>();
        private RecyclerAdapter viewAdapter;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        ButterKnife.bind(this);

        viewAdapter = new RecyclerAdapter(this, listDetails, this);
       RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
       recyclerView.setLayoutManager(mLayoutManager);
       recyclerView.setItemAnimator(new DefaultItemAnimator());
       recyclerView.setAdapter(viewAdapter);

        getMyData();

    }
        ...

    private void getMyData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.URL_MAIN)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
            ...
        });

RecyclerViewAdapter

private RecyclerViewItemClick mListener;

    public RecyclerAdapter(Context context, List<Details> listDetails, RecyclerViewItemClick listener) {
        this.context = context;
        this.listDetails = listDetails;
        this.mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
        ViewHolder holder = new ViewHolder(v, mListener);
        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Details getSet = listDetails.get(position);

        holder.tvName.setText(getSet.getName());
        holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
            @Override
            public void valueChanged(int value, ActionEnum action) {

                 Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public int getItemCount() {
        return listDetails.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView((R.id.nP))
        NumberPicker numberPickerTotalWin;

        @BindView(R.id.tvName)
        TextView tvName;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View view) {
            if (mListener != null){
//you can access to the current position if you want -> getLayoutPosition()
              mListener.yourMethod();

}
        }

public interface RecyclerViewItemClick {
   void yourMethod();

}
    }


问:
How can I add an attribute to a database query before returning?
So I have something like this:

```<code>$comments = Comments::select('id', 'topic', 'parent_id', 'username', 'comment', 'upvotes', 'created_at', 'updated_at')
        ->where('topic', '=', $topic)
        ->get();

// I'd like to add a human readable datetime difference like
// 1 day ago, 2 days ago, etc. before I return the $comments variable here.

return json_encode($comments);
</code>```

For a single row I would do something like this:

```<code>$comment->created_at->diffForHumans();
</code>```

How can I add an extra attribute to all the rows, something like carbon_date?

答:
Loop through the $comments array and add the attribute to each element.

```<code>foreach ($comments as $comment) {
    $comment->carbon_date = $comment->created_at->diffForHumans();
}
</code>```

Body:
So I have something like this:

$comments = Comments::select('id', 'topic', 'parent_id', 'username', 'comment', 'upvotes', 'created_at', 'updated_at')
        ->where('topic', '=', $topic)
        ->get();

// I'd like to add a human readable datetime difference like
// 1 day ago, 2 days ago, etc. before I return the $comments variable here.

return json_encode($comments);

For a single row I would do something like this:

$comment->created_at->diffForHumans();

How can I add an extra attribute to all the rows, something like carbon_date?

Body:
Loop through the $comments array and add the attribute to each element.

foreach ($comments as $comment) {
    $comment->carbon_date = $comment->created_at->diffForHumans();
}


问:
Storing React Class functions in separate files
Is there a way to store the functions of a react class in a separate file then import those functions for use? The reason for wanting to do this would be purely to cut down on the size of my component and to group functions by category.

For instance:

```<code>import functionIWantToImport from '../functions/functionIWantToImport';
import anotherFunction from '../functions/anotherFunction';

Class Test extends React.Component {
   constructor(props){
       super(props);

       this.state = {};
   }

   //and then include the functions like below:
   functionIWantToImport;
   anotherFunction;
}
</code>```

I know i can do this with helper functions that arent part of the component class. But I'd like to do it with my component functions to save space, and clean up my code.

答:
Use standard JS functions (not arrow functions), and bind the function to the instance in the constructor:

function externalMethod() { // simulates imported function
  return this.state.example;
}

class Test extends React.Component {
   constructor(props){
       super(props);

       this.state = { example: 'example' };

       this.externalMethod = externalMethod.bind(this);
   }

   render() {
    return (

{ this.externalMethod() }

    );
   }
}

ReactDOM.render(
  <Test />,
  test
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="test"></div></code>```

Body:
Is there a way to store the functions of a react class in a separate file then import those functions for use? The reason for wanting to do this would be purely to cut down on the size of my component and to group functions by category.

For instance:

import functionIWantToImport from '../functions/functionIWantToImport';
import anotherFunction from '../functions/anotherFunction';

Class Test extends React.Component {
   constructor(props){
       super(props);

       this.state = {};
   }

   //and then include the functions like below:
   functionIWantToImport;
   anotherFunction;
}

I know i can do this with helper functions that arent part of the component class. But I'd like to do it with my component functions to save space, and clean up my code.

Body:
Use standard JS functions (not arrow functions), and bind the function to the instance in the constructor:

function externalMethod() { // simulates imported function
  return this.state.example;
}

class Test extends React.Component {
   constructor(props){
       super(props);

       this.state = { example: 'example' };

       this.externalMethod = externalMethod.bind(this);
   }

   render() {
    return (
      <div>{ this.externalMethod() }</div>
    );
   }
}

ReactDOM.render(
  <Test />,
  test
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="test"></div>


问:
HttpURLConnection first works but stops without error
I build a app that gets it's data from json on a server. On this moment i use the code under this post to connect to the json files. First it works great but after some time it stopt working and i do not see a error in the monitor or on the android screen. I think it is the DataOutputStream, but i can not see what the problem is.

Can someone get it working?

```<code>public String makeServiceCall(String reqUrl, Context con) {
    String response = null;
    context = con;
    DB = new DatabaseVerwerker(context); //<-- database verbinden

    try {
        URL url = new URL(reqUrl);
        String[] UrlOnderdeel = reqUrl.split("://");
        if(UrlOnderdeel[0].equals("http")) {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setAllowUserInteraction(false);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
            dos.close();
            conn.connect();
            int responseCode = conn.getResponseCode();
            InputStream in = new BufferedInputStream(conn.getInputStream());
            if(responseCode >= 300 && responseCode < 400) {
                response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
            } else {
                response = convertStreamToString(in);
            }
        }
        if(UrlOnderdeel[0].equals("https")) {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{new TrustAll()}, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setAllowUserInteraction(false);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
            dos.close();
            conn.connect();
            int responseCode = conn.getResponseCode();
            if(responseCode >= 300 && responseCode < 400) {
                response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
            } else {
                response = convertStreamToString(conn.getInputStream());
            }
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }

    if(response != null) {
        Log.v("JsonRespons", response.toString());
    }
    return response;
}
</code>```

答:
It doesn't look like you're closing the connection. You'll want to do something like:

```<code>HttpUrlConnection conn = null;
InputStream is = null;
try {
    conn =  (HttpURLConnection) url.openConnection();
    // ... connection handling code here ...
    is = conn.getInputStream();
    // ... InputStream consumption here ...
} finally {
    if(conn != null) {
        conn.disconnect();
    }
    if(is != null) {
        is.close();
    }
}
</code>```

More info about the HttpUrlConnection can be found at the official dev docs explaining how to properly use the HttpUrlConnection.

Body:
I build a app that gets it's data from json on a server. On this moment i use the code under this post to connect to the json files. First it works great but after some time it stopt working and i do not see a error in the monitor or on the android screen. I think it is the DataOutputStream, but i can not see what the problem is.

Can someone get it working?

public String makeServiceCall(String reqUrl, Context con) {
    String response = null;
    context = con;
    DB = new DatabaseVerwerker(context); //<-- database verbinden

    try {
        URL url = new URL(reqUrl);
        String[] UrlOnderdeel = reqUrl.split("://");
        if(UrlOnderdeel[0].equals("http")) {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setAllowUserInteraction(false);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
            dos.close();
            conn.connect();
            int responseCode = conn.getResponseCode();
            InputStream in = new BufferedInputStream(conn.getInputStream());
            if(responseCode >= 300 && responseCode < 400) {
                response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
            } else {
                response = convertStreamToString(in);
            }
        }
        if(UrlOnderdeel[0].equals("https")) {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{new TrustAll()}, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setAllowUserInteraction(false);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
            dos.close();
            conn.connect();
            int responseCode = conn.getResponseCode();
            if(responseCode >= 300 && responseCode < 400) {
                response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
            } else {
                response = convertStreamToString(conn.getInputStream());
            }
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }

    if(response != null) {
        Log.v("JsonRespons", response.toString());
    }
    return response;
}

Body:
It doesn't look like you're closing the connection. You'll want to do something like:

HttpUrlConnection conn = null;
InputStream is = null;
try {
    conn =  (HttpURLConnection) url.openConnection();
    // ... connection handling code here ...
    is = conn.getInputStream();
    // ... InputStream consumption here ...
} finally {
    if(conn != null) {
        conn.disconnect();
    }
    if(is != null) {
        is.close();
    }
}

More info about the HttpUrlConnection can be found at the official dev docs explaining how to properly use the HttpUrlConnection.


问:
C# JSON.Net place items in one list into another
I have a JSON that I am creating in C# using JSON.net.  My object contains a meta and data sections.  The data section is a JSON Array and contains other JSON Array's in it.  The problem I have is my main data entity.  Right now I have all the data for that entity written in a list.  The problem is I need to extract all that data from the list and move it up to the data level.  Here is what I am outputting right now:

```<code>{
   "meta":
   {
      //meta info here.  This is static and formatted correctly.
   }
   "data":
   [
      {
        "main record data:"
        [
          {
            //Here is dynamically created data that I need to move.
          }
        ]
      }
   ]
}
</code>```

My object in C# has the main class which defines the meta and data sections of my JSON.  The data section is a List<DataModel>.  Within that are all my other lists to setup each section that is included in the data section of the JSON.  The list I need is an organization list.  Here is the the condensed model:

```<code>public class JSONModel
    {
        [JsonProperty(Order = 1)]
        public EntityProperties meta { get; set; }
        [JsonProperty(Order = 2)]
        public List<DataModel> data { get; set; }
    }
    public class DataModel
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public List<EntityProperties> org { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public List<EntityProperties> addresses { get; set; }
    }
</code>```

What I need to output is this:

```<code>{
   "meta":
   {
      //meta info here.  This is static and formatted correctly.
   }
   "data":
   [
      {
        //Here is dynamically created data from the org list.
      }
   ]
}
</code>```

The tool I am using is SCRIBE Online and this is a custom connector I am building.  That is where the <EntityProperties> comes from.  That is what they provide to me and then I just pass them into my list and it puts them into the proper JSON format with label: data.  If the org entity was going to have static fields like the meta, then it would be simple in my opionion.  I am hoping that I can just pull the data into a JObject and then insert them back in at the top of my data section, but this is my first go with JSON.net and I am not sure if I am on the right path.  Any input would be greatly appreciated.

答:
Instead of having a List<DataModel> you should just have a single object of DataModel.

If you want to organize your "org" and "address" into single object instances then create a class that holds a reference to a single object of each, and then create a list of that class in your DataModel class.

Body:
I have a JSON that I am creating in C# using JSON.net.  My object contains a meta and data sections.  The data section is a JSON Array and contains other JSON Array's in it.  The problem I have is my main data entity.  Right now I have all the data for that entity written in a list.  The problem is I need to extract all that data from the list and move it up to the data level.  Here is what I am outputting right now:

{
   "meta":
   {
      //meta info here.  This is static and formatted correctly.
   }
   "data":
   [
      {
        "main record data:"
        [
          {
            //Here is dynamically created data that I need to move.
          }
        ]
      }
   ]
}

My object in C# has the main class which defines the meta and data sections of my JSON.  The data section is a List<DataModel>.  Within that are all my other lists to setup each section that is included in the data section of the JSON.  The list I need is an organization list.  Here is the the condensed model:

public class JSONModel
    {
        [JsonProperty(Order = 1)]
        public EntityProperties meta { get; set; }
        [JsonProperty(Order = 2)]
        public List<DataModel> data { get; set; }
    }
    public class DataModel
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public List<EntityProperties> org { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public List<EntityProperties> addresses { get; set; }
    }

What I need to output is this:

{
   "meta":
   {
      //meta info here.  This is static and formatted correctly.
   }
   "data":
   [
      {
        //Here is dynamically created data from the org list.
      }
   ]
}

The tool I am using is SCRIBE Online and this is a custom connector I am building.  That is where the <EntityProperties> comes from.  That is what they provide to me and then I just pass them into my list and it puts them into the proper JSON format with label: data.  If the org entity was going to have static fields like the meta, then it would be simple in my opionion.  I am hoping that I can just pull the data into a JObject and then insert them back in at the top of my data section, but this is my first go with JSON.net and I am not sure if I am on the right path.  Any input would be greatly appreciated.


问:
How do I avoid `already defined` linking error with pugixml if two static libs contain pugixml objs?
So I have 2 static libs defined like this:

StaticLib1

```<code>// StaticLib1.h
#pragma once

class StaticLib1
{
public:
  void doSomething1();
};
</code>```

cpp:

```<code>// StaticLib1.cpp
#include "pugixml.hpp"
#include "StaticLib1.h"

void StaticLib1::doSomething1()
{
  pugi::xml_node node;
}
</code>```

StaticLib2

```<code>// StaticLib2.h
#pragma once

class StaticLib2
{
public:
  void doSomething2();
};
</code>```

cpp:

```<code>// StaticLib1.cpp
#include "pugixml.hpp"
#include "StaticLib2.h"

void StaticLib2::doSomething2()
{
  pugi::xml_node node;
}
</code>```

Main

```<code>#include <iostream>
#include "StaticLib1.h"
#include "StaticLib2.h"

int main(int argv, char** argc)
{
  StaticLib1 staticlib1;
  StaticLib2 staticlib2;

  staticlib1.doSemething1();
  staticlib2.doSemething2();

  getchar();
  return 0;
}
</code>```

Now, if I build this. I get a lot of linking errors. Here are the first few linking errors:

```<code>3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "public: __thiscall pugi::xml_attribute::xml_attribute(struct pugi::xml_attribute_struct *)" (??0xml_attribute@pugi@@QAE@PAUxml_attribute_struct@1@@Z) already defined in StaticLib1.lib(StaticLib1.obj)
3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "public: __thiscall pugi::xml_attribute::xml_attribute(void)" (??0xml_attribute@pugi@@QAE@XZ) already defined in StaticLib1.lib(StaticLib1.obj)
3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "private: __thiscall pugi::xml_attribute_iterator::xml_attribute_iterator(struct pugi::xml_attribute_struct *,struct pugi::xml_node_struct *)" (??0xml_attribute_iterator@pugi@@AAE@PAUxml_attribute_struct@1@PAUxml_node_struct@1@@Z) already defined in StaticLib1.lib(StaticLib1.obj)
...
...
</code>```

Now, I understand that this linking error is because there is a pugixml.obj inside StaticLib1.lib, and there is pugixml.obj inside StaticLib2.lib. But I don't understand why this would cause  linking error with pugixml signatures. Why would they be defined twice? If I call staticlib1.doSomething1() shouldn't main not care if there are multiple definitions of pugi? Shouldn't staticlib1.doSomething1() handle all of that?

on the pugiconfig.hpp I have these specific settings:

```<code>#ifndef HEADER_PUGICONFIG_HPP
#define HEADER_PUGICONFIG_HPP

#define PUGIXML_WCHAR_MODE

#define PUGIXML_HEAD_ONLY
#include "pugixml.cpp"

#endif
</code>```

答: So yes, from user0042advice, I realize it is better to compile a pugixml.lib on your own rather than having #include "pugixml.cpp" on the config. I'm working with legacy code so these surprises are there. Now, I've fixed my issue and made my company code slightly cleaner.

Body:
So I have 2 static libs defined like this:

StaticLib1

// StaticLib1.h
#pragma once

class StaticLib1
{
public:
  void doSomething1();
};

cpp:

// StaticLib1.cpp
#include "pugixml.hpp"
#include "StaticLib1.h"

void StaticLib1::doSomething1()
{
  pugi::xml_node node;
}

StaticLib2

// StaticLib2.h
#pragma once

class StaticLib2
{
public:
  void doSomething2();
};

cpp:

// StaticLib1.cpp
#include "pugixml.hpp"
#include "StaticLib2.h"

void StaticLib2::doSomething2()
{
  pugi::xml_node node;
}

Main

#include <iostream>
#include "StaticLib1.h"
#include "StaticLib2.h"

int main(int argv, char** argc)
{
  StaticLib1 staticlib1;
  StaticLib2 staticlib2;

  staticlib1.doSemething1();
  staticlib2.doSemething2();

  getchar();
  return 0;
}

Now, if I build this. I get a lot of linking errors. Here are the first few linking errors:

3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "public: __thiscall pugi::xml_attribute::xml_attribute(struct pugi::xml_attribute_struct *)" (??0xml_attribute@pugi@@QAE@PAUxml_attribute_struct@1@@Z) already defined in StaticLib1.lib(StaticLib1.obj)
3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "public: __thiscall pugi::xml_attribute::xml_attribute(void)" (??0xml_attribute@pugi@@QAE@XZ) already defined in StaticLib1.lib(StaticLib1.obj)
3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "private: __thiscall pugi::xml_attribute_iterator::xml_attribute_iterator(struct pugi::xml_attribute_struct *,struct pugi::xml_node_struct *)" (??0xml_attribute_iterator@pugi@@AAE@PAUxml_attribute_struct@1@PAUxml_node_struct@1@@Z) already defined in StaticLib1.lib(StaticLib1.obj)
...
...

Now, I understand that this linking error is because there is a pugixml.obj inside StaticLib1.lib, and there is pugixml.obj inside StaticLib2.lib. But I don't understand why this would cause  linking error with pugixml signatures. Why would they be defined twice? If I call staticlib1.doSomething1() shouldn't main not care if there are multiple definitions of pugi? Shouldn't staticlib1.doSomething1() handle all of that?

on the pugiconfig.hpp I have these specific settings:

#ifndef HEADER_PUGICONFIG_HPP
#define HEADER_PUGICONFIG_HPP

#define PUGIXML_WCHAR_MODE

#define PUGIXML_HEAD_ONLY
#include "pugixml.cpp"

#endif


问:
venn diagram 5 way (with 'venn' R)
First off I would like to apologize for my basic question.
I am sure that if I was an experienced user the other threads on this topic would have been satisfactory, but I couldn't manage even after reading them.
So if this might annoy you your welcome to ignore.

For those still wanting to help:
I am trying to create a 5-way venn diagram.
My data is arranged in excel as 5 columns (each representing a site A-E) and rows each representing a species abundance (0 - 16) for each of the five sites.

I want to create a nice venn diagram similar to this:
https://i.stack.imgur.com/TeRSJ.png

I am sure its probobly only takes a few clicks.
but I cant manage to:
Load my data in the write way -
which format should it be? dataset? list? matrix?

I think R seemed to suggest i can only use presence absence data (0/1) is that right?

eventually I figure I would use this command with x as my data

```<code>venn(x, snames = c(""), ilabels = FALSE, counts = FALSE, zcolor = c("bw"),
transparency = 0.3, ellipse = FALSE, size = 15, cexil = 0.45, cexsn = 0.85,
...)
</code>```

Can anyone show me what code to use ?
I can also upload my dataset if someone tells me how to do that here.

Thanks in advance

Title: venn diagram 5 way (with 'venn' R)

Body:
First off I would like to apologize for my basic question.
I am sure that if I was an experienced user the other threads on this topic would have been satisfactory, but I couldn't manage even after reading them.
So if this might annoy you your welcome to ignore.

For those still wanting to help:
I am trying to create a 5-way venn diagram.
My data is arranged in excel as 5 columns (each representing a site A-E) and rows each representing a species abundance (0 - 16) for each of the five sites.

I want to create a nice venn diagram similar to this:
https://i.stack.imgur.com/TeRSJ.png

I am sure its probobly only takes a few clicks.
but I cant manage to:
Load my data in the write way -
which format should it be? dataset? list? matrix?

I think R seemed to suggest i can only use presence absence data (0/1) is that right?

eventually I figure I would use this command with x as my data

venn(x, snames = c(""), ilabels = FALSE, counts = FALSE, zcolor = c("bw"),
transparency = 0.3, ellipse = FALSE, size = 15, cexil = 0.45, cexsn = 0.85,
...)

Can anyone show me what code to use ?
I can also upload my dataset if someone tells me how to do that here.

Thanks in advance

Body:
Hi Maurtis I tried the script u posted.
I caculatd the overlaps in excel and eventually got:

library(VennDiagram);
venn.plot <- draw.quintuple.venn(
  area1 = 104, area2 = 120, area3 = 117, area4 = 158, area5 = 107,
  n12 = 59, n13 = 39, n14 = 55, n15 = 41,
  n23 = 48, n24 = 71, n25 = 48,
  n34 = 53, n35 = 53, n45 = 62,
  n123 = 30, n124 = 44, n125 = 35,
  n134 = 34, n135 = 30, n145 = 38,
  n234 = 42, n235 = 35, n245 = 44,
  n345 = 40, n1234 = 28, n1235 = 25, n1245 = 33,
  n1345 = 27, n2345 = 32,
  n12345 = 24,
  category = c("A", "B", "C", "D", "E"),
  fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
  cat.col = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3"),
  cat.cex = 2,
  margin = 0.05,
  cex = c(
    1.5, 1.5, 1.5, 1.5, 1.5, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8, 1, 0.8,
    1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 0.55, 1, 1, 1, 1, 1, 1.5),
  ind = TRUE);

png("venn_5set.png");
grid.draw(venn.plot);
dev.off();

but I got an error:

error in draw.quintuple.venn(area1 = 104, area2 = 120, area3 = 117,
  area4 = 158,  :Impossible: a17 <- n135 - a27 - a29 - a31 produces
  negative area

Which is a17?


问:
Material on Three.js planes don't match lighting
I've created a shape in Three.Js by merging a curved plane and 2 flat planes. I've used MeshLambertMaterial for the material. The vertical plane and curved plane join perfectly. However there is noticeable hard line where the horizontal plane joins with the curve. The lighting does not seem to align. I want the 3 planes to appear as one object with smooth shading. Am I doing something wrong?

codepen

```<code>    addShape() {
                var radius =58, height=100, startAngle=THREE.Math.degToRad(0), endAngle=THREE.Math.degToRad(90), horizontalSegments=25, verticalSegments=25;
                var width = radius * 2 * Math.PI;
                var plane = new THREE.PlaneGeometry(width, height, horizontalSegments, verticalSegments);
                var index = 0;

                for(var i=0; i<=verticalSegments; i++) {
                    for(var j=0; j<=horizontalSegments; j++) {
                        var angle = startAngle + (j/horizontalSegments)*(endAngle - startAngle);
                        plane.vertices[index].z = radius * Math.cos(angle);
                        plane.vertices[index].x = radius * Math.sin(angle);
                        index++;
                    }
                }
                var material = new THREE.MeshLambertMaterial({color: 0xa2cddd, side: THREE.DoubleSide});
                var mesh = new THREE.Object3D();
                var curve = new THREE.Mesh(plane, material);
                curve.rotation.z = THREE.Math.degToRad(-90)

                var plane1 = new THREE.PlaneGeometry(height, height, horizontalSegments, verticalSegments);
                var side1 = new THREE.Mesh(plane1, material);
                side1.rotation.z = THREE.Math.degToRad(270)
                side1.position.z = radius;
                side1.position.x = -radius * 0.85;

                var plane2 = new THREE.PlaneGeometry(height, height, 1, 1);
                var side2 = new THREE.Mesh(plane2);
                side2.rotation.y = THREE.Math.degToRad(90)
                side2.position.x = radius * 1.0
                side2.position.z = -radius * 0.8;

                plane.mergeMesh(side1);
                plane.mergeMesh(side2);
                mesh.rotation.y = THREE.Math.degToRad(180);
                mesh.add(curve);
                this.mesh = mesh;
                this.scene.add(mesh);
            }
addLight() {
    let light1 = new THREE.PointLight(0xffffff, 1, 200);
    light1.position.set(0, 20, 10);
    this.scene.add(light1);

    let light2 = new THREE.AmbientLight(0x404040); // soft white light
    this.scene.add(light2);
  }
</code>```

答:
First of all you have to compute the vertex normals. Use THREE.Geometry.computeVertexNormals for this.

See THREE.Geometry

```<code>plane.computeVertexNormals();
</code>```

Further you can simplify things, if you draw the THREE.PlaneGeometry in one band With this solution, you can choose the start angle and the end angle as you like, and the planes at the start and the end will always be able to connect seamlessly to the curved part:

```<code>var radius = 58, height = 100,
    startAngle = THREE.Math.degToRad(-20),
    endAngle = THREE.Math.degToRad(110),
    horSegs = 25, vertSegs = 25,
    startLen = 100, endLen = 100;
var width = startLen + endLen + radius * (endAngle-startAngle);
var plane = new THREE.PlaneGeometry( width, height, horSegs+2, vertSegs);

var index = 0;
for (var i = 0; i <= vertSegs; i++) {
  plane.vertices[index].z = radius * Math.cos(startAngle) + startLen * Math.sin(startAngle);
  plane.vertices[index].x = radius * Math.sin(startAngle) - startLen * Math.cos(startAngle);
  index++;
  for (var j = 0; j <= horSegs; j++) {
    var angle = startAngle + j / horSegs * (endAngle - startAngle);
    plane.vertices[index].z = radius * Math.cos(angle);
    plane.vertices[index].x = radius * Math.sin(angle);
    index++;
  }
  plane.vertices[index].z = radius * Math.cos(endAngle) - endLen * Math.sin(endAngle);
  plane.vertices[index].x = radius * Math.sin(endAngle) + endLen * Math.cos(endAngle);
  index++;
}
plane.computeVertexNormals();
</code>```

See the code snippet:

class World {
  constructor() {
    this.scene = new THREE.Scene();
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setClearColor(0x000000);
    document.body.appendChild(this.renderer.domElement);
    this.resize();

    // this.addCube();
    this.addShape();
    this.addLight();

    requestAnimationFrame(this.render.bind(this));
    window.addEventListener("resize", this.resize.bind(this));
  }

  update() {
    if (this.cube) this.cube.rotation.y += 0.01;
    if (this.mesh) this.mesh.rotation.y += 0.01;
  }

  addLight() {
    let light1 = new THREE.PointLight(0xffffff, 1, 200);
    light1.position.set(0, 20, 10);
    this.scene.add(light1);

    let light2 = new THREE.AmbientLight(0x404040); // soft white light
    this.scene.add(light2);
  }

  addShape() {
    var radius = 58, height = 100,
        startAngle = THREE.Math.degToRad(-20),
        endAngle = THREE.Math.degToRad(110),
        horSegs = 25, vertSegs = 25,
        startLen = 100, endLen = 100;
    var width = startLen + endLen + radius * (endAngle-startAngle);
    var plane = new THREE.PlaneGeometry( width, height, horSegs+2, vertSegs);

    var index = 0;
    for (var i = 0; i <= vertSegs; i++) {
      plane.vertices[index].z = radius * Math.cos(startAngle) + startLen * Math.sin(startAngle);
      plane.vertices[index].x = radius * Math.sin(startAngle) - startLen * Math.cos(startAngle);
      index++;
      for (var j = 0; j <= horSegs; j++) {
        var angle = startAngle + j / horSegs * (endAngle - startAngle);
        plane.vertices[index].z = radius * Math.cos(angle);
        plane.vertices[index].x = radius * Math.sin(angle);
        index++;
      }
      plane.vertices[index].z = radius * Math.cos(endAngle) - endLen * Math.sin(endAngle);
      plane.vertices[index].x = radius * Math.sin(endAngle) + endLen * Math.cos(endAngle);
      index++;
    }
    plane.computeVertexNormals();

    var material = new THREE.MeshLambertMaterial({
      color: 0xa2cddd,
      side: THREE.DoubleSide
    });

    var mesh = new THREE.Object3D();
    var curve = new THREE.Mesh(plane, material);
    curve.rotation.z = THREE.Math.degToRad(-90);

    mesh.add(curve);
    this.mesh = mesh;
    this.scene.add(mesh);
  }

  render() {
    this.update();
    requestAnimationFrame(this.render.bind(this));
    this.renderer.render(this.scene, this.camera);
  }

  resize() {
    this.camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );

    this.camera.position.z = 200;

    this.renderer.setSize(window.innerWidth, window.innerHeight);
  }
}

var _w = new World();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://threejs.org/build/three.min.js"></script></code>```

Body:
I've created a shape in Three.Js by merging a curved plane and 2 flat planes. I've used MeshLambertMaterial for the material. The vertical plane and curved plane join perfectly. However there is noticeable hard line where the horizontal plane joins with the curve. The lighting does not seem to align. I want the 3 planes to appear as one object with smooth shading. Am I doing something wrong?

codepen

    addShape() {
                var radius =58, height=100, startAngle=THREE.Math.degToRad(0), endAngle=THREE.Math.degToRad(90), horizontalSegments=25, verticalSegments=25;
                var width = radius * 2 * Math.PI;
                var plane = new THREE.PlaneGeometry(width, height, horizontalSegments, verticalSegments);
                var index = 0;

                for(var i=0; i<=verticalSegments; i++) {
                    for(var j=0; j<=horizontalSegments; j++) {
                        var angle = startAngle + (j/horizontalSegments)*(endAngle - startAngle);
                        plane.vertices[index].z = radius * Math.cos(angle);
                        plane.vertices[index].x = radius * Math.sin(angle);
                        index++;
                    }
                }
                var material = new THREE.MeshLambertMaterial({color: 0xa2cddd, side: THREE.DoubleSide});
                var mesh = new THREE.Object3D();
                var curve = new THREE.Mesh(plane, material);
                curve.rotation.z = THREE.Math.degToRad(-90)

                var plane1 = new THREE.PlaneGeometry(height, height, horizontalSegments, verticalSegments);
                var side1 = new THREE.Mesh(plane1, material);
                side1.rotation.z = THREE.Math.degToRad(270)
                side1.position.z = radius;
                side1.position.x = -radius * 0.85;

                var plane2 = new THREE.PlaneGeometry(height, height, 1, 1);
                var side2 = new THREE.Mesh(plane2);
                side2.rotation.y = THREE.Math.degToRad(90)
                side2.position.x = radius * 1.0
                side2.position.z = -radius * 0.8;

                plane.mergeMesh(side1);
                plane.mergeMesh(side2);
                mesh.rotation.y = THREE.Math.degToRad(180);
                mesh.add(curve);
                this.mesh = mesh;
                this.scene.add(mesh);
            }
addLight() {
    let light1 = new THREE.PointLight(0xffffff, 1, 200);
    light1.position.set(0, 20, 10);
    this.scene.add(light1);

    let light2 = new THREE.AmbientLight(0x404040); // soft white light
    this.scene.add(light2);
  }

Body:
First of all you have to compute the vertex normals. Use THREE.Geometry.computeVertexNormals for this.

See THREE.Geometry

plane.computeVertexNormals();

Further you can simplify things, if you draw the THREE.PlaneGeometry in one band With this solution, you can choose the start angle and the end angle as you like, and the planes at the start and the end will always be able to connect seamlessly to the curved part:

var radius = 58, height = 100,
    startAngle = THREE.Math.degToRad(-20),
    endAngle = THREE.Math.degToRad(110),
    horSegs = 25, vertSegs = 25,
    startLen = 100, endLen = 100;
var width = startLen + endLen + radius * (endAngle-startAngle);
var plane = new THREE.PlaneGeometry( width, height, horSegs+2, vertSegs);

var index = 0;
for (var i = 0; i <= vertSegs; i++) {
  plane.vertices[index].z = radius * Math.cos(startAngle) + startLen * Math.sin(startAngle);
  plane.vertices[index].x = radius * Math.sin(startAngle) - startLen * Math.cos(startAngle);
  index++;
  for (var j = 0; j <= horSegs; j++) {
    var angle = startAngle + j / horSegs * (endAngle - startAngle);
    plane.vertices[index].z = radius * Math.cos(angle);
    plane.vertices[index].x = radius * Math.sin(angle);
    index++;
  }
  plane.vertices[index].z = radius * Math.cos(endAngle) - endLen * Math.sin(endAngle);
  plane.vertices[index].x = radius * Math.sin(endAngle) + endLen * Math.cos(endAngle);
  index++;
}
plane.computeVertexNormals();

See the code snippet:

class World {
  constructor() {
    this.scene = new THREE.Scene();
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setClearColor(0x000000);
    document.body.appendChild(this.renderer.domElement);
    this.resize();

    // this.addCube();
    this.addShape();
    this.addLight();

    requestAnimationFrame(this.render.bind(this));
    window.addEventListener("resize", this.resize.bind(this));
  }

  update() {
    if (this.cube) this.cube.rotation.y += 0.01;
    if (this.mesh) this.mesh.rotation.y += 0.01;
  }

  addLight() {
    let light1 = new THREE.PointLight(0xffffff, 1, 200);
    light1.position.set(0, 20, 10);
    this.scene.add(light1);

    let light2 = new THREE.AmbientLight(0x404040); // soft white light
    this.scene.add(light2);
  }

  addShape() {
    var radius = 58, height = 100,
        startAngle = THREE.Math.degToRad(-20),
        endAngle = THREE.Math.degToRad(110),
        horSegs = 25, vertSegs = 25,
        startLen = 100, endLen = 100;
    var width = startLen + endLen + radius * (endAngle-startAngle);
    var plane = new THREE.PlaneGeometry( width, height, horSegs+2, vertSegs);

    var index = 0;
    for (var i = 0; i <= vertSegs; i++) {
      plane.vertices[index].z = radius * Math.cos(startAngle) + startLen * Math.sin(startAngle);
      plane.vertices[index].x = radius * Math.sin(startAngle) - startLen * Math.cos(startAngle);
      index++;
      for (var j = 0; j <= horSegs; j++) {
        var angle = startAngle + j / horSegs * (endAngle - startAngle);
        plane.vertices[index].z = radius * Math.cos(angle);
        plane.vertices[index].x = radius * Math.sin(angle);
        index++;
      }
      plane.vertices[index].z = radius * Math.cos(endAngle) - endLen * Math.sin(endAngle);
      plane.vertices[index].x = radius * Math.sin(endAngle) + endLen * Math.cos(endAngle);
      index++;
    }
    plane.computeVertexNormals();

    var material = new THREE.MeshLambertMaterial({
      color: 0xa2cddd,
      side: THREE.DoubleSide
    });

    var mesh = new THREE.Object3D();
    var curve = new THREE.Mesh(plane, material);
    curve.rotation.z = THREE.Math.degToRad(-90);

    mesh.add(curve);
    this.mesh = mesh;
    this.scene.add(mesh);
  }

  render() {
    this.update();
    requestAnimationFrame(this.render.bind(this));
    this.renderer.render(this.scene, this.camera);
  }

  resize() {
    this.camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );

    this.camera.position.z = 200;

    this.renderer.setSize(window.innerWidth, window.innerHeight);
  }
}

var _w = new World();

<script src="https://threejs.org/build/three.min.js"></script>