问:
Postgresql how do I aggregate the data in a table to produce a summarized table with unique values in a range
So, I am new to postgresql. my data is as follows:

```<code>PRODUCT WKnum SALES
HAMMER  1   17
HAMMER  2   20
HAMMER  3   17
HAMMER  4   10
HAMMER  5   12
HAMMER  6   13
HAMMER  7   2
HAMMER  8   25
SINK    1   25
SINK    2   20
SINK    3   9
SINK    4   7
SINK    5   24
SINK    6   16
SINK    7   10
SINK    8   16
BUCKET  1   22
BUCKET  2   2
BUCKET  3   10
BUCKET  4   24
BUCKET  5   9
BUCKET  6   20
BUCKET  7   9
BUCKET  8   21
</code>```

I would then like an outcome like the below:

```<code>PRODUCT BEST_CONSEC_4WEEKS  BEST_CONSEC_4WEEKS_SLS
HAMMER    1-4                       64
SINK      5-8                       66
BUCKET    3-6                       63
</code>```

Where "BEST_CONSEC_4WEEKS" is a character string that tells the actual week numbers with the highest sum of sales over a consecutive 4 week period. And "BEST_CONSEC_4WEEKS_SLS" provides the total units sold for that product during the weeks identified above. Database-specific functions must be avoided.

The following piece of code was my attempt, but it is not working as I expected.

```<code>SELECT PRODUCT,
CASE WHEN Wknum IN ‘1 - 4’:: INTETER AS BEST_CONSEC_4WEEKS,
SUM (CASE WHEN Wknum IS BETWEEN ‘1 AND 4’::INTEGER THEN SALES ELSE 0 END) OR
SUM (CASE WHEN Wknum IS BETWEEN ‘5 AND 8’::INTEGER THEN SALES ELSE 0 END)
SUM (CASE WHEN Wknum IS BETWEEN ‘3 AND 6’::INTEGER THEN SALES ELSE 0 END) AS BEST_CONSEC_4WEEKS_SLS
FROM TABLE1
</code>```

Can anyone please tell me what I am doing wrong? Thanks

答:
You can use window functions with frames as follows:

```<code>with u as
(select PRODUCT,
WKnum,
sum(SALES) over(partition by PRODUCT order by WKnum rows between current row and 3 following) as BEST_CONSEC_4WEEKS_SLS
from TABLE1),
v as
(select *, rank() over(partition by PRODUCT order by BEST_CONSEC_4WEEKS_SLS desc) as r
from u)
select PRODUCT,
concat(wknum, '-', wknum + 3) as BEST_CONSEC_4WEEKS,
BEST_CONSEC_4WEEKS_SLS
from v where r = 1
</code>```

fiddle

Body:
So, I am new to postgresql. my data is as follows:

PRODUCT WKnum SALES
HAMMER  1   17
HAMMER  2   20
HAMMER  3   17
HAMMER  4   10
HAMMER  5   12
HAMMER  6   13
HAMMER  7   2
HAMMER  8   25
SINK    1   25
SINK    2   20
SINK    3   9
SINK    4   7
SINK    5   24
SINK    6   16
SINK    7   10
SINK    8   16
BUCKET  1   22
BUCKET  2   2
BUCKET  3   10
BUCKET  4   24
BUCKET  5   9
BUCKET  6   20
BUCKET  7   9
BUCKET  8   21

I would then like an outcome like the below:

PRODUCT BEST_CONSEC_4WEEKS  BEST_CONSEC_4WEEKS_SLS
HAMMER    1-4                       64
SINK      5-8                       66
BUCKET    3-6                       63

Where "BEST_CONSEC_4WEEKS" is a character string that tells the actual week numbers with the highest sum of sales over a consecutive 4 week period. And "BEST_CONSEC_4WEEKS_SLS" provides the total units sold for that product during the weeks identified above. Database-specific functions must be avoided.

The following piece of code was my attempt, but it is not working as I expected.

SELECT PRODUCT,
CASE WHEN Wknum IN ‘1 - 4’:: INTETER AS BEST_CONSEC_4WEEKS,
SUM (CASE WHEN Wknum IS BETWEEN ‘1 AND 4’::INTEGER THEN SALES ELSE 0 END) OR
SUM (CASE WHEN Wknum IS BETWEEN ‘5 AND 8’::INTEGER THEN SALES ELSE 0 END)
SUM (CASE WHEN Wknum IS BETWEEN ‘3 AND 6’::INTEGER THEN SALES ELSE 0 END) AS BEST_CONSEC_4WEEKS_SLS
FROM TABLE1

Can anyone please tell me what I am doing wrong? Thanks

Body:
You can use window functions with frames as follows:

with u as
(select PRODUCT,
WKnum,
sum(SALES) over(partition by PRODUCT order by WKnum rows between current row and 3 following) as BEST_CONSEC_4WEEKS_SLS
from TABLE1),
v as
(select *, rank() over(partition by PRODUCT order by BEST_CONSEC_4WEEKS_SLS desc) as r
from u)
select PRODUCT,
concat(wknum, '-', wknum + 3) as BEST_CONSEC_4WEEKS,
BEST_CONSEC_4WEEKS_SLS
from v where r = 1

fiddle


来源: stackexchange

问:
CocoaPods could not find compatible versions for pod "lottie-ios"
i can't install react-native-lottie throwing error compatatible version for lottie-react-native  CocoaPods could not find compatible versions for pod "lottie-ios"</p>

答:
Solved this issue by uninstalling the previous installed Lottie version and then</p>
```<code>1- yarn add lottie-react-native@4.0.3
2- yarn add lottie-ios@3.2.3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Solved this issue by uninstalling the previous installed Lottie version and then

1- yarn add lottie-react-native@4.0.3
2- yarn add lottie-ios@3.2.3


问:
Cant read a value from redux toolkit store on different components
I'm trying to create a redux toolkit that store an object so I could read the object values from different components on different react-router path

when calling to read the values that stores in the redux store, I'm getting the initial state I defined in the redux store instead of the updated value. (in this case I'm getting '0')

"login.js"

I'm pretty sure it is because of this "window.location.replace('/info');" because when I comment it out and called to read the value from the store (in the same component) it works (it doesn't work only after this line)

"Login.js" Component

How should I store those values correctly ?
Thank you

答:
If you reload (this operation append with window.location.replace, the store create with Redux-TK is erase and restart.
You need to you use React-Router (or React-Router-Dom for web) and use navigate to change your path without reload.

https://reactrouter.com


问:
React POST request to Django Rest ManyToMany field
What I want to do is post a ListLink object, which contains Link objects, to the database.

The Link objects are added by input field by the user and stored in the state until a request is sent for them to be saved in the database.

I am trying to make a post request to DRF, but I am getting the following response:

```<code>"Invalid data. Expected a dictionary, but got list."
</code>```

I am using axios to make the request:

Home.jsx

```<code>handleSave = event => {
    event.preventDefault();

    return axios({
        method: 'post',
        url: 'http://localhost:8000/api/lists/',
        headers: {
            'Authorization': 'Token ' + localStorage.getItem('token')
        },
        data: {
            links: this.state.links,
            name: this.state.listName
        }})
        .then(res => {
            console.log(res);
        });
}
</code>```

This is the state I am using to save the lists in:

```<code>    this.state = {
        listName: 'Link List',
        listDescription: 'Add description here',
        listURL: '',
        currentLink: 'https://www.example.com',
        links: []
    };
</code>```

Here are my models and serializers:

LinkList

```<code>class LinkList(models.Model):
owner = models.ForeignKey(
    User,
    related_name='lists',
    on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.CharField(max_length=250)
public = models.BooleanField(default=False)
links = models.ManyToManyField(
    Link,
    related_name='linklists')

def __str__(self):
    return "%s - %s" % (self.owner, self.name)

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
</code>```

Serializer:

```<code>class LinkListSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="lists-detail")
owner = serializers.ReadOnlyField(source='owner.username')
links = LinkSerializer()

class Meta:
    model = LinkList
    fields = ['url', 'owner', 'name', 'public', 'links']
</code>```

Link

```<code>class Link(models.Model):
link = models.URLField(max_length=200)

def __str__(self):
    return "%s" % (self.link)
</code>```

Serializer:

```<code>class LinkSerializer(serializers.ModelSerializer):
class Meta:
    model = Link
    fields = ['url', 'link']
</code>```

答:
You can try to add many=True parameter to LinkSerializer but you will need to handle this list yourself (pop links attribute and manually create every link object).

```<code>class LinkListSerializer(serializers.ModelSerializer):
    ...

    def create(self, validated_data):
        with transaction.atomic(): # optional - ensure that changes will be rolled back on error
            links = validated_data.pop('links', [])
            instance = super().create(validated_data)
            for l in links:
                instance.links.create(link=l)
            return instance
</code>```

Body:
What I want to do is post a ListLink object, which contains Link objects, to the database.

The Link objects are added by input field by the user and stored in the state until a request is sent for them to be saved in the database.

I am trying to make a post request to DRF, but I am getting the following response:

"Invalid data. Expected a dictionary, but got list."

I am using axios to make the request:

Home.jsx

handleSave = event => {
    event.preventDefault();

    return axios({
        method: 'post',
        url: 'http://localhost:8000/api/lists/',
        headers: {
            'Authorization': 'Token ' + localStorage.getItem('token')
        },
        data: {
            links: this.state.links,
            name: this.state.listName
        }})
        .then(res => {
            console.log(res);
        });
}

This is the state I am using to save the lists in:

    this.state = {
        listName: 'Link List',
        listDescription: 'Add description here',
        listURL: '',
        currentLink: 'https://www.example.com',
        links: []
    };

Here are my models and serializers:

LinkList

class LinkList(models.Model):
owner = models.ForeignKey(
    User,
    related_name='lists',
    on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.CharField(max_length=250)
public = models.BooleanField(default=False)
links = models.ManyToManyField(
    Link,
    related_name='linklists')

def __str__(self):
    return "%s - %s" % (self.owner, self.name)

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

Serializer:

class LinkListSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="lists-detail")
owner = serializers.ReadOnlyField(source='owner.username')
links = LinkSerializer()

class Meta:
    model = LinkList
    fields = ['url', 'owner', 'name', 'public', 'links']

Link

class Link(models.Model):
link = models.URLField(max_length=200)

def __str__(self):
    return "%s" % (self.link)

Serializer:

class LinkSerializer(serializers.ModelSerializer):
class Meta:
    model = Link
    fields = ['url', 'link']

Body:
You can try to add many=True parameter to LinkSerializer but you will need to handle this list yourself (pop links attribute and manually create every link object).

class LinkListSerializer(serializers.ModelSerializer):
    ...

    def create(self, validated_data):
        with transaction.atomic(): # optional - ensure that changes will be rolled back on error
            links = validated_data.pop('links', [])
            instance = super().create(validated_data)
            for l in links:
                instance.links.create(link=l)
            return instance


问:
How to correct Firebase Cloud Function admin reference not a function error
I've recently tried to update .WriteOn cloud function into a scheduled cloud function for my firebase app.  The objective is to run a function every 4 days that goes out deletes messages that are over 2 days old.  This worked perfectly for the .WriteOn function but of course that meant the function was executed every time a message was created; which was overkill.  Here is the function I have in my index.js file...

```<code>// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp()

    exports.scheduledFunction = functions.pubsub.schedule('every 96 hours').onRun(async (context) => {
      const ref = admin.database().reference('messages/{pushId}');
      var now = Date.now();
      var cutoff = now - 24 * 60 * 60 * 1000;
      var oldItemsQuery = ref.orderByChild('timeStamp').endAt(cutoff);
      return oldItemsQuery.once('value', function(snapshot) {
        // create a map with all children that need to be removed
        var updates = {};
        snapshot.forEach(function(child) {
          updates[child.key] = null
        });
        // execute all updates in one go and return the result to end the function
        return ref.update(updates);
      });
    });
</code>```

Here is the execution error I'm reading on my Firebase Functions console...

scheduledFunction TypeError: admin.database(...).reference is not a
function

答:
The error message is telling you that this line of code is calling a method that doesn't exist:

```<code>  const ref = admin.database().reference('messages/{pushId}');
</code>```

In fact, there is no method called "reference" on the Database object returned by admin.database().  Using the API documentation, you can see that database() returns a Database object which further extends a different Database.  In there, you'll see that there is a ref() method.  There is no reference().  Maybe that's what you meant to use.

```<code>  const ref = admin.database().ref('messages/{pushId}');
</code>```

Also, this is what you'll see in the example code in the documentation.  Please review that to make sure you're following the correct examples for JavaScript.

Body:
I've recently tried to update .WriteOn cloud function into a scheduled cloud function for my firebase app.  The objective is to run a function every 4 days that goes out deletes messages that are over 2 days old.  This worked perfectly for the .WriteOn function but of course that meant the function was executed every time a message was created; which was overkill.  Here is the function I have in my index.js file...

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp()

    exports.scheduledFunction = functions.pubsub.schedule('every 96 hours').onRun(async (context) => {
      const ref = admin.database().reference('messages/{pushId}');
      var now = Date.now();
      var cutoff = now - 24 * 60 * 60 * 1000;
      var oldItemsQuery = ref.orderByChild('timeStamp').endAt(cutoff);
      return oldItemsQuery.once('value', function(snapshot) {
        // create a map with all children that need to be removed
        var updates = {};
        snapshot.forEach(function(child) {
          updates[child.key] = null
        });
        // execute all updates in one go and return the result to end the function
        return ref.update(updates);
      });
    });

Here is the execution error I'm reading on my Firebase Functions console...

scheduledFunction TypeError: admin.database(...).reference is not a
function

Body:
The error message is telling you that this line of code is calling a method that doesn't exist:

  const ref = admin.database().reference('messages/{pushId}');

In fact, there is no method called "reference" on the Database object returned by admin.database().  Using the API documentation, you can see that database() returns a Database object which further extends a different Database.  In there, you'll see that there is a ref() method.  There is no reference().  Maybe that's what you meant to use.

  const ref = admin.database().ref('messages/{pushId}');

Also, this is what you'll see in the example code in the documentation.  Please review that to make sure you're following the correct examples for JavaScript.


问:
csv file upload at start of r shiny app (quasi placeholder file)
With this code I can upload a csv file in my shiny app.

```<code>library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File", accept = ".csv"),
      checkboxInput("header", "Header", TRUE)
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)

server <- function(input, output) {
  output$contents <- renderTable({
    file <- input$file1
    ext <- tools::file_ext(file$datapath)

    req(file)
    validate(need(ext == "csv", "Please upload a csv file"))

    read.csv(file$datapath, header = input$header)
  })
}

shinyApp(ui, server)
</code>```

I would like to load a placeholder csv file say df.csv automatically at the start of my shiny app.

I this possible or do I have rethink my strategy?

答:
In the server, we may use if/else to create the placeholder .csv while loading

```<code>server <- function(input, output) {
  output$contents <- renderTable({

    if(is.null(input$file1)) {

       dat <- read.csv(file.path(getwd(), "df.csv"))
    } else {
    file <- input$file1
    ext <- tools::file_ext(file$datapath)

    req(file)
      validate(need(ext == "csv", "Please upload a csv file"))

    dat <- read.csv(file$datapath, header = input$header)
    }

    dat

    })
}

shinyApp(ui, server)
</code>```

Body:
With this code I can upload a csv file in my shiny app.

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File", accept = ".csv"),
      checkboxInput("header", "Header", TRUE)
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)

server <- function(input, output) {
  output$contents <- renderTable({
    file <- input$file1
    ext <- tools::file_ext(file$datapath)

    req(file)
    validate(need(ext == "csv", "Please upload a csv file"))

    read.csv(file$datapath, header = input$header)
  })
}

shinyApp(ui, server)

I would like to load a placeholder csv file say df.csv automatically at the start of my shiny app.

I this possible or do I have rethink my strategy?

Body:
In the server, we may use if/else to create the placeholder .csv while loading

server <- function(input, output) {
  output$contents <- renderTable({

    if(is.null(input$file1)) {

       dat <- read.csv(file.path(getwd(), "df.csv"))
    } else {
    file <- input$file1
    ext <- tools::file_ext(file$datapath)

    req(file)
      validate(need(ext == "csv", "Please upload a csv file"))

    dat <- read.csv(file$datapath, header = input$header)
    }

    dat

    })
}

shinyApp(ui, server)


问:
rubocop on VScode not working.Error "rubocop is not executable"
Recently I installed rubocop on vscode. However, it doesn't work.Error message is below.

```<code>rubocop is not excutable
execute path is empty! please check ruby.rubocop.executePath
</code>```

How should I fix it? I searched some articles, never solved...

cf. vscode-ruby-rubocop
https://github.com/misogi/vscode-ruby-rubocop

答:
Short answer: Try starting VSCode a different way.

Explanation: A process inherits all the environment configuration it was started from. If rubocop is installed in your global environment, then, great no matter how you start VSCode rubocop will be available to the plug-in. On the downside, rubocop is now available to everything, most of which will never need it, and all the things that do use it need to require the same version of rubocop.

If rubocop was installed in a gemset using a ruby manager, or you have something like a dot-file manager that manipulates your environment, rubocop might not be in the PATH when you start VSCode.

I start VSCode from the terminal, always. I open a terminal and cd into my project folder. My ruby manager (rvm) and dot-file manager (direnv) automatically add and change some variables in the environment. Then I run code . to start VSCode with my project. This ensures VSCode is running in the same environment configuration as my app will run.

Body:
Recently I installed rubocop on vscode. However, it doesn't work.Error message is below.

rubocop is not excutable
execute path is empty! please check ruby.rubocop.executePath

How should I fix it? I searched some articles, never solved...

cf. vscode-ruby-rubocop
https://github.com/misogi/vscode-ruby-rubocop


问:
How do I provide an informal string representation of a python Class (not instance)
I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.

So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).

```<code>>>> class SomeClass:
...   def __str__(self):
...     return 'I am a SomeClass instance.'
...
>>> SomeClass
<class __main__.SomeClass at 0x2ba2f0fd3b30>
>>> print SomeClass
__main__.SomeClass
>>>
>>> x = SomeClass()
>>> x
<__main__.SomeClass instance at 0x2ba2f0ff3f38>
>>> print x
I am a SomeClass instance.
</code>```

答:
override __repr__ instead.

```<code>>>> class SomeClass(object):
...   def __repr__(self):
...     return 'I am a SomeClass instance.'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.

So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).

>>> class SomeClass:
...   def __str__(self):
...     return 'I am a SomeClass instance.'
...
>>> SomeClass
<class __main__.SomeClass at 0x2ba2f0fd3b30>
>>> print SomeClass
__main__.SomeClass
>>>
>>> x = SomeClass()
>>> x
<__main__.SomeClass instance at 0x2ba2f0ff3f38>
>>> print x
I am a SomeClass instance.

Body:
override __repr__ instead.

>>> class SomeClass(object):
...   def __repr__(self):
...     return 'I am a SomeClass instance.'


问:
EC2-Image builder failed with Unable to bootstrap TOE
I am using the AWS-Ec2 image builder for the first time and I have configured the pipeline with default configs and I am trying to run a component which is amazon-owned (python-3-linux), and I get the following error:

SSM execution 'da233246-f411-8324-9c46-23c23ee4519ae' failed with status = 'Failed' in state = 'BUILDING' and failure message = 'Unable to bootstrap TOE'

And when I looked into the SSM automation I see the following output for that step as below:

Waiting for Cloud-init to initialize ...
Cloud-init fails to initialize ... waiting another 5 minutes for the instance to stabilize
/var/lib/amazon/ssm/i-0227a2e739e04bd18/document/orchestration/ee2476f3-3swe-4197-g351-2j4912f2f4123/awsrunShellScript/0.awsrunShellScript/_script.sh: line 49: /tmp/imagebuilder/TaskOrchestratorAndExecutor/bootstrap.sh: No such file or directory
{"failureMessage":"Unable to bootstrap TOE"}

----------ERROR-------
chmod: cannot access '/tmp/imagebuilder/TaskOrchestratorAndExecutor/bootstrap.sh': No such file or directory
failed to run commands: exit status 1

Can someone help me why this is happening?

答:
If you get permission errors, you may have mounted /tmp with noexec. (This also causes SSM failures)

In your particular case, /tmp may not exist at all.

Try choosing a different location for your working directory in the workingDirectory field of the image recipe.

To debug: set TerminateInstanceOnFailure: false and add a KeyPair so you can log in after it fails.


问:
How can I make the "do" loop continue, but not infinitely in my code?
Basically, whenever I walk into the trigger it repeats the loop infinitely. I know the reason for this but I don't know the way to fix it so that it works properly. It's meant to do it until you leave the trigger.

```<code>public void OnTriggerEnter(Collider other)
        {

            InDamageRange = true;

            StartCoroutine(waiter());
        }

        public void OnTriggerExit(Collider other)
        {
            StopCoroutine(waiter());
            InDamageRange = false;

        }

        public IEnumerator waiter()
        {
            do
            {
                yield return new WaitForSeconds(1.5f);
                player.Health = player.Health - damage;
            } while (InDamageRange != false);

        }
</code>```

What can I do to make this work?

Edit: Turns out the issue was that I was trying to stop the coroutine before setting the bool to false. I swapped the two lines in OnTriggerExit and that fixed the issue, thanks for the help! :)

答:
Every time you call waiter() you are creating a new instance of your IEnumerator. You do need to keep a reference to the original one if you want to stop it. Try this:

```<code>private IEnumerator _waiter;

public void OnTriggerEnter(Collider other)
{
    InDamageRange = true;
    _waiter = waiter();
    StartCoroutine(_waiter);
}

public void OnTriggerExit(Collider other)
{
    StopCoroutine(_waiter);
    InDamageRange = false;
}

public IEnumerator waiter()
{
    do
    {
        yield return new WaitForSeconds(1.5f);
        player.Health = player.Health - damage;
    } while (InDamageRange != false);
}
</code>```

But given your code setting InDamageRange = true should have also stopped it. Is it your actual code?

Body:
Basically, whenever I walk into the trigger it repeats the loop infinitely. I know the reason for this but I don't know the way to fix it so that it works properly. It's meant to do it until you leave the trigger.

public void OnTriggerEnter(Collider other)
        {

            InDamageRange = true;

            StartCoroutine(waiter());
        }

        public void OnTriggerExit(Collider other)
        {
            StopCoroutine(waiter());
            InDamageRange = false;

        }

        public IEnumerator waiter()
        {
            do
            {
                yield return new WaitForSeconds(1.5f);
                player.Health = player.Health - damage;
            } while (InDamageRange != false);

        }

What can I do to make this work?

Edit: Turns out the issue was that I was trying to stop the coroutine before setting the bool to false. I swapped the two lines in OnTriggerExit and that fixed the issue, thanks for the help! :)

Body:
Every time you call waiter() you are creating a new instance of your IEnumerator. You do need to keep a reference to the original one if you want to stop it. Try this:

private IEnumerator _waiter;

public void OnTriggerEnter(Collider other)
{
    InDamageRange = true;
    _waiter = waiter();
    StartCoroutine(_waiter);
}

public void OnTriggerExit(Collider other)
{
    StopCoroutine(_waiter);
    InDamageRange = false;
}

public IEnumerator waiter()
{
    do
    {
        yield return new WaitForSeconds(1.5f);
        player.Health = player.Health - damage;
    } while (InDamageRange != false);
}

But given your code setting InDamageRange = true should have also stopped it. Is it your actual code?


问:
Having empty constructor that leaves arrays uninitialized makes slower calculation
I am very confused with one thing...
If I add constructor to struct A then calculating in for loop becomes many times slower. Why? I have no idea.

On my computer times of the snippet in outputs are:

With constructor: 1351

Without constructor: 220

Here is a code:

```<code>#include <iostream>
#include <chrono>
#include <cmath>

using namespace std;
using namespace std::chrono;

const int SIZE = 1024 * 1024 * 32;

using type = int;

struct A {
    type a1[SIZE];
    type a2[SIZE];
    type a3[SIZE];
    type a4[SIZE];
    type a5[SIZE];
    type a6[SIZE];

    A() {} // comment this line and iteration will be twice faster
};

int main() {
    A* a = new A();
    int r;
    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    for (int i = 0; i < SIZE; i++) {
        r = sin(a->a1[i] * a->a2[i] * a->a3[i] * a->a4[i] * a->a5[i] * a->a6[i]);
    }
    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    cout << duration_cast<milliseconds>(t2 - t1).count() << ": " << r << endl;

    delete a;

    system("pause");
    return 0;
}
</code>```

However if I remove sin() method from for loop like this:

```<code>for (int i = 0; i < SIZE; i++) {
    r = a->a1[i] * a->a2[i] * a->a3[i] * a->a4[i] * a->a5[i] * a->a6[i];
}
</code>```

removing constructor does not matter and the time of execution is the same and equals 78.

Do you have similar behaviour with this code? Do you know a reason of this?

EDIT:
I compile it with Visual Studio 2013

答:
Yes, this behavior is still reproducible in Visual Studio 2019 if compile in Release configuration (with optimization).

If struct A has empty user constructor, then its fields remain uninitialized after new A().

On the other hand, if struct A does not have a constructor, then it becomes an aggregate and new A() fills its fields with zeros.

Computing multiplications and then sine has the same performance independent of input arguments (if they are not de-normalized values, which is not the case here), but after the initialization of the fields with zeros they appear in CPU cache, so the following computation goes faster, which explains the "benefit" of no-constructor version (of course, if not include in the measurement the time of object construction).

If you keep empty constructor, and then manually fill the object with zeros:

```<code>    A* a = new A();
    for (int i = 0; i < SIZE; i++)
        a->a1[i] = a->a2[i] = a->a3[i] = a->a4[i] = a->a5[i] = a->a6[i] = 0;
</code>```

then the program will be same fast as in the case of no constructor in A.

Body:
I am very confused with one thing...
If I add constructor to struct A then calculating in for loop becomes many times slower. Why? I have no idea.

On my computer times of the snippet in outputs are:

With constructor: 1351

Without constructor: 220

Here is a code:

#include <iostream>
#include <chrono>
#include <cmath>

using namespace std;
using namespace std::chrono;

const int SIZE = 1024 * 1024 * 32;

using type = int;

struct A {
    type a1[SIZE];
    type a2[SIZE];
    type a3[SIZE];
    type a4[SIZE];
    type a5[SIZE];
    type a6[SIZE];

    A() {} // comment this line and iteration will be twice faster
};

int main() {
    A* a = new A();
    int r;
    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    for (int i = 0; i < SIZE; i++) {
        r = sin(a->a1[i] * a->a2[i] * a->a3[i] * a->a4[i] * a->a5[i] * a->a6[i]);
    }
    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    cout << duration_cast<milliseconds>(t2 - t1).count() << ": " << r << endl;

    delete a;

    system("pause");
    return 0;
}

However if I remove sin() method from for loop like this:

for (int i = 0; i < SIZE; i++) {
    r = a->a1[i] * a->a2[i] * a->a3[i] * a->a4[i] * a->a5[i] * a->a6[i];
}

removing constructor does not matter and the time of execution is the same and equals 78.

Do you have similar behaviour with this code? Do you know a reason of this?

EDIT:
I compile it with Visual Studio 2013

Body:
Yes, this behavior is still reproducible in Visual Studio 2019 if compile in Release configuration (with optimization).

If struct A has empty user constructor, then its fields remain uninitialized after new A().

On the other hand, if struct A does not have a constructor, then it becomes an aggregate and new A() fills its fields with zeros.

Computing multiplications and then sine has the same performance independent of input arguments (if they are not de-normalized values, which is not the case here), but after the initialization of the fields with zeros they appear in CPU cache, so the following computation goes faster, which explains the "benefit" of no-constructor version (of course, if not include in the measurement the time of object construction).

If you keep empty constructor, and then manually fill the object with zeros:

    A* a = new A();
    for (int i = 0; i < SIZE; i++)
        a->a1[i] = a->a2[i] = a->a3[i] = a->a4[i] = a->a5[i] = a->a6[i] = 0;

then the program will be same fast as in the case of no constructor in A.


问:
What's the point of Raku's 'mod' operator?
I previously incorrectly thought that the % operator returned the remainder and the mod operator returned the modulus (the remainder and modulus are the same when the operands are both positive or both negative but differ when one operand is positive and the other is negative.  Compare Raket's remainder and modulo functions).

However, that's not correct at all – both % and mod return the modulus; neither return the remainder.  In fact, it looks like mod will always return exactly the same value as % would have, if called with the same arguments.  As far as I can tell, the only difference is that % can be called with non-integer arguments, whereas mod throws an exception if called with anything other than Int:D or int.

So, what's the point of mod?  Is there some performance gain from using it (maybe by saving the optimizer some specialization work?) or is there some other difference I'm missing?

答:
The 'bible' of IEEE P754 says this...

Floating point remainder. This is not like a normal modulo operation, it can be negative for two positive numbers. It returns the exact value of x–(round(x/y)·y).


问:
Either _POST or _FILES is empty when submitting form
I am trying to upload a simple image file to my project using php and html but when I submit the form, either the _FILE method is empty or the _POST method is empty. My code never makes it passed the if statement checking that all fields are not empty, as I get the error: "All fields are mandatory, please fill all the fields."

Here is my CRUD.php file up until the error message:

```<code>// Include and initialize database class
require_once(ROOT_DIR . '/Classes/database.class.php');
$imageDB = new DB();

$tblName = 'image';

 // The folder where the images will be stored
 $uploadDir = CONTENT_PATH . '/';

 // Allow file formats
 $allowTypes = array('jpg', 'png', 'jpeg', 'gif');

 // Set default redirect url
 $redirectURL = PUBLIC_PATH . '/manageUploads.php';

 $statusMsg = '';
 $sessData = array();
 $statusType = 'danger';

// Check if user has uploaded new image
if (isset($_POST['imgSubmit'])) {
    //Set redirect url
    $redirectURL = PUBLIC_PATH . '/addEdit.php';

    //Get submitted data and clean it from injections
    $id = $_POST['id'];
    $image = $_FILES['image'];
    echo $image['name'];

    //Store title variable without any html or php tags and trims whitespace from beginning and end
    $title = strip_tags(trim($_POST['title']));

    // Validate user tags are separated by comma or space and contain only alphanumeric or space/comma input
    $regex = '/^[ ,]*[a-zA-Z0-9]+(?:[ ,]+[a-zA-Z0-9]+){0,5}[ ,]*$/';
    if (preg_match($regex, $_POST['tags']) == 0) {
        exit('Tags are not valid!');
    }
    // Makes all tags lower case
    $tag_input = strtolower($_POST['tags']);

    // Clean up multiple commas or whitespaces
    $clean_tag_input = preg_replace('/[\s,]+/', ' ', $tag_input);

    // Replaces spaces with commas
    $comma_tags = str_replace(' ', ',', $clean_tag_input);

    // Submitted user data
    $imgData = array('title' => $title,'tags' => $comma_tags);

    // Store submitted data into session
    $sessData['postData'] = $imgData;
    $sessData['postData']['id'] = $id;

    // ID query string
    $idStr = !empty($id)?'?id='.$id:'';

    // If the data is not empty
    if ((!empty($image['name']) && !empty($title) && !empty($comma_tags)) || (!empty($id) && !empty($title) && !empty($comma_tags))) {
        echo $title;
        if(!empty($image)) {
            $filename = basename($image['name']);

            // Get file extension in lower case
            $fileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            echo $fileType;

            // Generate a unique name for the image to prevent throwing exists error
            $unique_image_name = rand(10000, 990000) . '_' . time() . '.' . $fileType;

            // The path of the new uploaded image
            $targetFilePath = $uploadDir . $unique_image_name;
            echo $targetFilePath;

            if (in_array($fileType, $allowTypes)) {

                // Check to make sure the image is valid
                if (!empty($image['tmp_name']) && getimagesize($image['tmp_name'])) {

                    if (file_exists($unique_image_name)) {
                        $statusMsg = 'Image already exists, please choose another or rename that image.';

                    } else if ($image['size'] > 500000) {
                        $statusMsg = 'Image file size too large, please choose an image less than 500kb.';
                    } else {
                        // Everything checks out now we can move the uploaded image
                        if (move_uploaded_file($image['tmp_name'], $targetFilePath)){
                            $imgData['filename'] = $unique_image_name;
                            $imgData['username'] = $_SESSION['username'];
                        } else {
                            $statusMsg = 'Sorry, there was an error uploading your file.';
                        }
                    }
                }
                } else {
                        $statusMsg = 'Image file is empty or corrupt.';
                }
            } else {
                $statusMsg = 'Sorry, only JPG, JPEG, PNG && GIF files are allowed to be uploaded.';
            }
        } else {
            $statusMsg = 'Sorry something went wrong.';
        }

        if (!empty($id)) {
            // Previous filename
            $conditions['where'] = array('id' => $_GET['imageID'],);
            $conditions['return_type'] = 'single';
            $prevData = $imageDB->getRows('image', $conditions);

            // Update data
            $condition = array('id' => $id);
            $update = $imageDB->update($tblName, $imgData, $condition);

            if($update) {
                //Remove old file from server
                if (!empty($imgData['filename'])) {
                    @unlink($uploadDir . $prevData['filename']);
                }
                $statusType = 'success';
                $statusMsg = 'Image data has been updated successfully.';
                $sessData['postData'] = '';

                $redirectURL = PUBLIC_PATH . '/manageUploads.php';
            } else {
                $statusMsg = 'Some problem occurred, please try again.';
                //Set redirect url
                $redirectURL .= $idStr;
            }
        } elseif (!empty($imgData['filename'])) {
            // Insert data
            $insert = $imageDB->insert($tblName, $imgData);

            if ($insert) {
                $statusType = 'success';
                $statusMsg = 'Image has been uploaded successfully.';
                $sessData['postData'] = '';

                $redirectURL = PUBLIC_PATH . '/manageUploads.php';
            } else {
                $statusMsg = 'Some problem occurred, please try again.';
            }

    } else {
        $statusMsg = 'All fields are mandatory, please fill all the fields.';
    }
</code>```

And here is my addEdit.php file with the form:

```<code>require_once(ROOT_DIR . '/Templates/header.php');

$postData = $imgData = array();
$newViewkey = uniqid();

// Get image data
if (!empty($_GET['imageID'])) {
    //include and initialize DB class
    require_once(ROOT_DIR . '/Classes/database.class.php');
    $addEditDB = new DB();

    $conditions['where'] = array('id' => $_GET['imageID'],);

    $conditions['return_type'] = 'single';
    $imgData = $addEditDB->getRows('image', $conditions);
}

// Pre-filled data
$imgData = !empty($postData)?$postData:$imgData;

// Define action
$actionLabel = !empty($_GET['imageID'])?'Edit':'Add';

head('Upload Image', $_SESSION['username'])
?>
<!-- Display status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="message">
    <?php echo $statusMsg; ?>
</div>
<?php } ?>

<div class="upload-form">
    <h1>Upload Image</h1>

    <form action="<?php echo IMAGE_UTIL_PATH;?>/crud.php" method="POST" enctype="multipart/form-data">
        <label for="title">Title</label>
            <input
                type="text" name="title" id="title"
                placeholder="Type image title here."
                value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" required>

        <?php if (!empty($imgData['tags'])) {
            $tagsSpaces = preg_replace('/,/', ', ', trim($imgData['tags']));
        } ?>
        <label for="tags">Tags</label>
            <textarea name="tags" id="tags" placeholder="Enter at least 1 tag describing the image separated by a space ' ' or a ','."  required><?php echo !empty($imgData['tags'])?$tagsSpaces:''; ?></textarea>

        <input type="file" name="image" id="image" value="<?php echo !empty($imgData['filename'])?$imgData['filename']:''; ?>" required>

        <input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">

        <input type="hidden" name="modified" value="<?php echo !empty($imgData['id'])?date('Y/m/d h:m:s'):''; ?>">

        <input type="hidden" name="viewkey" value="<?php echo !empty($imgData['viewkey'])?$imgData['viewkey']:$newViewkey;?>">

        <?php if (!empty($imgData['filename'])) { ?>
        <div>
            <img src="<?php echo !empty($imgData['filename'])?$imgData['filename']:'';?>" height=75 width=auto >
        </div>
    <?php } ?>

        <input type="submit" value="Upload" name="imgSubmit">
    </form>
    <div class="message">
        <a href="manageUploads.php">Back to Manage Uploads</a>
    </div>

</div>

<?php require_once(ROOT_DIR . '/Templates/footer.php')?>
</code>```

And finally here is my config.php file with all the path definitions:

```<code>/*
Set include path to include files outside root directory
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\xampp\htdocs\Shape_Search\resources');

/*
Error reporting
*/
ini_set("display_errors", "true");
error_reporting(E_ALL|E_STRICT);

/*
Create constants for heavily used paths relative to config file location
*/
defined('ROOT_DIR')
    or define('ROOT_DIR', dirname(__FILE__));

defined('SRC_DIR')
    or define('SRC_DIR', dirname(dirname(__FILE__)) . '\src');

defined('PUBLIC_PATH')
    or define('PUBLIC_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html');

defined('CONTENT_PATH')
    or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');

defined('LAYOUT_PATH')
    or define('LAYOUT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/layout');

defined('CSS_PATH')
    or define('CSS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/css');

defined('JS_PATH')
    or define('JS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/js');

defined('LIBRARY_PATH')
    or define('LIBRARY_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/resources/Library');

defined('CLASSES_PATH')
    or define('CLASSES_PATH', realpath(dirname(__FILE__)) . '/Classes');

defined('TEMPLATES_PATH')
    or define('TEMPLATES_PATH', realpath(dirname(__FILE__)) . "\Templates");

defined('IMAGE_UTIL_PATH')
    or define('IMAGE_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/ImageUtilities');

defined('RATING_UTIL_PATH')
    or define('RATING_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/RatingUtilities');

defined('USER_UTIL_PATH')
    or define('USER_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/UserUtilities');

?>
</code>```

And here is my php error log:

[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning:  move_uploaded_file(/Shape_Search/public_html/img/content/973439_1644497526.jpg): Failed to open stream: No such file or directory in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116
[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning:  move_uploaded_file(): Unable to move "C:\xampp\tmp\phpCCA.tmp" to "/Shape_Search/public_html/img/content/973439_1644497526.jpg" in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116

答:
It was an issue of directory vs. path.

```<code> // The folder where the images will be stored
 $uploadDir = CONTENT_PATH . '/';
</code>```

Should be corrected to:

```<code> // The folder where the images will be stored
 $uploadDir = CONTENT_DIR . '/';
</code>```

Where the global variables CONTENT_PATH and CONTENT_DIR are:

```<code>defined('CONTENT_PATH')
    or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');

defined('CONTENT_DIR')
    or define('CONTENT_DIR', dirname(dirname(__FILE__)) . '/public_html/img/content');
</code>```

Body:
I am trying to upload a simple image file to my project using php and html but when I submit the form, either the _FILE method is empty or the _POST method is empty. My code never makes it passed the if statement checking that all fields are not empty, as I get the error: "All fields are mandatory, please fill all the fields."

Here is my CRUD.php file up until the error message:

// Include and initialize database class
require_once(ROOT_DIR . '/Classes/database.class.php');
$imageDB = new DB();

$tblName = 'image';

 // The folder where the images will be stored
 $uploadDir = CONTENT_PATH . '/';

 // Allow file formats
 $allowTypes = array('jpg', 'png', 'jpeg', 'gif');

 // Set default redirect url
 $redirectURL = PUBLIC_PATH . '/manageUploads.php';

 $statusMsg = '';
 $sessData = array();
 $statusType = 'danger';

// Check if user has uploaded new image
if (isset($_POST['imgSubmit'])) {
    //Set redirect url
    $redirectURL = PUBLIC_PATH . '/addEdit.php';

    //Get submitted data and clean it from injections
    $id = $_POST['id'];
    $image = $_FILES['image'];
    echo $image['name'];

    //Store title variable without any html or php tags and trims whitespace from beginning and end
    $title = strip_tags(trim($_POST['title']));

    // Validate user tags are separated by comma or space and contain only alphanumeric or space/comma input
    $regex = '/^[ ,]*[a-zA-Z0-9]+(?:[ ,]+[a-zA-Z0-9]+){0,5}[ ,]*$/';
    if (preg_match($regex, $_POST['tags']) == 0) {
        exit('Tags are not valid!');
    }
    // Makes all tags lower case
    $tag_input = strtolower($_POST['tags']);

    // Clean up multiple commas or whitespaces
    $clean_tag_input = preg_replace('/[\s,]+/', ' ', $tag_input);

    // Replaces spaces with commas
    $comma_tags = str_replace(' ', ',', $clean_tag_input);

    // Submitted user data
    $imgData = array('title' => $title,'tags' => $comma_tags);

    // Store submitted data into session
    $sessData['postData'] = $imgData;
    $sessData['postData']['id'] = $id;

    // ID query string
    $idStr = !empty($id)?'?id='.$id:'';

    // If the data is not empty
    if ((!empty($image['name']) && !empty($title) && !empty($comma_tags)) || (!empty($id) && !empty($title) && !empty($comma_tags))) {
        echo $title;
        if(!empty($image)) {
            $filename = basename($image['name']);

            // Get file extension in lower case
            $fileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            echo $fileType;

            // Generate a unique name for the image to prevent throwing exists error
            $unique_image_name = rand(10000, 990000) . '_' . time() . '.' . $fileType;

            // The path of the new uploaded image
            $targetFilePath = $uploadDir . $unique_image_name;
            echo $targetFilePath;

            if (in_array($fileType, $allowTypes)) {

                // Check to make sure the image is valid
                if (!empty($image['tmp_name']) && getimagesize($image['tmp_name'])) {

                    if (file_exists($unique_image_name)) {
                        $statusMsg = 'Image already exists, please choose another or rename that image.';

                    } else if ($image['size'] > 500000) {
                        $statusMsg = 'Image file size too large, please choose an image less than 500kb.';
                    } else {
                        // Everything checks out now we can move the uploaded image
                        if (move_uploaded_file($image['tmp_name'], $targetFilePath)){
                            $imgData['filename'] = $unique_image_name;
                            $imgData['username'] = $_SESSION['username'];
                        } else {
                            $statusMsg = 'Sorry, there was an error uploading your file.';
                        }
                    }
                }
                } else {
                        $statusMsg = 'Image file is empty or corrupt.';
                }
            } else {
                $statusMsg = 'Sorry, only JPG, JPEG, PNG && GIF files are allowed to be uploaded.';
            }
        } else {
            $statusMsg = 'Sorry something went wrong.';
        }

        if (!empty($id)) {
            // Previous filename
            $conditions['where'] = array('id' => $_GET['imageID'],);
            $conditions['return_type'] = 'single';
            $prevData = $imageDB->getRows('image', $conditions);

            // Update data
            $condition = array('id' => $id);
            $update = $imageDB->update($tblName, $imgData, $condition);

            if($update) {
                //Remove old file from server
                if (!empty($imgData['filename'])) {
                    @unlink($uploadDir . $prevData['filename']);
                }
                $statusType = 'success';
                $statusMsg = 'Image data has been updated successfully.';
                $sessData['postData'] = '';

                $redirectURL = PUBLIC_PATH . '/manageUploads.php';
            } else {
                $statusMsg = 'Some problem occurred, please try again.';
                //Set redirect url
                $redirectURL .= $idStr;
            }
        } elseif (!empty($imgData['filename'])) {
            // Insert data
            $insert = $imageDB->insert($tblName, $imgData);

            if ($insert) {
                $statusType = 'success';
                $statusMsg = 'Image has been uploaded successfully.';
                $sessData['postData'] = '';

                $redirectURL = PUBLIC_PATH . '/manageUploads.php';
            } else {
                $statusMsg = 'Some problem occurred, please try again.';
            }

    } else {
        $statusMsg = 'All fields are mandatory, please fill all the fields.';
    }

And here is my addEdit.php file with the form:

require_once(ROOT_DIR . '/Templates/header.php');

$postData = $imgData = array();
$newViewkey = uniqid();

// Get image data
if (!empty($_GET['imageID'])) {
    //include and initialize DB class
    require_once(ROOT_DIR . '/Classes/database.class.php');
    $addEditDB = new DB();

    $conditions['where'] = array('id' => $_GET['imageID'],);

    $conditions['return_type'] = 'single';
    $imgData = $addEditDB->getRows('image', $conditions);
}

// Pre-filled data
$imgData = !empty($postData)?$postData:$imgData;

// Define action
$actionLabel = !empty($_GET['imageID'])?'Edit':'Add';

head('Upload Image', $_SESSION['username'])
?>

<?php if(!empty($statusMsg)){ ?>

    <?php echo $statusMsg; ?>

<?php } ?>

Upload Image

    <form action="<?php echo IMAGE_UTIL_PATH;?>/crud.php" method="POST" enctype="multipart/form-data">
        Title
            <input
                type="text" name="title" id="title"
                placeholder="Type image title here."
                value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" required>

        <?php if (!empty($imgData['tags'])) {
            $tagsSpaces = preg_replace('/,/', ', ', trim($imgData['tags']));
        } ?>
        Tags
            <textarea name="tags" id="tags" placeholder="Enter at least 1 tag describing the image separated by a space ' ' or a ','."  required><?php echo !empty($imgData['tags'])?$tagsSpaces:''; ?></textarea>

        <input type="file" name="image" id="image" value="<?php echo !empty($imgData['filename'])?$imgData['filename']:''; ?>" required>

        <input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">

        <input type="hidden" name="modified" value="<?php echo !empty($imgData['id'])?date('Y/m/d h:m:s'):''; ?>">

        <input type="hidden" name="viewkey" value="<?php echo !empty($imgData['viewkey'])?$imgData['viewkey']:$newViewkey;?>">

        <?php if (!empty($imgData['filename'])) { ?>

            <img src="<?php echo !empty($imgData['filename'])?$imgData['filename']:'';?>" height=75 width=auto >

    <?php } ?>

        <input type="submit" value="Upload" name="imgSubmit">
    </form>

        Back to Manage Uploads

<?php require_once(ROOT_DIR . '/Templates/footer.php')?>

And finally here is my config.php file with all the path definitions:

/*
Set include path to include files outside root directory
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\xampp\htdocs\Shape_Search\resources');

/*
Error reporting
*/
ini_set("display_errors", "true");
error_reporting(E_ALL|E_STRICT);

/*
Create constants for heavily used paths relative to config file location
*/
defined('ROOT_DIR')
    or define('ROOT_DIR', dirname(__FILE__));

defined('SRC_DIR')
    or define('SRC_DIR', dirname(dirname(__FILE__)) . '\src');

defined('PUBLIC_PATH')
    or define('PUBLIC_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html');

defined('CONTENT_PATH')
    or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');

defined('LAYOUT_PATH')
    or define('LAYOUT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/layout');

defined('CSS_PATH')
    or define('CSS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/css');

defined('JS_PATH')
    or define('JS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/js');

defined('LIBRARY_PATH')
    or define('LIBRARY_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/resources/Library');

defined('CLASSES_PATH')
    or define('CLASSES_PATH', realpath(dirname(__FILE__)) . '/Classes');

defined('TEMPLATES_PATH')
    or define('TEMPLATES_PATH', realpath(dirname(__FILE__)) . "\Templates");

defined('IMAGE_UTIL_PATH')
    or define('IMAGE_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/ImageUtilities');

defined('RATING_UTIL_PATH')
    or define('RATING_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/RatingUtilities');

defined('USER_UTIL_PATH')
    or define('USER_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/UserUtilities');

?>

And here is my php error log:

[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning:  move_uploaded_file(/Shape_Search/public_html/img/content/973439_1644497526.jpg): Failed to open stream: No such file or directory in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116
[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning:  move_uploaded_file(): Unable to move "C:\xampp\tmp\phpCCA.tmp" to "/Shape_Search/public_html/img/content/973439_1644497526.jpg" in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116

Body:
It was an issue of directory vs. path.

 // The folder where the images will be stored
 $uploadDir = CONTENT_PATH . '/';

Should be corrected to:

 // The folder where the images will be stored
 $uploadDir = CONTENT_DIR . '/';

Where the global variables CONTENT_PATH and CONTENT_DIR are:

defined('CONTENT_PATH')
    or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');

defined('CONTENT_DIR')
    or define('CONTENT_DIR', dirname(dirname(__FILE__)) . '/public_html/img/content');


问:
For loop in function to move the item of the list
I want to move the negative numbers to the end of the list until I encounter the positive number.

List:

```<code>a=[-1,-2,2,3,4,-5]
</code>```

The result i want:

```<code>[-2, 2, 3, 4, -5, -1]
[2, 3, 4, -5, -1, -2]
</code>```

My function:

```<code>def f1(A):
  for i in A:
    if i>=0:
      break
    if 'Z' not in globals() or 'Z' not in locals():
     X=A
     X1=X[0]
     X.remove(X1)
     X.append(X1)
     Z=X
    else:
      X=Z
      X1=X[0]
      X.remove(X1)
      X.append(X1)
      Z=X
    print(Z)

a=[-1,-2,2,3,4,-5]
print (f1 (a))
</code>```

But the result

```<code>[-2, 2, 3, 4, -5, -1]
None
</code>```

can we solve it with this function?

答:
```<code>def f1(a):
    a = a.copy()
    while True:
        i = a[0]
        if i < 0:
            a.append(i)
            a = a[1:]
            print(a)
        else:
            return a
</code>```

Body:
I want to move the negative numbers to the end of the list until I encounter the positive number.

List:

a=[-1,-2,2,3,4,-5]

The result i want:

[-2, 2, 3, 4, -5, -1]
[2, 3, 4, -5, -1, -2]

My function:

def f1(A):
  for i in A:
    if i>=0:
      break
    if 'Z' not in globals() or 'Z' not in locals():
     X=A
     X1=X[0]
     X.remove(X1)
     X.append(X1)
     Z=X
    else:
      X=Z
      X1=X[0]
      X.remove(X1)
      X.append(X1)
      Z=X
    print(Z)

a=[-1,-2,2,3,4,-5]
print (f1 (a))

But the result

[-2, 2, 3, 4, -5, -1]
None

can we solve it with this function?


问:
Pylint cannot detect the missing space after # sign of comments and missing blank line, Python3
I have written a try_pylint.py file to try if pylint can detect some incorrect style with Python 3.10.

"""This is a try for pylint detection.
"""

#hello world!  --> missing a space, and it has only 1 (needs 2) blank line before it.

def print_hello():
    """print it
    """
    print('hello')

```
<p>If I run the command in terminal <code>pylint try_pylint.py</code>, it gives</p>
```Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)
```
<p>However, if I use <code>flake8</code>, it can detect both of them.
<code>flake8 try_pylint.py</code> gives</p>
```try_pylint.py:4:1: E265 block comment should start with '# '
try_pylint.py:6:1: E302 expected 2 blank lines, found 1
```

Could you please show me how to configure pylint to detect them? By the way, I am using VS Code for developing Python code. It would be great if you can show me how to configure it on VS Code.

Thanks in advance!

答:
The actual check is done by pycodestyle inside flake8. pylint do not check for this and for formatting in general (as black can format your code automatically, this kind of check are not very useful anymore).

You should use black, flake8 and pylint together, they are not mutually exclusive.

Body:
I have written a try_pylint.py file to try if pylint can detect some incorrect style with Python 3.10.

"""This is a try for pylint detection.
"""

#hello world!  --> missing a space, and it has only 1 (needs 2) blank line before it.

def print_hello():
    """print it
    """
    print('hello')

If I run the command in terminal pylint try_pylint.py, it gives

Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)

However, if I use flake8, it can detect both of them.
flake8 try_pylint.py gives

try_pylint.py:4:1: E265 block comment should start with '# '
try_pylint.py:6:1: E302 expected 2 blank lines, found 1

Could you please show me how to configure pylint to detect them? By the way, I am using VS Code for developing Python code. It would be great if you can show me how to configure it on VS Code.

Thanks in advance!


问:
CodeIgniter is discarding JOIN clause in SQL statement (Active Record)
I have the following function in one of my CI models:

```<code>function update_uu_feature($feature, $lang, $data)
{
    $feature = str_replace('_', '-', $feature);
    $this->db->where('navigation', $feature);
    $this->db->where('language', $lang);
    $this->db->join('all_video_names', 'all_video_names.video_id = all_uu_features.video_id', 'inner');
    return $this->db->update('all_uu_features', $data);
}
</code>```

But the “join” line gets discarded.  In the profiler, it outputs:

```<code>UPDATE `all_uu_features` SET `page_title` = 'Laser', `title` = 'Test', `keywords` = 'Test', `description` = 'Test', `feature_text` = '<p>Test text</p>', `learn_more_about` = 'Test Text 2', `overview` = 'test', `copy` = 'test' WHERE `navigation` = 'laser-interface' AND `language` = 'en'
</code>```

Can someone help me with the syntax?  Thanks.  Most of the data is in the all_uu_features table, except for the video name, which is in the all_video_names table.  The two are joined on the video_id column in each table. In other words, all of the columns in the above statement are in all_uu_features except for video name.  Hope that's clear.

The SQL statement above shows the data is being returned in the post and being processed by the function, it's just not accepting the join for some reason.

答:
It looks to me very much like CI's Active Record class doesn't support using joins in its update() operation. Certainly if you have a look at the code (in DB_active_rec.php), the update() method doesn't even look at any joins that have been set up

From update():

```<code>$sql = $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit);
</code>```

Body:
I have the following function in one of my CI models:

function update_uu_feature($feature, $lang, $data)
{
    $feature = str_replace('_', '-', $feature);
    $this->db->where('navigation', $feature);
    $this->db->where('language', $lang);
    $this->db->join('all_video_names', 'all_video_names.video_id = all_uu_features.video_id', 'inner');
    return $this->db->update('all_uu_features', $data);
}

But the “join” line gets discarded.  In the profiler, it outputs:

UPDATE `all_uu_features` SET `page_title` = 'Laser', `title` = 'Test', `keywords` = 'Test', `description` = 'Test', `feature_text` = '
Test text
', `learn_more_about` = 'Test Text 2', `overview` = 'test', `copy` = 'test' WHERE `navigation` = 'laser-interface' AND `language` = 'en'

Can someone help me with the syntax?  Thanks.  Most of the data is in the all_uu_features table, except for the video name, which is in the all_video_names table.  The two are joined on the video_id column in each table. In other words, all of the columns in the above statement are in all_uu_features except for video name.  Hope that's clear.

The SQL statement above shows the data is being returned in the post and being processed by the function, it's just not accepting the join for some reason.

Body:
It looks to me very much like CI's Active Record class doesn't support using joins in its update() operation. Certainly if you have a look at the code (in DB_active_rec.php), the update() method doesn't even look at any joins that have been set up

From update():

$sql = $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit);


问:
SQL Match table and multiple columns
I wanted to know a Query where in which i want to locate a specific table that contains two or more columns:

I tried:

```<code>SELECT *
FROM DB
WHERE TableName = 'TableName'
AND ColumName in('column1' , 'column2')
</code>```

But this query will look if any of those columns are there, but i want it to return only if all of them are a match.

I hope this questions makes sense.

答:
The operator IN is a concatenation of OR. However, there's no way to creare a short concatenation of AND as well.

See this question.

Title: SQL Match table and multiple columns

Body:
I wanted to know a Query where in which i want to locate a specific table that contains two or more columns:

I tried:

SELECT *
FROM DB
WHERE TableName = 'TableName'
AND ColumName in('column1' , 'column2')

But this query will look if any of those columns are there, but i want it to return only if all of them are a match.

I hope this questions makes sense.


问:
How can I fix the code so I can upload image to mongodb and not getting post error?
I have some user info that I want to save in mongodb database. I checked API post with postman by filling in some form-data fields in body. Simple data such as name or email, simple Strings work perfectly, but when I changed code(in controller.js file) so I can also get image file, it throws this generic error: "Cannot POST /api/users". The code seems fine to me but something's missing and can't figure it out.

server.js file:

```<code>const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const bodyparser = require("body-parser");
const path = require('path');
const fileUpload = require('express-fileupload');

const connectDB = require('./server/database/connection');
const bodyParser = require('body-parser');

const app = express();
app.use(fileUpload());

dotenv.config({path : 'config.env'})
const PORT = process.env.PORT || 8080

//log requests
app.use(morgan('tiny'));

//mongodb connection
connectDB();

//parse request to body-parser
app.use(bodyparser.urlencoded({extended : false}))
app.use(bodyparser.json())

//set view engine
app.set("view engine", "ejs")
//app.set("views", path.resolve(__dirname, "views/ejs"))

//load assets
app.use('/css', express.static(path.resolve(__dirname, "assets/css")))
app.use('/img', express.static(path.resolve(__dirname, "assets/img")))
app.use('/js', express.static(path.resolve(__dirname, "assets/js")))

//load routers
app.use('/', require('./server/routes/router'))

app.listen(PORT, ()=>{console.log(`Server is running on http://localhost:${PORT}`)});
</code>```

router.js file:

```<code>const express = require('express');
const route = express.Router()

const services = require('../services/render');
const controller = require('../controller/controller');

route.get('/', services.homeRoutes);
route.get('/add-user', services.add_user);
route.get('/update-user', services.update_user);

//API
route.post('/api/users', controller.create);
route.get('/api/users', controller.find);
route.put('/api/users/:id', controller.update);
route.delete('/api/users/:id', controller.delete);

module.exports = route
</code>```

model.js file:

```<code>const mongoose = require('mongoose');

var schema = new mongoose.Schema({
    profile_picture: {
        data: Buffer,
        contentType: String
    },
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    gender: String,
    favorite_movies: {
        type: String,
        text: true
    }
})

const Userdb = mongoose.model('userdb', schema);

module.exports = Userdb;
</code>```

controller.js file:

```<code>var multer = require('multer');
var fs = require('fs');
var path = require('path');

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads')
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now())
    }
});

var upload = multer({ storage: storage });

var Userdb = require('../model/model');

//create and save new user
exports.create = upload.single('image'), (req, res, next)=>{
    //validate request
    if(!req.body){
        res.status(400).send({ message : "Content cannot be empty!"});
        return;
    }

    //new user
    const user = new Userdb({
        profile_picture : {
            data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
            contentType: 'image/png'
        },
        name : req.body.name,
        email : req.body.email,
        gender : req.body.gender,
        favorite_movies : req.body.favorite_movies
    })

    //save user in the database
    user
      .save(user)
      .then(data=>{
          //res.send(data)
          res.redirect('/add-user');
      })
      .catch(err=>{
          res.status(500).send({
              message : err.message || "Some error occurred while creating a create operation"
          });
      });
}
</code>```

_form.ejs file:

```<code><!-- form handling -->
<form action="/api/users" method="POST" id="add_user">
<div class="new_user">
    <div class="form-group">
        <label for="image" class="text-light">Profile Picture<br><br></label>
        <div id="image">
            Choose File
            <input type="file" id="image" name="image" accept="image/*" class="hide_file">
        </div>
    </div>
    <div class="form-group">
        <label for="name" class="text-light"><br><br>Name</label>
        <input type="hidden" name="id" value="">
        <input type="text" name="name" value="" placeholder="Mark Harris">
    </div>
    <div class="form-group">
        <label for="Email" class="text-light">Email</label>
        <input type="text" name="email" value="" placeholder="example@gmail.com">
    </div>
    <div class="form-group">
        <label for="gender" class="text-light">Gender</label>
        <div class="radio inline">
            <input type="radio" id="radio-1" name="gender" value="Male" >
            <label for="radio-1" class="radio-label">Male</label>
        </div>
        <div class="radio inline">
            <input type="radio" id="radio-2" name="gender" value="Female" >
            <label for="radio-2" class="radio-label">Female</label>
        </div>
    </div>
    <div class="form-group">
        <label for="favorite_movies" class="text-light">Favorite Movies</label>
        <textarea name="favorite_movies" placeholder="Avengers: Age of Ultron&#10Shrek&#10..."></textarea>
    </div>
    <div class="form-group">
        <button type="submit" class="btn text-dark update">Save</button>
    </div>
</div>
</form>
</code>```

I believe the problem is somewhere in this controller.js file where I create and save a new user, the part exports.create = .......

答:
the problem is that the route handler is not implemented correctly: it returns upload middelware, and the response is not handled

you need to split them, export upload and create, and then call them in the POST handler:

controller.js file:

```<code>exports.upload = upload.single('image');

//create and save new user
exports.create = (req, res, next)=>{
</code>```

router.js file:

```<code>//API
route.post('/api/users', controller.upload, controller.create);
</code>```

Body:
I have some user info that I want to save in mongodb database. I checked API post with postman by filling in some form-data fields in body. Simple data such as name or email, simple Strings work perfectly, but when I changed code(in controller.js file) so I can also get image file, it throws this generic error: "Cannot POST /api/users". The code seems fine to me but something's missing and can't figure it out.

server.js file:

const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const bodyparser = require("body-parser");
const path = require('path');
const fileUpload = require('express-fileupload');

const connectDB = require('./server/database/connection');
const bodyParser = require('body-parser');

const app = express();
app.use(fileUpload());

dotenv.config({path : 'config.env'})
const PORT = process.env.PORT || 8080

//log requests
app.use(morgan('tiny'));

//mongodb connection
connectDB();

//parse request to body-parser
app.use(bodyparser.urlencoded({extended : false}))
app.use(bodyparser.json())

//set view engine
app.set("view engine", "ejs")
//app.set("views", path.resolve(__dirname, "views/ejs"))

//load assets
app.use('/css', express.static(path.resolve(__dirname, "assets/css")))
app.use('/img', express.static(path.resolve(__dirname, "assets/img")))
app.use('/js', express.static(path.resolve(__dirname, "assets/js")))

//load routers
app.use('/', require('./server/routes/router'))

app.listen(PORT, ()=>{console.log(`Server is running on http://localhost:${PORT}`)});

router.js file:

const express = require('express');
const route = express.Router()

const services = require('../services/render');
const controller = require('../controller/controller');

route.get('/', services.homeRoutes);
route.get('/add-user', services.add_user);
route.get('/update-user', services.update_user);

//API
route.post('/api/users', controller.create);
route.get('/api/users', controller.find);
route.put('/api/users/:id', controller.update);
route.delete('/api/users/:id', controller.delete);

module.exports = route

model.js file:

const mongoose = require('mongoose');

var schema = new mongoose.Schema({
    profile_picture: {
        data: Buffer,
        contentType: String
    },
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    gender: String,
    favorite_movies: {
        type: String,
        text: true
    }
})

const Userdb = mongoose.model('userdb', schema);

module.exports = Userdb;

controller.js file:

var multer = require('multer');
var fs = require('fs');
var path = require('path');

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads')
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now())
    }
});

var upload = multer({ storage: storage });

var Userdb = require('../model/model');

//create and save new user
exports.create = upload.single('image'), (req, res, next)=>{
    //validate request
    if(!req.body){
        res.status(400).send({ message : "Content cannot be empty!"});
        return;
    }

    //new user
    const user = new Userdb({
        profile_picture : {
            data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
            contentType: 'image/png'
        },
        name : req.body.name,
        email : req.body.email,
        gender : req.body.gender,
        favorite_movies : req.body.favorite_movies
    })

    //save user in the database
    user
      .save(user)
      .then(data=>{
          //res.send(data)
          res.redirect('/add-user');
      })
      .catch(err=>{
          res.status(500).send({
              message : err.message || "Some error occurred while creating a create operation"
          });
      });
}

_form.ejs file:

<form action="/api/users" method="POST" id="add_user">

        Profile Picture

            Choose File
            <input type="file" id="image" name="image" accept="image/*" class="hide_file">

Name
        <input type="hidden" name="id" value="">
        <input type="text" name="name" value="" placeholder="Mark Harris">

        Email
        <input type="text" name="email" value="" placeholder="example@gmail.com">

        Gender

            <input type="radio" id="radio-1" name="gender" value="Male" >
            Male

            <input type="radio" id="radio-2" name="gender" value="Female" >
            Female

        Favorite Movies
        <textarea name="favorite_movies" placeholder="Avengers: Age of Ultron&#10Shrek&#10..."></textarea>

        <button type="submit" class="btn text-dark update">Save</button>

</form>

I believe the problem is somewhere in this controller.js file where I create and save a new user, the part exports.create = .......

Body:
the problem is that the route handler is not implemented correctly: it returns upload middelware, and the response is not handled

you need to split them, export upload and create, and then call them in the POST handler:

controller.js file:

exports.upload = upload.single('image');

//create and save new user
exports.create = (req, res, next)=>{

router.js file:

//API
route.post('/api/users', controller.upload, controller.create);


问:
Adding a service reference to a website
I am trying to add a service reference to my website. When I add the service reference to a WPF application I get a reference.cs file that I can edit and add attributes to. When I try to do the same thing in a asp.net website there this file isn't present. I have also tried looking on the file system and the reference.cs isn't present. Can anyone provide some guidance?

EDIT:: Im using VS2010 and I need to edit the reference.cs to add [Webget] and [WebPost] attributes

答:
Depending on the version of VS it will create a folder under the project root. In my case under VS2010 I added a ref to http://www.webservicex.net/stockquote.asmx?WSDL, set the namespace to ServiceReference1 and it created a folder in the project root called \Service References\ServiceReference1 under which it stored all the ref files including Reference.cs

If you are not seeing this folder then there may be something wrong at your service that VS is unable to query the WSDL and generate the files. Try the stock service above to test.

And editing the generated files is usually a bad idea as they can get regenerated when you refresh the reference. Unless you want to rip the generated code out and never refresh it again.

UPDATE:

Seems like that webservicex service is slow, try this

Also, seems like there is a diff between "Web Reference" and "Service Reference". See here. But ultimately it creates a sub folder in your project root called either "Service References" or "Web References" with the sub folder of whatever you named your reference.

Title: Adding a service reference to a website


问:
How to run a simple click event on a div
I am trying to implement a simple click event but can't get it working.
If I remove the callback it works, but on load not on click.

Does anyone know what's wrong in my code?

script.js

```<code>const green = document.getElementById('green');

const clickColor = () => {
  alert('This is green color');
}

green.onclick = () => clickColor();
</code>```

答:
You could add a class to the element you're clicking on, and have the function pick that up.

const button = document.querySelector('button');

button.addEventListener('click', clickColor, false);

function clickColor() {
  const c = this.className;
  console.log(`This is ${c}`);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button { color: white; }
.green { background-color: green; }</code>```

<button class="green">Green</button>```

Body:
I am trying to implement a simple click event but can't get it working.
If I remove the callback it works, but on load not on click.

Does anyone know what's wrong in my code?

script.js

const green = document.getElementById('green');

const clickColor = () => {
  alert('This is green color');
}

green.onclick = () => clickColor();

Body:
You could add a class to the element you're clicking on, and have the function pick that up.

const button = document.querySelector('button');

button.addEventListener('click', clickColor, false);

function clickColor() {
  const c = this.className;
  console.log(`This is ${c}`);
}

button { color: white; }
.green { background-color: green; }

<button class="green">Green</button>


Title: For loop in function to move the item of the list

Body:
It's not a for loop, but:

>>> def shift(lst):
...     while lst[0] < 0:
...         lst = lst[1:] + [lst[0]]
...     return lst
...
>>> a
[-1, -2, 2, 3, 4, -5]
>>> b = shift(a)
>>> b
[2, 3, 4, -5, -1, -2]


问:
How do I account for daylight savings time when retrieving current time in PHP?
When getting the time via PHP script (time()), during Daylight Savings Time it seems to return a time value that is one hour off. Is there any way to get the correct time, accounting for Daylight Savings Time?

答: Either make sure the system time is current, or add/subtract in PHP: http://www.php.net/manual/en/function.date.php#69221</p>


问:
How to set two separate States with Redux Toolkit?
I'm trying to establish two separate states with Redux Toolkit, one called posts and another called countTest. However, at the moment the two states share the same value.

posts is set to display a value  of [] and countTest is set to display a value of  0. How do I differentiate the two states to display their unique value?

My actions file

```<code>import { createSlice } from "@reduxjs/toolkit";
import { database, auth } from "../firebase";
import { ref, set } from "firebase/database";

export const counterSlice = createSlice({
  name: "posts",
  initialState: {
    value: [],
  },
  reducers: {
    createAccount: (state, action) => {
      const user = auth.currentUser;
      const uid = user.uid;

      set(ref(database, `users/${uid}`), {
        email: action.payload.email,
        name: action.payload.name,
      });
    },
  },
});

export const testSlice = createSlice({
  name: "countTest",
  initialState: { value: 0 },
  reducers: {
    incrementAmount: (state, action) => {
      state.value = state.value + 1;
    },
    decrementAmount: (state, action) => {
      state.value = state.value - 1;
    },
  },
});

export const { createAccount, countTest } = counterSlice.actions;

export default counterSlice.reducer;
</code>```

My store  file

```<code>import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./actions";

export const store = configureStore({
  reducer: {
    posts: counterReducer,
    countTest: counterReducer,
  },
});
</code>```

I know in my store file I'm using counterReducer without specifically referring to the actions createAccount and countTest. How do I go about retrieving the unique values of each and displaying in store? Do I need to create a separate file for each action (is this best practice?) instead of having all the actions in one file?

Thank  you for any help

答:
You need to use a createAction (on an another file or on one of your slice import action from it) and use extraReducer.

Doc :
https://redux-toolkit.js.org/api/createSlice (the last exemple)

exemple create action:

```<code>export const incrementAll = createAction("incrementAll");
</code>```

use on your slices :

```<code>reducers : {//what you have for other things},
extraReducers: (builder) => {
    builder.addCase(incrementAll, (state) => {
      state.value++;
    });
</code>```

See the doc for more information or comment here if you need more explanation

Body:
I'm trying to establish two separate states with Redux Toolkit, one called posts and another called countTest. However, at the moment the two states share the same value.

posts is set to display a value  of [] and countTest is set to display a value of  0. How do I differentiate the two states to display their unique value?

My actions file

import { createSlice } from "@reduxjs/toolkit";
import { database, auth } from "../firebase";
import { ref, set } from "firebase/database";

export const counterSlice = createSlice({
  name: "posts",
  initialState: {
    value: [],
  },
  reducers: {
    createAccount: (state, action) => {
      const user = auth.currentUser;
      const uid = user.uid;

      set(ref(database, `users/${uid}`), {
        email: action.payload.email,
        name: action.payload.name,
      });
    },
  },
});

export const testSlice = createSlice({
  name: "countTest",
  initialState: { value: 0 },
  reducers: {
    incrementAmount: (state, action) => {
      state.value = state.value + 1;
    },
    decrementAmount: (state, action) => {
      state.value = state.value - 1;
    },
  },
});

export const { createAccount, countTest } = counterSlice.actions;

export default counterSlice.reducer;

My store  file

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./actions";

export const store = configureStore({
  reducer: {
    posts: counterReducer,
    countTest: counterReducer,
  },
});

I know in my store file I'm using counterReducer without specifically referring to the actions createAccount and countTest. How do I go about retrieving the unique values of each and displaying in store? Do I need to create a separate file for each action (is this best practice?) instead of having all the actions in one file?

Thank  you for any help

Body:
You need to use a createAction (on an another file or on one of your slice import action from it) and use extraReducer.

Doc :
https://redux-toolkit.js.org/api/createSlice (the last exemple)

exemple create action:

export const incrementAll = createAction("incrementAll");

use on your slices :

reducers : {//what you have for other things},
extraReducers: (builder) => {
    builder.addCase(incrementAll, (state) => {
      state.value++;
    });

See the doc for more information or comment here if you need more explanation


问:
Why can't my recyclerview scroll completely
I am trying to get recyclerview to scroll completely. For some reason the recyclerview stops to scroll at a particular spot, as if it as scrolled completedly.

Here's a picture of this:

Please keep in mind this is where the recyclerview scrolls to. And this fragment (screen) only contains the recyclerview.

this is the layout of the fragment containing the recyclerview:

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.ways.WaysFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/custom_ways_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

This the custom_view_item of the recyclerview:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="425dp">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="370dp"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_marginStart="30dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="30dp"
        android:foreground="?selectableItemBackground"
        app:cardCornerRadius="5dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        .....

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Thanks for your help in advance.. I'm more than happy to provide any information needed. Thanks again.

EDIT

Here's my activity_main.xml. I'm using navigation component method.

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/nav_host_fragment_activity_main"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/container"
        app:navGraph="@navigation/mobile_navigation" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="?android:attr/windowBackground"
        app:labelVisibilityMode="selected"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Give the recycler view a layout_height of 0dp so it can match constraints also link the bottom constraint to top of the bottom navigation menu.

```<code><fragment
    android:id="@+id/nav_host_fragment_activity_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@id/nav_view"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/bottom_nav_menu" />
</code>```

Body:
I am trying to get recyclerview to scroll completely. For some reason the recyclerview stops to scroll at a particular spot, as if it as scrolled completedly.

Here's a picture of this:

Please keep in mind this is where the recyclerview scrolls to. And this fragment (screen) only contains the recyclerview.

this is the layout of the fragment containing the recyclerview:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.ways.WaysFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/custom_ways_item" />
</androidx.constraintlayout.widget.ConstraintLayout>

This the custom_view_item of the recyclerview:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="425dp">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="370dp"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_marginStart="30dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="30dp"
        android:foreground="?selectableItemBackground"
        app:cardCornerRadius="5dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        .....

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

Thanks for your help in advance.. I'm more than happy to provide any information needed. Thanks again.

EDIT

Here's my activity_main.xml. I'm using navigation component method.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/nav_host_fragment_activity_main"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/container"
        app:navGraph="@navigation/mobile_navigation" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="?android:attr/windowBackground"
        app:labelVisibilityMode="selected"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Give the recycler view a layout_height of 0dp so it can match constraints also link the bottom constraint to top of the bottom navigation menu.

<fragment
    android:id="@+id/nav_host_fragment_activity_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@id/nav_view"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/bottom_nav_menu" />


问:
Propagating details of an error upwards in Rust
I would like to have the details of an error be propagated upwards. I used error-chain previously, but that has not been maintained or kept compatible with the rest of the ecosystem as far as i can tell.

For example, in this example:

```<code>use std::str::FromStr;
use anyhow::Result;

fn fail() -> Result<u64> {
  Ok(u64::from_str("Some String")?)
}

fn main() {

  if let Err(e) = fail(){
    println!("{:?}", e);
  }
</code>```

The error i am getting is:

```<code>invalid digit found in string
</code>```

I would need the error message to have the key details, including at the point of failure, for example:

```<code>- main: invalid digit found in string
- fail: "Some String" is not a valid digit
</code>```

What's the best way of doing this?

答: When you run your app with the environment variable RUST_BACKTRACE set to 1 or full, you'll get more error details, without the need to recompile your program. That, however, doesn't mean you're going to get an extra message like "Some String" is not a valid digit, as the parsing function simply doesn't generate such.

Body:
I would like to have the details of an error be propagated upwards. I used error-chain previously, but that has not been maintained or kept compatible with the rest of the ecosystem as far as i can tell.

For example, in this example:

use std::str::FromStr;
use anyhow::Result;

fn fail() -> Result<u64> {
  Ok(u64::from_str("Some String")?)
}

fn main() {

  if let Err(e) = fail(){
    println!("{:?}", e);
  }

The error i am getting is:

invalid digit found in string

I would need the error message to have the key details, including at the point of failure, for example:

- main: invalid digit found in string
- fail: "Some String" is not a valid digit

What's the best way of doing this?