问:
Add Custom Headers to Spring Cloud Stream (with Spring Reactor)
Being new to Spring Reactor, I am trying to stream the data using Spring cloud stream(using rabbitMQ).
I need to add some custom headers before the message is sent to the queue.

My spring-cloud-stream's configuration is:

```<code>spring:
  cloud:
    stream:
      default:
        producer:
          errorChannelEnabled: true
      bindings:
        input:
          binder: rabbitInput
          destination: inputDestination
        output:
          binder: rabbitOutput
          destination: outputDestination
      function:
        definition: processMessage|addHeaders

      binders:
        rabbitInput:
          type: rabbit
          environment:
            spring:
              rabbitmq:
                port: 5672
                host: localhost

        rabbitOutput:
          type: rabbit
          environment:
            spring:
              rabbitmq:
                port: 5670
                host: localhost
</code>```

Producer reference:

```<code>@SpringBootApplication
@EnableBinding(Processor.class)
public class MessageProcessor {

    public static void main(String[] args) {
        SpringApplication.run(MessageProcessor.class, args);
    }

    @Bean
    Function<Flux<String>, Flux<String>> processMessage(List<String> students) {
        return data -> data.map(d -> match(d, students));

    }
    private String match(String message, List<String> students){
        return Objects.isNull(message) || message.isBlank()
            ? message
            : String.valueOf(matchStudentName(message, students));
    }

    private Optional<String> matchStudentName(String message, List<String> students){
        return students.stream()
        .filter(name -> name.equals(message)).findFirst();
    }
    @Bean
    Function<Flux<String>, Flux<Message<String>>> addHeaders() {
        return data-> data.map(d-> MessageBuilder
            .withPayload( d )
            .setHeader("a", 1)
            .setHeader("b", "999")
            .build());
    }
}
</code>```

Headers are being added to the Message successfully, but it's getting overridden somewhere and not getting propagated to the consumer.

Could someone please share their thoughts on how we can add custom headers to a Message using Spring Cloud Stream.

Thanks in advance!

答:
Please upgrade to Hoxton.SR2 which will bring spring-cloud-stream 3.0.2.RELEASE. There were some updates but in short the Message you're producing and the header in it should be preserved.

Side note:
Also, due to added support for multiple in/out function arguments we had to update the binding name convention for functions. You can read more about it here, but what it means to you is that your configuration needs a quick update since input and output are no longer used by default so you should use names derived from function name

```<code>spring:
  cloud:
    stream:
      bindings:
        processMessageaddHeaders-in-0:
          binder: rabbitInput
          destination: inputDestination
        processMessageaddHeaders-out-0:
          binder: rabbitOutput
          destination: outputDestination
      function:
        definition: processMessage|addHeaders
</code>```

. . . or you can map the derived binding names to something more descriptive (e.g., input, output etc) and use that name instead

```<code>spring:
  cloud:
    stream:
      bindings:
        input:
          binder: rabbitInput
          destination: inputDestination
        output:
          binder: rabbitOutput
          destination: outputDestination
      function:
        definition: processMessage|addHeaders
        bindings:
          processMessageaddHeaders-in-0: input
          processMessageaddHeaders-out-0: output

</code>```

Body:
Being new to Spring Reactor, I am trying to stream the data using Spring cloud stream(using rabbitMQ).
I need to add some custom headers before the message is sent to the queue.

My spring-cloud-stream's configuration is:

spring:
  cloud:
    stream:
      default:
        producer:
          errorChannelEnabled: true
      bindings:
        input:
          binder: rabbitInput
          destination: inputDestination
        output:
          binder: rabbitOutput
          destination: outputDestination
      function:
        definition: processMessage|addHeaders

      binders:
        rabbitInput:
          type: rabbit
          environment:
            spring:
              rabbitmq:
                port: 5672
                host: localhost

        rabbitOutput:
          type: rabbit
          environment:
            spring:
              rabbitmq:
                port: 5670
                host: localhost

Producer reference:

@SpringBootApplication
@EnableBinding(Processor.class)
public class MessageProcessor {

    public static void main(String[] args) {
        SpringApplication.run(MessageProcessor.class, args);
    }

    @Bean
    Function<Flux<String>, Flux<String>> processMessage(List<String> students) {
        return data -> data.map(d -> match(d, students));

    }
    private String match(String message, List<String> students){
        return Objects.isNull(message) || message.isBlank()
            ? message
            : String.valueOf(matchStudentName(message, students));
    }

    private Optional<String> matchStudentName(String message, List<String> students){
        return students.stream()
        .filter(name -> name.equals(message)).findFirst();
    }
    @Bean
    Function<Flux<String>, Flux<Message<String>>> addHeaders() {
        return data-> data.map(d-> MessageBuilder
            .withPayload( d )
            .setHeader("a", 1)
            .setHeader("b", "999")
            .build());
    }
}

Headers are being added to the Message successfully, but it's getting overridden somewhere and not getting propagated to the consumer.

Could someone please share their thoughts on how we can add custom headers to a Message using Spring Cloud Stream.

Thanks in advance!

Body:
Please upgrade to Hoxton.SR2 which will bring spring-cloud-stream 3.0.2.RELEASE. There were some updates but in short the Message you're producing and the header in it should be preserved.

Side note:
Also, due to added support for multiple in/out function arguments we had to update the binding name convention for functions. You can read more about it here, but what it means to you is that your configuration needs a quick update since input and output are no longer used by default so you should use names derived from function name

spring:
  cloud:
    stream:
      bindings:
        processMessageaddHeaders-in-0:
          binder: rabbitInput
          destination: inputDestination
        processMessageaddHeaders-out-0:
          binder: rabbitOutput
          destination: outputDestination
      function:
        definition: processMessage|addHeaders

. . . or you can map the derived binding names to something more descriptive (e.g., input, output etc) and use that name instead

spring:
  cloud:
    stream:
      bindings:
        input:
          binder: rabbitInput
          destination: inputDestination
        output:
          binder: rabbitOutput
          destination: outputDestination
      function:
        definition: processMessage|addHeaders
        bindings:
          processMessageaddHeaders-in-0: input
          processMessageaddHeaders-out-0: output


来源: stackexchange

问:
My ELMo trained model gives output dictionary with different fields from those from the tf.hub model
When using a pre-trained ElMo model, I get an output dictionary different from the output dictionary explained in the published tf.hub model
My output dictionary's signature is

```<code>> model = BidirectionalLanguageModel(options_file, weight_file)
> ids_placeholder = tf.placeholder('int32', shape=(None, None, max_word_length))
> ops = model(ids_placeholder)
> print (ops)
{'token_embeddings': <tf.Tensor 'bilm/Reshape_1:0' shape=(?, ?, 512) dtype=float32>,
'lengths': <tf.Tensor 'sub:0' shape=(?,) dtype=int32>,
'mask': <tf.Tensor 'Cast_1:0' shape=(?, ?) dtype=bool>,
'lm_embeddings': <tf.Tensor 'concat_3:0' shape=(?, 3, ?, 1024) dtype=float32>}
</code>```

while the output dictionary from tf hub contains:

word_emb: the character-based word representations with shape [batch_size, max_length, 512].

lstm_outputs1: the first LSTM hidden state with shape [batch_size, max_length, 1024]

lstm_outputs2: the second LSTM hidden state with shape [batch_size, max_length, 1024].

elmo: the weighted sum of the 3 layers, where the weights are trainable. This tensor has shape [batch_size, max_length, 1024]

default: a fixed mean-pooling of all contextualized word representations with shape [batch_size, 1024].

how can I access the word_emb, lstm_outputs1, lstm_outputs2 .. fields in the output dictionary?
I am following the usage example to cache a dataset from this link

答:
If you're following the example from the tf-Hub website, you'll see :

```<code>elmo = hub.Module("https://tfhub.dev/google/elmo/3", trainable=True)
embeddings = elmo(
    ["the cat is on the mat", "dogs are in the fog"],
    signature="default",
    as_dict=True)["elmo"]
</code>```

Be sure that as_dict parameter is set to True.
Here this example directly retrieves the ["elmo"] value of the dictionary, if you get rid of it :

```<code>elmo = hub.Module("https://tfhub.dev/google/elmo/3", trainable=True)
embeddings = elmo(
    ["the cat is on the mat", "dogs are in the fog"],
    signature="default",
    as_dict=True)
</code>```

the variable elmo created will be the dictionary with the wanted word_emb, lstm_outputs1, lstm_outputs2 .. attributes.

Hope this helps !

ContentLicense: CC BY-SA 4.0

Body:
When using a pre-trained ElMo model, I get an output dictionary different from the output dictionary explained in the published tf.hub model
My output dictionary's signature is

> model = BidirectionalLanguageModel(options_file, weight_file)
> ids_placeholder = tf.placeholder('int32', shape=(None, None, max_word_length))
> ops = model(ids_placeholder)
> print (ops)
{'token_embeddings': <tf.Tensor 'bilm/Reshape_1:0' shape=(?, ?, 512) dtype=float32>,
'lengths': <tf.Tensor 'sub:0' shape=(?,) dtype=int32>,
'mask': <tf.Tensor 'Cast_1:0' shape=(?, ?) dtype=bool>,
'lm_embeddings': <tf.Tensor 'concat_3:0' shape=(?, 3, ?, 1024) dtype=float32>}

while the output dictionary from tf hub contains:

word_emb: the character-based word representations with shape [batch_size, max_length, 512].

lstm_outputs1: the first LSTM hidden state with shape [batch_size, max_length, 1024]

lstm_outputs2: the second LSTM hidden state with shape [batch_size, max_length, 1024].

elmo: the weighted sum of the 3 layers, where the weights are trainable. This tensor has shape [batch_size, max_length, 1024]

default: a fixed mean-pooling of all contextualized word representations with shape [batch_size, 1024].

how can I access the word_emb, lstm_outputs1, lstm_outputs2 .. fields in the output dictionary?
I am following the usage example to cache a dataset from this link

Body:
If you're following the example from the tf-Hub website, you'll see :

elmo = hub.Module("https://tfhub.dev/google/elmo/3", trainable=True)
embeddings = elmo(
    ["the cat is on the mat", "dogs are in the fog"],
    signature="default",
    as_dict=True)["elmo"]

Be sure that as_dict parameter is set to True.
Here this example directly retrieves the ["elmo"] value of the dictionary, if you get rid of it :

elmo = hub.Module("https://tfhub.dev/google/elmo/3", trainable=True)
embeddings = elmo(
    ["the cat is on the mat", "dogs are in the fog"],
    signature="default",
    as_dict=True)

the variable elmo created will be the dictionary with the wanted word_emb, lstm_outputs1, lstm_outputs2 .. attributes.

Hope this helps !


问:
Hadoop copyMerge not working properly: scala
I'm trying to combine 3 files present in HDFS through scala. All the 3 files are present in the HDFS location srcPath as mentioned in the code below.

Created a function as below:

```<code>def mergeFiles(conf: Configuration, fs: FileSystem, srcPath: Path, dstPath: String, finalFileName: String): Unit {
val localfs = FileSystem.getLocal(conf)
val status = fs.listStatus(srcPath)

status.foreach(x =>
FileUtil.copyMerge(fs, x.getPath, localfs, new Path(dstPath.toString), false, conf, null)
}
</code>```

I tried executing this, no result, no error, also no file gets created even.
I verified that I'm passing all the arguments properly.

Any clues?

答:
FileUtil#copyMerge method has been removed. See details for the major change:

https://issues.apache.org/jira/browse/HADOOP-12967

https://issues.apache.org/jira/browse/HADOOP-11392

You can use getmerge

Usage: hadoop fs -getmerge [-nl]

Body:
I'm trying to combine 3 files present in HDFS through scala. All the 3 files are present in the HDFS location srcPath as mentioned in the code below.

Created a function as below:

def mergeFiles(conf: Configuration, fs: FileSystem, srcPath: Path, dstPath: String, finalFileName: String): Unit {
val localfs = FileSystem.getLocal(conf)
val status = fs.listStatus(srcPath)

status.foreach(x =>
FileUtil.copyMerge(fs, x.getPath, localfs, new Path(dstPath.toString), false, conf, null)
}

I tried executing this, no result, no error, also no file gets created even.
I verified that I'm passing all the arguments properly.

Any clues?


问:
How to assert an integer is within range by using Unittest in Python?
I have a file to validate the label

```<code>#configmanager.py

class FunctionNode(object):
    def __validate_func_label(self, func_label):
        pattern = re.compile('^fn[1-9][0-9]{0,1}$')
        if not pattern.match(func_label):
            raise Exception(
                f"Invalid value {func_label} for function label in function config.")

</code>```

and I have to write a test case for it using Unit Testing. Test case will check if user enters fn is between 1 and 99, it will pass. Otherwise if fn out of range such as fn0 or fn100 then it fail. I writed a TestClass

```<code>#test__validate_func_label.py

import unittest
from configmanager import FunctionNode

class TestValidateFuncLabel(unittest.TestCase):
    def setUp(self):
        pass

    def test_fn_within_range(self):
        for i in range(1,99):
            self.assertEqual(fn(i),output[i])

if __name__ == "__main__":
    unittest.main()
</code>```

But I feel like I'm not on the right track.
Is there any way i can assert fn is within range from 1 to 99?

Any help is appreciated.

答:
```<code>self.assertTrue( 0<=y<=99)
</code>```

where y is the value of fn you are  checking.

However, I don't understand how your question relates to your code. In your code, you assert that fn(i) has a certain value (taken from a list named output which is not elsewhere defined), where i takes each value  from 1 to 98.

But in  your question you ask about asserting that a value is between these numbers.

Body:
I have a file to validate the label

#configmanager.py

class FunctionNode(object):
    def __validate_func_label(self, func_label):
        pattern = re.compile('^fn[1-9][0-9]{0,1}$')
        if not pattern.match(func_label):
            raise Exception(
                f"Invalid value {func_label} for function label in function config.")

and I have to write a test case for it using Unit Testing. Test case will check if user enters fn is between 1 and 99, it will pass. Otherwise if fn out of range such as fn0 or fn100 then it fail. I writed a TestClass

#test__validate_func_label.py

import unittest
from configmanager import FunctionNode

class TestValidateFuncLabel(unittest.TestCase):
    def setUp(self):
        pass

    def test_fn_within_range(self):
        for i in range(1,99):
            self.assertEqual(fn(i),output[i])

if __name__ == "__main__":
    unittest.main()

But I feel like I'm not on the right track.
Is there any way i can assert fn is within range from 1 to 99?

Any help is appreciated.

Body:
self.assertTrue( 0<=y<=99)

where y is the value of fn you are  checking.

However, I don't understand how your question relates to your code. In your code, you assert that fn(i) has a certain value (taken from a list named output which is not elsewhere defined), where i takes each value  from 1 to 98.

But in  your question you ask about asserting that a value is between these numbers.


问:
Slow down Flare animation in Flutter using time and reset at particular time
I made the following animation using flare.

Animation

I just want to move frame by frame for a particular time period and to reverse it after a particular time.

For example:

The animation has to start at 6 o'clock in the morning and has to end at 6 o'clock in the evening. The frame must change every 30 minutes.

答:
you can create a custom flare controller and give that controller in FlareActor widget.

```<code>Controller _controller = Controller();
@override
  Widget build(BuildContext context) {
    EdgeInsets devicePadding = MediaQuery.of(context).padding;
    return Scaffold(
      backgroundColor: Color.fromRGBO(93, 142, 155, 1.0),
      body: Container(
        child: Stack(
          children: <Widget>[
            Positioned.fill(
              child: SingleChildScrollView(
                padding: EdgeInsets.only(
                  left: 20.0,
                  right: 20.0,
                  top: devicePadding.top + 50.0,
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      height: 200,
                      padding: const EdgeInsets.only(left: 30.0, right: 30.0),
                      child: FlareActor(
                        "assets/Teddy.flr",
                        shouldClip: false,
                        alignment: Alignment.bottomCenter,
                        fit: BoxFit.contain,
                        controller: _controller,
                      ),
                    ),
</code>```

Now it's time to create controller

```<code>// you have to override three methods of Flare Controller

 @override
  void initialize(FlutterActorArtboard artboard) {
    _artboard = artboard;
    _demoAnimation = FlareAnimationLayer()
      ..animation = _artboard.getAnimation("Demo Mode");
    _skyAnimation = FlareAnimationLayer()
      ..animation = _artboard.getAnimation("Sun Rotate")
      ..mix = 1.0;
  }

  @override
  bool advance(FlutterActorArtboard artboard, double elapsed) {
here you can change time for your animation
    _skyAnimation.time =
        (_skyAnimation.time + elapsed) % _skyAnimation.duration;

    _skyAnimation.apply(artboard);

    /// Iterate from the top b/c elements might be removed.
    int len = _roomAnimations.length - 1;
    for (int i = len; i >= 0; i--) {
      FlareAnimationLayer layer = _roomAnimations[i];
      layer.time += elapsed;
      /// The mix quickly ramps up to 1, but interpolates for the first few frames.
      layer.mix = min(1.0, layer.time / 0.07);
      layer.apply(artboard);
      /// When done, remove it.
      if (layer.isDone) {
        // print("layer is done");
        _roomAnimations.removeAt(i);
      }
    }
    return true;
  }

  @override
  void setViewTransform(Mat2D viewTransform) {}
}
</code>```

Body:
you can create a custom flare controller and give that controller in FlareActor widget.

Controller _controller = Controller();
@override
  Widget build(BuildContext context) {
    EdgeInsets devicePadding = MediaQuery.of(context).padding;
    return Scaffold(
      backgroundColor: Color.fromRGBO(93, 142, 155, 1.0),
      body: Container(
        child: Stack(
          children: <Widget>[
            Positioned.fill(
              child: SingleChildScrollView(
                padding: EdgeInsets.only(
                  left: 20.0,
                  right: 20.0,
                  top: devicePadding.top + 50.0,
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      height: 200,
                      padding: const EdgeInsets.only(left: 30.0, right: 30.0),
                      child: FlareActor(
                        "assets/Teddy.flr",
                        shouldClip: false,
                        alignment: Alignment.bottomCenter,
                        fit: BoxFit.contain,
                        controller: _controller,
                      ),
                    ),

Now it's time to create controller

// you have to override three methods of Flare Controller

 @override
  void initialize(FlutterActorArtboard artboard) {
    _artboard = artboard;
    _demoAnimation = FlareAnimationLayer()
      ..animation = _artboard.getAnimation("Demo Mode");
    _skyAnimation = FlareAnimationLayer()
      ..animation = _artboard.getAnimation("Sun Rotate")
      ..mix = 1.0;
  }

  @override
  bool advance(FlutterActorArtboard artboard, double elapsed) {
here you can change time for your animation
    _skyAnimation.time =
        (_skyAnimation.time + elapsed) % _skyAnimation.duration;

    _skyAnimation.apply(artboard);

    /// Iterate from the top b/c elements might be removed.
    int len = _roomAnimations.length - 1;
    for (int i = len; i >= 0; i--) {
      FlareAnimationLayer layer = _roomAnimations[i];
      layer.time += elapsed;
      /// The mix quickly ramps up to 1, but interpolates for the first few frames.
      layer.mix = min(1.0, layer.time / 0.07);
      layer.apply(artboard);
      /// When done, remove it.
      if (layer.isDone) {
        // print("layer is done");
        _roomAnimations.removeAt(i);
      }
    }
    return true;
  }

  @override
  void setViewTransform(Mat2D viewTransform) {}
}


问:
Getting the error in react js that "this.props.sumOfPrices is not a function"?
I am new in react js and i am getting the following error "TypeError: this.props.sumOfPrices is not a function"
I am calling this function in the Course class clicker function using props.
My code is given below:

```<code>import React, { Component } from 'react';

class CourseSles extends Component {
    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }
    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(
        <div>
          <h1>You Can Buy Courses:</h1>
          <div id="courses">
              {courses}
        <p id="total">Toatal: <b>{this.state.total}</b></p>
          </div>
        </div>
        );
    }
}

class Course extends Component {
    clicker(){
      var active= !this.state.active;
      this.setState({active:active});
      this.props.sumOfPrices(active ? this.props.price : -this.props.price);
    }
    constructor(props) {
        super(props);
        this.state = { active:false };
        this.clicker=this.clicker.bind(this);
    }
    render() {
        return ( <div>
            <p onClick={this.clicker}>{this.props.name} <b>{this.props.price}</b></p>
        </div> );
    }
}

export default CourseSles;
</code>```

答: The problem is that sumOfPrices and sumofPrices={this.sumOfPrices} have the capital and small O.This is Typo Error.</p>

Body:
I am new in react js and i am getting the following error "TypeError: this.props.sumOfPrices is not a function"
I am calling this function in the Course class clicker function using props.
My code is given below:

import React, { Component } from 'react';

class CourseSles extends Component {
    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }
    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(

You Can Buy Courses:

              {courses}

Toatal: {this.state.total}

        );
    }
}

class Course extends Component {
    clicker(){
      var active= !this.state.active;
      this.setState({active:active});
      this.props.sumOfPrices(active ? this.props.price : -this.props.price);
    }
    constructor(props) {
        super(props);
        this.state = { active:false };
        this.clicker=this.clicker.bind(this);
    }
    render() {
        return (

{this.props.name} {this.props.price}

 );
    }
}

export default CourseSles;


问:
How to redirect in .htaccess for specific pattern URI
I want my site to be redirected to products.php when someone hits the URL mysite.com/products/sampeproductname/sampeproductid. It should show the products.php file.

Now I've written code like below.

```<code>RewriteCond %{REQUEST_URI} !^/products/[0-9a-zA-Z_-]/[0-9a-zA-Z_-]+$
RewriteRule ^(.*)$ products.php
</code>```

It redirects all the URLS but I want it to be redirected only the URL structure similar to

```<code>mysite.com/products/iPhone-xr/10
</code>```

答:
This should point you into the right direction:

```<code>RewriteEngine on
RewriteRule ^/?products/(\w+)/(\d+)$ /products.php?prdName=$1&prdId=$2 [END]
</code>```

Whether (\w+) matches the product name in all cases depends on the actual character set you are using there which you did not specify in the question. You may have to adapt that to your needs.

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Body:
I want my site to be redirected to products.php when someone hits the URL mysite.com/products/sampeproductname/sampeproductid. It should show the products.php file.

Now I've written code like below.

RewriteCond %{REQUEST_URI} !^/products/[0-9a-zA-Z_-]/[0-9a-zA-Z_-]+$
RewriteRule ^(.*)$ products.php

It redirects all the URLS but I want it to be redirected only the URL structure similar to

mysite.com/products/iPhone-xr/10

Body:
This should point you into the right direction:

RewriteEngine on
RewriteRule ^/?products/(\w+)/(\d+)$ /products.php?prdName=$1&prdId=$2 [END]

Whether (\w+) matches the product name in all cases depends on the actual character set you are using there which you did not specify in the question. You may have to adapt that to your needs.

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


问:
Kotlin map() reuse the same value
I have the following method

```<code>    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }
</code>```

where  l.split(" ") is called twice.

How to write in a smarter way in functional programming style ?

PS 1: I 'm curious for a solution with fold if possible

PS 2 : For readability, the original version was written as

```<code> fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }
</code>```

答:
Use map twice and combine it with destructuring:

```<code>val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String) =
    paragraph.split("\n").asSequence()
        .map { it.split(" ") }
        .map { (first, second) -> dateFormat.parse(first) to second }.toList()
</code>```

Title: Kotlin map() reuse the same value

Body:
I have the following method

    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }

where  l.split(" ") is called twice.

How to write in a smarter way in functional programming style ?

PS 1: I 'm curious for a solution with fold if possible

PS 2 : For readability, the original version was written as

 fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }

Body:
Use map twice and combine it with destructuring:

val dateFormat = SimpleDateFormat("yyyy-MM-dd")
fun parseBirthdateLines(paragraph: String) =
    paragraph.split("\n").asSequence()
        .map { it.split(" ") }
        .map { (first, second) -> dateFormat.parse(first) to second }.toList()


问:
Count total number of words in a corpus using NLTK's Conditional Frequency Distribution in Python (newbie)
I need to count the number of words (word appearances) in some corpus using NLTK package.

Here is my corpus:

```<code>corpus = PlaintextCorpusReader('C:\DeCorpus', '.*')
</code>```

Here is how I try to get the total number of words for each document:

```<code>cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.raw(fileids=textname).replace("\r", " ").replace("\n", " ").split()])
</code>```

(I split strings into words manually, somehow it works better then using corpus.words(), but the problem remains the same, so it's irrelevant). Generally, this does the same (wrong) job:

```<code>cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.words(fileids=textname)])
</code>```

This is what I get by typing cfd.appr.tabulate():

```<code>                        1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21
2022.12.06_Bild 2.txt   3  36 109  40  47  43  29  29  33  23  24  12   8   6   4   2   2   0   0   0   0
2022.12.06_Bild 3.txt   2  42 129  59  57  46  46  35  22  24  17  21  13   5   6   6   2   2   2   0   0
2022.12.06_Bild 4.txt   3  36 106  48  43  32  38  30  19  39  15  14  16   6   5   8   3   2   3   1   0
2022.12.06_Bild 5.txt   1  55 162  83  68  72  46  24  34  38  27  16  12   8   8   5   9   3   1   5   1
2022.12.06_Bild 6.txt   7  69 216  76 113  83  73  52  49  42  37  20  19   9   7   5   3   6   3   0   1
2022.12.06_Bild 8.txt   0   2   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
</code>```

But these are numbers of words of different length. What I need is just this (only one type of item (text) should be counted by number of words):

```<code>2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0
dtype: float64
</code>```

I.e. the sum of all words of different length (or sum of columns that was composed using DataFrame(cfd_appr).transpose().sum(axis=1). (By the way, if there is some way to set up a name for this column that would also a solution, but .rename({None: 'W. appear.'}, axis='columns') is not working, and the solution would be generally not clear enough.

So, what I need is:

```<code>                             1
2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0
</code>```

Would be grateful for help!

答:
Lets first try to replicate your table with the infamous BookCorpus, with directory structure:

```<code>/books_in_sentences
   books_large_p1.txt
   books_large_p2.txt
</code>```

In Code:

```<code>from nltk.corpus import PlaintextCorpusReader
from nltk import ConditionalFreqDist
from nltk import word_tokenize

from collections import Counter

import pandas as pd

corpus = PlaintextCorpusReader('books_in_sentences/', '.*')

cfd_appr = ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in
                     word_tokenize(corpus.raw(fileids=textname))])
</code>```

Then the pandas munging part:

```<code># Idiom to convert a FreqDist / ConditionalFreqDist into pd.DataFrame.
df = pd.DataFrame([dict(Counter(freqdist))
                   for freqdist in cfd_appr.values()],
                 index=cfd_appr.keys())
# Fill in the not-applicable with zeros.
df = df.fillna(0).astype(int)

# If necessary, sort order of columns and add accordingly.
df = df.sort_values(list(df))

# Sum all columns per row -> pd.Series
counts_per_row = df.sum(axis=1)
</code>```

Finally, to access the indexed Series, e.g. :

```<code>print('books_large_p1.txt', counts_per_row['books_large_p1.txt'])
</code>```

Alternatively

I would encourage the above solution so that you can work with the DataFrame to manipulate the numbers further but if all you need is really just the count of the columns per row, then try the following.

If there's a need to avoid pandas and use the values in CFD directly, then you would have to make use of the ConditionalFreqDist.values() and iterate through it carefully.

If we do:

```<code>>>> list(cfd_appr.values())
[FreqDist({3: 6, 6: 5, 1: 5, 9: 4, 4: 4, 2: 3, 8: 2, 10: 2, 7: 1, 14: 1}),
 FreqDist({4: 10, 3: 9, 1: 5, 7: 4, 2: 4, 5: 3, 6: 3, 11: 1, 9: 1})]
</code>```

We'll see a list of FreqDist, each one respective to the keys (in this case the filenames):

```<code>>>> list(cfd_appr.keys())
['books_large_p1.txt', 'books_large_p2.txt']
</code>```

Since we know that FreqDist is a subclass of collections.Counter object, if we sum the values of each Counter object, we will get:

```<code>>>> [sum(fd.values()) for fd in cfd_appr.values()]
[33, 40]
</code>```

Which outputs the same values as df.sum(axis=1) above.

So to put it together:

```<code>>>> dict(zip(cfd_appr.keys(), [sum(fd.values()) for fd in cfd_appr.values()]))
{'books_large_p1.txt': 33, 'books_large_p2.txt': 40}
</code>```

Body:
I need to count the number of words (word appearances) in some corpus using NLTK package.

Here is my corpus:

corpus = PlaintextCorpusReader('C:\DeCorpus', '.*')

Here is how I try to get the total number of words for each document:

cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.raw(fileids=textname).replace("\r", " ").replace("\n", " ").split()])

(I split strings into words manually, somehow it works better then using corpus.words(), but the problem remains the same, so it's irrelevant). Generally, this does the same (wrong) job:

cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.words(fileids=textname)])

This is what I get by typing cfd.appr.tabulate():

                        1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21
2022.12.06_Bild 2.txt   3  36 109  40  47  43  29  29  33  23  24  12   8   6   4   2   2   0   0   0   0
2022.12.06_Bild 3.txt   2  42 129  59  57  46  46  35  22  24  17  21  13   5   6   6   2   2   2   0   0
2022.12.06_Bild 4.txt   3  36 106  48  43  32  38  30  19  39  15  14  16   6   5   8   3   2   3   1   0
2022.12.06_Bild 5.txt   1  55 162  83  68  72  46  24  34  38  27  16  12   8   8   5   9   3   1   5   1
2022.12.06_Bild 6.txt   7  69 216  76 113  83  73  52  49  42  37  20  19   9   7   5   3   6   3   0   1
2022.12.06_Bild 8.txt   0   2   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

But these are numbers of words of different length. What I need is just this (only one type of item (text) should be counted by number of words):

2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0
dtype: float64

I.e. the sum of all words of different length (or sum of columns that was composed using DataFrame(cfd_appr).transpose().sum(axis=1). (By the way, if there is some way to set up a name for this column that would also a solution, but .rename({None: 'W. appear.'}, axis='columns') is not working, and the solution would be generally not clear enough.

So, what I need is:

                             1
2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0

Would be grateful for help!

Body:
Lets first try to replicate your table with the infamous BookCorpus, with directory structure:

/books_in_sentences
   books_large_p1.txt
   books_large_p2.txt

In Code:

from nltk.corpus import PlaintextCorpusReader
from nltk import ConditionalFreqDist
from nltk import word_tokenize

from collections import Counter

import pandas as pd

corpus = PlaintextCorpusReader('books_in_sentences/', '.*')

cfd_appr = ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in
                     word_tokenize(corpus.raw(fileids=textname))])

Then the pandas munging part:

# Idiom to convert a FreqDist / ConditionalFreqDist into pd.DataFrame.
df = pd.DataFrame([dict(Counter(freqdist))
                   for freqdist in cfd_appr.values()],
                 index=cfd_appr.keys())
# Fill in the not-applicable with zeros.
df = df.fillna(0).astype(int)

# If necessary, sort order of columns and add accordingly.
df = df.sort_values(list(df))

# Sum all columns per row -> pd.Series
counts_per_row = df.sum(axis=1)

Finally, to access the indexed Series, e.g. :

print('books_large_p1.txt', counts_per_row['books_large_p1.txt'])

Alternatively

I would encourage the above solution so that you can work with the DataFrame to manipulate the numbers further but if all you need is really just the count of the columns per row, then try the following.

If there's a need to avoid pandas and use the values in CFD directly, then you would have to make use of the ConditionalFreqDist.values() and iterate through it carefully.

If we do:

>>> list(cfd_appr.values())
[FreqDist({3: 6, 6: 5, 1: 5, 9: 4, 4: 4, 2: 3, 8: 2, 10: 2, 7: 1, 14: 1}),
 FreqDist({4: 10, 3: 9, 1: 5, 7: 4, 2: 4, 5: 3, 6: 3, 11: 1, 9: 1})]

We'll see a list of FreqDist, each one respective to the keys (in this case the filenames):

>>> list(cfd_appr.keys())
['books_large_p1.txt', 'books_large_p2.txt']

Since we know that FreqDist is a subclass of collections.Counter object, if we sum the values of each Counter object, we will get:

>>> [sum(fd.values()) for fd in cfd_appr.values()]
[33, 40]

Which outputs the same values as df.sum(axis=1) above.

So to put it together:

>>> dict(zip(cfd_appr.keys(), [sum(fd.values()) for fd in cfd_appr.values()]))
{'books_large_p1.txt': 33, 'books_large_p2.txt': 40}


答:
You could use map() with round().  round() can take the desired number of digits as the second argument.

for polygon in l_b:
    for point in polygon:
        point[:] = map(lambda x: round(x, 2), point)
```

Title: How to round floats in a nested list to 2 decimal places?

Body:
I have coordinate lists of several polygons as listed below:

l_b =  [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]]

How can I make all the numbers in list to round to 2 decimal places while keeping its format?

I've tried l_b = [ '%.2f' % elem for elem in l_b ] but it's giving me TypeError: must be real number, not list


问:
Reloading TableViewCell inside CollectionViewCell
I tried viewWillAppear, tableView.reloadData(), and collectionView.reloadData() but the data array never seems to show up

```<code>import UIKit

class yearOne: UICollectionViewController, coursesDelegate {

    let customCellIdentifier = "cellID"
    let customCellIdentifier2 = "cellID2"
    let customCellIdentifier3 = "cellID3"
    let customCellIdentifier4 = "cellID4"

    let quarters = [
        customLabel (title: "Fall Quarter"),
        customLabel (title: "Winter Quarter"),
        customLabel (title: "Spring Quarter"),
        customLabel (title: "Summer Quarter")
    ]

    func sendDataBackFall(data: String) {
        fallQuarterCell.data.append(data)
        //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackWinter(data2: String) {
        winterQuarterCell.data.append(data2)
        //UserDefaults.standard.set(winterQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSpring(data3: String) {
        springQuarterCell.data.append(data3)
        //UserDefaults.standard.set(springQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSummer(data4: String) {
        summerQuarterCell.data.append(data4)
        //UserDefaults.standard.set(summerQuarterCell.data, forKey: "SavedArray")
    }

    let vc = fallQuarterCell()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("1")
        print(fallQuarterCell.data)
        vc.tableView.reloadData()
        collectionView.reloadData()
        print("2")
        print(fallQuarterCell.data)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        self.collectionView!.register(fallQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier)
        self.collectionView!.register(winterQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier2)
        self.collectionView!.register(springQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier3)
        self.collectionView!.register(summerQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier4)

        navigationItem.title = "Year One"
        navigationController?.navigationBar.prefersLargeTitles = true
        collectionView?.backgroundColor = .lightGray
        //navigationItem.prompt = "Click the + button to add courses, Swipe left on a course to delete."

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return quarters.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if (indexPath.row == 0){
            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
            cell1.layer.borderColor = UIColor.orange.cgColor
            cell1.layer.borderWidth = 2
            cell1.layer.cornerRadius = 5
            cell1.quarters = self.quarters[0]
            return cell1
        }
        else if (indexPath.row == 1){
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier2, for: indexPath) as! winterQuarterCell
            cell2.layer.borderColor = UIColor.blue.cgColor
            cell2.layer.borderWidth = 2
            cell2.layer.cornerRadius = 5
            cell2.quarters = self.quarters[1]
            return cell2
        }
        else if (indexPath.row == 2){
            let cell3 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier3, for: indexPath) as! springQuarterCell
            cell3.layer.borderColor = UIColor.green.cgColor
            cell3.layer.borderWidth = 2
            cell3.layer.cornerRadius = 5
            cell3.quarters = self.quarters[2]
            return cell3
        }
        else if (indexPath.row == 3){
            let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier4, for: indexPath) as! summerQuarterCell
            cell4.layer.borderColor = UIColor.red.cgColor
            cell4.layer.borderWidth = 2
            cell4.layer.cornerRadius = 5
            cell4.quarters = self.quarters[3]
            return cell4
        }
        else{
            return UICollectionViewCell()
        }
    }

    @objc func buttonAction(sender: UIButton!) {
        switch sender.tag {
        case 0:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 1:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 2:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 3:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        default:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        }

    }
}

extension yearOne : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (view.frame.width - 30)
        return CGSize(width: width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10)
    }

}

class fallQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

//    var data = UserDefaults.standard.object(forKey: "SavedArray") as? [String] ?? [String](){
//        didSet{
//            self.tableView.reloadData()
//        }
//    }

    static var data: [String] = []

//    func load(){
//        if let loadeddata: [String] = UserDefaults.standard.object(forKey: "SavedArray") as? [String] {
//            data = loadeddata
//            tableView.reloadData()
//        }
//    }

    let cellId = "coursesName"

    let tableView:UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = UIColor.white
        return tableView
    }()

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(tableView)
        setupView()
    }

    func setupView(){

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.backgroundColor = UIColor.white
        contentView.addSubview(quarterLabel)
        contentView.addSubview(addButton)

        quarterLabel.translatesAutoresizingMaskIntoConstraints = false
        quarterLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        quarterLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true

        addButton.translatesAutoresizingMaskIntoConstraints = false
        addButton.topAnchor.constraint(equalTo: quarterLabel.topAnchor, constant: -5).isActive = true
        addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        addButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
        addButton.widthAnchor.constraint(equalToConstant: 25).isActive = true

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 35).isActive = true
        tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
        tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fallQuarterCell.data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let stringLabel = fallQuarterCell.data[indexPath.row]
        cell.textLabel?.text = stringLabel
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            if (indexPath.row == 0){
                fallQuarterCell.data.remove(at: 0)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 1){
                fallQuarterCell.data.remove(at: 1)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 2){
                fallQuarterCell.data.remove(at: 2)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 3){
                fallQuarterCell.data.remove(at: 3)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 4){
                fallQuarterCell.data.remove(at: 4)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        //add class information???
    }

    var quarters: customLabel? {
        didSet {
            guard let quarters = quarters else {return}
            quarterLabel.text = quarters.title
        }
    }

    let quarterLabel : UILabel = {
        let label = UILabel()//frame: CGRect(x: 15, y: -75, width: 300, height: 50))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.black
        label.font = UIFont.boldSystemFont(ofSize: 16)
        //label.textAlignment = .center
        return label
    }()

    let addButton : UIButton = {
        let button = UIButton()//frame: CGRect(x: 345, y: 10, width: 30, height: 30))
        button.setImage(UIImage(named: "addicon"), for: .normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        button.tag = 0
        button.addTarget(self, action: #selector(yearOne.buttonAction), for: .touchUpInside)
        return button
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
</code>```

I also have the

class winterQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class springQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class summerQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

similar to that of fallQuarterCell(). I used the print(fallQuarterCell.data) to see whether the delegation works and data string appends, and it does seem to append to the array, just that it won't appear on the fallQuarterCell tableView when backed out from the SearchPage()

Here is the 'SearchPage()where the user clicks on an element from the tableView to append to thefallQuarterCell.datathrough delegation and automatically pop backs toyearOne()`:

```<code>import UIKit

protocol coursesDelegate {
    func sendDataBackFall(data: String)
    func sendDataBackWinter(data2: String)
    func sendDataBackSpring(data3: String)
    func sendDataBackSummer(data4: String)
}

class SearchPage: UITableViewController {

    var delegate: coursesDelegate?

    let cellId = "course"

    var allCourses : NSArray = NSArray()
    var filteredCourses = [String]()
    var resultSearchController = UISearchController()

    var tag: Int?

    @objc func addTapped(sender: UIBarButtonItem!) {
        let addAlert = UIAlertController(title: "Create New Course", message: "Enter a course name", preferredStyle: .alert)

        addAlert.addTextField {(textfield:UITextField) in textfield.placeholder = "Course"}

        addAlert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action:UIAlertAction) in
            var _customCourse = String()

            if let courseTextField = addAlert.textFields?.first, let customCourse = courseTextField.text{
                _customCourse = customCourse
            }

        }))

        addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        self.present(addAlert, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let courses : CourseList = CourseList()
        allCourses = courses.coursesList

        navigationItem.title = "Select Courses"
        navigationController?.navigationBar.prefersLargeTitles = true

        let button1 = UIBarButtonItem(title: "Add Course", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

        self.view.backgroundColor = .systemBackground

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView()

        resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.obscuresBackgroundDuringPresentation = false
            controller.searchBar.placeholder = "Search Courses"
            controller.searchBar.sizeToFit()

            tableView.tableHeaderView = controller.searchBar

            return controller
        })()

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if  (resultSearchController.isActive) {
            return filteredCourses.count
        }
        else{
            return allCourses.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        if (resultSearchController.isActive) {
            cell.textLabel?.text = filteredCourses[indexPath.row]
            return cell
         }
         else {
            let courses = self.allCourses[indexPath.row]
            cell.textLabel?.text = courses as? String
            return cell
         }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)

        if (tag == 0){
            if (resultSearchController.isActive){
//                fallQuarterCelll.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
            else{
//                fallQuarterCelll.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
        }
    }

    var isSearchBarEmpty: Bool {
      return resultSearchController.searchBar.text?.isEmpty ?? true
    }
}

extension SearchPage: UISearchResultsUpdating {

  func updateSearchResults(for searchController: UISearchController) {
      filteredCourses.removeAll(keepingCapacity: false)

      let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
      let array = (allCourses as NSArray).filtered(using: searchPredicate)
      filteredCourses = array as! [String]

      self.tableView.reloadData()
  }

}
</code>```

Ignore the UsersDefault... I'm trying to make the data appear on the fallQuarterCell tableView first.

答:
You don't reload table view in fallQuarterCell.

let vc = fallQuarterCell() creates a new cell. Your collection view doesn't contain it, so vc.tableView.reloadData() does nothing.

When you use collectionView.dequeueReusableCell, you may get the old cell, so you should reload the table view in this cell. You should read documentation:

Call this method from your data source object when asked to provide a
  new cell for the collection view. This method dequeues an existing
  cell if one is available or creates a new one

For example, you can add func updateViews() in fallQuarterCell:

```<code>func updateViews() {
    tableView.reloadData()
}
</code>```

And call it here:

```<code>if (indexPath.row == 0){
    let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
    cell1.layer.borderColor = UIColor.orange.cgColor
    cell1.layer.borderWidth = 2
    cell1.layer.cornerRadius = 5
    cell1.quarters = self.quarters[0]
    cell1.updateViews()
    return cell1
}
</code>```

Body:
I tried viewWillAppear, tableView.reloadData(), and collectionView.reloadData() but the data array never seems to show up

import UIKit

class yearOne: UICollectionViewController, coursesDelegate {

    let customCellIdentifier = "cellID"
    let customCellIdentifier2 = "cellID2"
    let customCellIdentifier3 = "cellID3"
    let customCellIdentifier4 = "cellID4"

    let quarters = [
        customLabel (title: "Fall Quarter"),
        customLabel (title: "Winter Quarter"),
        customLabel (title: "Spring Quarter"),
        customLabel (title: "Summer Quarter")
    ]

    func sendDataBackFall(data: String) {
        fallQuarterCell.data.append(data)
        //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackWinter(data2: String) {
        winterQuarterCell.data.append(data2)
        //UserDefaults.standard.set(winterQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSpring(data3: String) {
        springQuarterCell.data.append(data3)
        //UserDefaults.standard.set(springQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSummer(data4: String) {
        summerQuarterCell.data.append(data4)
        //UserDefaults.standard.set(summerQuarterCell.data, forKey: "SavedArray")
    }

    let vc = fallQuarterCell()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("1")
        print(fallQuarterCell.data)
        vc.tableView.reloadData()
        collectionView.reloadData()
        print("2")
        print(fallQuarterCell.data)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        self.collectionView!.register(fallQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier)
        self.collectionView!.register(winterQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier2)
        self.collectionView!.register(springQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier3)
        self.collectionView!.register(summerQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier4)

        navigationItem.title = "Year One"
        navigationController?.navigationBar.prefersLargeTitles = true
        collectionView?.backgroundColor = .lightGray
        //navigationItem.prompt = "Click the + button to add courses, Swipe left on a course to delete."

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return quarters.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if (indexPath.row == 0){
            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
            cell1.layer.borderColor = UIColor.orange.cgColor
            cell1.layer.borderWidth = 2
            cell1.layer.cornerRadius = 5
            cell1.quarters = self.quarters[0]
            return cell1
        }
        else if (indexPath.row == 1){
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier2, for: indexPath) as! winterQuarterCell
            cell2.layer.borderColor = UIColor.blue.cgColor
            cell2.layer.borderWidth = 2
            cell2.layer.cornerRadius = 5
            cell2.quarters = self.quarters[1]
            return cell2
        }
        else if (indexPath.row == 2){
            let cell3 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier3, for: indexPath) as! springQuarterCell
            cell3.layer.borderColor = UIColor.green.cgColor
            cell3.layer.borderWidth = 2
            cell3.layer.cornerRadius = 5
            cell3.quarters = self.quarters[2]
            return cell3
        }
        else if (indexPath.row == 3){
            let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier4, for: indexPath) as! summerQuarterCell
            cell4.layer.borderColor = UIColor.red.cgColor
            cell4.layer.borderWidth = 2
            cell4.layer.cornerRadius = 5
            cell4.quarters = self.quarters[3]
            return cell4
        }
        else{
            return UICollectionViewCell()
        }
    }

    @objc func buttonAction(sender: UIButton!) {
        switch sender.tag {
        case 0:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 1:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 2:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 3:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        default:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        }

    }
}

extension yearOne : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (view.frame.width - 30)
        return CGSize(width: width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10)
    }

}

class fallQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

//    var data = UserDefaults.standard.object(forKey: "SavedArray") as? [String] ?? [String](){
//        didSet{
//            self.tableView.reloadData()
//        }
//    }

    static var data: [String] = []

//    func load(){
//        if let loadeddata: [String] = UserDefaults.standard.object(forKey: "SavedArray") as? [String] {
//            data = loadeddata
//            tableView.reloadData()
//        }
//    }

    let cellId = "coursesName"

    let tableView:UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = UIColor.white
        return tableView
    }()

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(tableView)
        setupView()
    }

    func setupView(){

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.backgroundColor = UIColor.white
        contentView.addSubview(quarterLabel)
        contentView.addSubview(addButton)

        quarterLabel.translatesAutoresizingMaskIntoConstraints = false
        quarterLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        quarterLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true

        addButton.translatesAutoresizingMaskIntoConstraints = false
        addButton.topAnchor.constraint(equalTo: quarterLabel.topAnchor, constant: -5).isActive = true
        addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        addButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
        addButton.widthAnchor.constraint(equalToConstant: 25).isActive = true

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 35).isActive = true
        tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
        tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fallQuarterCell.data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let stringLabel = fallQuarterCell.data[indexPath.row]
        cell.textLabel?.text = stringLabel
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            if (indexPath.row == 0){
                fallQuarterCell.data.remove(at: 0)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 1){
                fallQuarterCell.data.remove(at: 1)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 2){
                fallQuarterCell.data.remove(at: 2)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 3){
                fallQuarterCell.data.remove(at: 3)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 4){
                fallQuarterCell.data.remove(at: 4)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        //add class information???
    }

    var quarters: customLabel? {
        didSet {
            guard let quarters = quarters else {return}
            quarterLabel.text = quarters.title
        }
    }

    let quarterLabel : UILabel = {
        let label = UILabel()//frame: CGRect(x: 15, y: -75, width: 300, height: 50))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.black
        label.font = UIFont.boldSystemFont(ofSize: 16)
        //label.textAlignment = .center
        return label
    }()

    let addButton : UIButton = {
        let button = UIButton()//frame: CGRect(x: 345, y: 10, width: 30, height: 30))
        button.setImage(UIImage(named: "addicon"), for: .normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        button.tag = 0
        button.addTarget(self, action: #selector(yearOne.buttonAction), for: .touchUpInside)
        return button
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

I also have the

class winterQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class springQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class summerQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

similar to that of fallQuarterCell(). I used the print(fallQuarterCell.data) to see whether the delegation works and data string appends, and it does seem to append to the array, just that it won't appear on the fallQuarterCell tableView when backed out from the SearchPage()

Here is the 'SearchPage()where the user clicks on an element from the tableView to append to thefallQuarterCell.datathrough delegation and automatically pop backs toyearOne()`:

import UIKit

protocol coursesDelegate {
    func sendDataBackFall(data: String)
    func sendDataBackWinter(data2: String)
    func sendDataBackSpring(data3: String)
    func sendDataBackSummer(data4: String)
}

class SearchPage: UITableViewController {

    var delegate: coursesDelegate?

    let cellId = "course"

    var allCourses : NSArray = NSArray()
    var filteredCourses = [String]()
    var resultSearchController = UISearchController()

    var tag: Int?

    @objc func addTapped(sender: UIBarButtonItem!) {
        let addAlert = UIAlertController(title: "Create New Course", message: "Enter a course name", preferredStyle: .alert)

        addAlert.addTextField {(textfield:UITextField) in textfield.placeholder = "Course"}

        addAlert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action:UIAlertAction) in
            var _customCourse = String()

            if let courseTextField = addAlert.textFields?.first, let customCourse = courseTextField.text{
                _customCourse = customCourse
            }

        }))

        addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        self.present(addAlert, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let courses : CourseList = CourseList()
        allCourses = courses.coursesList

        navigationItem.title = "Select Courses"
        navigationController?.navigationBar.prefersLargeTitles = true

        let button1 = UIBarButtonItem(title: "Add Course", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

        self.view.backgroundColor = .systemBackground

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView()

        resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.obscuresBackgroundDuringPresentation = false
            controller.searchBar.placeholder = "Search Courses"
            controller.searchBar.sizeToFit()

            tableView.tableHeaderView = controller.searchBar

            return controller
        })()

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if  (resultSearchController.isActive) {
            return filteredCourses.count
        }
        else{
            return allCourses.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        if (resultSearchController.isActive) {
            cell.textLabel?.text = filteredCourses[indexPath.row]
            return cell
         }
         else {
            let courses = self.allCourses[indexPath.row]
            cell.textLabel?.text = courses as? String
            return cell
         }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)

        if (tag == 0){
            if (resultSearchController.isActive){
//                fallQuarterCelll.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
            else{
//                fallQuarterCelll.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
        }
    }

    var isSearchBarEmpty: Bool {
      return resultSearchController.searchBar.text?.isEmpty ?? true
    }
}

extension SearchPage: UISearchResultsUpdating {

  func updateSearchResults(for searchController: UISearchController) {
      filteredCourses.removeAll(keepingCapacity: false)

      let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
      let array = (allCourses as NSArray).filtered(using: searchPredicate)
      filteredCourses = array as! [String]

      self.tableView.reloadData()
  }

}

Ignore the UsersDefault... I'm trying to make the data appear on the fallQuarterCell tableView first.

Body:
You don't reload table view in fallQuarterCell.

let vc = fallQuarterCell() creates a new cell. Your collection view doesn't contain it, so vc.tableView.reloadData() does nothing.

When you use collectionView.dequeueReusableCell, you may get the old cell, so you should reload the table view in this cell. You should read documentation:

Call this method from your data source object when asked to provide a
  new cell for the collection view. This method dequeues an existing
  cell if one is available or creates a new one

For example, you can add func updateViews() in fallQuarterCell:

func updateViews() {
    tableView.reloadData()
}

And call it here:

if (indexPath.row == 0){
    let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
    cell1.layer.borderColor = UIColor.orange.cgColor
    cell1.layer.borderWidth = 2
    cell1.layer.cornerRadius = 5
    cell1.quarters = self.quarters[0]
    cell1.updateViews()
    return cell1
}


问:
Get component name in React
I'm developing a React application. I have a Loading component, which is a little animation for waiting. I want to add a message in this Loading component according to the component which called it.

Here is how i call my Loading component (with this.state.displayLoading at true or false) :

```<code>class LoginForm extends React.Component {
    render() {
        return (
            <div className="login-form-root">
                 {this.state.displayLoading && <Loading loadingFrom={?}/>}
            </div>
        );
    }
}
</code>```

I want to get "LoginForm" in my variable loadingFrom, which is the className. Maybe it's not the right way to do that.

答: For HOCs: you can use WrappedComponent.name

ContentLicense: CC BY-SA 3.0

Title: Get component name in React

Body:
I'm developing a React application. I have a Loading component, which is a little animation for waiting. I want to add a message in this Loading component according to the component which called it.

Here is how i call my Loading component (with this.state.displayLoading at true or false) :

class LoginForm extends React.Component {
    render() {
        return (

                 {this.state.displayLoading && <Loading loadingFrom={?}/>}

        );
    }
}

I want to get "LoginForm" in my variable loadingFrom, which is the className. Maybe it's not the right way to do that.


问:
in react native want to get Home Page data according with respect to logged in email
In my project i logged in with email password, after that want to get Home Page data according with respect to logged in email, The API will return the response data for that specific user, in useState() i have passed static email, which i need to change dynamic
Home Page code :

```<code>```import React,{useState} from 'react';
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
 const [email]= useState('test@xyz.com')
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen;```
</code>```

答:
when user loggs in with email and password if login is successful pass the email from Login Page to Home Page and then in Home page use routes prop to get the email then do your stuff,,

here is a simple example

Login Page

```<code>const Login = () => {
  const [email, setEmail] = useState('email');

  const navigation = useNavigation();

  const login = () => {
    // Login to server on Success
    // call navigation.navigate
    navigation.navigate('Home', { email })
  };

  return (
    <View style={styles.container}>
      <Button title="Login" onPress={login}/>
    </View>
  );
};
</code>```

Home Page

```<code>import React, { useEffect } from 'react';
import {useRoute} from '@react-navigation/native'
import {View, Text, StyleSheet} from 'react-native';

const Home = () => {

  const route = useRoute();

  useEffect(() => {
    const email = route.params.email;
    // get Data from  the server
  }, [])

  return (
    <View style={{flex: 1}}>
      <Text>Home</Text>
    </View>
  );
};
</code>```

Body:
In my project i logged in with email password, after that want to get Home Page data according with respect to logged in email, The API will return the response data for that specific user, in useState() i have passed static email, which i need to change dynamic
Home Page code :

```import React,{useState} from 'react';
import { Button} from 'react-native-paper';
import {
  View,
  Text,
  StatusBar,
  TouchableOpacity,
  KeyboardAvoidingView,
  Alert
} from 'react-native';

const ProductScreen = (props) => {
 const [email]= useState('test@xyz.com')
  const sendCred = async (props)=>{
    fetch("http://test.com:70/api/productForClient",{
      method:"POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type':'application/json'
      },
     body:JSON.stringify({
       "email":email,
      })
    })
    .then(res=>res.json())
    .then((data)=>{
      console.log("*****************************", data)
    })
 }

 return (
   <>
   <KeyboardAvoidingView behavior="position">
     <StatusBar backgroundColor="blue" barStyle="light-content" />
      <Text
      style={{fontSize:35,marginLeft:18,marginTop:10,color:"#3b3b3b"}}>welcome to</Text>

      <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
       onPress={() => sendCred(props)}>
        Get Data
      </Button>
      <TouchableOpacity>
        <Text
      style={{
        fontSize:18,marginLeft:18,marginTop:20
      }}
      onPress={()=>props.navigation.replace("signup")}
      >dont have a account ?</Text>
      </TouchableOpacity>

      </KeyboardAvoidingView>
   </>
  );
};
export default ProductScreen;```

Body:
when user loggs in with email and password if login is successful pass the email from Login Page to Home Page and then in Home page use routes prop to get the email then do your stuff,,

here is a simple example

Login Page

const Login = () => {
  const [email, setEmail] = useState('email');

  const navigation = useNavigation();

  const login = () => {
    // Login to server on Success
    // call navigation.navigate
    navigation.navigate('Home', { email })
  };

  return (
    <View style={styles.container}>
      <Button title="Login" onPress={login}/>
    </View>
  );
};

Home Page

import React, { useEffect } from 'react';
import {useRoute} from '@react-navigation/native'
import {View, Text, StyleSheet} from 'react-native';

const Home = () => {

  const route = useRoute();

  useEffect(() => {
    const email = route.params.email;
    // get Data from  the server
  }, [])

  return (
    <View style={{flex: 1}}>
      <Text>Home</Text>
    </View>
  );
};