问:
A get or set accessor is expected
```<code>using System.Collections.Generic;
using UnityEngine;

public class playercombat : MonoBehaviour
{

    public Animator animator;
    public Transform attackPoint;
    public float attackRange = 0.5f;
    public LayerMask enemyLayers;

    public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }

    // Update is called once per frame
    void Update()
    {
       if (Input.GetKeyDown(KeyCode.Q))
        {
            Attack();
        }
    }
    void Attack()
    {
        animator.SetTrigger("Attack");

        Physics2D.OverlapCircleAll(attackPoint.postion, AttackRange, enemyLayers);

        foreach (Collider2D enemy in hitEnemies)
        {
            Debug.lot("Hit" + enemy.name);
        }
    }
    void OnDrawGizmosSelected()
    {
        if (attackPoint == null)
            return;
        Gizmos.DrawWireSphere(attackPoint.position, AttackRange);
    }
}

</code>```

A get or set accesssor expected. What does that mean and how should I fix it?
Assets\playercombat.cs(13,52): error CS1014: A get or set accessor expected
Assets\playercombat.cs(13,60): error CS1014: A get or set accessor expected

答:
Typo?

```<code>public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }
</code>```

should be

```<code>public float AttackRange { get => attackRange; set => attackRange = 0.5f; }
</code>```

Title: A get or set accessor is expected

Body:
using System.Collections.Generic;
using UnityEngine;

public class playercombat : MonoBehaviour
{

    public Animator animator;
    public Transform attackPoint;
    public float attackRange = 0.5f;
    public LayerMask enemyLayers;

    public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }

    // Update is called once per frame
    void Update()
    {
       if (Input.GetKeyDown(KeyCode.Q))
        {
            Attack();
        }
    }
    void Attack()
    {
        animator.SetTrigger("Attack");

        Physics2D.OverlapCircleAll(attackPoint.postion, AttackRange, enemyLayers);

        foreach (Collider2D enemy in hitEnemies)
        {
            Debug.lot("Hit" + enemy.name);
        }
    }
    void OnDrawGizmosSelected()
    {
        if (attackPoint == null)
            return;
        Gizmos.DrawWireSphere(attackPoint.position, AttackRange);
    }
}

A get or set accesssor expected. What does that mean and how should I fix it?
Assets\playercombat.cs(13,52): error CS1014: A get or set accessor expected
Assets\playercombat.cs(13,60): error CS1014: A get or set accessor expected

Body:
Typo?

public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }

should be

public float AttackRange { get => attackRange; set => attackRange = 0.5f; }


来源: stackexchange

问:
How to make whole screen scrollable in flutter
This is my Code for Body of Scaffold of the Screen

```<code>Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  VideoPlay(widget: widget),

                  TitleVideo(widget: widget),
                  Padding(
                    padding: const EdgeInsets.only(top: 1.0, left: 10),
                    child: Opacity(
                      opacity: 0.5,
                      child: Row(
                        children: <Widget>[
                          Text(widget.video.viewCount + " views "),
                          SizedBox(
                            width: 5,
                            child: Text("|"),
                          ),
                          Text(" ${timeago.format(widget.video.timestamp)}"),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  IconRow(
                    video: widget.video,
                  ),
                  //User Panel
                  subscribe_panel(),
                  SizedBox(
                    height: 310,
                    child: suggestedVideo(),
                  ),

                  // Suggestions list
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
</code>```

The "suggestion list" Contains This Code

```<code>    class suggestedVideo extends StatelessWidget {
    const suggestedVideo({Key? key,}) : super(key: key);
    @override
    Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: suggestedVideos.length,
      itemBuilder: (context, index) => VideoCard(
        video: suggestedVideos[index],
        press: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      VideoScreen(video: suggestedVideos[index])));
        },
      ),
    );
  }
 }
</code>```

but The Screen is only scrolling the ListView Builder part rather than the whole screen,
I am trying to recreate youtube UI and for the VideoScrolling screen , I want to scroll the screen , by keeping the video at top and Every other widget being scrollable.

答: You can wrap your top-most Container with SingleChildScrollView, this will make all of your Widget scrollable, also you can replace SingleChildScrollView(child: Column(...  with ListView(...), it will give you same result

ContentLicense: CC BY-SA 4.0

Body:
This is my Code for Body of Scaffold of the Screen

Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  VideoPlay(widget: widget),

                  TitleVideo(widget: widget),
                  Padding(
                    padding: const EdgeInsets.only(top: 1.0, left: 10),
                    child: Opacity(
                      opacity: 0.5,
                      child: Row(
                        children: <Widget>[
                          Text(widget.video.viewCount + " views "),
                          SizedBox(
                            width: 5,
                            child: Text("|"),
                          ),
                          Text(" ${timeago.format(widget.video.timestamp)}"),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  IconRow(
                    video: widget.video,
                  ),
                  //User Panel
                  subscribe_panel(),
                  SizedBox(
                    height: 310,
                    child: suggestedVideo(),
                  ),

                  // Suggestions list
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

The "suggestion list" Contains This Code

    class suggestedVideo extends StatelessWidget {
    const suggestedVideo({Key? key,}) : super(key: key);
    @override
    Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: suggestedVideos.length,
      itemBuilder: (context, index) => VideoCard(
        video: suggestedVideos[index],
        press: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      VideoScreen(video: suggestedVideos[index])));
        },
      ),
    );
  }
 }

but The Screen is only scrolling the ListView Builder part rather than the whole screen,
I am trying to recreate youtube UI and for the VideoScrolling screen , I want to scroll the screen , by keeping the video at top and Every other widget being scrollable.


问:
How to write case in Switch else statement in javavscript?
//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:</p>
```<code>If the first character in string  is in the set {aeiou}, then return A.
If the first character in string  is in the set {bcdfg}, then return B.
If the first character in string  is in the set {hjklm},, then return C.
If the first character in string  is in the set {npqrstvwxyz}, then return D.

I am trying to implement the above scenarion and to dthis I have written the following code.

//Here is my code
    function getLetter(s) {
        let letter;
        // Write your code here

            switch (s) {
            case s.match(/[aeiou]/g).includes(s[0]):
            letter = 'A'
            break;

            case s.match(/[bcdfg]/g).includes(s[0]):
            letter = 'B'
            break;

            case s.match(/[hjklm]/g).includes(s[0]):
            letter = 'C';
            break;

            case s.match(/[npqrstvwxyz]/g).includes(s[0]):
            letter = 'D';
            break;
            default:
            console.log("hello")
        }
        return letter
    }

The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.
</code>```

答:
Based on how you're using this, you actually want to switch (true) and not switch (s)

i.e. when you have a case y in a switch (x), the test being done is x === y; so you want to do true === some.test()

const s = 'a';

switch (true) {
  case /a/.test(s):
    console.log('first match');
    break;
  case /b/.test(s):
    console.log('second match');
    break;
  default:
    console.log('no match');
    break;
}
```
<p>Will log <code>first match</code> because</p>
<ul>
<li><code>/a/.test('a')</code> is <code>true</code></li>
<li>and <code>true /* from switch */ === true /* from case test */</code></li>
</ul>
<hr />
<p>Note that in most cases <code>switch</code> can also be written as <code>if..else if..else</code>.<br />
Base your decision on which to use by which is the most readable (err on the side of <code>if</code> patterns)</p>
<p>The above example written as an <code>if</code> might look like this</p>
<pre class="lang-js prettyprint-override"><code>const s = 'a';

if (/a/.test(s)) {
  console.log('first match');
} else if (/b/.test(s)) {
  console.log('second match');
} else {
  console.log('no match');
}
</code>```

Body:
//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:

If the first character in string  is in the set {aeiou}, then return A.
If the first character in string  is in the set {bcdfg}, then return B.
If the first character in string  is in the set {hjklm},, then return C.
If the first character in string  is in the set {npqrstvwxyz}, then return D.

I am trying to implement the above scenarion and to dthis I have written the following code.

//Here is my code
    function getLetter(s) {
        let letter;
        // Write your code here

            switch (s) {
            case s.match(/[aeiou]/g).includes(s[0]):
            letter = 'A'
            break;

            case s.match(/[bcdfg]/g).includes(s[0]):
            letter = 'B'
            break;

            case s.match(/[hjklm]/g).includes(s[0]):
            letter = 'C';
            break;

            case s.match(/[npqrstvwxyz]/g).includes(s[0]):
            letter = 'D';
            break;
            default:
            console.log("hello")
        }
        return letter
    }

The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.

Body:
Based on how you're using this, you actually want to switch (true) and not switch (s)

i.e. when you have a case y in a switch (x), the test being done is x === y; so you want to do true === some.test()

const s = 'a';

switch (true) {
  case /a/.test(s):
    console.log('first match');
    break;
  case /b/.test(s):
    console.log('second match');
    break;
  default:
    console.log('no match');
    break;
}

Will log first match because

/a/.test('a') is true

and true /* from switch */ === true /* from case test */

Note that in most cases switch can also be written as if..else if..else.

Base your decision on which to use by which is the most readable (err on the side of if patterns)

The above example written as an if might look like this

const s = 'a';

if (/a/.test(s)) {
  console.log('first match');
} else if (/b/.test(s)) {
  console.log('second match');
} else {
  console.log('no match');
}


问:
How to custom sort a pandas dataframe per row by comparing values in columns?
I have a pandas dataframe like this

```<code>import pandas as pd
df = pd.DataFrame({'feature1': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'feature2': ['b', 'a', 'c', 'a', 'c', 'a'],
                   'val': [0.96, 0.96, 0.95, 0.95, 0.94, 0.94]})
df
    feature1    feature2    corr
0   a   b   0.96
1   b   a   0.96
2   a   c   0.95
3   c   a   0.95
4   b   c   0.94
5   c   a   0.94
</code>```

I want to sort individual rows by taking the lexicographical minimum value in feature1 and maximum value in feature2. The resultant dataframe will look like this

```<code>    feature1    feature2    corr
0   a   b   0.96
1   a   b   0.96
2   a   c   0.95
3   a   c   0.95
4   b   c   0.94
5   a   c   0.94
</code>```

答:
Managed to work this out using df.apply as well.

```<code>def custom_sort(x):
    min_val = min(x["feature1"], x["feature2"])
    max_val = max(x["feature1"], x["feature2"])
    x["feature1"] = min_val
    x["feature2"] = max_val
    return x
df.apply(custom_sort, axis=1)
> feature1    feature2    corr
0   a   b   0.96
1   a   b   0.96
2   a   c   0.95
3   a   c   0.95
4   b   c   0.94
5   a   c   0.94
</code>```

Body:
I have a pandas dataframe like this

import pandas as pd
df = pd.DataFrame({'feature1': ['a', 'b', 'a', 'c', 'b', 'c'],
                   'feature2': ['b', 'a', 'c', 'a', 'c', 'a'],
                   'val': [0.96, 0.96, 0.95, 0.95, 0.94, 0.94]})
df
    feature1    feature2    corr
0   a   b   0.96
1   b   a   0.96
2   a   c   0.95
3   c   a   0.95
4   b   c   0.94
5   c   a   0.94

I want to sort individual rows by taking the lexicographical minimum value in feature1 and maximum value in feature2. The resultant dataframe will look like this

    feature1    feature2    corr
0   a   b   0.96
1   a   b   0.96
2   a   c   0.95
3   a   c   0.95
4   b   c   0.94
5   a   c   0.94

Body:
Managed to work this out using df.apply as well.

def custom_sort(x):
    min_val = min(x["feature1"], x["feature2"])
    max_val = max(x["feature1"], x["feature2"])
    x["feature1"] = min_val
    x["feature2"] = max_val
    return x
df.apply(custom_sort, axis=1)
> feature1    feature2    corr
0   a   b   0.96
1   a   b   0.96
2   a   c   0.95
3   a   c   0.95
4   b   c   0.94
5   a   c   0.94


问:
Is there a performance difference between i++ and ++i in C++?
We have the question is there a performance difference between i++ and ++i in C?

What's the answer for C++?

答:
Since you asked for C++ too, here is a benchmark for java (made with jmh) :

```<code>private static final int LIMIT = 100000;

@Benchmark
public void postIncrement() {
    long a = 0;
    long b = 0;
    for (int i = 0; i < LIMIT; i++) {
        b = 3;
        a += i * (b++);
    }
    doNothing(a, b);
}

@Benchmark
public void preIncrement() {
    long a = 0;
    long b = 0;
    for (int i = 0; i < LIMIT; i++) {
        b = 3;
        a += i * (++b);
    }
    doNothing(a, b);
}
</code>```

The result shows, even when the value of the incremented variable (b) is actually used in some computation, forcing the need to store an additional value in case of post-increment, the time per operation is exactly the same :

```<code>Benchmark                         Mode  Cnt  Score   Error  Units
IncrementBenchmark.postIncrement  avgt   10  0,039   0,001  ms/op
IncrementBenchmark.preIncrement   avgt   10  0,039   0,001  ms/op
</code>```

OwnerDisplayName: Mark Harrison

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Mark Harrison

Body:
Since you asked for C++ too, here is a benchmark for java (made with jmh) :

private static final int LIMIT = 100000;

@Benchmark
public void postIncrement() {
    long a = 0;
    long b = 0;
    for (int i = 0; i < LIMIT; i++) {
        b = 3;
        a += i * (b++);
    }
    doNothing(a, b);
}

@Benchmark
public void preIncrement() {
    long a = 0;
    long b = 0;
    for (int i = 0; i < LIMIT; i++) {
        b = 3;
        a += i * (++b);
    }
    doNothing(a, b);
}

The result shows, even when the value of the incremented variable (b) is actually used in some computation, forcing the need to store an additional value in case of post-increment, the time per operation is exactly the same :

Benchmark                         Mode  Cnt  Score   Error  Units
IncrementBenchmark.postIncrement  avgt   10  0,039   0,001  ms/op
IncrementBenchmark.preIncrement   avgt   10  0,039   0,001  ms/op


问:
Retrieving values from multidimensional arrays
I have an array something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };
</code>```

if I want to retrieve 1 and 2 and feed them into this:

```<code>int a;
int b;
</code>```

How do I do it?

Is it something like this:

```<code>multiDimensionalArray2[0,0]
</code>```

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };
</code>```

To retrieve the second set would I do this, multiDimensionalArray2[1,1]

答:
Chao, I search documents in MSDN site for you, you should give it a try if you want.

Here is how I see on MSDN

List< > >
Dictionary<>

I guess it works for your problem too, it can dynamically grow longer or shorter. they say using generic classes might be better, I am not sure about whether it ought to be faster or not though.

Body:
I have an array something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };

if I want to retrieve 1 and 2 and feed them into this:

int a;
int b;

How do I do it?

Is it something like this:

multiDimensionalArray2[0,0]

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };

To retrieve the second set would I do this, multiDimensionalArray2[1,1]


问:
Find duplicate characters in a String and count the number of occurrences using Java
How can I find the number of occurrences of a character in a string?

For example: The quick brown fox jumped over the lazy dog.

Some example outputs are below,

```<code>'a' = 1
'o' = 4
'space' = 8
'.' = 1
</code>```

答:
```<code>    String str = "anand";
    Map<Character, Integer> map
        = new HashMap<Character, Integer>();

    // Converting string into a char array
    char[] charArray = str.toCharArray();

    for (char c : charArray) {

        if (map.containsKey(c)) {

            // If character is present increment count by 1
            map.put(c, map.get(c) + 1);
        }
        else {

          // If character is not present
          //putting this character into map with 1 as it's value.
            map.put(c, 1);
        }
    }

    for (Map.Entry<Character, Integer> entry :
         map.entrySet()) {

            System.out.println(entry.getKey()
                               + " : "
                               + entry.getValue());
    }
</code>```

Output:

a:2 n:2 d:1

Body:
How can I find the number of occurrences of a character in a string?

For example: The quick brown fox jumped over the lazy dog.

Some example outputs are below,

'a' = 1
'o' = 4
'space' = 8
'.' = 1

Body:
    String str = "anand";
    Map<Character, Integer> map
        = new HashMap<Character, Integer>();

    // Converting string into a char array
    char[] charArray = str.toCharArray();

    for (char c : charArray) {

        if (map.containsKey(c)) {

            // If character is present increment count by 1
            map.put(c, map.get(c) + 1);
        }
        else {

          // If character is not present
          //putting this character into map with 1 as it's value.
            map.put(c, 1);
        }
    }

    for (Map.Entry<Character, Integer> entry :
         map.entrySet()) {

            System.out.println(entry.getKey()
                               + " : "
                               + entry.getValue());
    }

Output:

a:2 n:2 d:1


问:
( Python ) Program doesn't respond to inputs ( key press or click )
I'm using the Turtle librarie in Python.
My program isn't detecting that I press a key.

```<code>def jump():
    if player.ground == True:
        player.dy += 10

game.listen()
game.onkeypress(jump, "w")
</code>```

This is the  code and I think it should work based on the tutorials I have seen.
I also tried the code like this but it doesn't work either.

```<code>def jump():
    if player.ground == True:
        player.dy += 10

game.listen()
game.onkeypress(jump(), "w")
</code>```

Adding the parenthesis on the last line doesn't seem to help.

Help me pls :(

答:
First I think you should put game.listen() after game.onkeypress().
And make sure that you have a loop that updates the game. And if you are able can you post the full code. For more information you can search some youtube videos about making a game with python turtle or you can go to: https://docs.python.org/3/library/turtle.html

Body:
I'm using the Turtle librarie in Python.
My program isn't detecting that I press a key.

def jump():
    if player.ground == True:
        player.dy += 10

game.listen()
game.onkeypress(jump, "w")

This is the  code and I think it should work based on the tutorials I have seen.
I also tried the code like this but it doesn't work either.

def jump():
    if player.ground == True:
        player.dy += 10

game.listen()
game.onkeypress(jump(), "w")

Adding the parenthesis on the last line doesn't seem to help.

Help me pls :(


问:
Access PHP Logfile
is there  any "sexy" solution to access the php error_log from remote? Like implemented in Zend Server CE?

Or how to you handle it, if there is no SSH Access for the server users?

To clarify: it is our own server running on winXP :-)

答:
I do not know what your goals are but if you are only interested in handling the application errors and not server errors, you need to log them. PHP provides a function for setting global error handler where you can perform your logging : http://php.net/manual/en/function.set-error-handler.php , I usually log them in a database and read it using a password protected form. For many applications I include it in the administration interface under 'logs'. Making your error logs publicly visible  is not a good idea because of security concerns.

However this would not be helpful if you want to log server errors too eg: 404, 500 errors.

Title: Access PHP Logfile


答:
on line 12 you have a typo,:

```<code>public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }
</code>```

You might want to modify it to:

```<code>public float AttackRange { get {return attackRange;}  set { attackRange = value; }}
</code>```

or

```<code>  public float AttackRange { get; set; }
</code>```

Title: A get or set accessor is expected

Body:
on line 12 you have a typo,:

public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }

You might want to modify it to:

public float AttackRange { get {return attackRange;}  set { attackRange = value; }}

or

  public float AttackRange { get; set; }


问:
Why my CartList is not working in flutter app?
after add to cart I find my Cart list empty in my flutter app. but in browser or postman when I hit Cart List Api after add to cart api it returns cart List. I am giving these two api below:

Add to cart: https://www.moharaj.com.bd/_public/addToCart?quantity=5&slug=cotton-fleece-hoodie-for-men-tekka-8486&variant_id=24469
(The response I get: {"status":"SUCCESS","message":"Cotton Fleece Hoodie For Men - Tekka add your cart"})

Cart List: https://www.moharaj.com.bd/_public/cartToContent
(the response i get: {"cart_total":"0.00","cart_content":[],"item_count":0}

this is my add to cart  api http call:

```<code>import 'package:http/http.dart' as http;

class AddToCartService {
  String addToCartStatus = "";
  Future<void> getData() async {
    var response = await http.get(Uri.parse(
        "https://www.moharaj.com.bd/_public/addToCart?quantity=5&slug=cotton-fleece-hoodie-for-men-tekka-8486&variant_id=24469"));

    if (response.statusCode == 200) {
      print(response.body);
      addToCartStatus = response.body;
    } else {
      print(response.reasonPhrase);
    }
  }
}
</code>```

this is my cart List Api http call:

```<code>import 'package:http/http.dart' as http;

class CartToContentService {
  var cartListStatus = "";
  Future<void> getCartContent() async {
    var response = await http
        .get(Uri.parse("https://www.moharaj.com.bd/_public/cartToContent"));

    if (response.statusCode == 200) {
      print(response.body);
      cartListStatus = response.body;
    } else {
      print(response.reasonPhrase);
    }
  }
}
</code>```

this is my homePage:

```<code>import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:practice_dio/Cart/AddToCartService.dart';
import 'package:practice_dio/Cart/CartToContentService.dart';
import 'package:practice_dio/Cart/CheckOutService.dart';
import 'package:practice_dio/Login/Login.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // const HomePage({Key? key}) : super(key: key);
  var cart = CartToContentService();

  var addCart = AddToCartService();

  String _addToCartStatus = "";
  String _cartListStatus = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Home Page")),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text("Add To Cart Status: \n" + _addToCartStatus),
              SizedBox(
                height: 10,
              ),
              Text("Cart List Status: \n" + _cartListStatus),
              SizedBox(
                height: 10,
              ),
              MaterialButton(
                  color: Colors.amber,
                  child: Text("Add To Cart"),
                  onPressed: () {
                    setState(() {
                      _addToCartStatus = addCart.addToCartStatus;
                    });
                    addCart.getData();
                  }),
              MaterialButton(
                  color: Colors.green,
                  child: Text("Cart List"),
                  onPressed: () {
                    setState(() {
                      _cartListStatus = cart.cartListStatus;
                    });
                    cart.getCartContent();
                  }),
            ]),
      ),
    );
  }
}
</code>```

答:
class Item {

```<code>final double  quantity;
final String slag;
final int  variant_id;
Item({required quantity , required slag, required  variant_id});
Map<String  ,dynamic> toMap(Item item)=>{
'quantity': this.quantity,
'slag': this.slag,
'variant_id': this.variant_id

 }
</code>```

}

```<code>why dont you use Post Verb?
// Create your  item Object
Item _item = Item(5 , 'test',3);
call the service
Service _service  = Service();
_service.AddItemToCard(_item.toMap());

Future<bool> AddItemTocard(Map<String, dynamic> item) async{
try{
    final _response  = await  http.post(Uri.parse(ApiBaseUrl), body: json.encode(item));`
  if(_response.statusCode == 200  || _response.statusCode == 201 )
    return true;
  else
    return false;
 }
catch(exception)
  {
   throw exception;
 }
}
</code>```

Body:
after add to cart I find my Cart list empty in my flutter app. but in browser or postman when I hit Cart List Api after add to cart api it returns cart List. I am giving these two api below:

Add to cart: https://www.moharaj.com.bd/_public/addToCart?quantity=5&slug=cotton-fleece-hoodie-for-men-tekka-8486&variant_id=24469
(The response I get: {"status":"SUCCESS","message":"Cotton Fleece Hoodie For Men - Tekka add your cart"})

Cart List: https://www.moharaj.com.bd/_public/cartToContent
(the response i get: {"cart_total":"0.00","cart_content":[],"item_count":0}

this is my add to cart  api http call:

import 'package:http/http.dart' as http;

class AddToCartService {
  String addToCartStatus = "";
  Future<void> getData() async {
    var response = await http.get(Uri.parse(
        "https://www.moharaj.com.bd/_public/addToCart?quantity=5&slug=cotton-fleece-hoodie-for-men-tekka-8486&variant_id=24469"));

    if (response.statusCode == 200) {
      print(response.body);
      addToCartStatus = response.body;
    } else {
      print(response.reasonPhrase);
    }
  }
}

this is my cart List Api http call:

import 'package:http/http.dart' as http;

class CartToContentService {
  var cartListStatus = "";
  Future<void> getCartContent() async {
    var response = await http
        .get(Uri.parse("https://www.moharaj.com.bd/_public/cartToContent"));

    if (response.statusCode == 200) {
      print(response.body);
      cartListStatus = response.body;
    } else {
      print(response.reasonPhrase);
    }
  }
}

this is my homePage:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:practice_dio/Cart/AddToCartService.dart';
import 'package:practice_dio/Cart/CartToContentService.dart';
import 'package:practice_dio/Cart/CheckOutService.dart';
import 'package:practice_dio/Login/Login.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // const HomePage({Key? key}) : super(key: key);
  var cart = CartToContentService();

  var addCart = AddToCartService();

  String _addToCartStatus = "";
  String _cartListStatus = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Home Page")),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text("Add To Cart Status: \n" + _addToCartStatus),
              SizedBox(
                height: 10,
              ),
              Text("Cart List Status: \n" + _cartListStatus),
              SizedBox(
                height: 10,
              ),
              MaterialButton(
                  color: Colors.amber,
                  child: Text("Add To Cart"),
                  onPressed: () {
                    setState(() {
                      _addToCartStatus = addCart.addToCartStatus;
                    });
                    addCart.getData();
                  }),
              MaterialButton(
                  color: Colors.green,
                  child: Text("Cart List"),
                  onPressed: () {
                    setState(() {
                      _cartListStatus = cart.cartListStatus;
                    });
                    cart.getCartContent();
                  }),
            ]),
      ),
    );
  }
}

Body:
class Item {

final double  quantity;
final String slag;
final int  variant_id;
Item({required quantity , required slag, required  variant_id});
Map<String  ,dynamic> toMap(Item item)=>{
'quantity': this.quantity,
'slag': this.slag,
'variant_id': this.variant_id

 }

}

why dont you use Post Verb?
// Create your  item Object
Item _item = Item(5 , 'test',3);
call the service
Service _service  = Service();
_service.AddItemToCard(_item.toMap());

Future<bool> AddItemTocard(Map<String, dynamic> item) async{
try{
    final _response  = await  http.post(Uri.parse(ApiBaseUrl), body: json.encode(item));`
  if(_response.statusCode == 200  || _response.statusCode == 201 )
    return true;
  else
    return false;
 }
catch(exception)
  {
   throw exception;
 }
}


问:
GSM location update in a roaming situation
I have a question regarding a location update in a roaming situation for a mobile station, what will be the signaling messages allowing this procedure to take place?
I know that 4 of the messages are LOCATION UPDATING REQUEST Global Title Translation
AUTHENTICATION REQUEST CHANNEL REQUEST but I don't know how these messages will be used and the scope for using each of them.</p>

答:
The best place to look is likely the 3GPP specs, and it is worth checking exactly which type of network and what specs they are using if you can.

The principles will stay the same across releases, but can differ between GSM, UMTS etc.

The specs are available online at the 3GPP site, free of charge, here: https://www.3gpp.org/specifications

A quick link to a recent spec covering location procedures is here: https://www.etsi.org/deliver/etsi_ts/123000_123099/123012/15.00.00_60/ts_123012v150000p.pdf


问:
I am trying to filter products in assending and descending order based on product price in vue js using vuex. But not sure how to do
I have been following youtube tutorials for learning Vue js.
so I want to add functionality to this project for filtering the products based upon price.

here is my  code

store/index.js

```<code>import { createStore } from 'vuex'

function updateLocalStorage(cart) {
    localStorage.setItem('cart', JSON.stringify(cart))
}

export default createStore({
    state: {
        cart: [],
    },
    getters: {
        productQuantity: state => product => {
            const item = state.cart.find(i => i.id === product.id)
            if (item) {
                return item.quantity;
            } else {
                return null;
            }
        },
        cartItems: state => {
            return state.cart
        },
        cartToatal: state => {
            return state.cart.reduce((a, b) => a + (b.val * b.quantity), 0)
        }
    },
    mutations: {
        addItemInCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)

            if (item) {
                item.quantity++;
            } else {
                state.cart.push({...product, quantity: 1 });
            }

            updateLocalStorage(state.cart);
        },
        removeItemFromCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)
            if (item) {
                if (item.quantity > 1) {
                    item.quantity--
                } else {
                    state.cart = state.cart.filter(i => i.id != product.id)
                }
            }

            updateLocalStorage(state.cart);
        },
        updateCartFromLocalStorage(state) {
            const cart = localStorage.getItem('cart')
            if (cart) {
                state.cart = JSON.parse(cart)
            }
        }
    },
    actions: {},
    modules: {}
})
</code>```

here is what my look like in file data/items.js

```<code>const items = [{
        id: 1,
        name: "One Tribe Black Edition",
        img: "https://enftymart.themenio.com/img/nft-lg.8f26d1a6.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 2,
        name: "One Tribe Black New",
        img: "https://miro.medium.com/max/2000/1*AJrLFnuCAD8dE1p1Bg0dbg.jpeg",
        val: "15.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 3,
        name: "One Tribe Black Edition",
        img: "https://creativereview.imgix.net/content/uploads/2021/09/F4E079D612B9653BEFC4D8D2F39781E39A3025C693B177A61D6C73A5156248EA.jpg?auto=compress,format&q=60&w=1200&h=849",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 4,
        name: "One Tribe Black Edition",
        img: "https://coffeebros.com/wp-content/uploads/2021/10/astronaut-background.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 5,
        name: "One Tribe Black Edition",
        img: "https://cloudfront-us-east-1.images.arcpublishing.com/coindesk/5NOWWNNEBRER7BXFZKCYRCA7NA.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 6,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 7,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/980/1*3iesg_sr8kC6NYN2iiFHRQ.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 8,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 9,
        name: "One Tribe Black Edition",
        img: "https://www.digitalmusicnews.com/wp-content/uploads/2021/11/are-nfts-a-scam-feat.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 10,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/1082/1*ZZdfsIVNuvbWB15csehQTg.jpeg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 11,
        name: "One Tribe Black Edition",
        img: "https://www.hollywoodreporter.com/wp-content/uploads/2021/10/Mutant-Demon-Ape-Credit-0xb1-copy-H-2021.jpg?w=681&h=383&crop=1",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 12,
        name: "One Tribe Black Edition",
        img: "https://wp-assets.futurism.com/2021/11/person-furious-right-click-saved-precious-nft.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
]

export default items
</code>```

here is the Vue page where I am trying to filter products I have created to buttons and to methods for descending and ascending order.

```<code><template>
  <div class="home">
    <span class="big-text">NFT</span>
    <div class="nx-container">
      <h1 class="py-45">Get NFT</h1>
      <button class="sort-as" @click="sortUp()">sort up</button>
      <button class="sort-as" @click="sortDown()">sort down</button>
      <div class="flex-it pad-130">
        <product-details
          :product="product"
          :active="active.product_detail"
          v-on:closeDetails="closeDetails()"
        ></product-details>
        <product-summary-container
          v-for="product in items"
          :key="product.id"
          :product="product"
          v-on:explore="viewProduct($event)"
        ></product-summary-container>
      </div>
    </div>
  </div>
</template>

<script>
import ProductSummaryContainer from "../components/products/ProductSummaryContainer.vue";
import ProductDetails from "../components/products/ProductDetails.vue";

import items from "../data/items";

export default {
  name: "Home",
  components: { ProductSummaryContainer, ProductDetails },
  data() {
    return {
      items: items,
      product: null,
      active: {
        product_detail: false,
      },
    };
  },
  methods: {
    viewProduct(product) {
      this.product = product;
      this.active.product_detail = true;
      console.log(product);
    },
    closeDetails() {
      this.active.product_detail = false;
    },
    sortUp($store) { //what i tried
      console.log(this.$store.items.val.sort((a, b) => a - b));
      return $store.items.val.sort((a, b) => a - b);
    },
    sortDown() {},//what i tried
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
  text-align: initial;
}
.nx-container {
  max-width: 1200px;
  overflow-x: hidden;
  overflow-y: auto;
  margin: 0 auto;
}
.flex-it {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.pad-130 {
  padding: 0px 15px 130px;
}
.big-text {
  font-family: "Poppins";
  font-size: 16em;
  text-transform: uppercase;
  font-weight: 800;
  position: absolute;
  top: 0;
  right: 0;
  z-index: -6;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke-width: 0.3px;
}
#app {
  position: relative;
}
</style>
</code>```

what changes need to be done?
Thank you in advance.

答:
What you need to update the list of items on the screes is to use following:

Implement a watcher on the sort data property which is binded to the sorting buttons, it will hold 'asc' 'desc'.

Implement a computed property e.g. filteredItems, in which you'll have a default items List being returned, and  if sort value changes then execute your filter logic and return that. And your product-summary-container will use the filteredItems .

Basically, a 'watcher' will detect a change in your sort term. And any 'computed' property, filteredItems in your case, will be fired when watched property changes.

Body:
I have been following youtube tutorials for learning Vue js.
so I want to add functionality to this project for filtering the products based upon price.

here is my  code

store/index.js

import { createStore } from 'vuex'

function updateLocalStorage(cart) {
    localStorage.setItem('cart', JSON.stringify(cart))
}

export default createStore({
    state: {
        cart: [],
    },
    getters: {
        productQuantity: state => product => {
            const item = state.cart.find(i => i.id === product.id)
            if (item) {
                return item.quantity;
            } else {
                return null;
            }
        },
        cartItems: state => {
            return state.cart
        },
        cartToatal: state => {
            return state.cart.reduce((a, b) => a + (b.val * b.quantity), 0)
        }
    },
    mutations: {
        addItemInCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)

            if (item) {
                item.quantity++;
            } else {
                state.cart.push({...product, quantity: 1 });
            }

            updateLocalStorage(state.cart);
        },
        removeItemFromCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)
            if (item) {
                if (item.quantity > 1) {
                    item.quantity--
                } else {
                    state.cart = state.cart.filter(i => i.id != product.id)
                }
            }

            updateLocalStorage(state.cart);
        },
        updateCartFromLocalStorage(state) {
            const cart = localStorage.getItem('cart')
            if (cart) {
                state.cart = JSON.parse(cart)
            }
        }
    },
    actions: {},
    modules: {}
})

here is what my look like in file data/items.js

const items = [{
        id: 1,
        name: "One Tribe Black Edition",
        img: "https://enftymart.themenio.com/img/nft-lg.8f26d1a6.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 2,
        name: "One Tribe Black New",
        img: "https://miro.medium.com/max/2000/1*AJrLFnuCAD8dE1p1Bg0dbg.jpeg",
        val: "15.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 3,
        name: "One Tribe Black Edition",
        img: "https://creativereview.imgix.net/content/uploads/2021/09/F4E079D612B9653BEFC4D8D2F39781E39A3025C693B177A61D6C73A5156248EA.jpg?auto=compress,format&q=60&w=1200&h=849",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 4,
        name: "One Tribe Black Edition",
        img: "https://coffeebros.com/wp-content/uploads/2021/10/astronaut-background.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 5,
        name: "One Tribe Black Edition",
        img: "https://cloudfront-us-east-1.images.arcpublishing.com/coindesk/5NOWWNNEBRER7BXFZKCYRCA7NA.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 6,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 7,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/980/1*3iesg_sr8kC6NYN2iiFHRQ.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 8,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 9,
        name: "One Tribe Black Edition",
        img: "https://www.digitalmusicnews.com/wp-content/uploads/2021/11/are-nfts-a-scam-feat.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 10,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/1082/1*ZZdfsIVNuvbWB15csehQTg.jpeg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 11,
        name: "One Tribe Black Edition",
        img: "https://www.hollywoodreporter.com/wp-content/uploads/2021/10/Mutant-Demon-Ape-Credit-0xb1-copy-H-2021.jpg?w=681&h=383&crop=1",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 12,
        name: "One Tribe Black Edition",
        img: "https://wp-assets.futurism.com/2021/11/person-furious-right-click-saved-precious-nft.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
]

export default items

here is the Vue page where I am trying to filter products I have created to buttons and to methods for descending and ascending order.

<template>

    NFT

Get NFT

      <button class="sort-as" @click="sortUp()">sort up</button>
      <button class="sort-as" @click="sortDown()">sort down</button>

        <product-details
          :product="product"
          :active="active.product_detail"
          v-on:closeDetails="closeDetails()"
        ></product-details>
        <product-summary-container
          v-for="product in items"
          :key="product.id"
          :product="product"
          v-on:explore="viewProduct($event)"
        ></product-summary-container>

</template>

what changes need to be done?
Thank you in advance.


问:
How to change change xpath dynamically in python
I have a feature file as:

```<code>Scenario: Verify user can select list value
Given Login user
When User clicks on column
Then Drop down list should be visible
Then User can select any value from the drop down
</code>```

In yml file I have locators as:

```<code>drop_down_list:
locator: "//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option"
strategy: XPATH
</code>```

I am getting list xpath and elements xpath is like follows

```<code>//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[1]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[2]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[3]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[4]
</code>```

.py file code is

```<code>pageName = get_node_from_description(page_name)
page_config_yaml = get_yaml_config_from(page_name)
dom_element_info = page_config_yaml.getValue(pageName, get_node_from_description(drop_down))
matching_element_on_pages = getMatchingElements(dom_element_info, browser)
dom_element_info = page_config_yaml.getValue(pageName, get_node_from_description(columnText))
matching_element_on_page = getMatchingElement(dom_element_info, browser)
value = matching_element_on_page.text
for element in matching_elements_on_page:
  val = element.text()
</code>```

#Here I wanted to add [1] .[2] at the end of the dom_enlement_info

The dom_element_info is returning value like

```<code> dom_element_info ={'locator': "//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option", 'strategy': 'XPATH'}
</code>```

How to add the [1],[2] as per drop down value need

答:
You can add the indexes using the following Locator Strategies:

Instead of:

```<code>//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[1]
</code>```

Use:

```<code>//div[@class='cdk-overlay-container']//div[@role='listbox']//following::mat-option[1]
</code>```

Body:
I have a feature file as:

Scenario: Verify user can select list value
Given Login user
When User clicks on column
Then Drop down list should be visible
Then User can select any value from the drop down

In yml file I have locators as:

drop_down_list:
locator: "//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option"
strategy: XPATH

I am getting list xpath and elements xpath is like follows

//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[1]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[2]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[3]
//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[4]

.py file code is

pageName = get_node_from_description(page_name)
page_config_yaml = get_yaml_config_from(page_name)
dom_element_info = page_config_yaml.getValue(pageName, get_node_from_description(drop_down))
matching_element_on_pages = getMatchingElements(dom_element_info, browser)
dom_element_info = page_config_yaml.getValue(pageName, get_node_from_description(columnText))
matching_element_on_page = getMatchingElement(dom_element_info, browser)
value = matching_element_on_page.text
for element in matching_elements_on_page:
  val = element.text()

#Here I wanted to add [1] .[2] at the end of the dom_enlement_info

The dom_element_info is returning value like

 dom_element_info ={'locator': "//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option", 'strategy': 'XPATH'}

How to add the [1],[2] as per drop down value need

Body:
You can add the indexes using the following Locator Strategies:

Instead of:

//div[@class='cdk-overlay-container']//div[@role='listbox']//mat-option[1]

Use:

//div[@class='cdk-overlay-container']//div[@role='listbox']//following::mat-option[1]


问:
How do I add a listener to a search form in Angular material?
I'm working with Angular material and I have a search form. As shown in the following code, I have a button and after a click event on the button, the words written in the search form are given to the  searchProductByName method as parameters. I'd like to substitute the button with a listener that, after having written something in the form and having clicked on enter (instead of the button), grabs the things written in the search form and passes them to the searchProductByName method as parameters. Is there a way to do so?

```<code><form class="search-form" >
    <mat-form-field class="example-full-width" appearance="fill">
      <mat-label >Search</mat-label>
      <input #input type="text" ngModel name="name" class="form-control" id="name"
             aria-label="Search"
             matInput
             >
             <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

    </mat-form-field>
  </form>
</code>```

答:
Easy way to do that in template is add keyup event to the input:

```<code><form class="search-form" >
    <input #input type="text" ngModel name="name" class="form-control" id="name"
         (keyup.enter)="searchProductByName(input.value)"
         aria-label="Search"
         matInput
         >
    <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

  </mat-form-field>
</form>
</code>```

Or you can get your input element in component with ViewChild and make listener there.

Body:
I'm working with Angular material and I have a search form. As shown in the following code, I have a button and after a click event on the button, the words written in the search form are given to the  searchProductByName method as parameters. I'd like to substitute the button with a listener that, after having written something in the form and having clicked on enter (instead of the button), grabs the things written in the search form and passes them to the searchProductByName method as parameters. Is there a way to do so?

<form class="search-form" >
    <mat-form-field class="example-full-width" appearance="fill">
      <mat-label >Search</mat-label>
      <input #input type="text" ngModel name="name" class="form-control" id="name"
             aria-label="Search"
             matInput
             >
             <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

    </mat-form-field>
  </form>

Body:
Easy way to do that in template is add keyup event to the input:

<form class="search-form" >
    <input #input type="text" ngModel name="name" class="form-control" id="name"
         (keyup.enter)="searchProductByName(input.value)"
         aria-label="Search"
         matInput
         >
    <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

  </mat-form-field>
</form>

Or you can get your input element in component with ViewChild and make listener there.


问:
ts instantiate a class passed as parameter
I was trying to implement a neat way to build multiple Plants (inspired by plants vs zombies). To make it easy to add more plant Types I wanted to make the cost and dmg of the plant static so I can set it once for all Plants of this type.

In this case I have only one Plant (Sunflower), now I would like to instantiate the Sunflowerplant. In the build method in the Cell class.

When doing it like this I get the error:
Cannot create an instance of an abstract class. which is understandable for me. So is there a way to only be able to pass non abstract classes which extend from Plant as a Parameter for the build() methode or do I have to implement some sort of if (!c isAbstract)

```<code>abstract class Plant {
  public static dmg: number;
  public static cost: number;

  constructor(cell: Cell) {
    this.cell = cell;
  }

  cell: Cell;
}

// I would like to create more Plants like this
class Sunflower extends Plant {
  public static dmg = 0;
  public static cost = 50;
  cell: Cell;

  constructor(cell: Cell) {
    super(cell);
  }
}

class Cell {
  build(c: typeof Plant) {
    if (c.cost <= game.money) {
      this.plant = new c(this); //Cannot create an instance of an abstract class.
      game.money -= c.cost;
    }
  }
}

// this is how I would build plants.
let c = new Cell();
c.build(Sunflower);
</code>```

答:
You can do it like this:

```<code>class Cell {

  build<T extends Plant>(plant: (new (cell:Cell) => T)) {
    const plantInstance = new plant(this);
  }
}
</code>```

Playground link

Body:
I was trying to implement a neat way to build multiple Plants (inspired by plants vs zombies). To make it easy to add more plant Types I wanted to make the cost and dmg of the plant static so I can set it once for all Plants of this type.

In this case I have only one Plant (Sunflower), now I would like to instantiate the Sunflowerplant. In the build method in the Cell class.

When doing it like this I get the error:
Cannot create an instance of an abstract class. which is understandable for me. So is there a way to only be able to pass non abstract classes which extend from Plant as a Parameter for the build() methode or do I have to implement some sort of if (!c isAbstract)

abstract class Plant {
  public static dmg: number;
  public static cost: number;

  constructor(cell: Cell) {
    this.cell = cell;
  }

  cell: Cell;
}

// I would like to create more Plants like this
class Sunflower extends Plant {
  public static dmg = 0;
  public static cost = 50;
  cell: Cell;

  constructor(cell: Cell) {
    super(cell);
  }
}

class Cell {
  build(c: typeof Plant) {
    if (c.cost <= game.money) {
      this.plant = new c(this); //Cannot create an instance of an abstract class.
      game.money -= c.cost;
    }
  }
}

// this is how I would build plants.
let c = new Cell();
c.build(Sunflower);

Body:
You can do it like this:

class Cell {

  build<T extends Plant>(plant: (new (cell:Cell) => T)) {
    const plantInstance = new plant(this);
  }
}

<a href="https://www.typescriptlang.org/play?#code/IYIwzgLgTsDGEAJYBthjAgCqgdog3gLABQCCADgK4jICWsCkwE9CAJgLYDmAXAjpQ4gAplADcJMlRqsmLBrAD2kPgKGiJxSUkU5IUSvEVQAFLGHJkfAMIXkASgRFSZBBAAWtMADpzlhAC8SHaaZAC+JNp+Vgi2lpoRWsQA9MkIAJIIAO6KlMhsCHQA1sJuikhQwsylHMal2MB4GMWlHl4kKGgYAMqUOABmyIpZogjCAB4QwjhsGA14TtrSdAxyrJxcgQgADKEU1CuMEMysSpBbAKy7kUlkSnrQhhDGZnY2do7OroyU5KKvlnse0SiQ6qHQsTsixcZG0IEotHyAB4ACpjSbTWZYXAQAB8JnIOL4JhwwiyCABVjiDkCuIQKPsn20ZFStH6FNgvmUiCRQS4wA4wm8tVJAE8mTDXPdzoTGhB0g9GuYtqTybK8CY2mAgQhUtZGjhFIhYJVqghGghaIqcMrFOyLaB9HBjeCfMypbowIpkEKhlwTAAieGIiABgA0FBxCqYNuE9ndLOS-MFwt0wlFCAAtEFOWcIHtwtoQTdUm5PBgvAh3MMMtlcvkEMGG+qIG7iD7jSqyZDLCYgR1vE22CZegMhiMoECgA" rel="nofollow noreferrer">Playground link


问:
using electron-store with ip as key
Hy,

i try to use electron-store to persist values by ip as key.
Using the code:

```<code>store.set('users.' + ip, 'foo')
</code>```

So i want to achieve following object:

{users: [{"192.186.0.0": "foo"},{"192.186.0.1": "bar"}]}

but what i got is

"192": {
"168": {
"192": {
"151": "Foo",
"134": "Bar",.....

So is there a way to use ips?

答:
So what you want is essentially an array of objects, where the objects key is the ip address. In this case though I would rather recommend using an array of arrays because it makes working with the data a bit easier.

So first we create a new Map, which holds our users ip and name:

```<code>let map=new Map();
map.set('192.186.0.0', 'foo');
map.set('192.186.0.1', 'bar');
</code>```

To store this Map using electron-store, we need to pack it into an array and populate the users key.

```<code>store.set('users', Array.from(map.entries(map)));
</code>```

If we want to read out or modify values from the users key, we need to convert the array back to a map.

Let's look at an example - we want to modify 192.186.0.0 to say title instead of foo:

```<code>let map=new Map(store.get('users'));
map.set('192.186.0.0', 'title');
store.set('users', Array.from(map.entries(map)));
</code>```

Title: using electron-store with ip as key

Body:
Hy,

i try to use electron-store to persist values by ip as key.
Using the code:

store.set('users.' + ip, 'foo')

So i want to achieve following object:

{users: [{"192.186.0.0": "foo"},{"192.186.0.1": "bar"}]}

but what i got is

"192": {
"168": {
"192": {
"151": "Foo",
"134": "Bar",.....

So is there a way to use ips?

Body:
So what you want is essentially an array of objects, where the objects key is the ip address. In this case though I would rather recommend using an array of arrays because it makes working with the data a bit easier.

So first we create a new Map, which holds our users ip and name:

let map=new Map();
map.set('192.186.0.0', 'foo');
map.set('192.186.0.1', 'bar');

To store this Map using electron-store, we need to pack it into an array and populate the users key.

store.set('users', Array.from(map.entries(map)));

If we want to read out or modify values from the users key, we need to convert the array back to a map.

Let's look at an example - we want to modify 192.186.0.0 to say title instead of foo:

let map=new Map(store.get('users'));
map.set('192.186.0.0', 'title');
store.set('users', Array.from(map.entries(map)));


问:
How to access query params inside getServerSideProps in Next.js?
I am trying to use get getServerSideProps in my code and I am not able to do it because I am not able to pass router.query.itmid.

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const router = useRouter();
  var id = router.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
```

Here is what I tried
https://codesandbox.io/s/youthful-lucy-427g1?file=/src/App.js

I am new to Next.js and and I have no much knowledge of Next.js so please don't tell me to read the docs if I understand the docs I wouldn't be asking this question.

答:
useRouter is used for client side routing and can be used at client side and getServerSideProps will be executed at server side.

Due to this reason you can't use useRouter() in getServerSideProps.

If you want to access the query parameters in getServerSideProps then you can use context.query.[parameter], so your code will looks like

```<code>export async function getServerSideProps(ctx) {
  // Call an external API endpoint to get posts
  var id = ctx.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}
</code>```

Body:
I am trying to use get getServerSideProps in my code and I am not able to do it because I am not able to pass router.query.itmid.

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const router = useRouter();
  var id = router.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}

Here is what I tried
https://codesandbox.io/s/youthful-lucy-427g1?file=/src/App.js

I am new to Next.js and and I have no much knowledge of Next.js so please don't tell me to read the docs if I understand the docs I wouldn't be asking this question.

Body:
useRouter is used for client side routing and can be used at client side and getServerSideProps will be executed at server side.

Due to this reason you can't use useRouter() in getServerSideProps.

If you want to access the query parameters in getServerSideProps then you can use context.query.[parameter], so your code will looks like

export async function getServerSideProps(ctx) {
  // Call an external API endpoint to get posts
  var id = ctx.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}


问:
Tree structure with data.tree in R: NAs
I am trying to develop a tree structure in R using data.tree . I am really new in using tree structures. Specifically, I have been following the tutorial: https://cran.r-project.org/web/packages/data.tree/vignettes/data.tree.html#trees-in-data.tree. However, when I am converting to node, the variables referring to each leaf appear to be NA. Specifically, my code is:

```<code>library(data.tree)
library(treemap)

library(vcd)
data(Arthritis)
head(Arthritis)
Arthritis$pathString <- paste("progress",
                              Arthritis$Treatment,
                              Arthritis$Improved,
                              Arthritis$ID,
                              sep= "/")

data_arth <- as.Node(Arthritis)
print(data_arth, "sex", limit = 10)
</code>```

Which gives me:

While I would expect next to each ID to have the respective sex value. Any ideas what might be wrong?

答:
There is a typo: The column name is Sex instead of sex:</p>
```<code>print(data_arth, "Sex", limit = 10)
#                          levelName Sex
#1  progress                          NA
#2   ¦--Treated                       NA
#3   ¦   ¦--Some                      NA
#4   ¦   ¦   ¦--57                     2
#5   ¦   ¦   ¦--5                      2

colnames(Arthritis)
#[1] "ID"         "Treatment"  "Sex"        "Age"        # "Improved"   "pathString"
</code>```

Title: Tree structure with data.tree in R: NAs

Body:
I am trying to develop a tree structure in R using data.tree . I am really new in using tree structures. Specifically, I have been following the tutorial: https://cran.r-project.org/web/packages/data.tree/vignettes/data.tree.html#trees-in-data.tree. However, when I am converting to node, the variables referring to each leaf appear to be NA. Specifically, my code is:

library(data.tree)
library(treemap)

library(vcd)
data(Arthritis)
head(Arthritis)
Arthritis$pathString <- paste("progress",
                              Arthritis$Treatment,
                              Arthritis$Improved,
                              Arthritis$ID,
                              sep= "/")

data_arth <- as.Node(Arthritis)
print(data_arth, "sex", limit = 10)

Which gives me:

While I would expect next to each ID to have the respective sex value. Any ideas what might be wrong?

Body:
There is a typo: The column name is Sex instead of sex:

print(data_arth, "Sex", limit = 10)
#                          levelName Sex
#1  progress                          NA
#2   ¦--Treated                       NA
#3   ¦   ¦--Some                      NA
#4   ¦   ¦   ¦--57                     2
#5   ¦   ¦   ¦--5                      2

colnames(Arthritis)
#[1] "ID"         "Treatment"  "Sex"        "Age"        # "Improved"   "pathString"


问:
Should I put my UserDefaults saving process into ViewModel? (good architecture)
I'm creating a simple NewsApp. I want to create the best app architecture I can made. So my question is that if I want save really simple data like username and maybe 5-6 tags as strings, should I put userDefaults logic into my viewModel or should I create a layer between ViewModel and UserDefaultsAPI which will take care about saving data?

I mean I will create StoreData protocol which UserDefaultsAPI will implement. And if I should do it how I can achieve that? I am using RxSwift and I don't now how to subscribe changing data in UserDefaults by UserDefaultsAPI.

答:
You should create a layer between, but given an Rx/functional architecture, it shouldn't be something heavy weight like a protocol.

Learn How to Control the World and do something like this instead:

```<code>struct Storage {
    static var shared = Storage()
    var saveProperty: (Property) -> Void = { property in
        UserDefaults.standard.set(try? JSONEncoder().encode(property), forKey: "property")
    }
    var deleteProperty: () -> Void = {
        UserDefaults.standard.removeObject(forKey: "property")
    }
    var currentProperty: () -> Observable<Property?> = {
        UserDefaults.standard.rx.observe(Data.self, "property")
            .map { $0.flatMap { try? JSONDecoder().decode(Property.self, from: $0) } }
            .distinctUntilChanged()
    }
}

struct Property: Codable, Equatable { }
</code>```

Body:
You should create a layer between, but given an Rx/functional architecture, it shouldn't be something heavy weight like a protocol.

Learn How to Control the World and do something like this instead:

struct Storage {
    static var shared = Storage()
    var saveProperty: (Property) -> Void = { property in
        UserDefaults.standard.set(try? JSONEncoder().encode(property), forKey: "property")
    }
    var deleteProperty: () -> Void = {
        UserDefaults.standard.removeObject(forKey: "property")
    }
    var currentProperty: () -> Observable<Property?> = {
        UserDefaults.standard.rx.observe(Data.self, "property")
            .map { $0.flatMap { try? JSONDecoder().decode(Property.self, from: $0) } }
            .distinctUntilChanged()
    }
}

struct Property: Codable, Equatable { }


问:
Why doesn't this html template render the scraped website data in the web browser(Python, Flask, HTML, Web-Scraping)?
Whenever I print out the scraped data in the terminal it shows the scraped data fine, but whenever I try serve it using Python Flask, the HTML template that I'm using does not render the data in the web browser. If you could help me fix this code.

Python (Flask) file:

```<code>from flask import Flask, render_template
from bs4 import BeautifulSoup as BS
import requests

src = requests.get('https://webscraper.netlify.app/').text

scraper = BS(src, 'lxml')

# head = scraper.find('main').select_one('article:nth-of-type(4)').div.text
# author = scraper.find('main').select_one('p').text

head = scraper.body.header.h1.text

snd_author = scraper.body.main.select_one('article:nth-of-type(2)').p.text

fst_article = scraper.body.main.article.div

app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html', **locals())

app.run(debug=True)
</code>```

HTML (view) file:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=2.0"/>
    <title>Python Flask Web Scraper</title>
  </head>
  <body>
    <!-- Python Flask Variables go here: -->

    <h1> {{ head }} </h1>

    <p>{{ snd_author }}</p>

    <article>{{ fst_article }}</article>

  </body>
</html>
</code>```

答:
You should instead use:</p>
```<code>return render_template('index.html', head=head, snd_author=snd_author, fst_article=fst_article)
</code>```

Body:
Whenever I print out the scraped data in the terminal it shows the scraped data fine, but whenever I try serve it using Python Flask, the HTML template that I'm using does not render the data in the web browser. If you could help me fix this code.

Python (Flask) file:

from flask import Flask, render_template
from bs4 import BeautifulSoup as BS
import requests

src = requests.get('https://webscraper.netlify.app/').text

scraper = BS(src, 'lxml')

# head = scraper.find('main').select_one('article:nth-of-type(4)').div.text
# author = scraper.find('main').select_one('p').text

head = scraper.body.header.h1.text

snd_author = scraper.body.main.select_one('article:nth-of-type(2)').p.text

fst_article = scraper.body.main.article.div

app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html', **locals())

app.run(debug=True)

HTML (view) file:

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=2.0"/>
    <title>Python Flask Web Scraper</title>

 {{ head }}

{{ snd_author }}

{{ fst_article }}

Body:
You should instead use:

return render_template('index.html', head=head, snd_author=snd_author, fst_article=fst_article)


问:
How to make dictionary entry a pandas dataframe by specifying columns?
I have a dictionary like this:

```<code>mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}
</code>```

And I would like to make it a dataframe like this:

```<code>ISBN, LINK, LANG
9788845278518, /book/show/24235201-numero-zero, Italian
9788845278518, /book/show/10522.Il_nome_della_rosa, Italian
</code>```

So I tried by doing:

```<code>df = pd.DataFrame.from_dict(mydict)
</code>```

And I wanted to use df.explode and then doing transpose, but it didn't really work because my column is not named. Also, there must be a simpler way to do it...

答:
```<code>df = pd.DataFrame.from_dict(mydict)
df = pd.melt(df, var_name='ISBN', value_name='value')
df[['LINK', 'LANG']] = df['value'].apply(pd.Series)
df.drop(columns='value')
</code>```

melt to move column names to the new ISBN column, and explode the lists into the two new columns LINK, LANG

Body:
I have a dictionary like this:

mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}

And I would like to make it a dataframe like this:

ISBN, LINK, LANG
9788845278518, /book/show/24235201-numero-zero, Italian
9788845278518, /book/show/10522.Il_nome_della_rosa, Italian

So I tried by doing:

df = pd.DataFrame.from_dict(mydict)

And I wanted to use df.explode and then doing transpose, but it didn't really work because my column is not named. Also, there must be a simpler way to do it...

Body:
df = pd.DataFrame.from_dict(mydict)
df = pd.melt(df, var_name='ISBN', value_name='value')
df[['LINK', 'LANG']] = df['value'].apply(pd.Series)
df.drop(columns='value')

melt to move column names to the new ISBN column, and explode the lists into the two new columns LINK, LANG


答:
You could try using a defaultdict before creating a Dataframe, since pandas operations are usually more expensive:

import pandas as pd
from collections import defaultdict

mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}

d = defaultdict(list)
for key,value in mydict.items():
  for v in value:
    d.setdefault('ISBN', []).append(key)
    d.setdefault('LINK', []).append(v[0])
    d.setdefault('LANG', []).append(v[1])

df = pd.DataFrame(dict(d))
print(df)
```
```            ISBN                                 LINK     LANG
0  9788845278518      /book/show/24235201-numero-zero  Italian
1  9788845278518  /book/show/10522.Il_nome_della_rosa  Italian
```

Title: How to make dictionary entry a pandas dataframe by specifying columns?

Body:
You could try using a defaultdict before creating a Dataframe, since pandas operations are usually more expensive:

import pandas as pd
from collections import defaultdict

mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}

d = defaultdict(list)
for key,value in mydict.items():
  for v in value:
    d.setdefault('ISBN', []).append(key)
    d.setdefault('LINK', []).append(v[0])
    d.setdefault('LANG', []).append(v[1])

df = pd.DataFrame(dict(d))
print(df)

            ISBN                                 LINK     LANG
0  9788845278518      /book/show/24235201-numero-zero  Italian
1  9788845278518  /book/show/10522.Il_nome_della_rosa  Italian


问:
A get or set accessor is expected
```<code>using System.Collections.Generic;
using UnityEngine;

public class playercombat : MonoBehaviour
{

    public Animator animator;
    public Transform attackPoint;
    public float attackRange = 0.5f;
    public LayerMask enemyLayers;

    public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }

    // Update is called once per frame
    void Update()
    {
       if (Input.GetKeyDown(KeyCode.Q))
        {
            Attack();
        }
    }
    void Attack()
    {
        animator.SetTrigger("Attack");

        Physics2D.OverlapCircleAll(attackPoint.postion, AttackRange, enemyLayers);

        foreach (Collider2D enemy in hitEnemies)
        {
            Debug.lot("Hit" + enemy.name);
        }
    }
    void OnDrawGizmosSelected()
    {
        if (attackPoint == null)
            return;
        Gizmos.DrawWireSphere(attackPoint.position, AttackRange);
    }
}

</code>```

A get or set accesssor expected. What does that mean and how should I fix it?
Assets\playercombat.cs(13,52): error CS1014: A get or set accessor expected
Assets\playercombat.cs(13,60): error CS1014: A get or set accessor expected

答:
Your setter on AttackRange is weird. KYL3R's answer implies that you want to set attackRange to 0.5f whenever you set it, no matter what you set it to. That seems equally weird. I think you want</p>
```<code>public float AttackRange { get => attackRange; set => attackRange = value; }
</code>```

Title: A get or set accessor is expected

Body:
using System.Collections.Generic;
using UnityEngine;

public class playercombat : MonoBehaviour
{

    public Animator animator;
    public Transform attackPoint;
    public float attackRange = 0.5f;
    public LayerMask enemyLayers;

    public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }

    // Update is called once per frame
    void Update()
    {
       if (Input.GetKeyDown(KeyCode.Q))
        {
            Attack();
        }
    }
    void Attack()
    {
        animator.SetTrigger("Attack");

        Physics2D.OverlapCircleAll(attackPoint.postion, AttackRange, enemyLayers);

        foreach (Collider2D enemy in hitEnemies)
        {
            Debug.lot("Hit" + enemy.name);
        }
    }
    void OnDrawGizmosSelected()
    {
        if (attackPoint == null)
            return;
        Gizmos.DrawWireSphere(attackPoint.position, AttackRange);
    }
}

A get or set accesssor expected. What does that mean and how should I fix it?
Assets\playercombat.cs(13,52): error CS1014: A get or set accessor expected
Assets\playercombat.cs(13,60): error CS1014: A get or set accessor expected

Body:
Your setter on AttackRange is weird. KYL3R's answer implies that you want to set attackRange to 0.5f whenever you set it, no matter what you set it to. That seems equally weird. I think you want

public float AttackRange { get => attackRange; set => attackRange = value; }


问:
v-if contains advanced statement
I have images with contains alt different names, and I want to make a filter with these names, what I want to do is for example if the "current_variant" is red I want to show images that have '#red' and images that do not have '#' together '#yellow' in that case.

1.image [image_alt#red]

2.image [image_alt#yellow]

3.image [image_alt]

4.image [image_alt]

current_variant.alt = image_alt#red

with this line, I manage to call images with alt names but the problem is on the second statement removes the first because it includes '#'

v-if="current_variant.alt == '{{ media.alt }}' !== current_variant.alt.indexOf('#') > -1"
```

答:
Your description is not clear but let me guess...

You probably have a list of images let's say a gallery and you are trying to do something similar to this:
https://codesandbox.io/s/agitated-poincare-j7enl?file=/src/App.vue

It would be very helpful though if you added more info on what you are trying to do.

Title: v-if contains advanced statement


问:
Filtering rows based on specific values: Pandas
I have the following dataframe.

```<code>ID Value1  Value2  Value3  Value4  Value5
1   0        0       50      100     0
2   0        0       0        0      0
3   0        0       0        50     0
4   0        100     0        0      0
5   50        0      100      50     50
</code>```

I would like to filter IDs which has only one non-zero values. For example ID == 1 has two non-zero values but ID == 3 and 4 has only one non-zero values and I would like to filter them.

The expected output is ID 3 and 4.

```<code>ID Value1  Value2  Value3  Value4  Value5
3   0        0       0        50     0
4   0        100     0        0      0
</code>```

Can anyone help on this?

答:
use a boolean filter with .set_index

you can filter the index by using .loc

```<code>df.set_index('ID').loc[df.set_index('ID').gt(0).sum(axis=1).eq(1)]

    Value1  Value2  Value3  Value4  Value5
ID
3        0       0       0      50       0
4        0     100       0       0       0
</code>```

```<code>print(df.set_index('ID').gt(0).sum(axis=1).eq(1))

ID
1    False
2    False
3     True # <-- filter this row
4     True # <-- and this.
5    False
dtype: bool
</code>```

another way using .filter

```<code>df.loc[df.filter(like='Val').gt(0).sum(axis=1).eq(1)]
</code>```

Body:
I have the following dataframe.

ID Value1  Value2  Value3  Value4  Value5
1   0        0       50      100     0
2   0        0       0        0      0
3   0        0       0        50     0
4   0        100     0        0      0
5   50        0      100      50     50

I would like to filter IDs which has only one non-zero values. For example ID == 1 has two non-zero values but ID == 3 and 4 has only one non-zero values and I would like to filter them.

The expected output is ID 3 and 4.

ID Value1  Value2  Value3  Value4  Value5
3   0        0       0        50     0
4   0        100     0        0      0

Can anyone help on this?

Body:
use a boolean filter with .set_index

you can filter the index by using .loc

df.set_index('ID').loc[df.set_index('ID').gt(0).sum(axis=1).eq(1)]

    Value1  Value2  Value3  Value4  Value5
ID
3        0       0       0      50       0
4        0     100       0       0       0

print(df.set_index('ID').gt(0).sum(axis=1).eq(1))

ID
1    False
2    False
3     True # <-- filter this row
4     True # <-- and this.
5    False
dtype: bool

another way using .filter

df.loc[df.filter(like='Val').gt(0).sum(axis=1).eq(1)]


问:
NoSuchMethodError on com.fasterxml.jackson.dataformat.xml.XmlMapper.coercionConfigDefaults()
I'm parsing a XML string to convert it to a JsonNode in Scala using a XmlMapper from the Jackson library. I code on a Databricks notebook, so compilation is done on a cloud cluster. When compiling my code I got this error java.lang.NoSuchMethodError: com.fasterxml.jackson.dataformat.xml.XmlMapper.coercionConfigDefaults()Lcom/fasterxml/jackson/databind/cfg/MutableCoercionConfig; with a hundred lines of "at com.databricks. ..."

I maybe forget to import something but for me this is ok (tell me if I'm wrong) :

import ch.qos.logback.classic._
import com.typesafe.scalalogging._
import com.fasterxml.jackson._
import com.fasterxml.jackson.core._
import com.fasterxml.jackson.databind.{ObjectMapper, JsonNode}
import com.fasterxml.jackson.dataformat.xml._
import com.fasterxml.jackson.module.scala._
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import java.io._
import java.time.Instant
import java.util.concurrent.TimeUnit
import javax.xml.parsers._
import okhttp3.{Headers, OkHttpClient, Request, Response, RequestBody, FormBody}
import okhttp3.OkHttpClient.Builder._
import org.apache.spark._
import org.xml.sax._
```
<p>As I'm using Databricks, there's no SBT file for dependencies. Instead I installed the libs I need directly on the cluster. Here are the ones I'm using :</p>
```com.squareup.okhttp:okhttp:2.7.5
com.squareup.okhttp3:okhttp:4.9.0
com.squareup.okhttp3:okhttp:3.14.9
org.scala-lang.modules:scala-swing_3:3.0.0
ch.qos.logback:logback-classic:1.2.6
com.typesafe:scalalogging-slf4j_2.10:1.1.0
cc.spray.json:spray-json_2.9.1:1.0.1
com.fasterxml.jackson.module:jackson-module-scala_3:2.13.0
javax.xml.parsers:jaxp-api:1.4.5
org.xml.sax:2.0.1
```
<p>The code causing the error is simply (coming from here : https://www.baeldung.com/jackson-convert-xml-json Chapter 5):</p>
<pre class="lang-scala prettyprint-override"><code>val xmlMapper: XmlMapper = new XmlMapper()
val jsonNode: JsonNode = xmlMapper.readTree(responseBody.getBytes())
</code>```

with responseBody being a String containing a XML document (I previously checked the integrity of the XML). When removing those two lines the code is working fine.

I've read tons of articles or forums but I can't figure out what's causing my issue. Can someone please help me ? Thanks a lot ! :)

答:
upgrading to 2.12.5 version fixed my issue.
this issue may also appear when there are multiple versions of jackson jars in project lib directory. you should remove the older versions.</p>

Body:
I'm parsing a XML string to convert it to a JsonNode in Scala using a XmlMapper from the Jackson library. I code on a Databricks notebook, so compilation is done on a cloud cluster. When compiling my code I got this error java.lang.NoSuchMethodError: com.fasterxml.jackson.dataformat.xml.XmlMapper.coercionConfigDefaults()Lcom/fasterxml/jackson/databind/cfg/MutableCoercionConfig; with a hundred lines of "at com.databricks. ..."

I maybe forget to import something but for me this is ok (tell me if I'm wrong) :

import ch.qos.logback.classic._
import com.typesafe.scalalogging._
import com.fasterxml.jackson._
import com.fasterxml.jackson.core._
import com.fasterxml.jackson.databind.{ObjectMapper, JsonNode}
import com.fasterxml.jackson.dataformat.xml._
import com.fasterxml.jackson.module.scala._
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import java.io._
import java.time.Instant
import java.util.concurrent.TimeUnit
import javax.xml.parsers._
import okhttp3.{Headers, OkHttpClient, Request, Response, RequestBody, FormBody}
import okhttp3.OkHttpClient.Builder._
import org.apache.spark._
import org.xml.sax._

As I'm using Databricks, there's no SBT file for dependencies. Instead I installed the libs I need directly on the cluster. Here are the ones I'm using :

com.squareup.okhttp:okhttp:2.7.5
com.squareup.okhttp3:okhttp:4.9.0
com.squareup.okhttp3:okhttp:3.14.9
org.scala-lang.modules:scala-swing_3:3.0.0
ch.qos.logback:logback-classic:1.2.6
com.typesafe:scalalogging-slf4j_2.10:1.1.0
cc.spray.json:spray-json_2.9.1:1.0.1
com.fasterxml.jackson.module:jackson-module-scala_3:2.13.0
javax.xml.parsers:jaxp-api:1.4.5
org.xml.sax:2.0.1

The code causing the error is simply (coming from here : https://www.baeldung.com/jackson-convert-xml-json Chapter 5):

val xmlMapper: XmlMapper = new XmlMapper()
val jsonNode: JsonNode = xmlMapper.readTree(responseBody.getBytes())

with responseBody being a String containing a XML document (I previously checked the integrity of the XML). When removing those two lines the code is working fine.

I've read tons of articles or forums but I can't figure out what's causing my issue. Can someone please help me ? Thanks a lot ! :)