问:
How to make a tkinter gui and display printed value
This is how far I came.... I got the winner know I want to display it on the gui here is my code:
I tried many google searches and found none I hoped that someone may help me</p>
```<code>import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'
class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = runn)
        run.pack(pady= 5, padx = 5)

def runn():
    PEOPLE = [
  'Juan',
  'Owen'
]

    print("\n\n")
    bar = Bar('And the winner is...', max=2)
    for i in range(2):
        [x for x in range(999999)]  # short pause...
        bar.next()
    bar.finish()
    print("\n\n\t{}!\n\n".format(random.choice(PEOPLE)))
    print("-" * 60 + "\n")

app = Application()
app.mainloop()
</code>```

答:
Something you could do is integrate the runn function into the class and update class variables (as in the example below, self.winner as the winner and self.display_winner as the label you want to show);

```<code>import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'

class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.winner = None
        self.display_winner = None
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = self.runn)
        run.pack(pady= 5, padx = 5)

    def runn(self):
        PEOPLE = [
    'Juan',
    'Owen'
    ]
        self.winner = random.choice(PEOPLE)
        if self.display_winner:
            self.display_winner.destroy()
        self.display_winner = tk.Label(self, text="The winner is " + self.winner + "!!!", font='Helvetica 32 bold', bg=backroundcolor)
        self.display_winner.pack(pady= 10, padx= 2)

app = Application()
app.mainloop()
</code>```

We check if we already have displayed a winner, if so we delete the label and make a new one. If not we just add the new label with the winner. If we do not check this, the labels will keep stacking in the window.

If you want to check the new winner against the old one you just add another variable and check if the new winner matches the old;

```<code>import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'

class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.winner = None
        self.display_winner = None
        self.old_winner = None
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = self.runn)
        run.pack(pady= 5, padx = 5)

    def runn(self):
        PEOPLE = [
    'Juan',
    'Owen'
    ]
        self.winner = random.choice(PEOPLE)
        if self.display_winner:
            self.display_winner.destroy()
        if self.winner == self.old_winner:
            self.display_winner = tk.Label(self, text="The winner is " + self.winner + " again!!!", font='Helvetica 24 bold', bg=backroundcolor)
        else:
            self.display_winner = tk.Label(self, text="The winner is " + self.winner + "!!!", font='Helvetica 24 bold', bg=backroundcolor)
        self.display_winner.pack(pady= 10, padx= 2)
        self.old_winner = self.winner

app = Application()
app.mainloop()
</code>```

Body:
This is how far I came.... I got the winner know I want to display it on the gui here is my code:
I tried many google searches and found none I hoped that someone may help me

import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'
class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = runn)
        run.pack(pady= 5, padx = 5)

def runn():
    PEOPLE = [
  'Juan',
  'Owen'
]

    print("\n\n")
    bar = Bar('And the winner is...', max=2)
    for i in range(2):
        [x for x in range(999999)]  # short pause...
        bar.next()
    bar.finish()
    print("\n\n\t{}!\n\n".format(random.choice(PEOPLE)))
    print("-" * 60 + "\n")

app = Application()
app.mainloop()

Body:
Something you could do is integrate the runn function into the class and update class variables (as in the example below, self.winner as the winner and self.display_winner as the label you want to show);

import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'

class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.winner = None
        self.display_winner = None
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = self.runn)
        run.pack(pady= 5, padx = 5)

    def runn(self):
        PEOPLE = [
    'Juan',
    'Owen'
    ]
        self.winner = random.choice(PEOPLE)
        if self.display_winner:
            self.display_winner.destroy()
        self.display_winner = tk.Label(self, text="The winner is " + self.winner + "!!!", font='Helvetica 32 bold', bg=backroundcolor)
        self.display_winner.pack(pady= 10, padx= 2)

app = Application()
app.mainloop()

We check if we already have displayed a winner, if so we delete the label and make a new one. If not we just add the new label with the winner. If we do not check this, the labels will keep stacking in the window.

If you want to check the new winner against the old one you just add another variable and check if the new winner matches the old;

import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'

class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.winner = None
        self.display_winner = None
        self.old_winner = None
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = self.runn)
        run.pack(pady= 5, padx = 5)

    def runn(self):
        PEOPLE = [
    'Juan',
    'Owen'
    ]
        self.winner = random.choice(PEOPLE)
        if self.display_winner:
            self.display_winner.destroy()
        if self.winner == self.old_winner:
            self.display_winner = tk.Label(self, text="The winner is " + self.winner + " again!!!", font='Helvetica 24 bold', bg=backroundcolor)
        else:
            self.display_winner = tk.Label(self, text="The winner is " + self.winner + "!!!", font='Helvetica 24 bold', bg=backroundcolor)
        self.display_winner.pack(pady= 10, padx= 2)
        self.old_winner = self.winner

app = Application()
app.mainloop()


来源: stackexchange

问:
Flask fails with "Error: While importing 'X', an ImportError was raised", but does not display the error. How to find the source of the error?
When starting a Flask app with:

$ flask run
```
<p>I received the error:</p>
<blockquote>
```Error: While importing 'wsgi', an ImportError was raised.

Usage: flask [OPTIONS] COMMAND [ARGS]...`
...
```

However, there is no stack trace or other information provided. What is the best way to get the ImportError stack trace?

答:
The only thing that I would add to Christopher Peisert's answer is the option that gave me the error messages that I was searching for:

```<code>(venv) ~/example_flask_app/$ python
>>> import app
</code>```

Or in my case

```<code>>>> import microblog
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When starting a Flask app with:

$ flask run

I received the error:

Error: While importing 'wsgi', an ImportError was raised.

Usage: flask [OPTIONS] COMMAND [ARGS]...`
...

However, there is no stack trace or other information provided. What is the best way to get the ImportError stack trace?

Body:
The only thing that I would add to Christopher Peisert's answer is the option that gave me the error messages that I was searching for:

(venv) ~/example_flask_app/$ python
>>> import app

Or in my case

>>> import microblog


问:
Dynamically filling two fields depending on a dropdown value
I have a database server name recommendation list coming from the backend, where "driverName" and "connectionURL" for that driver should auto-populate once the user picks a server.
I know it's possible to accomplish it with javascript, but I'm new to the language.
Could someone please assist me?

```<code>
                        <div class="form-group">
                            <form:label path="databaseServer">Database Server:</form:label>
                            <form:select path="databaseServer" class="form-control">
                                <form:option value="None" label="Please Select a Database Server"/>
                                <form:options items="${command.databaseServerMap}" />
                            </form:select>

                        </div>
                        <div class="form-group">
                            <form:label path="driverName">Driver Name:</form:label>
                            <form:input path="driverName" class="form-control"  readonly="true"/>

                        </div>
                        <div class="form-group">
                            <form:label path="connectionURL">connection URL:</form:label>
                            <form:input path="connectionURL" class="form-control" readonly="true"/>
                        </div>

</code>```

These are the maps I'm working with on the backend.

```<code>
  public Map<String, String> getDatabaseServerMap() {
        Map<String, String> driverList = new LinkedHashMap<>();
        driverList.put("MySQL", "MySQL");
        driverList.put("Postgres", "Postgres");
        return driverList;
    }

  [1]: https://i.stack.imgur.com/HKUWd.png
</code>```

答:
This javaScript code was effective.</p>
```<code>

<script>
        $(function () {
            $('.selectDatabase').change(function(){
       //         console.log( $(this).val() );
                const driverName=$('.driverName');
                const  connectionURL  = $('.connectionURL');

                if($(this).val()==='MySQL'){
                    driverName.val('com.microsoft.sqlserver.jdbc.SQLServerDriver');
                    connectionURL.val('jdbc:sqlserver://localhost:1433;databaseName=database');
                    driverName.attr('readonly',true);
                    connectionURL.attr('readonly',true);

                }else if($(this).val()==='Other'){
                    driverName.val('');
                    connectionURL.val('');
                    driverName.attr('readonly',false);
                    connectionURL.attr('readonly',false);

                }else{
                    driverName.val('');
                    connectionURL.val('');
                    driverName.attr('readonly',true);
                    connectionURL.attr('readonly',true);
                }

            });

        });

    </script>

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

<div class="form-group">
    <form:label path="databaseServer">Database Server:</form:label>
    <form:select path="databaseServer" class="form-control selectDatabase">
        <form:option value="None" label="Please Select a Database Server"/>
        <form:options items="${command.databaseServerMap}" />
    </form:select>

</div>
<div class="form-group">
    <form:label path="driverName">Driver Name:</form:label>
    <form:input path="driverName" class="form-control driverName"  readonly="true"/>
</div>
</code>```

Body:
I have a database server name recommendation list coming from the backend, where "driverName" and "connectionURL" for that driver should auto-populate once the user picks a server.
I know it's possible to accomplish it with javascript, but I'm new to the language.
Could someone please assist me?

                            <form:label path="databaseServer">Database Server:</form:label>
                            <form:select path="databaseServer" class="form-control">
                                <form:option value="None" label="Please Select a Database Server"/>
                                <form:options items="${command.databaseServerMap}" />
                            </form:select>

                            <form:label path="driverName">Driver Name:</form:label>
                            <form:input path="driverName" class="form-control"  readonly="true"/>

                            <form:label path="connectionURL">connection URL:</form:label>
                            <form:input path="connectionURL" class="form-control" readonly="true"/>

These are the maps I'm working with on the backend.

  public Map<String, String> getDatabaseServerMap() {
        Map<String, String> driverList = new LinkedHashMap<>();
        driverList.put("MySQL", "MySQL");
        driverList.put("Postgres", "Postgres");
        return driverList;
    }

  [1]: https://i.stack.imgur.com/HKUWd.png

Body:
This javaScript code was effective.

<script>
        $(function () {
            $('.selectDatabase').change(function(){
       //         console.log( $(this).val() );
                const driverName=$('.driverName');
                const  connectionURL  = $('.connectionURL');

                if($(this).val()==='MySQL'){
                    driverName.val('com.microsoft.sqlserver.jdbc.SQLServerDriver');
                    connectionURL.val('jdbc:sqlserver://localhost:1433;databaseName=database');
                    driverName.attr('readonly',true);
                    connectionURL.attr('readonly',true);

                }else if($(this).val()==='Other'){
                    driverName.val('');
                    connectionURL.val('');
                    driverName.attr('readonly',false);
                    connectionURL.attr('readonly',false);

                }else{
                    driverName.val('');
                    connectionURL.val('');
                    driverName.attr('readonly',true);
                    connectionURL.attr('readonly',true);
                }

            });

        });

    </script>

<div class="form-group">
    <form:label path="databaseServer">Database Server:</form:label>
    <form:select path="databaseServer" class="form-control selectDatabase">
        <form:option value="None" label="Please Select a Database Server"/>
        <form:options items="${command.databaseServerMap}" />
    </form:select>

</div>
<div class="form-group">
    <form:label path="driverName">Driver Name:</form:label>
    <form:input path="driverName" class="form-control driverName"  readonly="true"/>
</div>


问:
How to perform operation on specific elements of a list?
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

```<code>i=['0','7','2','3','4']
o=['0','14','2,'6','4']
</code>```

here's the code I tried:

```<code>list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)
</code>```

here's the error I get:

```<code>PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting
</code>```

答:
Example is a little misleading here. If we consider odd indices then

```<code>o=[int(i[x])*2 if x%2==1 else int(i[x]) for x in range(len(i))]
</code>```

If we consider numbers themselves

```<code>o= [str(int(x)*2) if int(x)%2!=0 else x for x in i]
</code>```

Body:
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

i=['0','7','2','3','4']
o=['0','14','2,'6','4']

here's the code I tried:

list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)

here's the error I get:

PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting

Body:
Example is a little misleading here. If we consider odd indices then

o=[int(i[x])*2 if x%2==1 else int(i[x]) for x in range(len(i))]

If we consider numbers themselves

o= [str(int(x)*2) if int(x)%2!=0 else x for x in i]


问:
Iterate over a list of lists and check for a condition using java 8
I'm trying to iterate over a list of a list of elements to test for a given condition, while it is possible with Java 7, I'm interested to know how to do it with java 8 stream.

```<code>import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class Main2 {
    static String[] positionsThatWillBeCovered = new String[]{"RB", "LB", "MD"};
    static String[] positionsThatWillNotBeCovered = new String[]{"RB", "LB", "MD", "GK"};

    public static void main(String[] args) {
        Position p1 = new Position("RB");
        Position p2 = new Position("LB");
        Position p3 = new Position("MD");

        Player alves = new Player(Arrays.asList(p1, p2));
        Player alba = new Player(Arrays.asList(p2));
        Player xavi = new Player(Arrays.asList(p3));

        Team team = new Team(Arrays.asList(alves, alba, xavi));

        //should print true
        System.out.println(testAllPositionsAreCovered(team, positionsThatWillBeCovered));

        //false
        System.out.println(testAllPositionsAreCovered(team, positionsThatWillNotBeCovered));
    }

    private static boolean testAllPositionsAreCovered(Team team, String[] positionsToCover) {
        for (String positionToCover : positionsToCover) {
            boolean positionWasCovered = false;
            A : for (Player player : team.getPlayerList()) {
                   for (Position playerPosition : player.getPositions()) {
                        if(playerPosition.getPosition().equals(positionToCover))
                        {
                            positionWasCovered = true;
                            break A;
                        }
                    }
                }
                if (!positionWasCovered) return false;
            }
        return true;
    }
}

class Team {
    private List<Player> playerList;
    Team(List<Player> playerList){
        this.playerList = playerList;
    }

    public List<Player> getPlayerList() {
        return playerList;
    }
}

class Player {
    private List<Position> positions;
    Player(List<Position> positions){
        this.positions = positions;
    }

    public List<Position> getPositions() {
        return positions;
    }
}

class Position {
    private String position;
    //some other fields...
    public Position(String position) {
        this.position = position;
    }

    public String getPosition() {
        return position;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Position position1 = (Position) o;
        return Objects.equals(position, position1.position);
    }

    @Override
    public int hashCode() {
        return Objects.hash(position);
    }
}
</code>```

a Team contains a list of Players, a Player can play in many positions.

Question:
Given a team and a list of positions, I need to know if that every position of the list can be played at least by one player.

I have a solution with Java 7 where we can go throught all positions and check if at least a player can play in it.

I'm interested for the java 8 solution with stream.

Thank you.

EDIT:
By The way after the comment of @Holger, I updated my java 7 version of the solution and it is a way better.

Here is the part I changed:

```<code>private static boolean testAllPositionsAreCovered(Team team, String[] positionsToCover) {
    for (String positionToCover : positionsToCover) { //"RB", "LB", "MD"
        if (!isThePositionCoveredByAPlayer(team, positionToCover))
            return false;
    }
    return true;
}

private static boolean isThePositionCoveredByAPlayer(Team team, String positionToCover) {
    for (Player player : team.getPlayerList()) {
         for (Position playerPosition : player.getPositions()) {
              if(playerPosition.getPosition().equals(positionToCover))
                return true;
         }
    }
    return false;
}
</code>```

答:
Use flatMap to combine all the players’ positions into a single Stream:</p>
```<code>public boolean testAllPositionsAreCovered(Team team,
                                          String[] positions) {

    Set<String> positionsOfTeams = team.getPlayers().stream()
        .flatMap(p -> p.getPositions().stream())
        .map(Position::getPosition)
        .collect(Collectors.toSet());
    return positionsOfTeams.containsAll(Arrays.asList(positions));
}
</code>```

Body:
I'm trying to iterate over a list of a list of elements to test for a given condition, while it is possible with Java 7, I'm interested to know how to do it with java 8 stream.

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class Main2 {
    static String[] positionsThatWillBeCovered = new String[]{"RB", "LB", "MD"};
    static String[] positionsThatWillNotBeCovered = new String[]{"RB", "LB", "MD", "GK"};

    public static void main(String[] args) {
        Position p1 = new Position("RB");
        Position p2 = new Position("LB");
        Position p3 = new Position("MD");

        Player alves = new Player(Arrays.asList(p1, p2));
        Player alba = new Player(Arrays.asList(p2));
        Player xavi = new Player(Arrays.asList(p3));

        Team team = new Team(Arrays.asList(alves, alba, xavi));

        //should print true
        System.out.println(testAllPositionsAreCovered(team, positionsThatWillBeCovered));

        //false
        System.out.println(testAllPositionsAreCovered(team, positionsThatWillNotBeCovered));
    }

    private static boolean testAllPositionsAreCovered(Team team, String[] positionsToCover) {
        for (String positionToCover : positionsToCover) {
            boolean positionWasCovered = false;
            A : for (Player player : team.getPlayerList()) {
                   for (Position playerPosition : player.getPositions()) {
                        if(playerPosition.getPosition().equals(positionToCover))
                        {
                            positionWasCovered = true;
                            break A;
                        }
                    }
                }
                if (!positionWasCovered) return false;
            }
        return true;
    }
}

class Team {
    private List<Player> playerList;
    Team(List<Player> playerList){
        this.playerList = playerList;
    }

    public List<Player> getPlayerList() {
        return playerList;
    }
}

class Player {
    private List<Position> positions;
    Player(List<Position> positions){
        this.positions = positions;
    }

    public List<Position> getPositions() {
        return positions;
    }
}

class Position {
    private String position;
    //some other fields...
    public Position(String position) {
        this.position = position;
    }

    public String getPosition() {
        return position;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Position position1 = (Position) o;
        return Objects.equals(position, position1.position);
    }

    @Override
    public int hashCode() {
        return Objects.hash(position);
    }
}

a Team contains a list of Players, a Player can play in many positions.

Question:
Given a team and a list of positions, I need to know if that every position of the list can be played at least by one player.

I have a solution with Java 7 where we can go throught all positions and check if at least a player can play in it.

I'm interested for the java 8 solution with stream.

Thank you.

EDIT:
By The way after the comment of @Holger, I updated my java 7 version of the solution and it is a way better.

Here is the part I changed:

private static boolean testAllPositionsAreCovered(Team team, String[] positionsToCover) {
    for (String positionToCover : positionsToCover) { //"RB", "LB", "MD"
        if (!isThePositionCoveredByAPlayer(team, positionToCover))
            return false;
    }
    return true;
}

private static boolean isThePositionCoveredByAPlayer(Team team, String positionToCover) {
    for (Player player : team.getPlayerList()) {
         for (Position playerPosition : player.getPositions()) {
              if(playerPosition.getPosition().equals(positionToCover))
                return true;
         }
    }
    return false;
}

Body:
Use flatMap to combine all the players’ positions into a single Stream:

public boolean testAllPositionsAreCovered(Team team,
                                          String[] positions) {

    Set<String> positionsOfTeams = team.getPlayers().stream()
        .flatMap(p -> p.getPositions().stream())
        .map(Position::getPosition)
        .collect(Collectors.toSet());
    return positionsOfTeams.containsAll(Arrays.asList(positions));
}


问:
Hidden features of Scala
What are the hidden features of Scala that every Scala developer should be aware of?

One hidden feature per answer, please.

答:
Traits with abstract override methods are a feature in Scala that is as not widely advertised as many others. The intend of methods with the abstract override modifier is to do some operations and delegating the call to super. Then these traits have to be mixed-in with concrete implementations of their abstract override methods.

```<code>trait A {
  def a(s : String) : String
}

trait TimingA extends A {
  abstract override def a(s : String) = {
    val start = System.currentTimeMillis
    val result = super.a(s)
    val dur = System.currentTimeMillis-start
    println("Executed a in %s ms".format(dur))
    result
  }
}

trait ParameterPrintingA extends A {
  abstract override def a(s : String) = {
    println("Called a with s=%s".format(s))
    super.a(s)
  }
}

trait ImplementingA extends A {
  def a(s: String) = s.reverse
}

scala> val a = new ImplementingA with TimingA with ParameterPrintingA

scala> a.a("a lotta as")
Called a with s=a lotta as
Executed a in 0 ms
res4: String = sa attol a
</code>```

While my example is really not much more than a poor mans AOP, I used these Stackable Traits much to my liking to build Scala interpreter instances with predefined imports, custom bindings and classpathes. The Stackable Traits made it possible to create my factory along the lines of new InterpreterFactory with JsonLibs with LuceneLibs and then have useful imports and scope varibles for the users scripts.

ContentLicense: CC BY-SA 2.5

Title: Hidden features of Scala

LastEditorDisplayName: Roger Pate

Body:
Traits with abstract override methods are a feature in Scala that is as not widely advertised as many others. The intend of methods with the abstract override modifier is to do some operations and delegating the call to super. Then these traits have to be mixed-in with concrete implementations of their abstract override methods.

trait A {
  def a(s : String) : String
}

trait TimingA extends A {
  abstract override def a(s : String) = {
    val start = System.currentTimeMillis
    val result = super.a(s)
    val dur = System.currentTimeMillis-start
    println("Executed a in %s ms".format(dur))
    result
  }
}

trait ParameterPrintingA extends A {
  abstract override def a(s : String) = {
    println("Called a with s=%s".format(s))
    super.a(s)
  }
}

trait ImplementingA extends A {
  def a(s: String) = s.reverse
}

scala> val a = new ImplementingA with TimingA with ParameterPrintingA

scala> a.a("a lotta as")
Called a with s=a lotta as
Executed a in 0 ms
res4: String = sa attol a

While my example is really not much more than a poor mans AOP, I used these Stackable Traits much to my liking to build Scala interpreter instances with predefined imports, custom bindings and classpathes. The Stackable Traits made it possible to create my factory along the lines of new InterpreterFactory with JsonLibs with LuceneLibs and then have useful imports and scope varibles for the users scripts.

ContentLicense: CC BY-SA 3.0


问:
React.js Bootstrap Accordion change background color when clicked
My question is how can I change accordion background color when it's active in react bootstrap? Thank you!</p>
```<code>class App extends React.Component {
  render() {
    return (
      <div>
         <Accordion>
           <Card>
            <Card.Header>
              <Accordion.Toggle as={Button} variant="link" eventKey="0">
              All movies
              </Accordion.Toggle>
            </Card.Header>
            [....]
      </div>
    );
  }
}
</code>```

答:
For react-bootstrap 5, just override CSS:

```<code>.accordion-button:not(.collapsed) {
    color: #ffffff;
    background-color: #29008a;
    box-shadow: inset 0 -1px 0 rgb(0 0 0 / 13%);
}
</code>```

Change color, background-color to your choice.

Body:
My question is how can I change accordion background color when it's active in react bootstrap? Thank you!

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

         <Accordion>
           <Card>
            <Card.Header>
              <Accordion.Toggle as={Button} variant="link" eventKey="0">
              All movies
              </Accordion.Toggle>
            </Card.Header>
            [....]

    );
  }
}

Body:
For react-bootstrap 5, just override CSS:

.accordion-button:not(.collapsed) {
    color: #ffffff;
    background-color: #29008a;
    box-shadow: inset 0 -1px 0 rgb(0 0 0 / 13%);
}

Change color, background-color to your choice.


问:
Bash "Syntax error: end of file unexpected" when called from Python's (2.7) subprocess.call()
I have a python (v2.7) script that needs to clear the contents of a file before writing to it (if it exists). I'm able to execute the 'same' command on the command line without issue, but I get a either a python or bash error when calling variations of this command from python. Don't know what I'm missing.

Ultimate question: How can I create an empty file (or clear, if it exists) using a system call from Python (v2.7)?

Bash (successfully creates empty or clears existing file)

```<code>$ > test.txt
$ ls -l test.txt
-rw-rw-r--+ 1 <owner> <group> 0 Feb  9 11:26 test.txt
</code>```

Python (w/o `shell=True'; fails with error)

I get the following error without using shell=True: OSError: [Errno 2] No such file or directory. Another post suggests I shouldn't get this error if I pass all arguments as individual string parameters. Not sure why I get this error.

```<code>$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt']) # Same result w/ single/double quotes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 172, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
</code>```

Python (w/ `shell=True'; fails with error)

I tried adding shell=True per suggestions from the other post (shouldn't be security risk since the command is static), but I get the following bash error: Syntax error: end of file unexpected. I thought it might need an ending ; (maybe because of how python makes the call?), so I tried two adding a ; argument with the same end result.

```<code>$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt'], shell=True) # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected
2
</code>```
```<code>>>> import subprocess
>>> subprocess.call(['>', 'test.txt', ';'], shell=True)  # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected
</code>```

答:
shell=True Error

When using this, the command given is meant to be formatted as ONE string

The command string given is then interpreted as a raw shell command

The correct usage should be like this:

```<code>>>> import subprocess
>>> subprocess.call('> test.txt', shell=True)
0
>>>
# There will now be an empty file called
# 'test.txt' in the same directory
</code>```

shell=False Error

The command you are running is meant to be ran on top of a shell, but when using this way, it tries to run your string by calling it as a command found in your PATH

However, I don't know how to solve this part of the issue for your case.

Body:
I have a python (v2.7) script that needs to clear the contents of a file before writing to it (if it exists). I'm able to execute the 'same' command on the command line without issue, but I get a either a python or bash error when calling variations of this command from python. Don't know what I'm missing.

Ultimate question: How can I create an empty file (or clear, if it exists) using a system call from Python (v2.7)?

Bash (successfully creates empty or clears existing file)

$ > test.txt
$ ls -l test.txt
-rw-rw-r--+ 1 <owner> <group> 0 Feb  9 11:26 test.txt

Python (w/o `shell=True'; fails with error)

I get the following error without using shell=True: OSError: [Errno 2] No such file or directory. Another post suggests I shouldn't get this error if I pass all arguments as individual string parameters. Not sure why I get this error.

$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt']) # Same result w/ single/double quotes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 172, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Python (w/ `shell=True'; fails with error)

I tried adding shell=True per suggestions from the other post (shouldn't be security risk since the command is static), but I get the following bash error: Syntax error: end of file unexpected. I thought it might need an ending ; (maybe because of how python makes the call?), so I tried two adding a ; argument with the same end result.

$ python
>>> import subprocess
>>> subprocess.call(['>', 'test.txt'], shell=True) # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected
2

>>> import subprocess
>>> subprocess.call(['>', 'test.txt', ';'], shell=True)  # Same result w/ single/double quotes
test.txt: 1: test.txt: Syntax error: end of file unexpected

Body:
shell=True Error

When using this, the command given is meant to be formatted as ONE string

The command string given is then interpreted as a raw shell command

The correct usage should be like this:

>>> import subprocess
>>> subprocess.call('> test.txt', shell=True)
0
>>>
# There will now be an empty file called
# 'test.txt' in the same directory

shell=False Error

The command you are running is meant to be ran on top of a shell, but when using this way, it tries to run your string by calling it as a command found in your PATH

However, I don't know how to solve this part of the issue for your case.


问:
How can I remove double quotations surrounding a list imported from a file in Python?
I'm trying to create a food storage application that tracks the items put in a food storage facility and recalls them for the user. This is a very early prototype of the program, only capable of tracking the information locally, but I ran into some problems with it. So my apologies if this code is unreadable, I just can't find a solution to my problem explained below.

```<code>print("Food Storage Application V1.0 - LOCAL ONLY")
UPC_List = []
with open('UPCList.txt', 'r') as file:
    for UPCentry in file:
        location = UPCentry[:-1]
        UPC_List.append(location)
print(UPC_List)

global i
i = 0
UPC_Input = ''
UPC_Count = 0
while True:
    UPC_Found = False
    UPC_Input = input("Enter UPC or enter 'end' to quit: ")
    if UPC_Input == "end":
        with open("UPCList.txt", "w") as file:
            for UPCsave in UPC_List:
                file.write('%s\n' % UPCsave)
        break
    try:
        UPC_Input = int(UPC_Input)
    except ValueError as v:
        print(f"Input '{UPC_Input}' is not an acceptable UPC")
        continue

    # print(UPC_List) # for debugging

    def newProduct(UPC):
        global UPC_Count
        product_name = input(f"Enter name of item {UPC}: ")
        product_quantity = input(f"Enter quantity of item {UPC}: ")
        try:
            product_quantity = int(product_quantity)
        except ValueError as v:
            print("Invalid quantity. Please enter a number.")
            newProduct(UPC_Input)
        product_unit = input(f"Enter unit type (box, bunch, can, etc...) of item {UPC}: ")
        print(f"You have added: \n {product_name} \n {UPC} \n Quantity: {product_quantity} \n Unit: {product_unit}")
        UPC_List.insert(UPC_Count, [UPC, product_name, product_quantity, product_unit])
        UPC_Count += 1

    def existingProduct(UPC):
        for sublist in UPC_List:
            if str(UPC) in str(sublist):
                UPC = int(UPC)
                print(f"Position: {UPC_List.index(sublist)} {sublist.index(UPC)}")
                position = UPC_List.index(sublist)
                addition = input(f"Enter the number of items to add to '{UPC_List[position][1]}' (Default entry: +1): ")
                try:
                    addition = int(addition)
                except ValueError as v:
                    addition = 0

                if addition == 0:
                    UPC_List[position][2] += 1
                else:
                    UPC_List[position][2] += addition
                print(f"New Quantity for item '{UPC_List[position][1]}': {UPC_List[position][2]}")

    #Find if UPC Exists
    for UPC in UPC_List:
        if UPC[0] ==  UPC_Input:
            print("UPC Found")
            existingProduct(UPC_Input)
            UPC_Found = True
    if UPC_Found == False:
        newProduct(UPC_Input)
</code>```

This is my code so far. I made a version of it without the read and writing to file lines and it worked great, but I'm stumped on getting the code to read a list from a file and use it in the code. It saves the list, but it won't retrieve it correctly. I found what I think is the problem by using that print(UPC_List) line, which prints ["[2, 'banana', 2, 'bunch']"] (that was a test entry I loaded into the file using the program). I think the problem lies in the double quotes on the outside of the list. This is a nested list, so those quotation marks lead to an index error when I try to access the list.

If this isn't enough info, I can try to provide more. I'm very new to python and coding in general so this was my best attempt at the script.

答:
To reproduce and solve, we need a minimal reproducible example including

the input (file contents posted as plain-text in code-block formatting)

the minimal code to reproduce

Input file

Contents of UPCList.txt:

```<code>[2, 'banana', 2, 'bunch']
</code>```

This is the string-representation of a list in Python (like str(list)). Probably it was written by your program.

Code

a minimal reproducible example (only first few lines to print the read list):

upc_locations = []
with open('UPCList.txt', 'r') as file:
    for upc in file:
        location = upc[:-1]
        upc_locations.append(location)
print(upc_locations)
```
<p>Prints:</p>
```["[2, 'banana', 2, 'bunch']"]
```
<h3>Debug</h3>
<p>add some debug print for each line read</p>
<pre class="lang-py prettyprint-override"><code>upc_locations = []
with open('UPCList.txt', 'r') as file:
    for line in file:
        print(line)
        location = line[:-1]  # read all chars from line until last (excluding)
        print(location)
        upc_locations.append(location)
print(upc_locations)
</code>```

Prints:

```<code>[2, 'banana', 2, 'bunch']

[2, 'banana', 2, 'bunch']
["[2, 'banana', 2, 'bunch']"]
</code>```

Note:

the second empty-line is the line-break \n at the end of the file's line.

the first line contains something like a Python list with strings and numbers

the third line has removed the line-break.

Fix

The line can be parsed as JSON array. Therefore we need to replace the single-quotes by double-quotes first.

import json

upc_locations = []
with open('UPCList.txt', 'r') as file:
    for line in file:
        cleaned = line.strip()  # remove the line-break and any surrounding whitespace
        print(cleaned)
        valid_json = cleaned.replace("'", '"')  # replace single quotes by double quotes to have valid JSON strings
        array = json.loads(valid_json)
        print(array)
        for element in array:
            upc_locations.append(element)
print(upc_locations)
```
<p>Prints:</p>
```[2, 'banana', 2, 'bunch']
[2, u'banana', 2, u'bunch']
[2, u'banana', 2, u'bunch']
```
<h3>Tip: save your objects as JSON to a file</h3>
<p>When saving objects from your programs to a plain text-file it is recommended to use a standard format like CSV, XML or JSON.
So you can use standard-parsers to read it (back).</p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>import json

def save(list):
    with open("UPCList.txt", "w") as file:
    json.dump(list, file)
    # file.write('%s\n' % UPCsave)

def load():
    with open("UPCList.txt", "r") as file:
    return json.load(file)
</code>```

Note:

The out-commented line wrote the list in Python's string-representation (see precent-formatting %s). Thus we had to replace the double-quotes when reading.

The json-dump writes a list as JSON-array. This format is readable by many programs and tools and the defacto web-standard.

See also:

Write JSON objects to file using python

Reading JSON from a file?

Body:
I'm trying to create a food storage application that tracks the items put in a food storage facility and recalls them for the user. This is a very early prototype of the program, only capable of tracking the information locally, but I ran into some problems with it. So my apologies if this code is unreadable, I just can't find a solution to my problem explained below.

print("Food Storage Application V1.0 - LOCAL ONLY")
UPC_List = []
with open('UPCList.txt', 'r') as file:
    for UPCentry in file:
        location = UPCentry[:-1]
        UPC_List.append(location)
print(UPC_List)

global i
i = 0
UPC_Input = ''
UPC_Count = 0
while True:
    UPC_Found = False
    UPC_Input = input("Enter UPC or enter 'end' to quit: ")
    if UPC_Input == "end":
        with open("UPCList.txt", "w") as file:
            for UPCsave in UPC_List:
                file.write('%s\n' % UPCsave)
        break
    try:
        UPC_Input = int(UPC_Input)
    except ValueError as v:
        print(f"Input '{UPC_Input}' is not an acceptable UPC")
        continue

    # print(UPC_List) # for debugging

    def newProduct(UPC):
        global UPC_Count
        product_name = input(f"Enter name of item {UPC}: ")
        product_quantity = input(f"Enter quantity of item {UPC}: ")
        try:
            product_quantity = int(product_quantity)
        except ValueError as v:
            print("Invalid quantity. Please enter a number.")
            newProduct(UPC_Input)
        product_unit = input(f"Enter unit type (box, bunch, can, etc...) of item {UPC}: ")
        print(f"You have added: \n {product_name} \n {UPC} \n Quantity: {product_quantity} \n Unit: {product_unit}")
        UPC_List.insert(UPC_Count, [UPC, product_name, product_quantity, product_unit])
        UPC_Count += 1

    def existingProduct(UPC):
        for sublist in UPC_List:
            if str(UPC) in str(sublist):
                UPC = int(UPC)
                print(f"Position: {UPC_List.index(sublist)} {sublist.index(UPC)}")
                position = UPC_List.index(sublist)
                addition = input(f"Enter the number of items to add to '{UPC_List[position][1]}' (Default entry: +1): ")
                try:
                    addition = int(addition)
                except ValueError as v:
                    addition = 0

                if addition == 0:
                    UPC_List[position][2] += 1
                else:
                    UPC_List[position][2] += addition
                print(f"New Quantity for item '{UPC_List[position][1]}': {UPC_List[position][2]}")

    #Find if UPC Exists
    for UPC in UPC_List:
        if UPC[0] ==  UPC_Input:
            print("UPC Found")
            existingProduct(UPC_Input)
            UPC_Found = True
    if UPC_Found == False:
        newProduct(UPC_Input)

This is my code so far. I made a version of it without the read and writing to file lines and it worked great, but I'm stumped on getting the code to read a list from a file and use it in the code. It saves the list, but it won't retrieve it correctly. I found what I think is the problem by using that print(UPC_List) line, which prints ["[2, 'banana', 2, 'bunch']"] (that was a test entry I loaded into the file using the program). I think the problem lies in the double quotes on the outside of the list. This is a nested list, so those quotation marks lead to an index error when I try to access the list.

If this isn't enough info, I can try to provide more. I'm very new to python and coding in general so this was my best attempt at the script.

Body:
To reproduce and solve, we need a minimal reproducible example including

the input (file contents posted as plain-text in code-block formatting)

the minimal code to reproduce

Input file

Contents of UPCList.txt:

[2, 'banana', 2, 'bunch']

This is the string-representation of a list in Python (like str(list)). Probably it was written by your program.

Code

a minimal reproducible example (only first few lines to print the read list):

upc_locations = []
with open('UPCList.txt', 'r') as file:
    for upc in file:
        location = upc[:-1]
        upc_locations.append(location)
print(upc_locations)

Prints:

["[2, 'banana', 2, 'bunch']"]

Debug

add some debug print for each line read

upc_locations = []
with open('UPCList.txt', 'r') as file:
    for line in file:
        print(line)
        location = line[:-1]  # read all chars from line until last (excluding)
        print(location)
        upc_locations.append(location)
print(upc_locations)

Prints:

[2, 'banana', 2, 'bunch']

[2, 'banana', 2, 'bunch']
["[2, 'banana', 2, 'bunch']"]

Note:

the second empty-line is the line-break \n at the end of the file's line.

the first line contains something like a Python list with strings and numbers

the third line has removed the line-break.

Fix

The line can be parsed as JSON array. Therefore we need to replace the single-quotes by double-quotes first.

import json

upc_locations = []
with open('UPCList.txt', 'r') as file:
    for line in file:
        cleaned = line.strip()  # remove the line-break and any surrounding whitespace
        print(cleaned)
        valid_json = cleaned.replace("'", '"')  # replace single quotes by double quotes to have valid JSON strings
        array = json.loads(valid_json)
        print(array)
        for element in array:
            upc_locations.append(element)
print(upc_locations)

Prints:

[2, 'banana', 2, 'bunch']
[2, u'banana', 2, u'bunch']
[2, u'banana', 2, u'bunch']

Tip: save your objects as JSON to a file

When saving objects from your programs to a plain text-file it is recommended to use a standard format like CSV, XML or JSON.
So you can use standard-parsers to read it (back).

For example:

import json

def save(list):
    with open("UPCList.txt", "w") as file:
    json.dump(list, file)
    # file.write('%s\n' % UPCsave)

def load():
    with open("UPCList.txt", "r") as file:
    return json.load(file)

Note:

The out-commented line wrote the list in Python's string-representation (see precent-formatting %s). Thus we had to replace the double-quotes when reading.

The json-dump writes a list as JSON-array. This format is readable by many programs and tools and the defacto web-standard.

See also:

Write JSON objects to file using python

Reading JSON from a file?


问:
How can I show the number of items inside a shopping cart?
I have a shopping cart in one of my projects about e-commerces, and I want to show in the side of the cart icon the number of items on it. There's so many ways to make it, but honestly my brain is so blocked right now, and I need help...

I thought about looping through the array to get the "cant" key value of each object within it and then adding them together to display them next to the shopping cart, but I still don't know how to do it yet...

答:
You can use the reduce method.

const totalCount = items.reduce((total, currentItem) => (
   total + currentItem.cant
), 0)```


问:
Passing arguments to cypress request
I have the following method inside my support/index.ts file

```<code>function testSkipping(channel='US', test:any){
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test) // will print nothing

                if (response.body.feature.test) {
                    this.skip();
                }
            }
        }
    )
}
</code>```

I am calling this from my test as follows

```<code>before(() => {
    cy.testSkipping('US','SkipPaymentTests');
})
</code>```

I need to skip the test, when a the provided value of test are set to true. This code is not working. The value of test does not get replaced with SkipPaymentTests

the response of the call is

```<code>{
"SkipPaymentTests":true
}
</code>```

答:
Yo don't need template literals, using the variable directly in square brackets is enough

if (response.body.feature[test]) {
```

Title: Passing arguments to cypress request

Body:
I have the following method inside my support/index.ts file

function testSkipping(channel='US', test:any){
cy.log(test) // will print SkipPaymentTests

    cy.request({
        method: 'GET',
        url: Cypress.env('EndPoint') + 'features',
        headers: {
            'Channel': `${channel}`,
            'Subscription-Key': Cypress.env('sKey'),
        }
    }).then(function (response) {
            if (response?.status === 200) {
                expect(response.body.feature).to.exist;
            cy.log(response.body.featureFlags.test) // will print nothing

                if (response.body.feature.test) {
                    this.skip();
                }
            }
        }
    )
}

I am calling this from my test as follows

before(() => {
    cy.testSkipping('US','SkipPaymentTests');
})

I need to skip the test, when a the provided value of test are set to true. This code is not working. The value of test does not get replaced with SkipPaymentTests

the response of the call is

{
"SkipPaymentTests":true
}


问:
Problem with position:absolute on input
I have this code :

```<code><div class="areaButton">
    <input type="submit" value="Add">
</div>

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}
</code>```

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?

答:
put a height to the .areaButton div the same with the height of the input.

```<code>.areaButton
{
   height: <same height as the input>;
   ....
}
</code>```

or put another element inside the div

```<code><div class="areaButton">
    <input type="submit" value="Add">
    <span> </span>
</div>
</code>```

Title: Problem with position:absolute on input

Body:
I have this code :

    <input type="submit" value="Add">

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?

Body:
put a height to the .areaButton div the same with the height of the input.

.areaButton
{
   height: <same height as the input>;
   ....
}

or put another element inside the div

<div class="areaButton">
    <input type="submit" value="Add">
    <span>&nbsp;</span>
</div>


问:
Using python 3.10, but pylance still says "alternative syntax for unions requires python 3.10 or newer?"
So I just upgraded python to 3.10 for the new features, and when I do import sys; sys.version using the ipython console in vs code, it prints python version 3.10.0. But when I open an editor window and try to enter a type annotation using | for sum types, eg x:int|float, pylance highlights the | and says "alternative syntax for unions requires python 3.10 or newer."

Any thoughts?

Thanks.

答:
VS Code may be using a different version of python.  Make sure that the default python interpreter  (under settings, search for python) is python3.10
(if you are using linux, /usr/bin/python3.10 will probably work)</p>


问:
ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)
Does anyone know why this code doesn't work:

```<code>public class CollectionViewModel : ViewModelBase {
    public ObservableCollection<EntityViewModel> ContentList
    {
        get { return _contentList; }
        set
        {
            _contentList = value;
            RaisePropertyChanged("ContentList");
            //I want to be notified here when something changes..?
            //debugger doesn't stop here when IsRowChecked is toggled
        }
     }
}

public class EntityViewModel : ViewModelBase
{

    private bool _isRowChecked;

    public bool IsRowChecked
    {
        get { return _isRowChecked; }
        set { _isRowChecked = value; RaisePropertyChanged("IsRowChecked"); }
    }
}
</code>```

ViewModelBase containts everything for RaisePropertyChanged etc. and it's working for everything else except this problem..

答:
For me helps this trick - removeAt and insert to replace item, during this "Change" - events rise properly.</p>
```<code>private ObservableCollection<CollectionItem> collection = new ObservableCollection<CollectionItem>();

public void Update(CollectionItem newItem, CollectionItem old ) {
            int j = collection.IndexOf(old);
            collection.RemoveAt(j);
            collection.Insert(j, newComplexCondition);
        }
</code>```

Body:
Does anyone know why this code doesn't work:

public class CollectionViewModel : ViewModelBase {
    public ObservableCollection<EntityViewModel> ContentList
    {
        get { return _contentList; }
        set
        {
            _contentList = value;
            RaisePropertyChanged("ContentList");
            //I want to be notified here when something changes..?
            //debugger doesn't stop here when IsRowChecked is toggled
        }
     }
}

public class EntityViewModel : ViewModelBase
{

    private bool _isRowChecked;

    public bool IsRowChecked
    {
        get { return _isRowChecked; }
        set { _isRowChecked = value; RaisePropertyChanged("IsRowChecked"); }
    }
}

ViewModelBase containts everything for RaisePropertyChanged etc. and it's working for everything else except this problem..

Body:
For me helps this trick - removeAt and insert to replace item, during this "Change" - events rise properly.

private ObservableCollection<CollectionItem> collection = new ObservableCollection<CollectionItem>();

public void Update(CollectionItem newItem, CollectionItem old ) {
            int j = collection.IndexOf(old);
            collection.RemoveAt(j);
            collection.Insert(j, newComplexCondition);
        }


问:
Expectation Maximization using a Poisson likelihood function
I am trying to apply the expectation-maximization algorithm to estimate missing count data but all the packages in R, such as missMethods, assume a multivariate Gaussian distribution. How would I apply the expectation-maximization algorithm to estimate missing count data assuming a Poisson distribution?

Say we have data that look like this:

```<code>x <- c(100,  96,  79, 109, 111,  NA,  93,  95, 119,  90, 121,  96,  NA,
       NA,  85,  95, 110,  97,  87, 104, 101,  87,  87,  NA,  89,  NA,
       113,  NA,  95,  NA, 119, 115,  NA, 105,  NA,  80,  90, 108,  90,
       99, 111,  93,  99,  NA,  87,  89,  87, 126, 101, 106)
</code>```

Applying impute_EM using missMethods (missMethods::impute_EM(x, stochastic = FALSE)) gives an answer but the data are not continuous but discrete.

I understand that questions like these require a minimum, reproducible example, but I honestly do not know where to start. Even suggested reading to point me in the right direction would be helpful.

答:
Defining x0:

```<code>x0 <- x[!is.na(x)]
</code>```

The Jeffreys/reference prior for a Poisson distribution with mean lambda is 1/sqrt(lambda). From the observed values, this results in lambda having a gamma reference posterior with a shape parameter sum(x0) + 0.5 and a rate parameter 1/length(x0). You could take n samples of lambda with:

```<code>lambda <- rgamma(n, sum(x0) + 0.5, length(x0))
</code>```

Then sample n missing values (xm) with

```<code>xm <- rpois(n, lambda)
</code>```

Alternatively, since a Gamma-Poisson compound distribution can be formulated as a negative binomial (after integrating out lambda):

```<code>xm <- rnbinom(n, sum(x0) + 0.5, length(x0)/(length(x0) + 1L))
</code>```

As a function:

```<code>MI_poisson <- function(x, n) {
  x0 <- x[!is.na(x)]
  rbind(matrix(x0, ncol = n, nrow = length(x0)),
        matrix(rnbinom(n*(length(x) - length(x0)), sum(x0) + 0.5, length(x0)/(length(x0) + 1L)), ncol = n))
}
</code>```

This will return a matrix with n columns where each column contains the original vector x with all NA values imputed. Each column could be used separately in further analysis, then the results can be aggregated.

Body:
I am trying to apply the expectation-maximization algorithm to estimate missing count data but all the packages in R, such as missMethods, assume a multivariate Gaussian distribution. How would I apply the expectation-maximization algorithm to estimate missing count data assuming a Poisson distribution?

Say we have data that look like this:

x <- c(100,  96,  79, 109, 111,  NA,  93,  95, 119,  90, 121,  96,  NA,
       NA,  85,  95, 110,  97,  87, 104, 101,  87,  87,  NA,  89,  NA,
       113,  NA,  95,  NA, 119, 115,  NA, 105,  NA,  80,  90, 108,  90,
       99, 111,  93,  99,  NA,  87,  89,  87, 126, 101, 106)

Applying impute_EM using missMethods (missMethods::impute_EM(x, stochastic = FALSE)) gives an answer but the data are not continuous but discrete.

I understand that questions like these require a minimum, reproducible example, but I honestly do not know where to start. Even suggested reading to point me in the right direction would be helpful.

Body:
Defining x0:

x0 <- x[!is.na(x)]

The Jeffreys/reference prior for a Poisson distribution with mean lambda is 1/sqrt(lambda). From the observed values, this results in lambda having a gamma reference posterior with a shape parameter sum(x0) + 0.5 and a rate parameter 1/length(x0). You could take n samples of lambda with:

lambda <- rgamma(n, sum(x0) + 0.5, length(x0))

Then sample n missing values (xm) with

xm <- rpois(n, lambda)

Alternatively, since a Gamma-Poisson compound distribution can be formulated as a negative binomial (after integrating out lambda):

xm <- rnbinom(n, sum(x0) + 0.5, length(x0)/(length(x0) + 1L))

As a function:

MI_poisson <- function(x, n) {
  x0 <- x[!is.na(x)]
  rbind(matrix(x0, ncol = n, nrow = length(x0)),
        matrix(rnbinom(n*(length(x) - length(x0)), sum(x0) + 0.5, length(x0)/(length(x0) + 1L)), ncol = n))
}

This will return a matrix with n columns where each column contains the original vector x with all NA values imputed. Each column could be used separately in further analysis, then the results can be aggregated.


问:
Login using laravel and angular using jwt
I'm using angular and Laravel for user authentication followed this link :

https://www.positronx.io/laravel-jwt-authentication-tutorial-user-login-signup-api/
https://www.positronx.io/laravel-angular-token-based-authentication-with-jwt/

Authentication is working, this is login function :

```<code>onSubmit() {
    this.authService.signin(this.loginForm.value).subscribe(
      (result: any) => {
          this.responseHandler(result);
      },
      error => {
        this.errors = error.error;
          if(this.errors.error_message)
          {
            this.toastr.error('', this.errors.error_message);
          }
        // }
      },() => {
        this.authState.setAuthState(true);
        this.loginForm.reset()
        this.router.navigate(['user/dashboard']);
        this.toastr.success('Success', 'Logged In Successfully');
      }
    );
}

  // Handle response
  responseHandler(data :any ){
    this.token.handleData(data.access_token);
  }
}
</code>```

issue is when 401 is returned from the server then also it is executing this success block :

```<code>            this.authState.setAuthState(true);
            this.loginForm.reset()
            this.router.navigate(['user/dashboard']);
            this.toastr.success('Success', 'Logged In Successfully');
</code>```

In laravel i'm returning 401 :

```<code>  if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
        }
</code>```

答:
That's not success block. A subscribe takes 3 arguments.

1.Next

2.Error

3.Complete

No matter what happens to your observable(success or error), if you write a complete method it always will be called. so in order to prevent this, put those 4 lines in Next method

```<code>this.authService.signin(this.loginForm.value).subscribe(
    (result: any) => {
      this.responseHandler(result);
      this.authState.setAuthState(true);
      this.loginForm.reset()
      this.toastr.success('Success', 'Logged In Successfully');
      this.router.navigate(['user/dashboard']);
    },
    error => {
      this.errors = error.error;
      if(this.errors.error_message){
          this.toastr.error('', this.errors.error_message);
      }
 });
</code>```

Body:
I'm using angular and Laravel for user authentication followed this link :

https://www.positronx.io/laravel-jwt-authentication-tutorial-user-login-signup-api/
https://www.positronx.io/laravel-angular-token-based-authentication-with-jwt/

Authentication is working, this is login function :

onSubmit() {
    this.authService.signin(this.loginForm.value).subscribe(
      (result: any) => {
          this.responseHandler(result);
      },
      error => {
        this.errors = error.error;
          if(this.errors.error_message)
          {
            this.toastr.error('', this.errors.error_message);
          }
        // }
      },() => {
        this.authState.setAuthState(true);
        this.loginForm.reset()
        this.router.navigate(['user/dashboard']);
        this.toastr.success('Success', 'Logged In Successfully');
      }
    );
}

  // Handle response
  responseHandler(data :any ){
    this.token.handleData(data.access_token);
  }
}

issue is when 401 is returned from the server then also it is executing this success block :

            this.authState.setAuthState(true);
            this.loginForm.reset()
            this.router.navigate(['user/dashboard']);
            this.toastr.success('Success', 'Logged In Successfully');

In laravel i'm returning 401 :

  if (! $token = auth()->attempt($validator->validated())) {
            return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
        }

Body:
That's not success block. A subscribe takes 3 arguments.

1.Next

2.Error

3.Complete

No matter what happens to your observable(success or error), if you write a complete method it always will be called. so in order to prevent this, put those 4 lines in Next method

this.authService.signin(this.loginForm.value).subscribe(
    (result: any) => {
      this.responseHandler(result);
      this.authState.setAuthState(true);
      this.loginForm.reset()
      this.toastr.success('Success', 'Logged In Successfully');
      this.router.navigate(['user/dashboard']);
    },
    error => {
      this.errors = error.error;
      if(this.errors.error_message){
          this.toastr.error('', this.errors.error_message);
      }
 });


问:
How to update the Google Cloud scheduler with Python api
I am trying to update google scheduler job.But,it does not work well.How do I this?
Now I understand what problem is.The problem is that the option class is wrong.
How should I write this place?

Target(topic_name="projects/aaa/topics/bbb",data="test".encode("utf-8"))

The error message.

TypeError: Parameter to MergeFrom() must be instance of same class: expected google.cloud.scheduler.v1.PubsubTarget got PubsubTarget.

my code

```<code>import os
from google.cloud import scheduler_v1
from google.cloud.scheduler_v1 import PubsubTarget as Target

from google.protobuf import field_mask_pb2

pub = Target(topic_name="projects/aaa/topics/bbb",data="test".encode("utf-8"))

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './test.json'
client = scheduler_v1.CloudSchedulerClient()
job = { 'name': "projects/aaa/locations/us-central1/jobs/test",
       "description": "c",
       "schedule": "59 * * * *",
       "pubsub_target":pub
        }
update_mask = field_mask_pb2.FieldMask(paths=['description','schedule','pubsub_target'])

response = client.update_job(job=job,update_mask=update_mask)
print(response)

</code>```

答:
```<code>   import os
   from google.cloud import scheduler_v1
   from google.cloud.scheduler_v1 import PubsubTarget as Target

   os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './test.json'
   client = scheduler_v1.CloudSchedulerClient()

   job = Job()
   job.name = 'projects/aaa/locations/us-central1/jobs/test'
   job.description = 'c'
   job.schedule = '59 * * * *'
   job.time_zone = 'America/Los_Angeles'
   pt = Target()
   pt.topic_name = 'projects/aaa/topics/bbb'
   pt.data = 'test'.encode('utf-8')
   job.pubsub_target = pt
   job = client.create_job(parent='projects/aaa/locations/us-central1', job=job)
</code>```

Body:
I am trying to update google scheduler job.But,it does not work well.How do I this?
Now I understand what problem is.The problem is that the option class is wrong.
How should I write this place?

Target(topic_name="projects/aaa/topics/bbb",data="test".encode("utf-8"))

The error message.

TypeError: Parameter to MergeFrom() must be instance of same class: expected google.cloud.scheduler.v1.PubsubTarget got PubsubTarget.

my code

import os
from google.cloud import scheduler_v1
from google.cloud.scheduler_v1 import PubsubTarget as Target

from google.protobuf import field_mask_pb2

pub = Target(topic_name="projects/aaa/topics/bbb",data="test".encode("utf-8"))

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './test.json'
client = scheduler_v1.CloudSchedulerClient()
job = { 'name': "projects/aaa/locations/us-central1/jobs/test",
       "description": "c",
       "schedule": "59 * * * *",
       "pubsub_target":pub
        }
update_mask = field_mask_pb2.FieldMask(paths=['description','schedule','pubsub_target'])

response = client.update_job(job=job,update_mask=update_mask)
print(response)


问:
How to make a tkinter gui and display printed value
This is how far I came.... I got the winner know I want to display it on the gui here is my code:
I tried many google searches and found none I hoped that someone may help me</p>
```<code>import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'
class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = runn)
        run.pack(pady= 5, padx = 5)

def runn():
    PEOPLE = [
  'Juan',
  'Owen'
]

    print("\n\n")
    bar = Bar('And the winner is...', max=2)
    for i in range(2):
        [x for x in range(999999)]  # short pause...
        bar.next()
    bar.finish()
    print("\n\n\t{}!\n\n".format(random.choice(PEOPLE)))
    print("-" * 60 + "\n")

app = Application()
app.mainloop()
</code>```

答:
I recommend you to read more in the Tkinter docs: https://docs.python.org/3/library/tk.html

You should also start using the grid GUI and not the stack GUI. The grid version is newer and easier to learn and modify.

It should be enough for you to import only:
 from tkinter import *
 from tkinter.ttk import *.

Here is a full description how to make a progressbar from Stackoverflow: tkinter gui with progress bar

There is many ways to display your code: showbox'es, labels, textboxes etc. So read through the docs and find the one that fits your widget.

Body:
This is how far I came.... I got the winner know I want to display it on the gui here is my code:
I tried many google searches and found none I hoped that someone may help me

import tkinter as tk
import random
from progress.bar import Bar
backroundcolor = '#C46C6C'
class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('500x500')
        self.title('TheXoGenie')
        self.configure(bg=backroundcolor)
        title = tk.Label(self, text="Welcome to TheXoGenie", font='Helvetica 18 bold', bg=backroundcolor)
        title.pack(pady= 2, padx= 2)
        run = tk.Button(self, text ="Run", command = runn)
        run.pack(pady= 5, padx = 5)

def runn():
    PEOPLE = [
  'Juan',
  'Owen'
]

    print("\n\n")
    bar = Bar('And the winner is...', max=2)
    for i in range(2):
        [x for x in range(999999)]  # short pause...
        bar.next()
    bar.finish()
    print("\n\n\t{}!\n\n".format(random.choice(PEOPLE)))
    print("-" * 60 + "\n")

app = Application()
app.mainloop()


问:
imagePicker Flutter can't convert image to FIle
i wanna convert my photo from gallery to File i need that beacause i will take the image to firebase when i try convert to File, it will throw me error The argument type 'String' can't be assigned to the parameter type 'List'

My code:

```<code>File? _imageFile;
final picker = ImagePicker();

Future  getImage() async{
 final  photo = await _picker.pickImage(source: ImageSource.gallery);
_imageFile=File(photo!.path,""); #that line give error
 }
</code>```

EDIT: I DELETE "import 'dart:html';" and it work

答:
To pick image

 final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
```
<p>And use like</p>
<pre class="lang-dart prettyprint-override"><code>if(pickedFile !=null) Image.file(File(pickedFile.path)),
</code>```

Body:
i wanna convert my photo from gallery to File i need that beacause i will take the image to firebase when i try convert to File, it will throw me error The argument type 'String' can't be assigned to the parameter type 'List'

My code:

File? _imageFile;
final picker = ImagePicker();

Future  getImage() async{
 final  photo = await _picker.pickImage(source: ImageSource.gallery);
_imageFile=File(photo!.path,""); #that line give error
 }

EDIT: I DELETE "import 'dart:html';" and it work

Body:
To pick image

 final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );

And use like

if(pickedFile !=null) Image.file(File(pickedFile.path)),


问:
Flutter :- How to keep centre three words vertically in details page? Below i've attached a image for your reference
eg: details about the questions ........................................................... i want to keep three words(text) vertically align in centre. when i try this not able to display three words vertically centre. I've tried with one word work fine but when i try three words not able to display.Below I've attached a image for reference.I want to display like this image for details page

Details page :

```<code>import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:odia_rasiphala/HomePage.dart';
import 'dart:convert';

class DetailsPage extends StatelessWidget {
  const DetailsPage({Key? key, required this.title, required this.main_img, required this.content}) : super(key: key);
  // Declare a field that holds the strings passed to this class.
  final String title;
  final String main_img;
  final String content;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async => false,
        child: new Scaffold(
          appBar: new AppBar(
            title: new Text('ଆଜିର ରାଶିଫଳ'),
            leading: new IconButton(
              icon: new Icon(Icons.arrow_back_outlined),
              onPressed: () => Navigator.pushReplacement(context,
                  new MaterialPageRoute(builder: (context) => HomePage())),
            ),
            actions: [
              IconButton(
                onPressed: () {},
                icon: Icon(Icons.share),
              ),
            ],
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.network(
                main_img,
                width: 200.0,
                height: 200.0,
              ),
              new Center(
                child: new Text(title,
                    style: TextStyle(color: Colors.black, fontSize: 17)),
              )
            ],
          ),
        ));
  }
}
</code>```

答:
use replace function:</p>
```<code>String str = "Some useless words";

String newStr = str.replaceAll(' ', '\n'));
</code>```

Body:
eg: details about the questions ........................................................... i want to keep three words(text) vertically align in centre. when i try this not able to display three words vertically centre. I've tried with one word work fine but when i try three words not able to display.Below I've attached a image for reference.I want to display like this image for details page

Details page :

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:odia_rasiphala/HomePage.dart';
import 'dart:convert';

class DetailsPage extends StatelessWidget {
  const DetailsPage({Key? key, required this.title, required this.main_img, required this.content}) : super(key: key);
  // Declare a field that holds the strings passed to this class.
  final String title;
  final String main_img;
  final String content;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async => false,
        child: new Scaffold(
          appBar: new AppBar(
            title: new Text('ଆଜିର ରାଶିଫଳ'),
            leading: new IconButton(
              icon: new Icon(Icons.arrow_back_outlined),
              onPressed: () => Navigator.pushReplacement(context,
                  new MaterialPageRoute(builder: (context) => HomePage())),
            ),
            actions: [
              IconButton(
                onPressed: () {},
                icon: Icon(Icons.share),
              ),
            ],
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.network(
                main_img,
                width: 200.0,
                height: 200.0,
              ),
              new Center(
                child: new Text(title,
                    style: TextStyle(color: Colors.black, fontSize: 17)),
              )
            ],
          ),
        ));
  }
}

Body:
use replace function:

String str = "Some useless words";

String newStr = str.replaceAll(' ', '\n'));


问:
How to properly post url in android with java using HttpURLConnection
I try to use HttpURLConnection to send a post request to my local (xampp) server with an url like this http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2 , the server php file take param in url and send data to mysql database .

The url works fine on postman agent , and even another get method request works smooth in the android application .

Yet when i try the post method with following code :

```<code>public void postOrder() {
        TextView tv = findViewById(R.id.tv1);
        Thread t = new Thread( new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    String link = "http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2";
                    URL url = new URL(link);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setReadTimeout(10000 /*ms*/);
                    conn.setConnectTimeout(15000 /*ms*/);
                    conn.connect();
                }
                catch (IOException e) {
                    Log.d("HTTP error: ", e.toString());
                }
                finally {
                    conn.disconnect();
                }
            }
        } );
        t.start();
}
</code>```

It never sent the url and thus no data is stored to database .

And with 6 hours of trial and error , google and searching , i added this line of code :

```<code>InputStream is = conn.getInputStream();
</code>```

And it finally works .
Please answer me why it only works after adding this line of code , what does it do ? I thought the url is triggered right after conn.connect();

答: Calling connect() only connects, but it doesn't send anything yet. Call getResponseCode() to force the request to be sent. That method is safer than getInputStream() which will throw an exception if the response is not a 2xx (in which case you'd need getErrorStream()).

Body:
I try to use HttpURLConnection to send a post request to my local (xampp) server with an url like this http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2 , the server php file take param in url and send data to mysql database .

The url works fine on postman agent , and even another get method request works smooth in the android application .

Yet when i try the post method with following code :

public void postOrder() {
        TextView tv = findViewById(R.id.tv1);
        Thread t = new Thread( new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    String link = "http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2";
                    URL url = new URL(link);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setReadTimeout(10000 /*ms*/);
                    conn.setConnectTimeout(15000 /*ms*/);
                    conn.connect();
                }
                catch (IOException e) {
                    Log.d("HTTP error: ", e.toString());
                }
                finally {
                    conn.disconnect();
                }
            }
        } );
        t.start();
}

It never sent the url and thus no data is stored to database .

And with 6 hours of trial and error , google and searching , i added this line of code :

InputStream is = conn.getInputStream();

And it finally works .
Please answer me why it only works after adding this line of code , what does it do ? I thought the url is triggered right after conn.connect();


问:
Is there a name for the feature of an IDE that allows you to execute code in the command line during debugging?
For example, in MATLAB you can set a breakpoints, execute up to the breakpoint, and then try things out in the command window using the variables in the current scope at that point in the program. It is much easier and faster to iron out bugs this way.

Is there a name given to this feature of an IDE? What allows this in an IDE? Are there other IDEs and/or programming languages that feature this?

答:
If you have to use command line, gdb and breakpoint meet your requirement.

If you can use UI, vscode is a good option for many languages: https://code.visualstudio.com/


问:
Alternative routines when using Mercurial Hg
I would like to get your opinion on which of the following routines should I use, or which of them is more desirable, when using Mercurial. Suppose that I have the latest code.

First routine is following:

Do my work

hg commit

Repeat steps 1 and 2 if needed

When I'm ready to push I hg pull, hg update

hg merge, hg commit

hg push

Second is:

Do my work

when I'm ready to commit I hg pull, hg update

hg commit, hg push

The thing is that, as far as I know the first alternative is the one which most of the developers (should) use because, unlike in second option of usage, it provides the opportunity to use local repository, as it is a normal thing for DVCS.

My colleagues encourage me to use the second way, because that way I avoid branching and later possible problems with merging (because in past, somehow, they had such problems), so I stay on trunk development line.
I guess that the first option is the option that should be preferable because merging is something that shouldn't be afraid of in DVCS, unlike in CVCS, and it gives me the opportunity of using local repository.

答:
There is not any difference in the work you will be doing in both cases:

with the first workflow, you will do a merge in step 5.

with the second workflow, you do the exact same merge as part of the update in step 2.

The first workflow feels safer to many since you're working on already committed work. This means that it's trivial to get back to a clean state if the merge turns out to be complicated: hg update -C ..

But you can actually get your original files back even with the second workflow: hg resolve --all --tool internal:local will redo the merge that hg update started and select the original version for all files.

The real difference is that the first workflow better shows what actually happened. With that workflow you can present your change in smaller and more logical steps. That helps a lot when your colleges try to understand what you did (code reviews) and with future debugging (with hg bisect).

You can get the best of both world with hg rebase. That lets you make small and logical commits and then finally move those commits on top of the work done by your colleges. There wont be a merge changeset in that case -- nice and rich linear history.

So if you have this history after the pull:

```<code>... [a] --- [b] --- [x] --- [y] --- [z]
               \
                [d] --- [e]
</code>```

where you have created x to z, then a normal merge would create this history:

```<code>... [a] --- [b] --- [x] --- [y] --- [z]
               \                       \
                [d] --- [e] ----------- [f]
</code>```

With a rebase you get

```<code>... [a] --- [b] --- [d] --- [e] --- [x'] --- [y'] --- [z']
</code>```

where x' to z' are the rebased versions of x to z (different changeset IDs because they have different ancestors).

I use rebase like this all the time and I feel it gives the best overall history. Just remember not to rebase changesets that have already been made public: rebasing modifies the changesets, but if the changesets are already public, then it's difficult for you to modify the other copies. The result is duplicate changesets and confusion.

Body:
There is not any difference in the work you will be doing in both cases:

with the first workflow, you will do a merge in step 5.

with the second workflow, you do the exact same merge as part of the update in step 2.

The first workflow feels safer to many since you're working on already committed work. This means that it's trivial to get back to a clean state if the merge turns out to be complicated: hg update -C ..

But you can actually get your original files back even with the second workflow: hg resolve --all --tool internal:local will redo the merge that hg update started and select the original version for all files.

The real difference is that the first workflow better shows what actually happened. With that workflow you can present your change in smaller and more logical steps. That helps a lot when your colleges try to understand what you did (code reviews) and with future debugging (with hg bisect).

You can get the best of both world with hg rebase. That lets you make small and logical commits and then finally move those commits on top of the work done by your colleges. There wont be a merge changeset in that case -- nice and rich linear history.

So if you have this history after the pull:

... [a] --- [b] --- [x] --- [y] --- [z]
               \
                [d] --- [e]

where you have created x to z, then a normal merge would create this history:

... [a] --- [b] --- [x] --- [y] --- [z]
               \                       \
                [d] --- [e] ----------- [f]

With a rebase you get

... [a] --- [b] --- [d] --- [e] --- [x'] --- [y'] --- [z']

where x' to z' are the rebased versions of x to z (different changeset IDs because they have different ancestors).

I use rebase like this all the time and I feel it gives the best overall history. Just remember not to rebase changesets that have already been made public: rebasing modifies the changesets, but if the changesets are already public, then it's difficult for you to modify the other copies. The result is duplicate changesets and confusion.


问:
VBA for a matrix with count of co-occurrences
I am trying to produce a co-occurrence matrix in an Excel File. My data looks like this:

```<code>person1  A
person1  B
person2  A
person2  C
person2  D
person3  A
person3  B
person4  A
person4  C
...
</code>```

But what I need is essentially a co-occurrence matrix that looks like this (it counts how often any of the combos between A-D occured):

```<code>    A   B   C   D
A   0   2   2   1
B   2   0   0   0
C   2   0   0   1
D   1   0   1   0
</code>```

I unfortunately cannot find a useful VBA or Macro or any other approach (I am a beginner with VBA) - so if you have any idea how I could do this, please share.
I tried doing a Pivot but I cannot put the second column of the data on both of the two axis.
In R I would do this with crossprod() but I cannot get the data out of a save environment and cannot install R there either...
Many thanks!

答:
Use a dictionary with column B as key, collection of column A as value. Iterate the combinations and count the matches. Results written to Sheet2.

Option Explicit

Sub CoOccurence()

    Dim dict As Object, k, ar, m, v1, v2
    Set dict = CreateObject("Scripting.Dictionary")

    Dim lastrow As Long, i As Long, j As Long
    Dim a As String, b As String

    With Sheet1
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        For i = 1 To lastrow
            a = .Cells(i, "A")
            b = .Cells(i, "B")

            If Not dict.exists(b) Then
                dict.Add b, New Collection
            End If
            dict(b).Add a
        Next
    End With

    ' results
    ar = dict.keys
    i = dict.Count
    ReDim m(1 To i, 1 To i)
    With Sheet2
        For i = 1 To UBound(m)
            ' headers
            .Cells(1, i + 1) = ar(i - 1)
            .Cells(i + 1, 1) = ar(i - 1)
            ' counts
            For j = 1 To UBound(m, 2)
                a = ar(i - 1)
                b = ar(j - 1)
                m(i, j) = 0
                If a <> b Then
                    For Each v1 In dict(a)
                       For Each v2 In dict(b)
                           If v1 = v2 Then m(i, j) = m(i, j) + 1
                       Next
                    Next
                End If
               .Cells(i + 1, j + 1) = m(i, j)
            Next
        Next
    End With
    MsgBox "Done"
End Sub
```

Body:
I am trying to produce a co-occurrence matrix in an Excel File. My data looks like this:

person1  A
person1  B
person2  A
person2  C
person2  D
person3  A
person3  B
person4  A
person4  C
...

But what I need is essentially a co-occurrence matrix that looks like this (it counts how often any of the combos between A-D occured):

    A   B   C   D
A   0   2   2   1
B   2   0   0   0
C   2   0   0   1
D   1   0   1   0

I unfortunately cannot find a useful VBA or Macro or any other approach (I am a beginner with VBA) - so if you have any idea how I could do this, please share.
I tried doing a Pivot but I cannot put the second column of the data on both of the two axis.
In R I would do this with crossprod() but I cannot get the data out of a save environment and cannot install R there either...
Many thanks!


问:
Sequelize fields must be specified through options.field error
So I created a table and modified it later on to add a foreign key. I followed this https://stackoverflow.com/a/47428160/12539780 but it gives me an error that says

"ERROR: Fields must be specified through options.fields"

I am using sequelize ^6.6.5 and my node version is 14.17.6 my code is provided below

```<code>module.exports = {
  up: async (queryInterface, Sequelize) =>
    Promise.all([
      await queryInterface.addColumn('bonus_transactions', 'wallet_id', {
        type: Sequelize.INTEGER.UNSIGNED,
        allowNull: false,
        after: 'order_id'
      }),
      await queryInterface.addConstraint('bonus_transactions', ['wallet_id'], {
        type: 'FOREIGN KEY',
        name: 'FK_bonus_transactions_wallet_id',
        references: {
          table: 'wallets',
          field: 'id'
        },
        onDelete: 'CASCADE'
      })
    ]),
  down: queryInterface => queryInterface.removeColumn('bonus_transactions', 'wallet_id')
</code>```

could this be because of the sequelize version? I search through the v6 documentation and there doesn't seem to be any implementation that is similar to this.

答:
Fields in addConstaint should be indicated in fields option like this:

queryInterface.addConstraint('bonus_transactions',{
        type: 'FOREIGN KEY',
        name: 'FK_bonus_transactions_wallet_id',
        fields: ['wallet_id'],
        references: {
          table: 'wallets',
          field: 'id'
        },
        onDelete: 'CASCADE'
      })
```

Body:
So I created a table and modified it later on to add a foreign key. I followed this https://stackoverflow.com/a/47428160/12539780 but it gives me an error that says

"ERROR: Fields must be specified through options.fields"

I am using sequelize ^6.6.5 and my node version is 14.17.6 my code is provided below

module.exports = {
  up: async (queryInterface, Sequelize) =>
    Promise.all([
      await queryInterface.addColumn('bonus_transactions', 'wallet_id', {
        type: Sequelize.INTEGER.UNSIGNED,
        allowNull: false,
        after: 'order_id'
      }),
      await queryInterface.addConstraint('bonus_transactions', ['wallet_id'], {
        type: 'FOREIGN KEY',
        name: 'FK_bonus_transactions_wallet_id',
        references: {
          table: 'wallets',
          field: 'id'
        },
        onDelete: 'CASCADE'
      })
    ]),
  down: queryInterface => queryInterface.removeColumn('bonus_transactions', 'wallet_id')

could this be because of the sequelize version? I search through the v6 documentation and there doesn't seem to be any implementation that is similar to this.


问:
Redirection to microsoft teams app from browser
I'm working on angular project and I have a teams icon in .html. I need to redirect from browser to the teams app when the icon is clicked. Similar functionality is implemented for mail and phone number. When a user clicks on phone icon or mail icon, I'm doing this:

```<code>window.location.href = 'tel: 456****';
windo.location.href = 'mailto: example@gmail.com'
</code>```

Tried for a while to know what should be assigned to window.location.href so that the redirection happens to teams app and didn't find any way for it. How do I redirect to teams using window location?

答:
Take a look at the official documentation here:

https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links#deep-linking-to-an-audio-or-audio-video-call

There's examples for both if you have an email address and if you have a phone number. (You'll need that 4: part before the phone number.)

```<code>https://teams.microsoft.com/l/call/0/0?users={emailaddress}
https://teams.microsoft.com/l/call/0/0?users=4:{phonenumber}
</code>```

Body:
I'm working on angular project and I have a teams icon in .html. I need to redirect from browser to the teams app when the icon is clicked. Similar functionality is implemented for mail and phone number. When a user clicks on phone icon or mail icon, I'm doing this:

window.location.href = 'tel: 456****';
windo.location.href = 'mailto: example@gmail.com'

Tried for a while to know what should be assigned to window.location.href so that the redirection happens to teams app and didn't find any way for it. How do I redirect to teams using window location?

Body:
Take a look at the official documentation here:

https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links#deep-linking-to-an-audio-or-audio-video-call

There's examples for both if you have an email address and if you have a phone number. (You'll need that 4: part before the phone number.)

https://teams.microsoft.com/l/call/0/0?users={emailaddress}
https://teams.microsoft.com/l/call/0/0?users=4:{phonenumber}


问:
Why are shader-stage input variables not writable
The GLSLangSpec.3.30 says:

Values from the previous pipeline stage are copied into input
variables at the beginning of shader execution. Variables declared as in or centroid in may not be written
to during shader execution.

If they are copied in and the original values are left untouched, why are input variables not writable?

答:
The standard describes behavior, not implementation. Thus, the statement about being "copied in" merely describes the apparent effect, not what the actual hardware does.

Indeed, the whole point of these two specific requirements is to allow implementations to not copy inputs into specific variables. Or rather, to allow VS implementations to avoid having to allocate storage for a variable if it doesn't need to. If an implementation wants to make a use of a shader-stage input variable read from the buffer directly (or a cache), it can do so.

Now yes, you can still have that implementation with the ability to modify in variables. But the compiler would have to check to see if the shader does modify them. So it'd be a lot easier to implement such optimizations (where relevant) if the compiler didn't have to check to see if you're doing something you shouldn't be doing.


问:
Escaping strings in bash
I have this simple bash script:

```<code>#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi
</code>```

The script returns:

```<code>./script.sh: line 3: [ 0: command not found
</code>```

What did i do wrong?

答:
Change the if to:

```<code>if [ "$isRunning" -eq "0" ]; then
</code>```

Title: Escaping strings in bash

Body:
I have this simple bash script:

#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi

The script returns:

./script.sh: line 3: [ 0: command not found

What did i do wrong?

Body:
Change the if to:

if [ "$isRunning" -eq "0" ]; then