答:
Your return statement needs to be fixed. return [coin_tokens] returns a list with your list inside it. So this:

```<code>    return[coin_tokens]
</code>```

should be:

```<code>    return coin_tokens
</code>```

Then, assign the return value:

```<code>coin_tokens = choose_coins()
</code>```

Body:
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.

import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()

Body:
Your return statement needs to be fixed. return [coin_tokens] returns a list with your list inside it. So this:

    return[coin_tokens]

should be:

    return coin_tokens

Then, assign the return value:

coin_tokens = choose_coins()


来源: stackexchange

问:
Unable to return variable from one function and use it in another function
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.</p>
```<code>import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()
</code>```

答:
There are multiple problems with your code.
The syntax to call a function is as follows:

```<code>return_value = function_name(arguments)
</code>```

You are calling choose_coins() but not storing the return value:

```<code>def main():

    coin_tokens = choose_coins()
    add_coins(coin_tokens)
</code>```

Or even:

```<code> add_coins(choose_coins())
</code>```

When you write:

```<code>return[coin_tokens]
</code>```

It is wrapping your coin_tokens which is already a list into another list. Change it to:

```<code>return coin_tokens
</code>```

You do not need this line; it has no effect:

```<code>coin_tokens.split()
print(coin_tokens)
</code>```

You should use token instead of i in the for loop. And have not initialized coin_total to 0 before the loop:

```<code>def add_coins(coin_tokens):

    print(coin_tokens)
    # Initialize to 0
    coin_total = 0

    #Iterate through coin_tokens list
    for token in coin_tokens:
        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

    print(coin_total)

</code>```

And it would be a better idea to return coin_total:

```<code>return coin_total
</code>```

And use it like this in main:

```<code>coin_tokens = choose_coins()
total = add_coins(coin_tokens)
print(f"Total is {total}")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are multiple problems with your code.
The syntax to call a function is as follows:

return_value = function_name(arguments)

You are calling choose_coins() but not storing the return value:

def main():

    coin_tokens = choose_coins()
    add_coins(coin_tokens)

Or even:

 add_coins(choose_coins())

When you write:

return[coin_tokens]

It is wrapping your coin_tokens which is already a list into another list. Change it to:

return coin_tokens

You do not need this line; it has no effect:

coin_tokens.split()
print(coin_tokens)

You should use token instead of i in the for loop. And have not initialized coin_total to 0 before the loop:

def add_coins(coin_tokens):

    print(coin_tokens)
    # Initialize to 0
    coin_total = 0

    #Iterate through coin_tokens list
    for token in coin_tokens:
        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

    print(coin_total)

And it would be a better idea to return coin_total:

return coin_total

And use it like this in main:

coin_tokens = choose_coins()
total = add_coins(coin_tokens)
print(f"Total is {total}")


问:
OpenCypher - Get all nodes that not connect to the center of the graph
I have a graph on Neptune and I used OpenCypher to query on it.

At the middle of the graph I have a big connected nodes,
at the edges you can see that I have some single nodes/ nodes that connected only to 1-5 other nodes. (see on the picture)

I want to get all of them, there is an option to do so?

I tried to think about options like take a random Id from the center and check all the nodes that don't have a path from them to this node, or maybe say get a table with all nodes and number of connected nodes to them, and ask for all nodes that not contain more than 10 nodes connected

but I didn't find a way to write this query,
Must to know that opencypher on Neptune not contains all the magic keys like 'all' predicate function, so need to find a way with the functions that neptune support

答: Ideally, you would want to run Weakly Connected Components algorithm to identify the largest component and then return all nodes that are not part of it. It seems that Neptune doesn't support that algorithm out-of-the-box, but you could implement it with gremlin as discussed in another SO question: Find largest connected components AWS Neptune</p>


问:
Where to find the default Winforms icon in Windows?
I assume this is a shared resource somewhere in Windows. Rather than making a copy for each app, is there a way to use this icon just like all Winforms apps use it?

How is this specified for Winforms apps by default? I don't see any reference of any icons in code or project settings. Just that it uses the "default icon".

答:
I had a problem which was similar, but different.  Rather than needing to get the default icon, I needed to check to see whether the icon on a form was set or if it was left as the default.  While I could have used reflection to get it, I ended up using a simpler solution:</p>
```<code>private static Icon defaultIcon = new Form().Icon;

// ...

if(this.Icon == defaultIcon)
{
    // ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I had a problem which was similar, but different.  Rather than needing to get the default icon, I needed to check to see whether the icon on a form was set or if it was left as the default.  While I could have used reflection to get it, I ended up using a simpler solution:

private static Icon defaultIcon = new Form().Icon;

// ...

if(this.Icon == defaultIcon)
{
    // ...
}


问:
How to hide change a field with PHP
My apologies for not knowing how to do this, but it seems like it should be simple.  I am trying to use PHP to hide certain events on a calendar that are being imported with an incorrect timestamp (2:00 AM should be All Day).

This is what I'm trying to use, but it is not working.

Any help would be greatly appreciated.

```<code><?php
$t = field_event_date;

if ($t ="2:00 AM") {
  echo "All Day";
}
?>
</code>```

答:
```<code>if ($t == "2:00 AM") {
  echo "All Day";
}
</code>```

you have an error in if condition

Title: How to hide change a field with PHP

Body:
My apologies for not knowing how to do this, but it seems like it should be simple.  I am trying to use PHP to hide certain events on a calendar that are being imported with an incorrect timestamp (2:00 AM should be All Day).

This is what I'm trying to use, but it is not working.

Any help would be greatly appreciated.

<?php
$t = field_event_date;

if ($t ="2:00 AM") {
  echo "All Day";
}
?>

Body:
if ($t == "2:00 AM") {
  echo "All Day";
}

you have an error in if condition


问:
Why can't I include my header file in another file?
Why I can't use my custom header file?
The IDE marks the include as unused. In C++ I have very mediocre knowledge. Perhaps I misunderstand something and incorrectly implement the .h and .cpp files.

There is a header file describing the structure of the mgportfolio.h class:

```<code>class LIBMGPORTFOLIO_EXPORT MgPortfolio : IComponent
    {
    public:
        MgPortfolio();
        explicit MgPortfolio();
        ~MgPortfolio();

        void accept(IVisitor& visitor) override;

    private:
        //std::string m_portfolioFilePath;
        //std::string m_portfolioName;
        //std::string m_owner;
    };
</code>```

Next, I want to implement a pattern "visitor" for some of my logic.
I add one more header file visitor.h:

```<code>#pragma once
#include "portfoliooption.h"
#include "playlistitem.h"
#include "archiveddata.h"
#include "mgportfolio.h" //Ide underlines this header file as unused. Although in the first visit() method I use the object from this file.

namespace mg
{
    class IVisitor
    {
    public:
        virtual ~IVisitor() = default;

        virtual void visit(MgPortfolio& portfolio) const; //here the ide suggests including #include "mgportfolio.h" but I already did that above.
        virtual void visit(PortfolioOption& portfolioOption) const; //here and below the header file is connected without problems
        virtual void visit(PlaylistItem& playlistItem) const;
        virtual void visit(ArchivedData& archivedData) const;
    };

    class IComponent
    {
    public:
        virtual ~IComponent() = default;
        virtual void accept(IVisitor& visitor) = 0;
    };
}
</code>```

The PortfolioOption, PlaylistItem, ArchivedData classes differ from MgPortfolio only in that they do not have an implementation in .cpp files. As soon as I add the implementation, the same error appears as with MgPortfolio.What could be my problem?

答:
Why can't I include my header file in another file?

You can include a file in another.

The IDE marks the include as unused.

The tool seems to be warning you that you are including a file unnecessarily. You should avoid doing that.

Although in the first visit() method I use the object from this file.

You don't need to include the definition of MgPortfolio to do that. A declaration is sufficient:

```<code>class MgPortfolio;
</code>```

the same error appears

"Is unused" is generally not an error, but a warning.

Body:
Why I can't use my custom header file?
The IDE marks the include as unused. In C++ I have very mediocre knowledge. Perhaps I misunderstand something and incorrectly implement the .h and .cpp files.

There is a header file describing the structure of the mgportfolio.h class:

class LIBMGPORTFOLIO_EXPORT MgPortfolio : IComponent
    {
    public:
        MgPortfolio();
        explicit MgPortfolio();
        ~MgPortfolio();

        void accept(IVisitor& visitor) override;

    private:
        //std::string m_portfolioFilePath;
        //std::string m_portfolioName;
        //std::string m_owner;
    };

Next, I want to implement a pattern "visitor" for some of my logic.
I add one more header file visitor.h:

#pragma once
#include "portfoliooption.h"
#include "playlistitem.h"
#include "archiveddata.h"
#include "mgportfolio.h" //Ide underlines this header file as unused. Although in the first visit() method I use the object from this file.

namespace mg
{
    class IVisitor
    {
    public:
        virtual ~IVisitor() = default;

        virtual void visit(MgPortfolio& portfolio) const; //here the ide suggests including #include "mgportfolio.h" but I already did that above.
        virtual void visit(PortfolioOption& portfolioOption) const; //here and below the header file is connected without problems
        virtual void visit(PlaylistItem& playlistItem) const;
        virtual void visit(ArchivedData& archivedData) const;
    };

    class IComponent
    {
    public:
        virtual ~IComponent() = default;
        virtual void accept(IVisitor& visitor) = 0;
    };
}

The PortfolioOption, PlaylistItem, ArchivedData classes differ from MgPortfolio only in that they do not have an implementation in .cpp files. As soon as I add the implementation, the same error appears as with MgPortfolio.What could be my problem?

Body:
Why can't I include my header file in another file?

You can include a file in another.

The IDE marks the include as unused.

The tool seems to be warning you that you are including a file unnecessarily. You should avoid doing that.

Although in the first visit() method I use the object from this file.

You don't need to include the definition of MgPortfolio to do that. A declaration is sufficient:

class MgPortfolio;

the same error appears

"Is unused" is generally not an error, but a warning.


问:
Is there an equivalent to the .Net FileSystemWatcher in the Linux world?
I find the .Net FileSystemWatcher class really handy for writing utilities that automatically come to life when files show up in their watched folders. Is there any equivalent to this functionality in the *nix world that would allow me to watch a folder (and possibly all of its subdirectories)?

Edit: Preferably this will be something that doesn't require kernel patches.

答: If you're using the wonderful QT library (www.qtsoftware.com) it's included as the QFileSystemWatcher.</p>

OwnerDisplayName: Luke

LastEditorDisplayName: Luke

OwnerDisplayName: JMR


问:
MongoDB compass Error creating SSH tunnel: All configured authentication methods failed
I am trying to connect to my MongoDB. It worked the last time I connected which was a few months ago, but I think I am missing some auth. When I go to recents and press connect, it gives me this error:

```<code>Error creating SSH Tunnel: All configured authentication methods failed
</code>```

Here is my connection string (with some fields removed for privacy):

```<code>mongodb://[URL]:27017/[DBname]?readPreference=primary&authSource=admin&appname=MongoDB%20Compass%20Community&ssl=false
</code>```

If I try to make a new connection instead of using recents, it tells me "connection timed out" after about 5 seconds

答: Try with the ~/.ssh/id_rsa, and enter the passphrase you used at the time of creating your private key. Without the passphrase, you might get the error of no passphrase has been given.

Body:
I am trying to connect to my MongoDB. It worked the last time I connected which was a few months ago, but I think I am missing some auth. When I go to recents and press connect, it gives me this error:

Error creating SSH Tunnel: All configured authentication methods failed

Here is my connection string (with some fields removed for privacy):

mongodb://[URL]:27017/[DBname]?readPreference=primary&authSource=admin&appname=MongoDB%20Compass%20Community&ssl=false

If I try to make a new connection instead of using recents, it tells me "connection timed out" after about 5 seconds


问:
Return new instance of child class from parent class in JAVA
I have been working on ORM.wanted a feature where any child class which extends DbModel class will be able to use all the static methods within the parent class. However, most static methods return instance of Parent class.

 Is there any way whereby which child class will get an instance of itself from the methods?

 DbModel.java -> access the db

public class DbModel {

     public DbModel(String tableName)
     {
     }

    public static DbModel findById(String tableName , String id){
        //some logic ....
        return new DbModel(tableName);
    }

    public static DbModel findByValue(String tableName ,String value){
        //some logic ....
        return new DbModel(tableName);
    }

}
```
<p><code>Users</code> -> users class which contains users logic. Similarly, there will be many classes.</p>
<pre class="lang-java prettyprint-override"><code>public class Users extends DbModel {

    public Users() {
        super("users");
    }

    //some method
    public String getFullName(){
        //some logic
        return "fullname";
    }

}
</code>```

Test.java -> test class

public class Test {

    public static void main(String[] args) {

        //--> ERROR : DbModel cannot be cast to Users
        Users users = Users.findById("","");
        //what I want : Users.findById should return Users type not DbModel

    }

}
```

答:
You can add a param that lets you specify the type you want to be returned to bind the generics, then just invoke the appropriate constructor of that type.

public class DbModel {

    public DbModel(String tableName) { ...}

    public static <T extends DbModel> T findById(
            String tableName, String id, Class<T> type
    ) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        //stuff

        return type.getConstructor(String.class).newInstance(tableName);
    }

}
```

The amount of checked exceptions here should tell you that this is not the safest or most maintainable way to code this. You should look into using the https://en.wikipedia.org/wiki/Abstract_factory_pattern instead.

Body:
I have been working on ORM.wanted a feature where any child class which extends DbModel class will be able to use all the static methods within the parent class. However, most static methods return instance of Parent class.

 Is there any way whereby which child class will get an instance of itself from the methods?

 DbModel.java -> access the db

public class DbModel {

     public DbModel(String tableName)
     {
     }

    public static DbModel findById(String tableName , String id){
        //some logic ....
        return new DbModel(tableName);
    }

    public static DbModel findByValue(String tableName ,String value){
        //some logic ....
        return new DbModel(tableName);
    }

}

Users -> users class which contains users logic. Similarly, there will be many classes.

public class Users extends DbModel {

    public Users() {
        super("users");
    }

    //some method
    public String getFullName(){
        //some logic
        return "fullname";
    }

}

Test.java -> test class

public class Test {

    public static void main(String[] args) {

        //--> ERROR : DbModel cannot be cast to Users
        Users users = Users.findById("","");
        //what I want : Users.findById should return Users type not DbModel

    }

}

Body:
You can add a param that lets you specify the type you want to be returned to bind the generics, then just invoke the appropriate constructor of that type.

public class DbModel {

    public DbModel(String tableName) { ...}

    public static <T extends DbModel> T findById(
            String tableName, String id, Class<T> type
    ) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

        //stuff

        return type.getConstructor(String.class).newInstance(tableName);
    }

}

The amount of checked exceptions here should tell you that this is not the safest or most maintainable way to code this. You should look into using the https://en.wikipedia.org/wiki/Abstract_factory_pattern instead.


问:
Can we create an object in Java with out class like in js or python with random key and values
Like in other programing languages - python or JS, when we create a rest api specifically post for the request body we attract some JSON Object

EX:

url: .../employee (Post)

request body: {option: {filter: "suman"}}

In Python or JS we can just do request_body.option.filter and get the data

How can I achieve the same with Java ?
Do I need need to create a class for the reqeust_body and for option and make an instance object request_body

答: This depends with other framework elements you use in your application. For example if you bring Spring into the scene, you would be looking to use in built features like dependency injection and support for hibernate (JPA implementation), which depends on the concept of entities that are POJOs with extra annotations. So yes you would need to define entity classes and DTOs for those.</p>


问:
ORA-65175: cannot grant SYSDBA privilege locally in the root
I have a oracle 12c database .
I would like to grant sysdba to C##user1.
Here is user table.

When I execute this command I can get a error.

```<code>grant sysdba to c##user1 container=current

Error report -
SQL Error: ORA-65175: cannot grant SYSDBA privilege locally in the root
65175. 00000 -  "cannot grant SYSDBA privilege locally in the root"
*Cause:    An attempt was made to grant SYSDBA privilege locally in the root
           of a multitenant container database (CDB).
*Action:   While connected to the root, SYSDBA privilege can only be granted
           commonly.
</code>```

and when I execute this command , I can get 2 users of C##user1.

```<code>grant sysdba to c##user1 container=all
</code>```

How can I grant sysdba to C##user1.
Thank you for viewing.
Pls help me.

答:
under cdb connection try it</p>
```<code>grant sysdba to c##user1 container=all
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a oracle 12c database .
I would like to grant sysdba to C##user1.
Here is user table.

When I execute this command I can get a error.

grant sysdba to c##user1 container=current

Error report -
SQL Error: ORA-65175: cannot grant SYSDBA privilege locally in the root
65175. 00000 -  "cannot grant SYSDBA privilege locally in the root"
*Cause:    An attempt was made to grant SYSDBA privilege locally in the root
           of a multitenant container database (CDB).
*Action:   While connected to the root, SYSDBA privilege can only be granted
           commonly.

and when I execute this command , I can get 2 users of C##user1.

grant sysdba to c##user1 container=all

How can I grant sysdba to C##user1.
Thank you for viewing.
Pls help me.

Body:
under cdb connection try it

grant sysdba to c##user1 container=all


问:
Can you explain what the arguments to GeneratedBy.HiLo(...) do?
There are a few overloads:

```<code>GeneratedBy.HiLo(string maxLo);
GeneratedBy.HiLo(string maxLo, Action<ParamBuilder> paramValues);
GeneratedBy.HiLo(string table, string column, string maxLo);
GeneratedBy.HiLo(string table, string column, string maxLo, string where);
GeneratedBy.HiLo(string table, string column, string maxLo, Action<ParamBuilder> paramValues);
</code>```

I understand conceptually what the hi/lo algorithm does.  But what do these parameters do?  I can't find the documentation in Hibernate on what they actually do.

Is maxLo supposed to be a name, or a number?  What are the paramValues?  What are the purposes of table and column?

Example usage based on the NHibernate getting started tutorial:

```<code>public class StoreMap : ClassMap<Store>
{
    public StoreMap()
    {
        Id(x => x.Id).GeneratedBy.HiLo("something");
        Map(x => x.Name);
        HasMany(x => x.Staff)
            .Inverse()
            .Cascade.All();
        HasManyToMany(x => x.Products)
            .Cascade.All()
            .Table("StoreProduct");
    }
}
</code>```

答:
maxLo is the Lo-value of the HiLo.

Depending on the frequency of inserts into the table you should specify the value as 10, 100, or 1000. If you specify the value as 10, NHibernate will grab the Hi value from the database and use the low value to generate your HiLo.

If you insert often then you should specify a high Lo (such as 100 or 1000), if you insert less often then you should specify a low Lo. This is because a new Hi value is pulled from the database every time the session factory is created. If you have a current Hi of 5 with a Lo of 100, and have inserted 13 of 100 items, and you create a new Session Factory (from restarting the website, or app) then it will get a new Hi of 6, and you will have gaps from 513 to 600

So if your Hi is currently 3, then it will generate values from 31 to 40. Likewise if your Lo is 1000, it will generates values from 3001 to 4000.

The additional parameters allow you to specify a table where the Hi value is stored. By default NHibernate will generate this table for you if it's configured to create/update the database, however the parameters allow you to setup the tables yourself.

I wrote a blog post a while ago which shows Column per Hi, and Row per Hi.

http://www.philliphaydon.com/2010/10/24/using-hilo-with-fluentnhibernate/

Edit: Behaviour of a Lo such as 7

HiLo is calculated as a range of numbers, for example if we have a Hi of 3, and a Lo of 10, the range is between:

3*10 = 30 to 3*10+10 = 40

So the session factory will have a range of 30 to 40, when you ask for an Id for an object it grabs it's current value (30) and add's 1. So the Id = 31. The next object will take 31+1 = 32. And this occurs until it reaches 40, at which point it goes to the database and asks for the next Hi.

If you had two web servers, the second Web Server may have asked for the next Hi which was 4, which means the first Web Server will get 5.

So your next range is 50 to 60.

If the Lo was 7, we would get:

0*7 = 0 / 0*7+7 = 7 = 1-7

1*7 = 7 / 1*7+7 = 14 = 8-14

2*7 = 14 / 2*7+7 = 21 = 15-21

So it still works.

But my personal opinion is it's easier to work with whole values, 10, 100, 1000.

Body:
There are a few overloads:

GeneratedBy.HiLo(string maxLo);
GeneratedBy.HiLo(string maxLo, Action<ParamBuilder> paramValues);
GeneratedBy.HiLo(string table, string column, string maxLo);
GeneratedBy.HiLo(string table, string column, string maxLo, string where);
GeneratedBy.HiLo(string table, string column, string maxLo, Action<ParamBuilder> paramValues);

I understand conceptually what the hi/lo algorithm does.  But what do these parameters do?  I can't find the documentation in Hibernate on what they actually do.

Is maxLo supposed to be a name, or a number?  What are the paramValues?  What are the purposes of table and column?

Example usage based on the NHibernate getting started tutorial:

public class StoreMap : ClassMap<Store>
{
    public StoreMap()
    {
        Id(x => x.Id).GeneratedBy.HiLo("something");
        Map(x => x.Name);
        HasMany(x => x.Staff)
            .Inverse()
            .Cascade.All();
        HasManyToMany(x => x.Products)
            .Cascade.All()
            .Table("StoreProduct");
    }
}


问:
Vue3 prop updates title attribute but not computed prop
I'm using an external library rendered using Vue3. It has the following component from a third part library [Edit: I realize the GitHub repo for that library is out of date, so updating with the actual code in my node_modules.]

```<code><template>
  <div class="socket" :class="className" :title="socket.name"></div>
</template>

<script>
import { defineComponent, computed } from "vue";
import { kebab } from "./utils";
export default defineComponent({
  props: ["type", "socket"],
  setup(props) {
    const className = computed(() => {
      return kebab([props.type, props.socket.name]);
    });
    return {
      className
    };
  }
});
</script>
</code>```

It renders based on a Socket object passed as a prop. When I updated the name property of the Socket, I see the title updated accordingly. However, the CSS/class does not update. I've tried $forceRefresh() on its parent, but this changes nothing.

Update: I was able to move the rendering code to my own repo, so I can now edit this component if needed.

Based on this updated code, it seems the issue is that the class is computed. Is there any way to force this to refresh?

The only time it does is when I reload the code (without refreshing the page) during vue-cli-service serve.

For reference, the | kebab filter is defined here:

```<code>Vue.filter('kebab', (str) => {
    const replace = s =>  s.toLowerCase().replace(/ /g, '-');

    return Array.isArray(str) ?  str.map(replace) : replace(str);
});
</code>```

Do filtered attributes update differently? I wouldn't think so.

I was also wondering if it could be a reactivity issue, and whether I needed to set the value using Vue.set, but as I understand it that's not necessary in Vue3, and it's also not consistent with the title properly updating.

答:
Computed properties are reactive, however Vue does not expect you to mutate a prop object.

From the documentation:

Warning

Note that objects and arrays in JavaScript are passed by reference, so
if the prop is an array or object, mutating the object or array itself
inside the child component will affect the parent state and Vue is
unable to warn you against this. As a general rule, you should avoid
mutating any prop, including objects and arrays as doing so ignores
one-way data binding and may cause undesired results.

https://v3.vuejs.org/guide/component-props.html#one-way-data-flow

I know that this says, that you should not mutate it in the child, but the general rule is, that you should not mutate properties at all, but instead create new object with the modified data.

In your case the computed function will look for changes in the properties itself, but not the members of the properties, that is why it is not updating.

Body:
I'm using an external library rendered using Vue3. It has the following component from a third part library [Edit: I realize the GitHub repo for that library is out of date, so updating with the actual code in my node_modules.]

<template>

</template>

It renders based on a Socket object passed as a prop. When I updated the name property of the Socket, I see the title updated accordingly. However, the CSS/class does not update. I've tried $forceRefresh() on its parent, but this changes nothing.

Update: I was able to move the rendering code to my own repo, so I can now edit this component if needed.

Based on this updated code, it seems the issue is that the class is computed. Is there any way to force this to refresh?

The only time it does is when I reload the code (without refreshing the page) during vue-cli-service serve.

For reference, the | kebab filter is defined here:

Vue.filter('kebab', (str) => {
    const replace = s =>  s.toLowerCase().replace(/ /g, '-');

    return Array.isArray(str) ?  str.map(replace) : replace(str);
});

Do filtered attributes update differently? I wouldn't think so.

I was also wondering if it could be a reactivity issue, and whether I needed to set the value using Vue.set, but as I understand it that's not necessary in Vue3, and it's also not consistent with the title properly updating.


问:
Dotenv issues/error with create-react-app react-scripts
I keep getting this error in my react app

```<code>    Compiled with problems: X

    ERROR in ./ node_modules / dotenv / lib / main.js 1: 11 - 24

    Module not found: Error: Can't resolve 'fs' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\lib'

    ERROR in ./ node_modules / dotenv / lib / main.js 3: 13 - 28

    Module not found: Error: Can't resolve 'path' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\lib'

    BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
    This is no longer the case. Verify if you need this module and configure a polyfill for it.

    If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
        - install 'path-browserify'
    If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "path": false }

    ERROR in ./ node_modules / dotenv / lib / main.js 5: 11 - 24

    Module not found: Error: Can't resolve 'os' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\lib'

    BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
    This is no longer the case. Verify if you need this module and configure a polyfill for it.

    If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
        - install 'os-browserify'
    If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "os": false }
</code>```

I after tried following the instruction provided by creating webpack.config.js and adding the fallback as show below

```<code>module.exports = {
    resolve: {
        fallback: { "path": require.resolve("path-browserify")  },
    },
}
</code>```

There is no difference. I checked a similar issue on their github page and couldn't find a working fix(most were comments emphasizing the problem that didn't even point to a reasonable working solution)

答:
Thanks to @user3133, i was able to understand the real issue. It seems dotenv should only be used in backend application like nodejs and not frontend apps like react.

When the error came up, it didn't point to where the error originated from, so I was basically "lost in the blizzard". I was able to figure out that the error came from referencing dotenv in the src directory which is the domain of react which overseas all of your react code.

So basically I was able to fix the issue by removing all lines of code that referenced dotenv in the src dir eg:

```<code>require('dotenv').config();
</code>```

Note that it is okay to put it anywhere else outside the src directory.

Fun fact: react has it's own dotenv, which you can access by just putting REACT_APP_ in front of your env variable.

Read more here: Is it possible to use dotenv in a react project?

Body:
I keep getting this error in my react app

    Compiled with problems: X

    ERROR in ./ node_modules / dotenv / lib / main.js 1: 11 - 24

    Module not found: Error: Can't resolve 'fs' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\lib'

    ERROR in ./ node_modules / dotenv / lib / main.js 3: 13 - 28

    Module not found: Error: Can't resolve 'path' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\lib'

    BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
    This is no longer the case. Verify if you need this module and configure a polyfill for it.

    If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
        - install 'path-browserify'
    If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "path": false }

    ERROR in ./ node_modules / dotenv / lib / main.js 5: 11 - 24

    Module not found: Error: Can't resolve 'os' in 'C: \Users\USER\Desktop\dapps\nefty\node_modules\dotenv\lib'

    BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
    This is no longer the case. Verify if you need this module and configure a polyfill for it.

    If you want to include a polyfill, you need to:
    - add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
        - install 'os-browserify'
    If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "os": false }

I after tried following the instruction provided by creating webpack.config.js and adding the fallback as show below

module.exports = {
    resolve: {
        fallback: { "path": require.resolve("path-browserify")  },
    },
}

There is no difference. I checked a similar issue on their github page and couldn't find a working fix(most were comments emphasizing the problem that didn't even point to a reasonable working solution)

Body:
Thanks to @user3133, i was able to understand the real issue. It seems dotenv should only be used in backend application like nodejs and not frontend apps like react.

When the error came up, it didn't point to where the error originated from, so I was basically "lost in the blizzard". I was able to figure out that the error came from referencing dotenv in the src directory which is the domain of react which overseas all of your react code.

So basically I was able to fix the issue by removing all lines of code that referenced dotenv in the src dir eg:

require('dotenv').config();

Note that it is okay to put it anywhere else outside the src directory.

Fun fact: react has it's own dotenv, which you can access by just putting REACT_APP_ in front of your env variable.

Read more here: Is it possible to use dotenv in a react project?


问:
Responsive iframe with fixed height
I'm trying to make an iframe with responsive width (filling a div) but fixed height (overflow hidden by div). But when I scale the page the video also scales down. I want the iframe to keep 100% height.

Does anyone know what I'm doing wrong here? I've tried not setting the iframes height, og setting it to auto, but it doesn't work.

HTML:

```<code><div class="container">
<div class="video-wrapper">
<iframe class="video" src="https://player.vimeo.com/video/82481183?background=1" frameborder="0" allow="autoplay" ></iframe>
</div>
</div>
</code>```

CSS:

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}
```

https://codepen.io/marteteigen/pen/NWwdGXd

Any help is much appreciated!

答:
Instead of iframe using video HTML tag will solve work.

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="video-wrapper">
<!--     <iframe class="video" src="https://player.vimeo.com/video/82481183?background=1"     frameborder="0" allow="autoplay" ></iframe> -->
    <video class="video" controls>
  <source src="https://player.vimeo.com/video/82481183?background=1" type="video/mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
    </div>
</div></code>```

Let me know if it works for you . CODEPEN

Title: Responsive iframe with fixed height

Body:
I'm trying to make an iframe with responsive width (filling a div) but fixed height (overflow hidden by div). But when I scale the page the video also scales down. I want the iframe to keep 100% height.

Does anyone know what I'm doing wrong here? I've tried not setting the iframes height, og setting it to auto, but it doesn't work.

HTML:

CSS:

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}

https://codepen.io/marteteigen/pen/NWwdGXd

Any help is much appreciated!

Body:
Instead of iframe using video HTML tag will solve work.

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}

<div class="container">
  <div class="video-wrapper">
<!--     <iframe class="video" src="https://player.vimeo.com/video/82481183?background=1"     frameborder="0" allow="autoplay" ></iframe> -->
    <video class="video" controls>
  <source src="https://player.vimeo.com/video/82481183?background=1" type="video/mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
    </div>
</div>

Let me know if it works for you . CODEPEN


问:
Unsupported Chrome Driver
It seems that every time chrome has a new version, I get stuck with this error when running pipeline

```<code>System.InvalidOperationException : session not created: This version of ChromeDriver only supports Chrome version 98

Current browser version is 97.0.4692.99 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe (SessionNotCreated)
</code>```

I've tried install webdriver-manager, it shows the right version, but the problem keeps on. When running locally it all works.

What am I missing here?

答:
You need to upgrade chrome in your release environment to the latest version, 98.0.

If you are running on a windows VM, for example, that means you need to:

RDP on to the server

load Chrome

view the About Chrome page (chrome://settings/help)

let it upgrade to the newer version

relaunch chrome

Title: Unsupported Chrome Driver

Body:
It seems that every time chrome has a new version, I get stuck with this error when running pipeline

System.InvalidOperationException : session not created: This version of ChromeDriver only supports Chrome version 98

Current browser version is 97.0.4692.99 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe (SessionNotCreated)

I've tried install webdriver-manager, it shows the right version, but the problem keeps on. When running locally it all works.

What am I missing here?


问:
SQL query execution fails
I am trying to execute query and it doesnt work.

```<code>SELECT id,
       idOperacije,
       idRadniNalog,
       sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9
AND idOperacije = 105
AND total > 2000
GROUP BY idOperacije
</code>```

Error I get is:

Unknown column 'total' in 'where clause' Even if I use sum(kolicina)
in where statement I get same issue.

I need to sum(kolicina) for idRadniNalog and idOperacije and display only items where sum is higer than 2000

答:
I am also getting the same problem when I use the alias name with any Column...
Just try this code this time it will work.</p>
```<code>SELECT id,
       idOperacije,
       idRadniNalog,
       sum(kolicina)
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9
and idOperacije = 105
and sum(kolicina) > 2000
group by idOperacije
</code>```

Title: SQL query execution fails

Body:
I am trying to execute query and it doesnt work.

SELECT id,
       idOperacije,
       idRadniNalog,
       sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9
AND idOperacije = 105
AND total > 2000
GROUP BY idOperacije

Error I get is:

Unknown column 'total' in 'where clause' Even if I use sum(kolicina)
in where statement I get same issue.

I need to sum(kolicina) for idRadniNalog and idOperacije and display only items where sum is higer than 2000

Body:
I am also getting the same problem when I use the alias name with any Column...
Just try this code this time it will work.

SELECT id,
       idOperacije,
       idRadniNalog,
       sum(kolicina)
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9
and idOperacije = 105
and sum(kolicina) > 2000
group by idOperacije


问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
So just to build on the other answers with an example, short-circuiting is crucial in the following defensive checks:

```<code>if (foo == null || foo.isClosed()) {
    return;
}

if (bar != null && bar.isBlue()) {
    foo.doSomething();
}
</code>```

Using | and & instead could result in a NullPointerException being thrown here.

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

Body:
So just to build on the other answers with an example, short-circuiting is crucial in the following defensive checks:

if (foo == null || foo.isClosed()) {
    return;
}

if (bar != null && bar.isBlue()) {
    foo.doSomething();
}

Using | and & instead could result in a NullPointerException being thrown here.


问:
How to center text in ZPL language?
I have the following code which I print a label with the information of a product. But I have the problem that the product name is not centered. It happens to me that if the name is very long, it goes outside the limits of the label and does not appear. What I want is for the name to start from the center and expand along the label and if it exceeds the limits to continue writing on the next line.

I would appreciate any help

```<code>    ^XA
   ^CF0,30
  ^FO150,30^FDNombre del Producto^FS
  ^CF0,60
  ^FO200,90^FDPrecio^FS
 ^FX Third section with bar code.
  ^BY2,2,50
  ^FO170,180^BC^FD1234789^FS
 ^XZ
</code>```

答:
NOTE: This only works if you are using dots as the unit of measurements (this is the default but specified as ^MUd in the example below). If mm is used (^MUm) the center-thingy does NOT work properly (tested on labelary.com and Zebra S4m).

Use ^FB to define a Field Block. From the manual:

The ^FB command allows you to print text into a defined block type
format. This command formats an ^FD or ^SN string into a block of text
using the origin, font, and rotation specified for the text string.
The ^FB command also contains an automatic word-wrap function.

You could view this example at labelary.com or tryit out yourself:

```<code>^XA
^MUd
^LH10,10
^CF0,50
^GB500,500,10^FS
^FO0,50  ^FDNormal^FS
^FO0,150 ^FB500,,,L ^FDLeft^FS
^FO0,250 ^FB500,,,C ^FDCenter^FS
^FO0,350 ^FB500,,,R ^FDRight^FS
^XZ
</code>```

Title: How to center text in ZPL language?

Body:
I have the following code which I print a label with the information of a product. But I have the problem that the product name is not centered. It happens to me that if the name is very long, it goes outside the limits of the label and does not appear. What I want is for the name to start from the center and expand along the label and if it exceeds the limits to continue writing on the next line.

I would appreciate any help

    ^XA
   ^CF0,30
  ^FO150,30^FDNombre del Producto^FS
  ^CF0,60
  ^FO200,90^FDPrecio^FS
 ^FX Third section with bar code.
  ^BY2,2,50
  ^FO170,180^BC^FD1234789^FS
 ^XZ

Body:
NOTE: This only works if you are using dots as the unit of measurements (this is the default but specified as ^MUd in the example below). If mm is used (^MUm) the center-thingy does NOT work properly (tested on labelary.com and Zebra S4m).

Use ^FB to define a Field Block. From the manual:

The ^FB command allows you to print text into a defined block type
format. This command formats an ^FD or ^SN string into a block of text
using the origin, font, and rotation specified for the text string.
The ^FB command also contains an automatic word-wrap function.

You could view this example at labelary.com or tryit out yourself:

^XA
^MUd
^LH10,10
^CF0,50
^GB500,500,10^FS
^FO0,50  ^FDNormal^FS
^FO0,150 ^FB500,,,L ^FDLeft^FS
^FO0,250 ^FB500,,,C ^FDCenter^FS
^FO0,350 ^FB500,,,R ^FDRight^FS
^XZ


问:
PyCharm changes keyboard layout for shortcuts under Manjaro
i am using PyCharm under Manjaro Linux.
I have two languge bindings, german and english (which i use for coding and work). If i want to execute a short cut in PyCharm (e.g. ctrl+z for undo), it executes ctrl+y, so PyCharm switches to the german layout even though it stays in the english layout for the normal coding part. If i press y in the editor, a y is inserted.
How do i circumvent that, so that i can press ctrl+z and it executes undo.

答:
Hey for me changing the order of the keyboard layouts solved the issue. Previously it was German -> English and I swapped the order to English -> German and now it works fine. Not sure if this is works for Manjaro as well.

To change the order go to "Region & Language" in the settings and then change it with drag and drop.

Source of my solution


问:
How do I check if there is a variable inside a 2d list?
I am trying to make code that asks what movie you would like to know about and gives you the movie + the director + a rating.

```<code>movieDirectorRatingList = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P.","Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieSelection = input("What movie would you like to know about?")

if movieSelection in movieDirectorRatingList:
    movieLocation = movieDirectorRatingList.count(movieSelection) - 1
    print(f"{movieSelection} directed by {movieDirectorRatingList[movieLocation][2]}{movieDirectorRatingList[movieLocation][3]}" )

elif movieSelection not in movieDirectorRatingList:
    print("Movie not in list")

else:
    print("An unexpected error has occured")
</code>```

I managed to have it working when I used 1-dimensional lists, but when I use 2 dimensional ones it says the Movie isn't in the list. Thank you in advance for any help.

答:
I used your code and reformatted it and made this. It does what I believe you want, but slightly simpler.

```<code>mdrl = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P. and Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieChoice = input("Which movie would you like to get data from?: ")

for i in range(len(mdrl)):
    if mdrl[i][0] == movieChoice:
        print(mdrl[i][0], "Was directed by", mdrl[i][1], "and had a rating of ", mdrl[i][2])
</code>```

P.S. I changed a piece of data from your "waterloo" data due to their being two directors being in two different sections in the array.

Body:
I am trying to make code that asks what movie you would like to know about and gives you the movie + the director + a rating.

movieDirectorRatingList = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P.","Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieSelection = input("What movie would you like to know about?")

if movieSelection in movieDirectorRatingList:
    movieLocation = movieDirectorRatingList.count(movieSelection) - 1
    print(f"{movieSelection} directed by {movieDirectorRatingList[movieLocation][2]}{movieDirectorRatingList[movieLocation][3]}" )

elif movieSelection not in movieDirectorRatingList:
    print("Movie not in list")

else:
    print("An unexpected error has occured")

I managed to have it working when I used 1-dimensional lists, but when I use 2 dimensional ones it says the Movie isn't in the list. Thank you in advance for any help.

Body:
I used your code and reformatted it and made this. It does what I believe you want, but slightly simpler.

mdrl = [
    ["Munich: The Edge of War", "Christian Schwochow", "4.1"],
    ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", "4.8"],
    ["Tombstone", "Cosmatos and Kevin Jarre", "4.1"],
    ["Waterloo", "George P. and Sergei Bondarchuk", "4.0"],
    ["Iron Man", "Jon Favreau", "4.9"]
]

movieChoice = input("Which movie would you like to get data from?: ")

for i in range(len(mdrl)):
    if mdrl[i][0] == movieChoice:
        print(mdrl[i][0], "Was directed by", mdrl[i][1], "and had a rating of ", mdrl[i][2])

P.S. I changed a piece of data from your "waterloo" data due to their being two directors being in two different sections in the array.


问:
Identifying maximum value in a row, from multiple columns, with an output including all columns in the dataset?
I have a fairly large dataset, and I need to determine the maximum value of each row, from several columns. So in the below sample data, for "II" what the highest value is, and if the highest value is in "N" or "P". I know very similar questions to this have been posted previously, however I need the output to not remove the other metadata columns in my dataset. This also means I need to specify the range of columns which should be included in the "max" query.
Thanks in advance for any guidance with this.

```<code>data<-data_frame(Exp = c("I", "II", "III", "IV", "V", "VI", "VII", "VIII"),
                  N = c(8.77, 1.67, 7.47, 7.58, 1.1, 8.9, 7.5, 7.7),
                  P = c(1.848, 3.029, 1.925, 2.725, 1.900, 3.100,
                                    2.000, 9.800))
</code>```

I have tried several variations of the below code

```<code>test %>%
  mutate(Max = pmax(!!! rlang::syms(names(.)[c("N", "P"),]))) %>%
  group_by(data, Exp) %>%
  summarise(Max = max(Max))

</code>```

and receive the error:
Error in UseMethod("mutate_") :
  no applicable method for 'mutate_' applied to an object of class "function"

This is my first question asked on here, so apologies for any incorrect formatting etc, any advice on this (and my question) would be much appreciated.

答:
Looking to solve the same problem I found a different solution, that is  clearer to me.

cur_data returns the current working group.

rowwise can have columns specified which work like groups while using summarise.

ungroup is needed to revert to the default column-wise format.

The summarise method drops the non-grouping variables.

```<code># using names
v = c('N', 'P')
data %>% rowwise %>% mutate(m=max(cur_data()[v])) %>% ungroup

# using ranges
start = 8
end = 25
data %>% rowwise %>% mutate(m=max(cur_data()[start:end])) %>% ungroup

# using summarize
data %>% rowwise(Exp) %>% summarize(m=max(cur_data()))
</code>```

Body:
I have a fairly large dataset, and I need to determine the maximum value of each row, from several columns. So in the below sample data, for "II" what the highest value is, and if the highest value is in "N" or "P". I know very similar questions to this have been posted previously, however I need the output to not remove the other metadata columns in my dataset. This also means I need to specify the range of columns which should be included in the "max" query.
Thanks in advance for any guidance with this.

data<-data_frame(Exp = c("I", "II", "III", "IV", "V", "VI", "VII", "VIII"),
                  N = c(8.77, 1.67, 7.47, 7.58, 1.1, 8.9, 7.5, 7.7),
                  P = c(1.848, 3.029, 1.925, 2.725, 1.900, 3.100,
                                    2.000, 9.800))

I have tried several variations of the below code

test %>%
  mutate(Max = pmax(!!! rlang::syms(names(.)[c("N", "P"),]))) %>%
  group_by(data, Exp) %>%
  summarise(Max = max(Max))

and receive the error:
Error in UseMethod("mutate_") :
  no applicable method for 'mutate_' applied to an object of class "function"

This is my first question asked on here, so apologies for any incorrect formatting etc, any advice on this (and my question) would be much appreciated.

Body:
Looking to solve the same problem I found a different solution, that is  clearer to me.

cur_data returns the current working group.

rowwise can have columns specified which work like groups while using summarise.

ungroup is needed to revert to the default column-wise format.

The summarise method drops the non-grouping variables.

# using names
v = c('N', 'P')
data %>% rowwise %>% mutate(m=max(cur_data()[v])) %>% ungroup

# using ranges
start = 8
end = 25
data %>% rowwise %>% mutate(m=max(cur_data()[start:end])) %>% ungroup

# using summarize
data %>% rowwise(Exp) %>% summarize(m=max(cur_data()))


问:
How can I return the primitive data type from polymorphism?
Given some custom sum data type,

```<code>data Type = Thing Char | NotThing Char
</code>```

How can I use == to compare between the Char here and some other Char? As below:

```<code>let f = 'a'
NotThing e == f
>>> True
</code>```

Of course, this code cannot compare between types as NotThing is a separate type to Char.

答:
If x :: Char and y :: Type, then the following expressions (among others) are well-typed:

```<code>y == Thing x
y == NotThing x
y `elem` [Thing x, NotThing x]
case y of { Thing x' -> x == x'; NotThing x' -> x == x' }
</code>```

Probably the last one is closest to what you want. I would abstract slightly and write

```<code>extract :: Type -> Char
extract (Thing x') = x'
extract (NotThing x') = x'
</code>```

because I would expect that to occasionally be useful in other contexts. With that in hand, the following expression is also well-typed:

```<code>extract y == x
</code>```

Of course, you'll want to pick a better name than extract, just like you'll do for Type, Thing, and NotThing.

Body:
Given some custom sum data type,

data Type = Thing Char | NotThing Char

How can I use == to compare between the Char here and some other Char? As below:

let f = 'a'
NotThing e == f
>>> True

Of course, this code cannot compare between types as NotThing is a separate type to Char.

Body:
If x :: Char and y :: Type, then the following expressions (among others) are well-typed:

y == Thing x
y == NotThing x
y `elem` [Thing x, NotThing x]
case y of { Thing x' -> x == x'; NotThing x' -> x == x' }

Probably the last one is closest to what you want. I would abstract slightly and write

extract :: Type -> Char
extract (Thing x') = x'
extract (NotThing x') = x'

because I would expect that to occasionally be useful in other contexts. With that in hand, the following expression is also well-typed:

extract y == x

Of course, you'll want to pick a better name than extract, just like you'll do for Type, Thing, and NotThing.


问:
PowerShell add a function to a custom object
I try to add an existing function as a method to a new created object.
Writing an inline function works:

```<code>$myObject | Add-Member ScriptMethod -name Calc -value{param([int]$a,[int]$b;$a+$b}
</code>```

Having a function:

```<code>function get-Calc{param([int]$a,[int]$b) $a +$b}
</code>```

this doesn't work:

```<code>$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)
</code>```

答:
You could also do it passing a script block as -Value, see the Constructor for PSScriptMethod Class.

```<code>function Get-Calc { param([int] $a, [int] $b) $a + $b }

$myObject = [pscustomobject]@{
    A = 1
    B = 2
}

# If you're referencing the existing Properties of the Object:
$myObject | Add-Member ScriptMethod -Name MyMethod1 -Value {
    Get-Calc $this.A $this.B
}

# If you want the Instance Method to reference the arguments being passed:
$myObject | Add-Member ScriptMethod -Name MyMethod2 -Value {
    param([int] $a, [int] $b)

    Get-Calc $a $b
}

# This is another alternative as the one above:
$myObject.PSObject.Methods.Add(
    [psscriptmethod]::new(
        'MyMethod3', {
            param([int] $a, [int] $b)

            Get-Calc $a $b
        }
    )
)

$myObject.MyMethod1()
$myObject.MyMethod2(1, 2)
$myObject.MyMethod3(3, 4)
</code>```

Note: All examples in this answer require that the function Get-Calc is defined in the parent scope and will fail as soon as the definition for the function has changed. Instead you should pass in the definition as a Script Block as Mathias's helpful answer is showing.

Body:
I try to add an existing function as a method to a new created object.
Writing an inline function works:

$myObject | Add-Member ScriptMethod -name Calc -value{param([int]$a,[int]$b;$a+$b}

Having a function:

function get-Calc{param([int]$a,[int]$b) $a +$b}

this doesn't work:

$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)

Body:
You could also do it passing a script block as -Value, see the Constructor for PSScriptMethod Class.

function Get-Calc { param([int] $a, [int] $b) $a + $b }

$myObject = [pscustomobject]@{
    A = 1
    B = 2
}

# If you're referencing the existing Properties of the Object:
$myObject | Add-Member ScriptMethod -Name MyMethod1 -Value {
    Get-Calc $this.A $this.B
}

# If you want the Instance Method to reference the arguments being passed:
$myObject | Add-Member ScriptMethod -Name MyMethod2 -Value {
    param([int] $a, [int] $b)

    Get-Calc $a $b
}

# This is another alternative as the one above:
$myObject.PSObject.Methods.Add(
    [psscriptmethod]::new(
        'MyMethod3', {
            param([int] $a, [int] $b)

            Get-Calc $a $b
        }
    )
)

$myObject.MyMethod1()
$myObject.MyMethod2(1, 2)
$myObject.MyMethod3(3, 4)

Note: All examples in this answer require that the function Get-Calc is defined in the parent scope and will fail as soon as the definition for the function has changed. Instead you should pass in the definition as a Script Block as Mathias's helpful answer is showing.


问:
Breaking up a large ggplot by category; subset shows no errors but plots no data
I have a very large dataset derived from a spreadsheet of the format below:

```<code>df = data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
                issued = c(UKS, USD, UKS, UKS, USD, USD),
                mat = c(2024-01-31, 2023-01-31, 2026-10-22, 2022-07-22, 2029-01-31, 2025-06-07)
                volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417)
</code>```

Currently, I plot all the data on one very long ggplot with the following code:

```<code>chart1<-ggplot(df)+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
    labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
</code>```

Now while that worked for a while, given the size the dataset has grown to it is no longer feasible to use that way. Therefore I'd like to plot the data based on the contents of the "issued" column.

I first thought about a condition statement of the type:

```<code>if (df$issued == "UKS"){
chart1<-ggplot(df)+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
      theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
        labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
}
</code>```

It unfortunately didn't work (although on closer inspection my logic wasn't particularly well thought-out)

I have then tried using the subset() function in the hopes that would allow to only plot data meeting my requirements as so:

```<code>chart1<-ggplot(subset(df, 'issued' == "UKS"))+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
          theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
            labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
</code>```

This particular code didn't show up any errors, but the chart that was produced had no data on it all. Does anyone have any ideas on how I can filter and plot this data?

答:
You don't need quote "" for column names in subset().

```<code>ggplot(subset(df, issued == "UKS")) +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
</code>```

Or use a tidyverse way of plotting:

```<code>library(tidyverse)

df %>% filter(issued == "UKS") %>%
  ggplot() +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
</code>```

Body:
I have a very large dataset derived from a spreadsheet of the format below:

df = data.frame(name = c('Ger1', 'Ger2', 'Ger3', 'Ger4', 'Ger5', 'Ger6'),
                issued = c(UKS, USD, UKS, UKS, USD, USD),
                mat = c(2024-01-31, 2023-01-31, 2026-10-22, 2022-07-22, 2029-01-31, 2025-06-07)
                volume = c(0.476, 0.922, 0.580, 1.259, 0.932, 0.417)

Currently, I plot all the data on one very long ggplot with the following code:

chart1<-ggplot(df)+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
    labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")

Now while that worked for a while, given the size the dataset has grown to it is no longer feasible to use that way. Therefore I'd like to plot the data based on the contents of the "issued" column.

I first thought about a condition statement of the type:

if (df$issued == "UKS"){
chart1<-ggplot(df)+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
      theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
        labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")
}

It unfortunately didn't work (although on closer inspection my logic wasn't particularly well thought-out)

I have then tried using the subset() function in the hopes that would allow to only plot data meeting my requirements as so:

chart1<-ggplot(subset(df, 'issued' == "UKS"))+geom_bar(stat="ID",aes(x=volume,y=name),fill="#1170aa")+
          theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
            labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")

This particular code didn't show up any errors, but the chart that was produced had no data on it all. Does anyone have any ideas on how I can filter and plot this data?

Body:
You don't need quote "" for column names in subset().

ggplot(subset(df, issued == "UKS")) +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")

Or use a tidyverse way of plotting:

library(tidyverse)

df %>% filter(issued == "UKS") %>%
  ggplot() +
  geom_bar(stat="identity", aes(x=volume,y=name),fill="#1170aa")+
  theme(title=element_text(size=12),
        panel.background = element_rect(fill='white',color='black'),
        legend.position='right')+
  labs(title = "Total carriage by Volume on the day", x = "Volume", y = "Name")


答:
There are 2 problems with your example that do not work.

You are not passing Get-Calc as a scriptblock (The expected value for a scriptmethod is a scriptblock)

You are not passing your expected parameters

Instead of

```<code>$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)
</code>```

Do this:

```<code>$myObject | Add-Member ScriptMethod -name Calc3 -value {param([int]$a,[int]$b) get-Calc -a $a -b $b}
</code>```

Title: PowerShell add a function to a custom object

Body:
There are 2 problems with your example that do not work.

You are not passing Get-Calc as a scriptblock (The expected value for a scriptmethod is a scriptblock)

You are not passing your expected parameters

Instead of

$myObject | Add-Member ScriptMethod -name Calc -value(get-Calc)

Do this:

$myObject | Add-Member ScriptMethod -name Calc3 -value {param([int]$a,[int]$b) get-Calc -a $a -b $b}


问:
How can I get a Python generator to return None rather than StopIteration?
I am using generators to perform searches in lists like this simple example:

```<code>>>> a = [1,2,3,4]
>>> (i for i, v in enumerate(a) if v == 4).next()
3
</code>```

(Just to frame the example a bit, I am using very much longer lists compared to the one above, and the entries are a little bit more complicated than int. I do it this way so the entire lists won't be traversed each time I search them)

Now if I would instead change that to i == 666, it would return a StopIteration because it can't find any 666 entry in a.

How can I make it return None instead? I could of course wrap it in a try ... except clause, but is there a more pythonic way to do it?

答:
You can chain the generator with (None,):

```<code>from itertools import chain
a = [1,2,3,4]
print chain((i for i, v in enumerate(a) if v == 6), (None,)).next()
</code>```

but I think a.index(2) will not traverse the full list, when 2 is found, the search is finished. you can test this:

```<code>>>> timeit.timeit("a.index(0)", "a=range(10)")
0.19335955439601094
>>> timeit.timeit("a.index(99)", "a=range(100)")
2.1938486138533335
</code>```

Body:
I am using generators to perform searches in lists like this simple example:

>>> a = [1,2,3,4]
>>> (i for i, v in enumerate(a) if v == 4).next()
3

(Just to frame the example a bit, I am using very much longer lists compared to the one above, and the entries are a little bit more complicated than int. I do it this way so the entire lists won't be traversed each time I search them)

Now if I would instead change that to i == 666, it would return a StopIteration because it can't find any 666 entry in a.

How can I make it return None instead? I could of course wrap it in a try ... except clause, but is there a more pythonic way to do it?

Body:
You can chain the generator with (None,):

from itertools import chain
a = [1,2,3,4]
print chain((i for i, v in enumerate(a) if v == 6), (None,)).next()

but I think a.index(2) will not traverse the full list, when 2 is found, the search is finished. you can test this:

>>> timeit.timeit("a.index(0)", "a=range(10)")
0.19335955439601094
>>> timeit.timeit("a.index(99)", "a=range(100)")
2.1938486138533335


问:
How to correctly return api response when using retrofit in android?
I am trying to make an app using mvvm design and in the repository class I am calling my api using retrofit.
I am getting correct response from my api and I want to return that response but while returning the data from my method the data value is null.
Please help me correct what I am doing wrong here.

My repository class:

```<code>public class UserStatusRepository {

private static ApiInterface apiInterface;
private static MutableLiveData<List<Submission>> submissions;
public UserStatusRepository() {
    apiInterface = RetrofitClient.getApiInterface();
    submissions = new MutableLiveData<>();
}

public LiveData<List<Submission>> loadUserStats(String params) {
    apiInterface.getUsersStatus("myapihere",params).enqueue(new Callback<UserStatusResponse>() {
        @Override
        public void onResponse(Call<UserStatusResponse> call, Response<UserStatusResponse> response) {
            if(response.isSuccessful() && response.body() != null) {
                submissions.postValue(response.body().getSubmissions());
                //receiving correct response here
            }
        }

        @Override
        public void onFailure(Call<UserStatusResponse> call, Throwable t) {
            submissions.postValue(null);
        }
    });
    return submissions; // but while returning response is null
}

}
</code>```

I think that I am returning the value before receiving the response from api so
What do I need to do so that while data(here data means submissions variable in my code) returned is not null?

答:
Please try below code</p>
```<code>public class UserStatusRepository {

private static ApiInterface apiInterface;
public UserStatusRepository() {
            apiInterface = RetrofitClient.getApiInterface();
        }

        public LiveData<List<Submission>> loadUserStats(String params) {
        MutableLiveData<List<Submission>> submissions = new MutableLiveData<>();
            apiInterface.getUsersStatus("myapihere",params).enqueue(new Callback<UserStatusResponse>() {
                @Override
                public void onResponse(Call<UserStatusResponse> call, Response<UserStatusResponse> response) {
                    if(response.isSuccessful() && response.body() != null) {
                        submissions.setValue(response.body().getSubmissions());
                        //receiving correct response here
                    }
                }

                @Override
                public void onFailure(Call<UserStatusResponse> call, Throwable t) {
                    submissions.setValue(null);
                }
            });
            return submissions; // but while returning response is null
        }
       }
</code>```

Body:
I am trying to make an app using mvvm design and in the repository class I am calling my api using retrofit.
I am getting correct response from my api and I want to return that response but while returning the data from my method the data value is null.
Please help me correct what I am doing wrong here.

My repository class:

public class UserStatusRepository {

private static ApiInterface apiInterface;
private static MutableLiveData<List<Submission>> submissions;
public UserStatusRepository() {
    apiInterface = RetrofitClient.getApiInterface();
    submissions = new MutableLiveData<>();
}

public LiveData<List<Submission>> loadUserStats(String params) {
    apiInterface.getUsersStatus("myapihere",params).enqueue(new Callback<UserStatusResponse>() {
        @Override
        public void onResponse(Call<UserStatusResponse> call, Response<UserStatusResponse> response) {
            if(response.isSuccessful() && response.body() != null) {
                submissions.postValue(response.body().getSubmissions());
                //receiving correct response here
            }
        }

        @Override
        public void onFailure(Call<UserStatusResponse> call, Throwable t) {
            submissions.postValue(null);
        }
    });
    return submissions; // but while returning response is null
}

}

I think that I am returning the value before receiving the response from api so
What do I need to do so that while data(here data means submissions variable in my code) returned is not null?

Body:
Please try below code

public class UserStatusRepository {

private static ApiInterface apiInterface;
public UserStatusRepository() {
            apiInterface = RetrofitClient.getApiInterface();
        }

        public LiveData<List<Submission>> loadUserStats(String params) {
        MutableLiveData<List<Submission>> submissions = new MutableLiveData<>();
            apiInterface.getUsersStatus("myapihere",params).enqueue(new Callback<UserStatusResponse>() {
                @Override
                public void onResponse(Call<UserStatusResponse> call, Response<UserStatusResponse> response) {
                    if(response.isSuccessful() && response.body() != null) {
                        submissions.setValue(response.body().getSubmissions());
                        //receiving correct response here
                    }
                }

                @Override
                public void onFailure(Call<UserStatusResponse> call, Throwable t) {
                    submissions.setValue(null);
                }
            });
            return submissions; // but while returning response is null
        }
       }


问:
Let all instances of object call method at same time (java)
So I have a superclass called Tile and many subclasses like BlueTile, GreenTile etc..

All instances of the different subclasses are stored in an ArrayList (eg. (blueTile1, blueTile2, greenTile1....)).

There is a method called "activateTile()" in the superclass, that all subclasses use in a different way.

Now when I loop trough the array and activate all blue Tiles with blueTile.activateTile() they will be activated one after another right?

How can I let all blueTiles in the Array call the method at the same time?
Or is there a way to simply say "all instances of that class, do that method now"?

Thank you :)

答:
Unless you intend to launch a new Thread per instance, they will always being running methods sequentially.

Do you intend something like this?

```<code>void activateInParallel() {
    ArrayList<Thread> tileThreads = new ArrayList<>();
    for(Tile t : allTiles) {
        tileThreads .add(new Thread(()->t.activateTile()));
    }
    tileThreads.forEach(Thread::start);
}
</code>```

I don't know enough details, but that is very likely not the best way to do it.
I would consider using an Executor with a thread pool and offloading the work to it in a similar way.

```<code>    Executor executor = Executors.newFixedThreadPool(8);
    void activateInParallel() {
        for(Tile t : allTiles) {
            executor.execute(t::activateTile);
        }
    }
</code>```

Body:
Unless you intend to launch a new Thread per instance, they will always being running methods sequentially.

Do you intend something like this?

void activateInParallel() {
    ArrayList<Thread> tileThreads = new ArrayList<>();
    for(Tile t : allTiles) {
        tileThreads .add(new Thread(()->t.activateTile()));
    }
    tileThreads.forEach(Thread::start);
}

I don't know enough details, but that is very likely not the best way to do it.
I would consider using an Executor with a thread pool and offloading the work to it in a similar way.

    Executor executor = Executors.newFixedThreadPool(8);
    void activateInParallel() {
        for(Tile t : allTiles) {
            executor.execute(t::activateTile);
        }
    }


问:
Query JOIN or not? (optimization)
i was wondering if to use 2 tables is better then using 1 single table .

Scenario:

i have a simple user table and a simple user_details table. i can JOIN tables and select both records.

But i was wondering if to merge 2 table into 1 single table.

what if i have 2milions users records in both tables?

in terms of speed and exec time is better to have a single table when selecting records?

答:
You should easily be able to make either scenario perform well with proper indexing.  Two million rows is not that many for any modern RDBMS.

However, one table is a better design if rows in the two tables represent the same logical entity.  If the user table has a 1:1 relationship with the user_detail table, you should (probably) combine them.

Edit: A few other answers have mentioned de-normalizing--this assumes the relationship between the tables is 1:n (I read your question to mean the relationship was 1:1).  If the relationship is indeed 1:n, you absolutely want to keep them as two tables.

Title: Query JOIN or not? (optimization)


问:
Remove characters from the last column of a list of data frame
I have a list listDF of 30 data frames (~1000 rows X 3 columns). In the last column of each one, I have a composite character as shown below :

```<code>Date        Origin              Chemical
28/10/2012  Artificial nuclides Cs-137__Sea
28/10/2012  Natural nuclides    Ra-226__Clouds
28/10/2012  Natural nuclides    Ra-228__Sands
28/10/2012  Natural nuclides    Th-228__Sea
28/10/2012  Artificial nuclides Cs-137__Rocks
</code>```

For the last column of each df, how can I simply remove "__Sea", "__Clouds"... and just keep the chemical name ?

答:
For-loop solution:</p>
```<code>for (df in listDF){
  for (i in 1:nrow(listDF)){
    df[i, "Chemical"] = unlist(strsplit(df[i, "Chemical"], "__"))[1]
  }
}
</code>```

Body:
I have a list listDF of 30 data frames (~1000 rows X 3 columns). In the last column of each one, I have a composite character as shown below :

Date        Origin              Chemical
28/10/2012  Artificial nuclides Cs-137__Sea
28/10/2012  Natural nuclides    Ra-226__Clouds
28/10/2012  Natural nuclides    Ra-228__Sands
28/10/2012  Natural nuclides    Th-228__Sea
28/10/2012  Artificial nuclides Cs-137__Rocks

For the last column of each df, how can I simply remove "__Sea", "__Clouds"... and just keep the chemical name ?

Body:
For-loop solution:

for (df in listDF){
  for (i in 1:nrow(listDF)){
    df[i, "Chemical"] = unlist(strsplit(df[i, "Chemical"], "__"))[1]
  }
}


问:
Generating a time-series based condition in R
Consider a data frame that has 3 columns: A - a name; B - the yearly food intake (one name can eat different foods); C - the year in which the person stops eating that food

Such as:

A           B     C

Peter     400   2035

Peter     500   2050

Peter     350   2024

John      700   2050

I need to create a time series that sums all the food intake for each person, from today (2022) to 2050. In the case of John is easy: 700 * (2050-2022). But for Peter, I need to add some restrictions: sum the 3 lines until 2024, then one of them goes to zero, but the time series keeps summing the other two lines, until eventually there is only one line to sum.

So year 2022 would be (400+500+350), the same for years 2023 to 2024. Then would be (400+500), until 2035, etc.

This allows me to have a time-series, per person, which contains the yearly intake of food, taking into consideration that the yearly food intake will decrease throughout the years.

答:
Are you after the total intake over the period? Then this will calculate it:

```<code>library(tidyverse)

data <- tribble(~"A", ~"B", ~"C",
                "Peter", 400, 2035,
                "Peter", 500, 2050,
                "Peter", 350, 2024,
                "John", 700, 2050)

data %>%
  mutate(line_total = B*(C - 2022)) %>% # 2022 being the start year
  group_by(A) %>%
  summarise(person_total = sum(line_total))
</code>```

If you actually want a time-series, with a column for each row and the total for the row at the end, then try this:

```<code>years <- 2022:max(data$C)

mat <- matrix(nrow = nrow(data), ncol = length(years))
colnames(mat) <- c(years)

timeseries <- cbind(data, mat) %>%
  as_tibble() %>%
  pivot_longer(-c(A, B, C)) %>%
  mutate(value = ifelse(name <= C, B, 0)) %>%
  pivot_wider() %>%
  select(-c(B, C)) %>%
  mutate(rowsum = rowSums(across(where(is.numeric))))
</code>```

Body:
Are you after the total intake over the period? Then this will calculate it:

library(tidyverse)

data <- tribble(~"A", ~"B", ~"C",
                "Peter", 400, 2035,
                "Peter", 500, 2050,
                "Peter", 350, 2024,
                "John", 700, 2050)

data %>%
  mutate(line_total = B*(C - 2022)) %>% # 2022 being the start year
  group_by(A) %>%
  summarise(person_total = sum(line_total))

If you actually want a time-series, with a column for each row and the total for the row at the end, then try this:

years <- 2022:max(data$C)

mat <- matrix(nrow = nrow(data), ncol = length(years))
colnames(mat) <- c(years)

timeseries <- cbind(data, mat) %>%
  as_tibble() %>%
  pivot_longer(-c(A, B, C)) %>%
  mutate(value = ifelse(name <= C, B, 0)) %>%
  pivot_wider() %>%
  select(-c(B, C)) %>%
  mutate(rowsum = rowSums(across(where(is.numeric))))


问:
Vertically aligned FlatButtons in Alert Dialog?
I want to display an AlertDialog in Flutter with 3 buttons, but vertically aligned as the text of the buttons takes up too much space. So far I only get them displayed horizontally. Any idea how to solve it? The solutions from this post (How to make an AlertDialog in Flutter?) didn't work for me, still shown horizontally.

```<code>  static Future<void> showLogoutAllDevicesOrOnlyThisDialog(
      BuildContext context) {
    var b1 = FlatButton(
      textColor: Colors.red,
      child: Text('Only on this device'),
      onPressed: () {
        Navigator.of(context).pop();
        RxBus.post(HideSpinnerEvent());
      },
    );
    var b2 = FlatButton(
      textColor: Colors.red,
      child: Text('On all devices'),
      onPressed: () {
        Navigator.of(context).pop();
        RxBus.post(HideSpinnerEvent());
      },
    );

    var b3 = FlatButton(
      child: Text('Cancel'),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );

    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(''),
          content: Text(
              "Möchtest du dich auf allen Geräten abmelden oder nur auf diesem Gerät?"),
          actions: <Widget>[
            b1, b2, b3
          ],

        );
      },
    );
  }
}
</code>```

答:
actionsOverflowDirection: VerticalDirection.up will automatically makes actions list vertical if it not fits in the row

AlertDialog(
  title: const Text('AlertDialog Title'),
  content: const Text('AlertDialog description'),
  scrollable: true,
  actionsOverflowDirection: VerticalDirection.up,
  actions: <Widget>[
    TextButton(
      onPressed: () => Navigator.pop(context, 'Cancel'),
      child: const Text('Save'),
    ),
    TextButton(
      onPressed: () => Navigator.pop(context, 'Cancel'),
      child: const Text('Cancel'),
    ),
    TextButton(
      onPressed: () => Navigator.pop(context, 'OK'),
      child: const Text('OK'),
    ),
    TextButton(
      onPressed: () => Navigator.pop(context, 'Cancel'),
      child: const Text('Delete'),
    ),
  ],
)
```

[1

Body:
I want to display an AlertDialog in Flutter with 3 buttons, but vertically aligned as the text of the buttons takes up too much space. So far I only get them displayed horizontally. Any idea how to solve it? The solutions from this post (How to make an AlertDialog in Flutter?) didn't work for me, still shown horizontally.

  static Future<void> showLogoutAllDevicesOrOnlyThisDialog(
      BuildContext context) {
    var b1 = FlatButton(
      textColor: Colors.red,
      child: Text('Only on this device'),
      onPressed: () {
        Navigator.of(context).pop();
        RxBus.post(HideSpinnerEvent());
      },
    );
    var b2 = FlatButton(
      textColor: Colors.red,
      child: Text('On all devices'),
      onPressed: () {
        Navigator.of(context).pop();
        RxBus.post(HideSpinnerEvent());
      },
    );

    var b3 = FlatButton(
      child: Text('Cancel'),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );

    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(''),
          content: Text(
              "Möchtest du dich auf allen Geräten abmelden oder nur auf diesem Gerät?"),
          actions: <Widget>[
            b1, b2, b3
          ],

        );
      },
    );
  }
}

Body:
actionsOverflowDirection: VerticalDirection.up will automatically makes actions list vertical if it not fits in the row

AlertDialog(
  title: const Text('AlertDialog Title'),
  content: const Text('AlertDialog description'),
  scrollable: true,
  actionsOverflowDirection: VerticalDirection.up,
  actions: <Widget>[
    TextButton(
      onPressed: () => Navigator.pop(context, 'Cancel'),
      child: const Text('Save'),
    ),
    TextButton(
      onPressed: () => Navigator.pop(context, 'Cancel'),
      child: const Text('Cancel'),
    ),
    TextButton(
      onPressed: () => Navigator.pop(context, 'OK'),
      child: const Text('OK'),
    ),
    TextButton(
      onPressed: () => Navigator.pop(context, 'Cancel'),
      child: const Text('Delete'),
    ),
  ],
)

[1


问:
Compare working copy with specific repository

Possible Duplicate:

  SVN diff across 2 different repositories

How can I compare a working copy with a repository different than the one which the working copy is associated?

I need this comparison, because I was forced to apply some changes directly on the production server (current version connected to a tag) and I would like to check if those changes were already applied on trunk.

答:
If you are going to compare against a specific revision then you can create a patch of the working copy and a patch of the specific revision in the other repo and then do a diff to see if the patch files match or not.

Or if you have TortoiseSVN installed you can do the following:

Difference to another branch/tag

If you want to see what has changed on trunk (if you are working on a branch) or on a specific branch (if you are working on trunk), you can use the explorer context menu. Just hold down the Shift key while you right click on the file. Then select TortoiseSVN → Diff with URL. In the following dialog, specify the URL in the repository with which you want to compare your local file to.

Source: Viewing Differences