问:
Modal Component doesn't update even though data is sourced from useContext, where the Array is updated by the useReducer Hook
the title says it all - but I will try to give a more eloquent description of the problem. I am trying to build a food order App for practice (I am a beginner).
This App has a Cart, where you can put in items, which you can then order - this cart has a display in the nav-bar on how many items you currently have in your cart, because a big part of the pages functionality, so my thought pattern, depends on the state of the cart (being able to order and proceed to payment, delete items, display item amount in navbar) I thought it would be a good idea to put this in a context component. In this context component I implemented the useReducer hook, to update itemCount, cartState, and the modalState (show / don't show). Adding items works fine, UI updates the corresponding number of items in the cart, and when opening the cart-modal the correct items are displayed. However when I click on an item to delete it, the delete operation gets performed correctly (array splice), but the modal doesn't get updated and I can't figure why.
A theory which I have, is that it may be because I have put more then one component in the modal component in order to work with react portals (and I haven't yet completely understood how react portals work) and therefore have messed something up there - or that I got some kind of logical error, that I am not able to resolve myself.

I am thankful for any input, if you have advice on how to better structure my code or architect the app, let me know - I am eager to learn from you!

Modal Component

```<code>export default function Modal() {

  const cartC = useContext(cContext)

  const Backdrop = () => {
    return (
      <div
        onClick={cartC.onShowCart}
        className="w-full h-full bg-gray-800 fixed bg-opacity-75"
      ></div>
    );
  };
  const Modal = () => {
    return (
      <div className="bg-slate-300 w-1/3 h-auto flex absolute left-1/3 top-1/3 flex-col rounded">
        <h1 className="self-center p-2 text-2xl font-bolder">Your Cart</h1>
        <div>
          {console.log(cartC.cartItems)}
          {cartC.cartItems.map((ci, index) => {
            return (
              <ModalCard
                id={index}
                key={index}
                itemName={ci.dishName}
              ></ModalCard>
            );
          })}
        </div>
        <div className="rounded bg-red-400 p-1 m-1 hover:scale-105 hover:bg-red-500 duration-300">
          <button onClick={cartC.onShowCart}>
            <div>Order and Procced to Payment</div>
          </button>
        </div>
      </div>
    );
  };
  return (
    <Fragment>
      {reactDom.createPortal(
        <Backdrop></Backdrop>,
        document.getElementById("overlay-root")
      )}
      {reactDom.createPortal(
        <Modal></Modal>,
        document.getElementById("modal-root")
      )}
    </Fragment>
  );
}
</code>```

App Component

```<code>import { Fragment, useContext } from "react";
import Navbar from "./Nav/Navbar";
import alpen from "./alpen.jpg";
import Description from "./Ui/Description";
import Menu from "./Ui/Menu";
import Modal from "./Ui/Modal";
import { cContext } from "./store/CartContext";

function App() {
  const cCart = useContext(cContext);
  const showCart = cCart.showCart;

  return (
    <Fragment>
      <div className="bg-gray-900 h-screen">
        <Navbar></Navbar>
        {showCart ? <Modal></Modal> : null}
        <img className="object-cover h-1/3 w-full bg-fixed z-0" src={alpen} alt="" />
        <div className="flex flex-col">
        <Description></Description>
        <Menu></Menu>
        </div>
      </div>
    </Fragment>
  );
}

export default App;
</code>```

CartContext

```<code>import { createContext, useReducer } from "react";
import { dishData } from "../data";

const cartReducer = (state, action) => {
  switch (action.type) {
    case "CART_COUNT":
      console.log(action.value);
      return {
        count: action.value,
        items: state.items,
        cartState: false,
      };
    case "CART_ITEMS":
      console.log(action.value);
      return {
        count: state.count,
        items: action.value,
        cartState: false,
      };
    case "DELETE_ITEM":
      console.log(action.value);
      return {
        count: state.count,
        items: action.value,
        cartState: false,
      };
    case "CART_STATE":
      console.log(action.value);
      return {
        count: state.count,
        items: state.items,
        cartState: action.value,
      };
    default:
      return state;
  }
};

export const cContext = createContext({
  cartItems: [],
  cartItemsCount: 0,
  onAdd: (id, amount) => {},
  onDelete: (id) => {},
  showCart: false,
  onShowCart: () => {},
});
var cartArray = [];
var cartCount = 0;

export default function Context(props) {
  const [cartState, dispatchCartReducer] = useReducer(cartReducer, {
    count: 0,
    state: false,
    items: [],
  });

  const addCartHandler = (id, amount) => {
    if (amount > 0 && id >= 0) {
      for (let x = 0; x < amount; x++) {
        cartArray.push(dishData[id]);
      }
    } else {
      return;
    }
    cartCount = cartArray.length;
    dispatchCartReducer({ type: "CART_COUNT", value: cartCount });
    dispatchCartReducer({ type: "CART_ITEMS", value: cartArray });
  };
  const deleteCartHandler = (id) => {
    const stackArray = cartState.items;
    stackArray.splice(id, 1);
    console.log(stackArray);
    dispatchCartReducer({ type: "DELETE_ITEM", value: stackArray });
  };

  const showCartHandler = () => {
    if (!cartState.cartState) {
      dispatchCartReducer({ type: "CART_STATE", value: true });
    } else if (cartState.cartState) {
      dispatchCartReducer({ type: "CART_STATE", value: false });
    }
  };
  return (
    <cContext.Provider
      value={{
        cartItems: cartState.items,
        cartItemsCount: cartState.count,
        onAdd: addCartHandler,
        showCart: cartState.cartState,
        onShowCart: showCartHandler,
        onDelete: deleteCartHandler,
      }}
    >
      {console.log(cartState)}
      {props.children}
    </cContext.Provider>
  );
}
</code>```

Modal Card Component

```<code>import { useContext } from "react";
import { cContext } from "../store/CartContext";

export default function ModalCard(props) {
  const cartContext = useContext(cContext);
  function deleteItem() {
    const id = props.id;
    cartContext.onDelete(id);
  }

  return (
    <div onClick={deleteItem} className="flex flex-row justify-center">
      <div className="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
        <p>{props.itemName}</p>
        <p>{props.itemCount}</p>
        <p>X</p>
      </div>
    </div>
  );
}
</code>```

答:
By using Rotems and Marius Florescu's recommendation I fixed it now, by refactoring the useState Hooks into one useReducer in the CartContext Component, now the UI rerenders correctly - thank you for your help.</p>
```<code>import { createContext, useReducer } from "react";
import { dishData } from "../data";

const cartReducer = (state, action) => {
  switch (action.type) {
    case "CART_COUNT":
      console.log(action.value);
      return {
        count: action.value,
        items: state.items,
        cartState: false,
      };
    case "CART_ITEMS":
      console.log(action.value);
      return {
        count: state.count,
        items: action.value,
        cartState: false,
      };
    case "DELETE_ITEM":
      console.log(action.value);
      return {
        count: action.value.length,
        items: action.value,
        cartState: state.cartState,
      };
    case "CART_STATE":
      return {
        count: state.count,
        items: state.items,
        cartState: !state.cartState,
      };
    default:
      return state;
  }
};

export const cContext = createContext({
  cartItems: [],
  cartItemsCount: 0,
  cartTotal: 0,
  onAdd: (id, amount) => {},
  onDelete: (id) => {},
  showCart: false,
  onShowCart: () => {},
});
var cartArray = [];
var cartCount = 0;

export default function Context(props) {
  const [cartState, dispatchCartReducer] = useReducer(cartReducer, {
    count: 0,
    state: false,
    items: [],
  });

  const addCartHandler = (id, amount) => {
    if (amount > 0 && id >= 0) {
      for (let x = 0; x < amount; x++) {
        cartArray.push(dishData[id]);
      }
    } else {
      return;
    }
    cartCount = cartArray.length;
    dispatchCartReducer({ type: "CART_COUNT", value: cartCount });
    dispatchCartReducer({ type: "CART_ITEMS", value: cartArray });
  };
  const deleteCartHandler = (id) => {
    const stackArray = cartState.items;
    stackArray.splice(id, 1);
    dispatchCartReducer({ type: "DELETE_ITEM", value: stackArray });
  };

  const showCartHandler = () => {
    dispatchCartReducer({ type: "CART_STATE" });
  };

  let totalCartPrice = 0;
  for (let x = 0; x < cartState.items.length; x++) {
    console.log(cartState.items[x].dishPrice);
    totalCartPrice += cartState.items[x].dishPrice;
  }
  totalCartPrice = Math.round(totalCartPrice);
  console.log(totalCartPrice);
  return (
    <cContext.Provider
      value={{
        cartItems: cartState.items,
        cartItemsCount: cartState.count,
        cartTotal: totalCartPrice,
        onAdd: addCartHandler,
        showCart: cartState.cartState,
        onShowCart: showCartHandler,
        onDelete: deleteCartHandler,
      }}
    >
      {props.children}
    </cContext.Provider>
  );
}
</code>```

Body:
the title says it all - but I will try to give a more eloquent description of the problem. I am trying to build a food order App for practice (I am a beginner).
This App has a Cart, where you can put in items, which you can then order - this cart has a display in the nav-bar on how many items you currently have in your cart, because a big part of the pages functionality, so my thought pattern, depends on the state of the cart (being able to order and proceed to payment, delete items, display item amount in navbar) I thought it would be a good idea to put this in a context component. In this context component I implemented the useReducer hook, to update itemCount, cartState, and the modalState (show / don't show). Adding items works fine, UI updates the corresponding number of items in the cart, and when opening the cart-modal the correct items are displayed. However when I click on an item to delete it, the delete operation gets performed correctly (array splice), but the modal doesn't get updated and I can't figure why.
A theory which I have, is that it may be because I have put more then one component in the modal component in order to work with react portals (and I haven't yet completely understood how react portals work) and therefore have messed something up there - or that I got some kind of logical error, that I am not able to resolve myself.

I am thankful for any input, if you have advice on how to better structure my code or architect the app, let me know - I am eager to learn from you!

Modal Component

export default function Modal() {

  const cartC = useContext(cContext)

  const Backdrop = () => {
    return (

    );
  };
  const Modal = () => {
    return (

Your Cart

          {console.log(cartC.cartItems)}
          {cartC.cartItems.map((ci, index) => {
            return (
              <ModalCard
                id={index}
                key={index}
                itemName={ci.dishName}
              ></ModalCard>
            );
          })}

          <button onClick={cartC.onShowCart}>

Order and Procced to Payment

          </button>

    );
  };
  return (
    <Fragment>
      {reactDom.createPortal(
        <Backdrop></Backdrop>,
        document.getElementById("overlay-root")
      )}
      {reactDom.createPortal(
        <Modal></Modal>,
        document.getElementById("modal-root")
      )}
    </Fragment>
  );
}

App Component

import { Fragment, useContext } from "react";
import Navbar from "./Nav/Navbar";
import alpen from "./alpen.jpg";
import Description from "./Ui/Description";
import Menu from "./Ui/Menu";
import Modal from "./Ui/Modal";
import { cContext } from "./store/CartContext";

function App() {
  const cCart = useContext(cContext);
  const showCart = cCart.showCart;

  return (
    <Fragment>

        <Navbar></Navbar>
        {showCart ? <Modal></Modal> : null}

        <Description></Description>
        <Menu></Menu>

    </Fragment>
  );
}

export default App;

CartContext

import { createContext, useReducer } from "react";
import { dishData } from "../data";

const cartReducer = (state, action) => {
  switch (action.type) {
    case "CART_COUNT":
      console.log(action.value);
      return {
        count: action.value,
        items: state.items,
        cartState: false,
      };
    case "CART_ITEMS":
      console.log(action.value);
      return {
        count: state.count,
        items: action.value,
        cartState: false,
      };
    case "DELETE_ITEM":
      console.log(action.value);
      return {
        count: state.count,
        items: action.value,
        cartState: false,
      };
    case "CART_STATE":
      console.log(action.value);
      return {
        count: state.count,
        items: state.items,
        cartState: action.value,
      };
    default:
      return state;
  }
};

export const cContext = createContext({
  cartItems: [],
  cartItemsCount: 0,
  onAdd: (id, amount) => {},
  onDelete: (id) => {},
  showCart: false,
  onShowCart: () => {},
});
var cartArray = [];
var cartCount = 0;

export default function Context(props) {
  const [cartState, dispatchCartReducer] = useReducer(cartReducer, {
    count: 0,
    state: false,
    items: [],
  });

  const addCartHandler = (id, amount) => {
    if (amount > 0 && id >= 0) {
      for (let x = 0; x < amount; x++) {
        cartArray.push(dishData[id]);
      }
    } else {
      return;
    }
    cartCount = cartArray.length;
    dispatchCartReducer({ type: "CART_COUNT", value: cartCount });
    dispatchCartReducer({ type: "CART_ITEMS", value: cartArray });
  };
  const deleteCartHandler = (id) => {
    const stackArray = cartState.items;
    stackArray.splice(id, 1);
    console.log(stackArray);
    dispatchCartReducer({ type: "DELETE_ITEM", value: stackArray });
  };

  const showCartHandler = () => {
    if (!cartState.cartState) {
      dispatchCartReducer({ type: "CART_STATE", value: true });
    } else if (cartState.cartState) {
      dispatchCartReducer({ type: "CART_STATE", value: false });
    }
  };
  return (
    <cContext.Provider
      value={{
        cartItems: cartState.items,
        cartItemsCount: cartState.count,
        onAdd: addCartHandler,
        showCart: cartState.cartState,
        onShowCart: showCartHandler,
        onDelete: deleteCartHandler,
      }}
    >
      {console.log(cartState)}
      {props.children}
    </cContext.Provider>
  );
}

Modal Card Component

import { useContext } from "react";
import { cContext } from "../store/CartContext";

export default function ModalCard(props) {
  const cartContext = useContext(cContext);
  function deleteItem() {
    const id = props.id;
    cartContext.onDelete(id);
  }

  return (

{props.itemName}

{props.itemCount}

X

  );
}

Body:
By using Rotems and Marius Florescu's recommendation I fixed it now, by refactoring the useState Hooks into one useReducer in the CartContext Component, now the UI rerenders correctly - thank you for your help.

import { createContext, useReducer } from "react";
import { dishData } from "../data";

const cartReducer = (state, action) => {
  switch (action.type) {
    case "CART_COUNT":
      console.log(action.value);
      return {
        count: action.value,
        items: state.items,
        cartState: false,
      };
    case "CART_ITEMS":
      console.log(action.value);
      return {
        count: state.count,
        items: action.value,
        cartState: false,
      };
    case "DELETE_ITEM":
      console.log(action.value);
      return {
        count: action.value.length,
        items: action.value,
        cartState: state.cartState,
      };
    case "CART_STATE":
      return {
        count: state.count,
        items: state.items,
        cartState: !state.cartState,
      };
    default:
      return state;
  }
};

export const cContext = createContext({
  cartItems: [],
  cartItemsCount: 0,
  cartTotal: 0,
  onAdd: (id, amount) => {},
  onDelete: (id) => {},
  showCart: false,
  onShowCart: () => {},
});
var cartArray = [];
var cartCount = 0;

export default function Context(props) {
  const [cartState, dispatchCartReducer] = useReducer(cartReducer, {
    count: 0,
    state: false,
    items: [],
  });

  const addCartHandler = (id, amount) => {
    if (amount > 0 && id >= 0) {
      for (let x = 0; x < amount; x++) {
        cartArray.push(dishData[id]);
      }
    } else {
      return;
    }
    cartCount = cartArray.length;
    dispatchCartReducer({ type: "CART_COUNT", value: cartCount });
    dispatchCartReducer({ type: "CART_ITEMS", value: cartArray });
  };
  const deleteCartHandler = (id) => {
    const stackArray = cartState.items;
    stackArray.splice(id, 1);
    dispatchCartReducer({ type: "DELETE_ITEM", value: stackArray });
  };

  const showCartHandler = () => {
    dispatchCartReducer({ type: "CART_STATE" });
  };

  let totalCartPrice = 0;
  for (let x = 0; x < cartState.items.length; x++) {
    console.log(cartState.items[x].dishPrice);
    totalCartPrice += cartState.items[x].dishPrice;
  }
  totalCartPrice = Math.round(totalCartPrice);
  console.log(totalCartPrice);
  return (
    <cContext.Provider
      value={{
        cartItems: cartState.items,
        cartItemsCount: cartState.count,
        cartTotal: totalCartPrice,
        onAdd: addCartHandler,
        showCart: cartState.cartState,
        onShowCart: showCartHandler,
        onDelete: deleteCartHandler,
      }}
    >
      {props.children}
    </cContext.Provider>
  );
}


来源: stackexchange

问:
Image Replacement Script (jQuery)
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

```<code>$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});
</code>```

My HTML would be as follows:

```<code><div class = "thumbnail" style = "background-image: url(color.jpg);">
<img src="blackandwhite.jpg" />
</div>
</code>```

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

答:
When you empty the html there is nothing on which your mouseleave event will fire to set the html back again.

Working demo. In this demo I am just setting a character show that you can see the event getting fired, remove the character, it won't work.

ContentLicense: CC BY-SA 3.0

Title: Image Replacement Script (jQuery)

Body:
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});

My HTML would be as follows:

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?


问:
Printing Simple Diamond Pattern in Python
I would like to print the following pattern in Python 3.5 (I'm new to coding):

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

But I only know how to print the following using the code below, but not sure how to invert it to make it a complete diamond:

```<code>n = 5

print("Pattern 1")

for a1 in range (0,n):
    for a2 in range (a1):
        print("*", end="")
    print()

for a1 in range (n,0,-1):
    for a2 in range (a1):
        print("*", end="")
    print()

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

Any help would be appreciated!

Body:
I would like to print the following pattern in Python 3.5 (I'm new to coding):

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

But I only know how to print the following using the code below, but not sure how to invert it to make it a complete diamond:

n = 5

print("Pattern 1")

for a1 in range (0,n):
    for a2 in range (a1):
        print("*", end="")
    print()

for a1 in range (n,0,-1):
    for a2 in range (a1):
        print("*", end="")
    print()

*
**
***
****
*****
****
***
**
*

Any help would be appreciated!

Body:
h = int(input('Height -> '))

for i in range(h):
    if i <= (h // 2):
        print(' ' * (h // 2 - i), end='')
        print('*' * (i + 1), end='')
        print('*' * (i + 1))
    else:
        print(' ' * abs((h // 2 - i)), end='')
        print('*' * (h - i), end='')
        print('*' * (h - i))

ContentLicense: CC BY-SA 4.0


问:
Surf dependency causes "cannot be shared between threads safely" error in previously compiling program with matrix_sdk and async-trait
I'm trying to write a chat bot that supports the matrix protocol, and I ran into this problem that I can't wrap my head around. On its own the code compiles without issue, but adding "surf" as a dependency to the Cargo.toml causes a "dyn log::kv::source::Source` cannot be shared between threads safely" error.

This is the minimal code for which this happens:

main.rs:

use std::convert::TryFrom;
use matrix_sdk::{
    Client, Result,
    ruma::{UserId},
};
use async_trait::async_trait;

async fn new_matrix_connector() -> Option<()> {
    let username = "NAME";
    let password = "PASSWORD";

    let alice = match UserId::try_from(username) {
        Ok(user) => user,
        Err(_) => {return None;}
    };
    let client = match Client::new_from_user_id(alice.clone()).await {
        Ok(client) => client,
        Err(_) => {return None;}
    };
    match client.login(alice.localpart(), password, None, None).await {
        Ok(_) => {},
        Err(_) => {return None;}
    }
    Some(())
}

#[async_trait]
trait Loader {
    async fn load(&self) -> Option<()>;
}

struct TestLoader {}

#[async_trait]
impl Loader for TestLoader {
    async fn load(&self) -> Option<()> {
        new_matrix_connector().await
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let loader = TestLoader{};
    let _res = loader.load();
    Ok(())
}
```
<p>Cargo.toml:</p>
```[package]
name = "matrixtest"
version = "0.1.0"
edition = "2018"

[dependencies]
matrix-sdk = "0.4.1"
tokio = { version = "1", features = ["full"] }
async-trait = "0.1.52"
surf = "2.3.2"
```
<p>These are the full errors caused:</p>
```error[E0277]: `dyn log::kv::source::Source` cannot be shared between threads safely
  --> src/main.rs:38:40
   |
38 |       async fn load(&self) -> Option<()> {
   |  ________________________________________^
39 | |         new_matrix_connector().await
40 | |     }
   | |_____^ `dyn log::kv::source::Source` cannot be shared between threads safely
   |
   = help: the trait `Sync` is not implemented for `dyn log::kv::source::Source`
   = note: required because of the requirements on the impl of `Send` for `&dyn log::kv::source::Source`
   = note: required because it appears within the type `log::KeyValues<'_>`
   = note: required because it appears within the type `log::Record<'_>`
   = note: required because it appears within the type `log::RecordBuilder<'_>`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10, 't11, 't12, 't13, 't14, 't15, 't16, 't17, 't18, 't19, 't20, 't21, 't22, 't23, 't24, 't25> {ResumeTy, log::Level, log::Metadata<'r>, &'s (dyn log::Log + 't0), &'t1 mut log::RecordBuilder<'t2>, log::RecordBuilder<'t3>, &'t4 str, std::option::Option<&'t5 str>, u32, std::option::Option<u32>, [&'t6 str; 2], &'t7 [&'t8 str], &'t9 [&'t10 str; 2], &'t11 matrix_sdk::Client, impl for<'t12> std::future::Future, (), tracing_core::subscriber::Interest, &'t13 tracing_core::metadata::Metadata<'t14>, tracing_core::field::Iter, &'t15 tracing_core::field::FieldSet, &'t16 mut tracing_core::field::Iter, std::option::Option<tracing_core::field::Field>, tracing_core::field::Field, &'t17 tracing_core::field::Field, LoginInfo<'t18>, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Request<'t19>, std::option::Option<RequestConfig>, impl for<'t20, 't21> std::future::Future, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, matrix_sdk::Client, &'t22 matrix_sdk_base::client::BaseClient, matrix_sdk_base::client::BaseClient, &'t23 matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, impl for<'t24, 't25> std::future::Future}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10> {ResumeTy, &'r matrix_sdk::Client, &'s str, std::option::Option<&'t0 str>, tracing::span::Span, impl for<'t1, 't2, 't3, 't4, 't5> std::future::Future, tracing::instrument::Instrumented<impl for<'t6, 't7, 't8, 't9, 't10> std::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {ResumeTy, &'r str, matrix_sdk::ruma::UserId, &'s matrix_sdk::ruma::UserId, impl std::future::Future, (), matrix_sdk::Client, &'t0 matrix_sdk::Client, std::option::Option<&'t1 str>, impl for<'t2, 't3, 't4, 't5, 't6> std::future::Future}`
   = note: required because it appears within the type `[static generator@src/main.rs:8:47: 27:2]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:8:47: 27:2]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r> {ResumeTy, &'r TestLoader, impl std::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:38:40: 40:6]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:38:40: 40:6]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required for the cast to the object type `dyn std::future::Future<Output = std::option::Option<()>> + Send`

error[E0277]: `core::fmt::Opaque` cannot be shared between threads safely
  --> src/main.rs:38:40
   |
38 |       async fn load(&self) -> Option<()> {
   |  ________________________________________^
39 | |         new_matrix_connector().await
40 | |     }
   | |_____^ `core::fmt::Opaque` cannot be shared between threads safely
   |
   = help: within `[ArgumentV1<'_>]`, the trait `Sync` is not implemented for `core::fmt::Opaque`
   = note: required because it appears within the type `&core::fmt::Opaque`
   = note: required because it appears within the type `ArgumentV1<'_>`
   = note: required because it appears within the type `[ArgumentV1<'_>]`
   = note: required because of the requirements on the impl of `Send` for `&[ArgumentV1<'_>]`
   = note: required because it appears within the type `Arguments<'_>`
   = note: required because it appears within the type `log::Record<'_>`
   = note: required because it appears within the type `log::RecordBuilder<'_>`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10, 't11, 't12, 't13, 't14, 't15, 't16, 't17, 't18, 't19, 't20, 't21, 't22, 't23, 't24, 't25> {ResumeTy, log::Level, log::Metadata<'r>, &'s (dyn log::Log + 't0), &'t1 mut log::RecordBuilder<'t2>, log::RecordBuilder<'t3>, &'t4 str, std::option::Option<&'t5 str>, u32, std::option::Option<u32>, [&'t6 str; 2], &'t7 [&'t8 str], &'t9 [&'t10 str; 2], &'t11 matrix_sdk::Client, impl for<'t12> std::future::Future, (), tracing_core::subscriber::Interest, &'t13 tracing_core::metadata::Metadata<'t14>, tracing_core::field::Iter, &'t15 tracing_core::field::FieldSet, &'t16 mut tracing_core::field::Iter, std::option::Option<tracing_core::field::Field>, tracing_core::field::Field, &'t17 tracing_core::field::Field, LoginInfo<'t18>, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Request<'t19>, std::option::Option<RequestConfig>, impl for<'t20, 't21> std::future::Future, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, matrix_sdk::Client, &'t22 matrix_sdk_base::client::BaseClient, matrix_sdk_base::client::BaseClient, &'t23 matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, impl for<'t24, 't25> std::future::Future}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10> {ResumeTy, &'r matrix_sdk::Client, &'s str, std::option::Option<&'t0 str>, tracing::span::Span, impl for<'t1, 't2, 't3, 't4, 't5> std::future::Future, tracing::instrument::Instrumented<impl for<'t6, 't7, 't8, 't9, 't10> std::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {ResumeTy, &'r str, matrix_sdk::ruma::UserId, &'s matrix_sdk::ruma::UserId, impl std::future::Future, (), matrix_sdk::Client, &'t0 matrix_sdk::Client, std::option::Option<&'t1 str>, impl for<'t2, 't3, 't4, 't5, 't6> std::future::Future}`
   = note: required because it appears within the type `[static generator@src/main.rs:8:47: 27:2]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:8:47: 27:2]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r> {ResumeTy, &'r TestLoader, impl std::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:38:40: 40:6]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:38:40: 40:6]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required for the cast to the object type `dyn std::future::Future<Output = std::option::Option<()>> + Send`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `matrix` due to 2 previous errors
```

Without the surf dependency this compiles without issue. It also doesn't happen if the load() function is implemented for the TestLoader struct directly.

答:
A friend of mine figured out what the problem was:

The problem wasn't surf directly, but the tracing crate with the log feature enabled, on which surf indirectly depends. There is already an issue on github on it, but it's not yet resolved.

The problem gets triggered by matrix-sdk because it also uses tracing, but usually without the log feature. The line that triggers it is this:

info!("Registering to {}", self.homeserver().await);
```
<p>Changing it to</p>
```let homeserver = self.homeserver().await;
info!("Registering to {}", homeserver);
```

resolves the issue. A fix to this exists in a fork of matrix-sdk (fixed in this commit), but as far as I can tell it hasn't been merged as of yet. There was also no release since then (most recent version is 0.4.1), so maybe it'll get fixed for the next release.

For the time being my workaround for this problem is to not depend on surf.

Body:
I'm trying to write a chat bot that supports the matrix protocol, and I ran into this problem that I can't wrap my head around. On its own the code compiles without issue, but adding "surf" as a dependency to the Cargo.toml causes a "dyn log::kv::source::Source` cannot be shared between threads safely" error.

This is the minimal code for which this happens:

main.rs:

use std::convert::TryFrom;
use matrix_sdk::{
    Client, Result,
    ruma::{UserId},
};
use async_trait::async_trait;

async fn new_matrix_connector() -> Option<()> {
    let username = "NAME";
    let password = "PASSWORD";

    let alice = match UserId::try_from(username) {
        Ok(user) => user,
        Err(_) => {return None;}
    };
    let client = match Client::new_from_user_id(alice.clone()).await {
        Ok(client) => client,
        Err(_) => {return None;}
    };
    match client.login(alice.localpart(), password, None, None).await {
        Ok(_) => {},
        Err(_) => {return None;}
    }
    Some(())
}

#[async_trait]
trait Loader {
    async fn load(&self) -> Option<()>;
}

struct TestLoader {}

#[async_trait]
impl Loader for TestLoader {
    async fn load(&self) -> Option<()> {
        new_matrix_connector().await
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let loader = TestLoader{};
    let _res = loader.load();
    Ok(())
}

Cargo.toml:

[package]
name = "matrixtest"
version = "0.1.0"
edition = "2018"

[dependencies]
matrix-sdk = "0.4.1"
tokio = { version = "1", features = ["full"] }
async-trait = "0.1.52"
surf = "2.3.2"

These are the full errors caused:

error[E0277]: `dyn log::kv::source::Source` cannot be shared between threads safely
  --> src/main.rs:38:40
   |
38 |       async fn load(&self) -> Option<()> {
   |  ________________________________________^
39 | |         new_matrix_connector().await
40 | |     }
   | |_____^ `dyn log::kv::source::Source` cannot be shared between threads safely
   |
   = help: the trait `Sync` is not implemented for `dyn log::kv::source::Source`
   = note: required because of the requirements on the impl of `Send` for `&dyn log::kv::source::Source`
   = note: required because it appears within the type `log::KeyValues<'_>`
   = note: required because it appears within the type `log::Record<'_>`
   = note: required because it appears within the type `log::RecordBuilder<'_>`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10, 't11, 't12, 't13, 't14, 't15, 't16, 't17, 't18, 't19, 't20, 't21, 't22, 't23, 't24, 't25> {ResumeTy, log::Level, log::Metadata<'r>, &'s (dyn log::Log + 't0), &'t1 mut log::RecordBuilder<'t2>, log::RecordBuilder<'t3>, &'t4 str, std::option::Option<&'t5 str>, u32, std::option::Option<u32>, [&'t6 str; 2], &'t7 [&'t8 str], &'t9 [&'t10 str; 2], &'t11 matrix_sdk::Client, impl for<'t12> std::future::Future, (), tracing_core::subscriber::Interest, &'t13 tracing_core::metadata::Metadata<'t14>, tracing_core::field::Iter, &'t15 tracing_core::field::FieldSet, &'t16 mut tracing_core::field::Iter, std::option::Option<tracing_core::field::Field>, tracing_core::field::Field, &'t17 tracing_core::field::Field, LoginInfo<'t18>, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Request<'t19>, std::option::Option<RequestConfig>, impl for<'t20, 't21> std::future::Future, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, matrix_sdk::Client, &'t22 matrix_sdk_base::client::BaseClient, matrix_sdk_base::client::BaseClient, &'t23 matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, impl for<'t24, 't25> std::future::Future}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10> {ResumeTy, &'r matrix_sdk::Client, &'s str, std::option::Option<&'t0 str>, tracing::span::Span, impl for<'t1, 't2, 't3, 't4, 't5> std::future::Future, tracing::instrument::Instrumented<impl for<'t6, 't7, 't8, 't9, 't10> std::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {ResumeTy, &'r str, matrix_sdk::ruma::UserId, &'s matrix_sdk::ruma::UserId, impl std::future::Future, (), matrix_sdk::Client, &'t0 matrix_sdk::Client, std::option::Option<&'t1 str>, impl for<'t2, 't3, 't4, 't5, 't6> std::future::Future}`
   = note: required because it appears within the type `[static generator@src/main.rs:8:47: 27:2]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:8:47: 27:2]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r> {ResumeTy, &'r TestLoader, impl std::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:38:40: 40:6]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:38:40: 40:6]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required for the cast to the object type `dyn std::future::Future<Output = std::option::Option<()>> + Send`

error[E0277]: `core::fmt::Opaque` cannot be shared between threads safely
  --> src/main.rs:38:40
   |
38 |       async fn load(&self) -> Option<()> {
   |  ________________________________________^
39 | |         new_matrix_connector().await
40 | |     }
   | |_____^ `core::fmt::Opaque` cannot be shared between threads safely
   |
   = help: within `[ArgumentV1<'_>]`, the trait `Sync` is not implemented for `core::fmt::Opaque`
   = note: required because it appears within the type `&core::fmt::Opaque`
   = note: required because it appears within the type `ArgumentV1<'_>`
   = note: required because it appears within the type `[ArgumentV1<'_>]`
   = note: required because of the requirements on the impl of `Send` for `&[ArgumentV1<'_>]`
   = note: required because it appears within the type `Arguments<'_>`
   = note: required because it appears within the type `log::Record<'_>`
   = note: required because it appears within the type `log::RecordBuilder<'_>`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10, 't11, 't12, 't13, 't14, 't15, 't16, 't17, 't18, 't19, 't20, 't21, 't22, 't23, 't24, 't25> {ResumeTy, log::Level, log::Metadata<'r>, &'s (dyn log::Log + 't0), &'t1 mut log::RecordBuilder<'t2>, log::RecordBuilder<'t3>, &'t4 str, std::option::Option<&'t5 str>, u32, std::option::Option<u32>, [&'t6 str; 2], &'t7 [&'t8 str], &'t9 [&'t10 str; 2], &'t11 matrix_sdk::Client, impl for<'t12> std::future::Future, (), tracing_core::subscriber::Interest, &'t13 tracing_core::metadata::Metadata<'t14>, tracing_core::field::Iter, &'t15 tracing_core::field::FieldSet, &'t16 mut tracing_core::field::Iter, std::option::Option<tracing_core::field::Field>, tracing_core::field::Field, &'t17 tracing_core::field::Field, LoginInfo<'t18>, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Request<'t19>, std::option::Option<RequestConfig>, impl for<'t20, 't21> std::future::Future, matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, matrix_sdk::Client, &'t22 matrix_sdk_base::client::BaseClient, matrix_sdk_base::client::BaseClient, &'t23 matrix_sdk::ruma::api::ruma_client_api::r0::session::login::Response, impl for<'t24, 't25> std::future::Future}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6, 't7, 't8, 't9, 't10> {ResumeTy, &'r matrix_sdk::Client, &'s str, std::option::Option<&'t0 str>, tracing::span::Span, impl for<'t1, 't2, 't3, 't4, 't5> std::future::Future, tracing::instrument::Instrumented<impl for<'t6, 't7, 't8, 't9, 't10> std::future::Future>, ()}`
   = note: required because it appears within the type `[static generator@matrix_sdk::Client::login::{closure#0}]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@matrix_sdk::Client::login::{closure#0}]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r, 's, 't0, 't1, 't2, 't3, 't4, 't5, 't6> {ResumeTy, &'r str, matrix_sdk::ruma::UserId, &'s matrix_sdk::ruma::UserId, impl std::future::Future, (), matrix_sdk::Client, &'t0 matrix_sdk::Client, std::option::Option<&'t1 str>, impl for<'t2, 't3, 't4, 't5, 't6> std::future::Future}`
   = note: required because it appears within the type `[static generator@src/main.rs:8:47: 27:2]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:8:47: 27:2]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required because it appears within the type `for<'r> {ResumeTy, &'r TestLoader, impl std::future::Future, ()}`
   = note: required because it appears within the type `[static generator@src/main.rs:38:40: 40:6]`
   = note: required because it appears within the type `from_generator::GenFuture<[static generator@src/main.rs:38:40: 40:6]>`
   = note: required because it appears within the type `impl std::future::Future`
   = note: required for the cast to the object type `dyn std::future::Future<Output = std::option::Option<()>> + Send`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `matrix` due to 2 previous errors

Without the surf dependency this compiles without issue. It also doesn't happen if the load() function is implemented for the TestLoader struct directly.

Body:
A friend of mine figured out what the problem was:

The problem wasn't surf directly, but the tracing crate with the log feature enabled, on which surf indirectly depends. There is already an issue on github on it, but it's not yet resolved.

The problem gets triggered by matrix-sdk because it also uses tracing, but usually without the log feature. The line that triggers it is this:

info!("Registering to {}", self.homeserver().await);

Changing it to

let homeserver = self.homeserver().await;
info!("Registering to {}", homeserver);

resolves the issue. A fix to this exists in a fork of matrix-sdk (fixed in this commit), but as far as I can tell it hasn't been merged as of yet. There was also no release since then (most recent version is 0.4.1), so maybe it'll get fixed for the next release.

For the time being my workaround for this problem is to not depend on surf.


问:
Reactflow EDGES not visible
I have installed react-flow  in my existig react project as per instructions here https://reactflow.dev/ with package.json contents listed here;

```<code>"dependencies": {
    "@types/humanize-duration": "^3.18.1",
    "@types/jest": "^26.0.14",
    "@types/js-base64": "^3.0.0",
    "@types/js-cookie": "^2.2.6",
    "@types/lodash": "^4.14.162",
    "@types/react": "^16.9.53",
    "@types/react-dom": "^16.9.8",
    "@types/react-modal": "1.6.8",
    "@types/react-select": "3.0.22",
    "ansi-to-react": "^5.1.1",
    "humanize-duration": "^3.24.0",
    "js-base64": "^2.6.4",
    "js-cookie": "^2.2.1",
    "lodash": "^4.17.19",
    "protobufjs": "^6.10.2",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-flow-renderer": "^9.7.2",
    "react-modal": "^3.11.2",
    "react-scripts": "^3.4.3",
    "react-select": "^3.1.0",
    "react-swipeable": "^5.5.1",
    "react-switch": "^5.0.1",
    "sass": "^1.43.4",
    "swagger-parser": "^7.0.1",
    "typescript": "4.0.3",
    "xterm": "^3.14.5",
    "yaml": "^1.10.0"
  },
</code>```

Everything renders perfectly fine but edges are not visible (even though I can see svg path in chrome inspector);

my component code is here that renders ReactFlow component

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

import ReactFlow, {
  removeElements, addEdge,
  ReactFlowProvider,
  MiniMap,
  Controls,
  Background,
} from 'react-flow-renderer';

type Props = {

}

type State = {
  filter: string;
  elements: any[];
}

export default class Editor extends Component<Props, State> {

  state: State = {
    filter: '',
    elements: [
      {
        id: '1',
        type: 'input',
        data: {
          label: (
            <>
              Welcome to <strong>React Flow!</strong>
            </>
          ),
        },
        position: { x: 250, y: 0 },
      },
      {
        id: '2',
        data: {
          label: (
            <>
              This is a <strong>default node</strong>
            </>
          ),
        },
        position: { x: 100, y: 100 },
      },
      {
        id: '3',
        data: {
          label: (
            <>
              This one has a <strong>custom style</strong>
            </>
          ),
        },
        position: { x: 400, y: 100 },
        style: {
          background: '#D6D5E6',
          color: '#333',
          border: '1px solid #222138',
          width: 180,
        },
      },
      { id: 'e1-2', source: '1', target: '2', label: 'this is an edge label',arrowHeadType: 'arrowclosed', animated: true, type: 'smoothstep' },
      // { id: 'e1-3', source: '1', target: '3', labelStyle: { fill: '#f6ab6c', fontWeight: 700 },style: { zIndex:999, stroke: "red", strokeWidth: 30, cursor: "pointer" } }
    ]
  };

  onElementRemove(elem: any) {
    console.log(elem);
  }

  onConnect(params:any, comp:any){
    console.log(params);
    addEdge(params, comp)
  }

  onClick(ev:any, el:any, elem:any) {
      console.log(el);
    }

    onLoad(){
      console.log('loaded')
    }
    onNodeStrokeColor(n:any){
      if (n.style?.background) return n.style.background;
      if (n.type === 'input') return '#0041d0';
      if (n.type === 'output') return '#ff0072';
      if (n.type === 'default') return '#1a192b';

      return '#eee';
    }
    onNodeColor(n:any){
      if (n.style?.background) return n.style.background;
      return '#fff';
    }

  render() {
    const { elements, filter } = this.state;

    return (
      <div style={{ height: 300 }}>
        <ReactFlow elements={elements}
        onElementsRemove={x=>this.onElementRemove(x)}
        onConnect={params => this.onConnect(params, elements)}
        onElementClick={(ev, el) =>this.onClick(ev, el, elements)}
        onlyRenderVisibleElements={false}
        deleteKeyCode={46}
        onLoad={this.onLoad}
        snapToGrid={true}
        snapGrid={[15, 15]}
        >
          <MiniMap style={{ width: 150, height:150 }}
            nodeStrokeColor={n => this.onNodeStrokeColor(n)}
            nodeColor={n => this.onNodeColor(n)}
            nodeBorderRadius={2}
      />
      <Controls />
      <Background color="#00a" gap={15} />
          </ReactFlow>
      </div>
    );
  }
}
</code>```

Any help would be highly appreciated!

答:
I have found the problem and it turns out that I have a scss file that overrides SVG styles of react-flow-renderer

```<code>svg {
    ...
    width: 25px;
    height: 25px;
}
</code>```

https://github.com/wbkd/react-flow/issues/1880

Title: Reactflow EDGES not visible

Body:
I have installed react-flow  in my existig react project as per instructions here https://reactflow.dev/ with package.json contents listed here;

"dependencies": {
    "@types/humanize-duration": "^3.18.1",
    "@types/jest": "^26.0.14",
    "@types/js-base64": "^3.0.0",
    "@types/js-cookie": "^2.2.6",
    "@types/lodash": "^4.14.162",
    "@types/react": "^16.9.53",
    "@types/react-dom": "^16.9.8",
    "@types/react-modal": "1.6.8",
    "@types/react-select": "3.0.22",
    "ansi-to-react": "^5.1.1",
    "humanize-duration": "^3.24.0",
    "js-base64": "^2.6.4",
    "js-cookie": "^2.2.1",
    "lodash": "^4.17.19",
    "protobufjs": "^6.10.2",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-flow-renderer": "^9.7.2",
    "react-modal": "^3.11.2",
    "react-scripts": "^3.4.3",
    "react-select": "^3.1.0",
    "react-swipeable": "^5.5.1",
    "react-switch": "^5.0.1",
    "sass": "^1.43.4",
    "swagger-parser": "^7.0.1",
    "typescript": "4.0.3",
    "xterm": "^3.14.5",
    "yaml": "^1.10.0"
  },

Everything renders perfectly fine but edges are not visible (even though I can see svg path in chrome inspector);

my component code is here that renders ReactFlow component

import React, { Component } from 'react';

import ReactFlow, {
  removeElements, addEdge,
  ReactFlowProvider,
  MiniMap,
  Controls,
  Background,
} from 'react-flow-renderer';

type Props = {

}

type State = {
  filter: string;
  elements: any[];
}

export default class Editor extends Component<Props, State> {

  state: State = {
    filter: '',
    elements: [
      {
        id: '1',
        type: 'input',
        data: {
          label: (
            <>
              Welcome to React Flow!
            </>
          ),
        },
        position: { x: 250, y: 0 },
      },
      {
        id: '2',
        data: {
          label: (
            <>
              This is a default node
            </>
          ),
        },
        position: { x: 100, y: 100 },
      },
      {
        id: '3',
        data: {
          label: (
            <>
              This one has a custom style
            </>
          ),
        },
        position: { x: 400, y: 100 },
        style: {
          background: '#D6D5E6',
          color: '#333',
          border: '1px solid #222138',
          width: 180,
        },
      },
      { id: 'e1-2', source: '1', target: '2', label: 'this is an edge label',arrowHeadType: 'arrowclosed', animated: true, type: 'smoothstep' },
      // { id: 'e1-3', source: '1', target: '3', labelStyle: { fill: '#f6ab6c', fontWeight: 700 },style: { zIndex:999, stroke: "red", strokeWidth: 30, cursor: "pointer" } }
    ]
  };

  onElementRemove(elem: any) {
    console.log(elem);
  }

  onConnect(params:any, comp:any){
    console.log(params);
    addEdge(params, comp)
  }

  onClick(ev:any, el:any, elem:any) {
      console.log(el);
    }

    onLoad(){
      console.log('loaded')
    }
    onNodeStrokeColor(n:any){
      if (n.style?.background) return n.style.background;
      if (n.type === 'input') return '#0041d0';
      if (n.type === 'output') return '#ff0072';
      if (n.type === 'default') return '#1a192b';

      return '#eee';
    }
    onNodeColor(n:any){
      if (n.style?.background) return n.style.background;
      return '#fff';
    }

  render() {
    const { elements, filter } = this.state;

    return (

        <ReactFlow elements={elements}
        onElementsRemove={x=>this.onElementRemove(x)}
        onConnect={params => this.onConnect(params, elements)}
        onElementClick={(ev, el) =>this.onClick(ev, el, elements)}
        onlyRenderVisibleElements={false}
        deleteKeyCode={46}
        onLoad={this.onLoad}
        snapToGrid={true}
        snapGrid={[15, 15]}
        >
          <MiniMap style={{ width: 150, height:150 }}
            nodeStrokeColor={n => this.onNodeStrokeColor(n)}
            nodeColor={n => this.onNodeColor(n)}
            nodeBorderRadius={2}
      />
      <Controls />
      <Background color="#00a" gap={15} />
          </ReactFlow>

    );
  }
}

Any help would be highly appreciated!

Body:
I have found the problem and it turns out that I have a scss file that overrides SVG styles of react-flow-renderer

svg {
    ...
    width: 25px;
    height: 25px;
}

https://github.com/wbkd/react-flow/issues/1880


问:
Why my button in tkinter don't works normal
I wanted to make button in tkinter, but when I started program, the command always calls when code just starts.
Here is example code:

```<code>import tkinter as tk
from tkinter import messagebox

window = tk.Tk()
window.title("Why this don't works???")
window.wm_geometry("100x100")

def message():
    messagebox.showinfo("Hi there")

button = tk.Button(text="Hello", command=message())
button.grid(column=0, row=0)

while True:
    window.update()
</code>```

And then, button didn't worked. (When you press it, it don't works.)

I don't know what I'm doing wrong, so I need help.

答:
The problem is you are requesting a return value from the fucnction. Try using this.</p>
```<code>from tkinter import *

# import messagebox from tkinter module
import tkinter.messagebox

# create a tkinter root window
root = tkinter.Tk()

# root window title and dimension
root.title("When you press a button the message will pop up")
root.geometry('75x50')

# Create a messagebox showinfo

def onClick():
   tkinter.messagebox.showinfo("Hello World!.",  "Hi I'm your message")

# Create a Button
button = Button(root, text="Click Me", command=onClick, height=5, width=10)

 # Set the position of button on the top of window.
 button.pack(side='top')
 root.mainloop()
</code>```

Body:
I wanted to make button in tkinter, but when I started program, the command always calls when code just starts.
Here is example code:

import tkinter as tk
from tkinter import messagebox

window = tk.Tk()
window.title("Why this don't works???")
window.wm_geometry("100x100")

def message():
    messagebox.showinfo("Hi there")

button = tk.Button(text="Hello", command=message())
button.grid(column=0, row=0)

while True:
    window.update()

And then, button didn't worked. (When you press it, it don't works.)

I don't know what I'm doing wrong, so I need help.

Body:
The problem is you are requesting a return value from the fucnction. Try using this.

from tkinter import *

# import messagebox from tkinter module
import tkinter.messagebox

# create a tkinter root window
root = tkinter.Tk()

# root window title and dimension
root.title("When you press a button the message will pop up")
root.geometry('75x50')

# Create a messagebox showinfo

def onClick():
   tkinter.messagebox.showinfo("Hello World!.",  "Hi I'm your message")

# Create a Button
button = Button(root, text="Click Me", command=onClick, height=5, width=10)

 # Set the position of button on the top of window.
 button.pack(side='top')
 root.mainloop()


问:
How to import custom css files using Chakra UI for React?
This is a very specific question, but I am using the Chakra UI component library for React and I want to import my own custom css files, although it doesn't allow me to do this.

I don't know if this is a bug or if it is intended, but is there any way I can go around it?

Thanks.

答:
Make sure that you import css files in right place. Try to import your css files into App.js or if be more specific into the file where you init ChakraProvider. This approach works fine for my project:

```<code>import { ChakraProvider } from '@chakra-ui/react';
import './yourCssFile.css';
</code>```

Body:
Make sure that you import css files in right place. Try to import your css files into App.js or if be more specific into the file where you init ChakraProvider. This approach works fine for my project:

import { ChakraProvider } from '@chakra-ui/react';
import './yourCssFile.css';


问:
How to get name of a specific item in array and increment its value
I am working on a simple cart, for a homework project. I would like to ask, what would be the best way to take an item from array and increment its value by one? I have 25 items in the array, and each of them has unique name, so I am not using any IDs. Would it be possible to take these items by their name value?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Nákupný košík</title>

//Database with items

let basket = [];

let products = [
{
   type: "mb",
   name: "Asus Motherboard",
   price: "320",
   link: "products/asusmb.html",
   image: "/Eshop_project/img/asusmb.jfif",
},

{
   type: "cpu",
   name: "Intel Core i3",
   price: "150",
   image: "../img/corei3.jfif",
},

{
   type: "cpu",
   name: "Intel Core i5",
   price: "300",
   image: "../img/corei5.jfif",
},

{
   type: "cpu",
   name: "Intel Core i7",
   price: "450",
   image: "../img/corei7.jfif",
},

{
   type: "cpu",
   name: "Intel Core i9",
   price: "600",
   image: "../img/corei9.jfif",
},

{
   type: "ram",
   name: "Corsair 16gb",
   price: "80",
   image: "../img/corsair16gb.jfif",
},

{
   type: "psu",
   name: "Corsair PSU",
   price: "100",
   image: "../img/corsairpsu.jfif",
},

{
   type: "ram",
   name: "Crucial 32gb",
   price: "160",
   image: "../img/crucial32gb.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX3070",
   price: "750",
   image: "../img/gforce 3070.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX 3080",
   price: "950",
   image: "../img/gforce_3080.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX 3090",
   price: "1200",
   image: "../img/gforce_3090.jfif",
},

{
   type: "mb",
   name: "Gigabyte Motherboard",
   price: "400",
   image: "../img/gigabytemb.jfif",
},

{
   type: "psu",
   name: "Gigabyte PSU",
   price: "80",
   image: "../img/gigabytepsu.jfif",
},

{
   type: "ram",
   name: "Kingston 16gb",
   price: "90",
   image: "../img/kingston16gb.jfif",
},

{
   type: "mb",
   name: "MSI Motherboard",
   price: "300",
   image: "../img/msimb.jfif",
},

{
   type: "case",
   name: "Phanteks Case",
   price: "70",
   image: "../img/Phaktekscase.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6500",
   price: "500",
   image: "../img/radeon_6500.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6800",
   price: "650",
   image: "../img/radeon_6800.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6900",
   price: "800",
   image: "../img/radeon_6900.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 3790",
   price: "400",
   image: "../img/ryzen3790.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 5600",
   price: "550",
   image: "../img/ryzen5600.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 5800",
   price: "700",
   image: "../img/ryzen5800.jfif",
},

{
   type: "psu",
   name: "Seasonic PSU",
   price: "95",
   image: "../img/seasonicpsu.jfif",
},

{
   type: "case",
   name: "Zalmancase",
   price: "90",
   image: "../img/zalmancase.jfif",
},

{
   type: "psu",
   name: "Evga PSU",
   price: "80",
   image: "../img/evgapsu.jfif",
}

]
localStorage.setItem('products', JSON.stringify(products));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
It really depends on your coding style, and how its going to self-document.

You can use map:

const products=[{type:"mb",name:"Asus Motherboard",price:"320",link:"products/asusmb.html",image:"/Eshop_project/img/asusmb.jfif"},{type:"cpu",name:"Intel Core i3",price:"150",image:"../img/corei3.jfif"},{type:"cpu",name:"Intel Core i5",price:"300",image:"../img/corei5.jfif"},{type:"cpu",name:"Intel Core i7",price:"450",image:"../img/corei7.jfif"},{type:"cpu",name:"Intel Core i9",price:"600",image:"../img/corei9.jfif"},{type:"ram",name:"Corsair 16gb",price:"80",image:"../img/corsair16gb.jfif"},{type:"psu",name:"Corsair PSU",price:"100",image:"../img/corsairpsu.jfif"},{type:"ram",name:"Crucial 32gb",price:"160",image:"../img/crucial32gb.jfif"},{type:"gpu",name:"Nvidia Geforce RTX3070",price:"750",image:"../img/gforce 3070.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3080",price:"950",image:"../img/gforce_3080.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3090",price:"1200",image:"../img/gforce_3090.jfif"},{type:"mb",name:"Gigabyte Motherboard",price:"400",image:"../img/gigabytemb.jfif"},{type:"psu",name:"Gigabyte PSU",price:"80",image:"../img/gigabytepsu.jfif"},{type:"ram",name:"Kingston 16gb",price:"90",image:"../img/kingston16gb.jfif"},{type:"mb",name:"MSI Motherboard",price:"300",image:"../img/msimb.jfif"},{type:"case",name:"Phanteks Case",price:"70",image:"../img/Phaktekscase.jfif"},{type:"gpu",name:"AMD Radeon 6500",price:"500",image:"../img/radeon_6500.jfif"},{type:"gpu",name:"AMD Radeon 6800",price:"650",image:"../img/radeon_6800.jfif"},{type:"gpu",name:"AMD Radeon 6900",price:"800",image:"../img/radeon_6900.jfif"},{type:"cpu",name:"AMD Ryzen 3790",price:"400",image:"../img/ryzen3790.jfif"},{type:"cpu",name:"AMD Ryzen 5600",price:"550",image:"../img/ryzen5600.jfif"},{type:"cpu",name:"AMD Ryzen 5800",price:"700",image:"../img/ryzen5800.jfif"},{type:"psu",name:"Seasonic PSU",price:"95",image:"../img/seasonicpsu.jfif"},{type:"case",name:"Zalmancase",price:"90",image:"../img/zalmancase.jfif"},{type:"psu",name:"Evga PSU",price:"80",image:"../img/evgapsu.jfif"}];

const search = 'Corsair 16gb';

// Iterate over the objects and return each in its initial
// state except the one that you increase the price for
const newProducts = products.map(product => {
  if (product.name === search) ++product.price;
  return product;
});

console.log(newProducts);```
</div>
</div>
</p>
<p>Or maybe <code>find</code> the object, increase the price, <code>filter</code> the array to remove that object, and then create an updated array from the filtered array, and the new updated object.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const products=[{type:"mb",name:"Asus Motherboard",price:"320",link:"products/asusmb.html",image:"/Eshop_project/img/asusmb.jfif"},{type:"cpu",name:"Intel Core i3",price:"150",image:"../img/corei3.jfif"},{type:"cpu",name:"Intel Core i5",price:"300",image:"../img/corei5.jfif"},{type:"cpu",name:"Intel Core i7",price:"450",image:"../img/corei7.jfif"},{type:"cpu",name:"Intel Core i9",price:"600",image:"../img/corei9.jfif"},{type:"ram",name:"Corsair 16gb",price:"80",image:"../img/corsair16gb.jfif"},{type:"psu",name:"Corsair PSU",price:"100",image:"../img/corsairpsu.jfif"},{type:"ram",name:"Crucial 32gb",price:"160",image:"../img/crucial32gb.jfif"},{type:"gpu",name:"Nvidia Geforce RTX3070",price:"750",image:"../img/gforce 3070.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3080",price:"950",image:"../img/gforce_3080.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3090",price:"1200",image:"../img/gforce_3090.jfif"},{type:"mb",name:"Gigabyte Motherboard",price:"400",image:"../img/gigabytemb.jfif"},{type:"psu",name:"Gigabyte PSU",price:"80",image:"../img/gigabytepsu.jfif"},{type:"ram",name:"Kingston 16gb",price:"90",image:"../img/kingston16gb.jfif"},{type:"mb",name:"MSI Motherboard",price:"300",image:"../img/msimb.jfif"},{type:"case",name:"Phanteks Case",price:"70",image:"../img/Phaktekscase.jfif"},{type:"gpu",name:"AMD Radeon 6500",price:"500",image:"../img/radeon_6500.jfif"},{type:"gpu",name:"AMD Radeon 6800",price:"650",image:"../img/radeon_6800.jfif"},{type:"gpu",name:"AMD Radeon 6900",price:"800",image:"../img/radeon_6900.jfif"},{type:"cpu",name:"AMD Ryzen 3790",price:"400",image:"../img/ryzen3790.jfif"},{type:"cpu",name:"AMD Ryzen 5600",price:"550",image:"../img/ryzen5600.jfif"},{type:"cpu",name:"AMD Ryzen 5800",price:"700",image:"../img/ryzen5800.jfif"},{type:"psu",name:"Seasonic PSU",price:"95",image:"../img/seasonicpsu.jfif"},{type:"case",name:"Zalmancase",price:"90",image:"../img/zalmancase.jfif"},{type:"psu",name:"Evga PSU",price:"80",image:"../img/evgapsu.jfif"}];

const search = 'Corsair 16gb';

// Find the product
const product = products.find(product => product.name === search);

// Increase the price
++product.price;

// Filter out the object from the array
const filtered = products.filter(product => product.name !== search);

// Create a new array from the filtered array,
// and the updated object.
const newProducts = [...filtered, product ];

console.log(newProducts);</code>```

Both these methods produce new arrays. You could also use forEach which operates on each array element in place (and doesn't return a new array) but because this is React I wouldn't recommend it in this instance.

Body:
It really depends on your coding style, and how its going to self-document.

You can use map:

const products=[{type:"mb",name:"Asus Motherboard",price:"320",link:"products/asusmb.html",image:"/Eshop_project/img/asusmb.jfif"},{type:"cpu",name:"Intel Core i3",price:"150",image:"../img/corei3.jfif"},{type:"cpu",name:"Intel Core i5",price:"300",image:"../img/corei5.jfif"},{type:"cpu",name:"Intel Core i7",price:"450",image:"../img/corei7.jfif"},{type:"cpu",name:"Intel Core i9",price:"600",image:"../img/corei9.jfif"},{type:"ram",name:"Corsair 16gb",price:"80",image:"../img/corsair16gb.jfif"},{type:"psu",name:"Corsair PSU",price:"100",image:"../img/corsairpsu.jfif"},{type:"ram",name:"Crucial 32gb",price:"160",image:"../img/crucial32gb.jfif"},{type:"gpu",name:"Nvidia Geforce RTX3070",price:"750",image:"../img/gforce 3070.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3080",price:"950",image:"../img/gforce_3080.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3090",price:"1200",image:"../img/gforce_3090.jfif"},{type:"mb",name:"Gigabyte Motherboard",price:"400",image:"../img/gigabytemb.jfif"},{type:"psu",name:"Gigabyte PSU",price:"80",image:"../img/gigabytepsu.jfif"},{type:"ram",name:"Kingston 16gb",price:"90",image:"../img/kingston16gb.jfif"},{type:"mb",name:"MSI Motherboard",price:"300",image:"../img/msimb.jfif"},{type:"case",name:"Phanteks Case",price:"70",image:"../img/Phaktekscase.jfif"},{type:"gpu",name:"AMD Radeon 6500",price:"500",image:"../img/radeon_6500.jfif"},{type:"gpu",name:"AMD Radeon 6800",price:"650",image:"../img/radeon_6800.jfif"},{type:"gpu",name:"AMD Radeon 6900",price:"800",image:"../img/radeon_6900.jfif"},{type:"cpu",name:"AMD Ryzen 3790",price:"400",image:"../img/ryzen3790.jfif"},{type:"cpu",name:"AMD Ryzen 5600",price:"550",image:"../img/ryzen5600.jfif"},{type:"cpu",name:"AMD Ryzen 5800",price:"700",image:"../img/ryzen5800.jfif"},{type:"psu",name:"Seasonic PSU",price:"95",image:"../img/seasonicpsu.jfif"},{type:"case",name:"Zalmancase",price:"90",image:"../img/zalmancase.jfif"},{type:"psu",name:"Evga PSU",price:"80",image:"../img/evgapsu.jfif"}];

const search = 'Corsair 16gb';

// Iterate over the objects and return each in its initial
// state except the one that you increase the price for
const newProducts = products.map(product => {
  if (product.name === search) ++product.price;
  return product;
});

console.log(newProducts);

Or maybe find the object, increase the price, filter the array to remove that object, and then create an updated array from the filtered array, and the new updated object.

const products=[{type:"mb",name:"Asus Motherboard",price:"320",link:"products/asusmb.html",image:"/Eshop_project/img/asusmb.jfif"},{type:"cpu",name:"Intel Core i3",price:"150",image:"../img/corei3.jfif"},{type:"cpu",name:"Intel Core i5",price:"300",image:"../img/corei5.jfif"},{type:"cpu",name:"Intel Core i7",price:"450",image:"../img/corei7.jfif"},{type:"cpu",name:"Intel Core i9",price:"600",image:"../img/corei9.jfif"},{type:"ram",name:"Corsair 16gb",price:"80",image:"../img/corsair16gb.jfif"},{type:"psu",name:"Corsair PSU",price:"100",image:"../img/corsairpsu.jfif"},{type:"ram",name:"Crucial 32gb",price:"160",image:"../img/crucial32gb.jfif"},{type:"gpu",name:"Nvidia Geforce RTX3070",price:"750",image:"../img/gforce 3070.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3080",price:"950",image:"../img/gforce_3080.jfif"},{type:"gpu",name:"Nvidia Geforce RTX 3090",price:"1200",image:"../img/gforce_3090.jfif"},{type:"mb",name:"Gigabyte Motherboard",price:"400",image:"../img/gigabytemb.jfif"},{type:"psu",name:"Gigabyte PSU",price:"80",image:"../img/gigabytepsu.jfif"},{type:"ram",name:"Kingston 16gb",price:"90",image:"../img/kingston16gb.jfif"},{type:"mb",name:"MSI Motherboard",price:"300",image:"../img/msimb.jfif"},{type:"case",name:"Phanteks Case",price:"70",image:"../img/Phaktekscase.jfif"},{type:"gpu",name:"AMD Radeon 6500",price:"500",image:"../img/radeon_6500.jfif"},{type:"gpu",name:"AMD Radeon 6800",price:"650",image:"../img/radeon_6800.jfif"},{type:"gpu",name:"AMD Radeon 6900",price:"800",image:"../img/radeon_6900.jfif"},{type:"cpu",name:"AMD Ryzen 3790",price:"400",image:"../img/ryzen3790.jfif"},{type:"cpu",name:"AMD Ryzen 5600",price:"550",image:"../img/ryzen5600.jfif"},{type:"cpu",name:"AMD Ryzen 5800",price:"700",image:"../img/ryzen5800.jfif"},{type:"psu",name:"Seasonic PSU",price:"95",image:"../img/seasonicpsu.jfif"},{type:"case",name:"Zalmancase",price:"90",image:"../img/zalmancase.jfif"},{type:"psu",name:"Evga PSU",price:"80",image:"../img/evgapsu.jfif"}];

const search = 'Corsair 16gb';

// Find the product
const product = products.find(product => product.name === search);

// Increase the price
++product.price;

// Filter out the object from the array
const filtered = products.filter(product => product.name !== search);

// Create a new array from the filtered array,
// and the updated object.
const newProducts = [...filtered, product ];

console.log(newProducts);

Both these methods produce new arrays. You could also use forEach which operates on each array element in place (and doesn't return a new array) but because this is React I wouldn't recommend it in this instance.


问:
Discord.js collector filter is not working?
So, I have this part of the code from a quiz bot made with discord.js.

I set collector filter max: 1, but when 2 or more users reply with the correct answer in the same SECOND, they both get the points and it should be only one user, not 2 or more.

Example of this occurring:

The code:

const filter = (m) => !m.author.bot && m.content.toLowerCase() == current.answer.toLowerCase();
const collector = message.channel.createMessageCollector({ filter, max: 1, time: 45000 });

collector.on('collect', async m => {
    if (stop == true) return;
    if (m.content == null || current.answer == null || m.content.toLowerCase() != current.answer.toLowerCase()) return;

    collector.stop();

    remaining = Date.now() - time;
    points = remaining <= 5000 ? 10 : (remaining <= 15000 ? 8 : remaining <= 25000 ? 6 :(remaining < 35000 ? 4 : 2));

    message.channel.send(`Correct! The answer is **${current.answer}**\n**${m.author.tag}**! You got **${points}** points!`).catch((err) => {console.log(err)});

    if (fs.existsSync(`./system/users/${m.author.id}.json`)) {
        data = JSON.parse(fs.readFileSync(`./system/users/${m.author.id}.json`));
        data.total += points;
        data.current += points;
        data.tag = m.author.tag;
        fs.writeFileSync(`./system/users/${m.author.id}.json`, JSON.stringify(data, null, 4));
    } else {
        fs.writeFileSync(`./system/users/${m.author.id}.json`, JSON.stringify({
            "id": m.author.id,
            "tag": m.author.tag,
            "current": points,
            "total": points
        }, null, 4));
    }
    await wait(5000);
    return(md('NEXT'));
});
```

答:
As you haven't provided the code where the original message is defined, it's hard to find an exact answer to the issue.

One method would be to check the authors ID against the original message, like so:

const filter = (m) => m.author.id === <Message>.author.id
```
<p>Full example:</p>
<pre class="lang-js prettyprint-override"><code>const filter = (m) => !m.author.bot && m.content.toLowerCase() == current.answer.toLowerCase() && m.author.id === <Message>.author.id;
</code>```

Replacing <Message> with the original message object.

Body:
As you haven't provided the code where the original message is defined, it's hard to find an exact answer to the issue.

One method would be to check the authors ID against the original message, like so:

const filter = (m) => m.author.id === <Message>.author.id

Full example:

const filter = (m) => !m.author.bot && m.content.toLowerCase() == current.answer.toLowerCase() && m.author.id === <Message>.author.id;

Replacing <Message> with the original message object.


问:
How to get current logger date format pattern in log4j2?
I want to get my current logger format pattern dynamically, how can I get it?</p>

答:
I'm curious what the use case is. Try this out. :)</p>
```<code>final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
</code>```

Body:
I'm curious what the use case is. Try this out. :)

final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();


问:
How to make docker container connect everything through proxy
I know it is possible to pass http_proxy and https_proxy environment variables to a container as shown in eg. this SO answer. However, this only works for proxy-aware commands like wget and curl as they merely read and use these environment variables.

I need to connect everything through the proxy, so that all internet access is routed via the proxy. Essentially, the proxy should be transformed into a kind of VPN.

I am thinking about something similar to the --net=container option where the container gets its network from another container.

How do I configure a container to run everything through the proxy?

答:
Jan Garaj's comment actually pointed me in the right direction.

As noted in my question, not all programs and commands use the proxy environment variables so simply passing the http_proxy and https_proxy env vars to docker is not a solution. I needed a solution where the whole docker container is directing every network requests (on certain ports) through the proxy. No matter which program or command.

The Medium article demonstrates how to build and setup a docker container that, by the help of redsocks, will redirect all ftp requests to another running docker container acting as a proxy. The communication between the containers is done via a docker network.

In my case I already have a running proxy so I don't need a docker network and a docker proxy. Also, I need to proxy http and https, not ftp.

By changing the configuration files I got it working. In this example I simply call wget ipecho.net/plain to retrieve my outside IP. If it works, this should be the IP of the proxy, not my real IP.

Configuration

Dockerfile:

```<code>FROM debian:latest
LABEL maintainer="marlar"
WORKDIR /app
ADD . /app
RUN apt-get update
RUN apt-get upgrade -qy
RUN apt-get install iptables redsocks curl wget lynx -qy
COPY redsocks.conf /etc/redsocks.conf
ENTRYPOINT /bin/bash run.sh
</code>```

setup script (run.sh):

```<code>#!/bin/bash
echo "Configuration:"
echo "PROXY_SERVER=$PROXY_SERVER"
echo "PROXY_PORT=$PROXY_PORT"
echo "Setting config variables"
sed -i "s/vPROXY-SERVER/$PROXY_SERVER/g" /etc/redsocks.conf
sed -i "s/vPROXY-PORT/$PROXY_PORT/g" /etc/redsocks.conf
echo "Restarting redsocks and redirecting traffic via iptables"
/etc/init.d/redsocks restart
iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to-port 12345
iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to-port 12345
echo "Getting IP ..."
wget -q -O- https://ipecho.net/plain
</code>```

redsocks.conf:

```<code>base {
 log_debug = off;
 log_info = on;
 log = "file:/var/log/redsocks.log";
 daemon = on;
 user = redsocks;
 group = redsocks;
 redirector = iptables;
}
redsocks {
 local_ip = 127.0.0.1;
 local_port = 12345;
 ip = vPROXY-SERVER;
 port = vPROXY-PORT;
 type = http-connect;

}
</code>```

Building the container

```<code>build -t proxy-via-iptables .
</code>```

Running the container

```<code>docker run -i -t  --privileged -e PROXY_SERVER=x.x.x.x -e PROXY_PORT=xxxx proxy-via-iptables
</code>```

Replace the proxy server and port with the relevant numbers.

If the container works and uses the external proxy, wget should spit out the IP of the proxy even though the wget command does not use the -e use_proxy=yes option. If it doesn't work, it will give you your own IP. Or perhaps no IP at all, depending on how it fails.

Body:
Jan Garaj's comment actually pointed me in the right direction.

As noted in my question, not all programs and commands use the proxy environment variables so simply passing the http_proxy and https_proxy env vars to docker is not a solution. I needed a solution where the whole docker container is directing every network requests (on certain ports) through the proxy. No matter which program or command.

The Medium article demonstrates how to build and setup a docker container that, by the help of redsocks, will redirect all ftp requests to another running docker container acting as a proxy. The communication between the containers is done via a docker network.

In my case I already have a running proxy so I don't need a docker network and a docker proxy. Also, I need to proxy http and https, not ftp.

By changing the configuration files I got it working. In this example I simply call wget ipecho.net/plain to retrieve my outside IP. If it works, this should be the IP of the proxy, not my real IP.

Configuration

Dockerfile:

FROM debian:latest
LABEL maintainer="marlar"
WORKDIR /app
ADD . /app
RUN apt-get update
RUN apt-get upgrade -qy
RUN apt-get install iptables redsocks curl wget lynx -qy
COPY redsocks.conf /etc/redsocks.conf
ENTRYPOINT /bin/bash run.sh

setup script (run.sh):

#!/bin/bash
echo "Configuration:"
echo "PROXY_SERVER=$PROXY_SERVER"
echo "PROXY_PORT=$PROXY_PORT"
echo "Setting config variables"
sed -i "s/vPROXY-SERVER/$PROXY_SERVER/g" /etc/redsocks.conf
sed -i "s/vPROXY-PORT/$PROXY_PORT/g" /etc/redsocks.conf
echo "Restarting redsocks and redirecting traffic via iptables"
/etc/init.d/redsocks restart
iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to-port 12345
iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to-port 12345
echo "Getting IP ..."
wget -q -O- https://ipecho.net/plain

redsocks.conf:

base {
 log_debug = off;
 log_info = on;
 log = "file:/var/log/redsocks.log";
 daemon = on;
 user = redsocks;
 group = redsocks;
 redirector = iptables;
}
redsocks {
 local_ip = 127.0.0.1;
 local_port = 12345;
 ip = vPROXY-SERVER;
 port = vPROXY-PORT;
 type = http-connect;

}

Building the container

build -t proxy-via-iptables .

Running the container

docker run -i -t  --privileged -e PROXY_SERVER=x.x.x.x -e PROXY_PORT=xxxx proxy-via-iptables

Replace the proxy server and port with the relevant numbers.

If the container works and uses the external proxy, wget should spit out the IP of the proxy even though the wget command does not use the -e use_proxy=yes option. If it doesn't work, it will give you your own IP. Or perhaps no IP at all, depending on how it fails.


问:
Filtering: An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft
I have this project, and I have api and through this api, the users in the Database are returned, but in the response, data is returned in addition to two variables, the first “isActive” and the second “isVerified”, and through these two values I can control the display, which means I can control the The data values that will be displayed on the interface,

If the value of the previous two variables is False, it means that the user has been rejected. Therefore, I save the rejected user in the "UsersRequests" array, and then I display the values in the "UsersRequests" array on the interface called "Users Requests"

And if the value of the previous two variables is true, then this means that the user has been accepted and has become a user of the site, so I save the user in the array “Users”,
Then I display the values in the "Users" array on the interface called "Users".

And based on the previous cases, I filtered the values coming from the backend

But I got this error:

```<code>[Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.
</code>```

How can I solve the problem?

```<code>import {
  createSlice,
  createAsyncThunk,
  createEntityAdapter,
} from "@reduxjs/toolkit";
import axios from "axios";

export const getUsersRequests = createAsyncThunk(
  "usersRequests/getUsersRequests",
  async () => {
    const response = await axios
      .get("/users/for-admin")
      .catch((err) => console.log(err));
    const usersRequestsData = response.data.data;
    console.log("data inside Slice:", usersRequestsData);
    return usersRequestsData;
  }
);

// This is one of the keys 'slice name' which is 'usersRequests'
const contactsSlice = createSlice({
  name: "usersRequests",
  initialState: {
    data: [],
    usersRequests: [],
    status: null,
    approve: null,
    acceptedUsers: [],
  },
  reducers: {},
  extraReducers: {
    [getUsersRequests.pending]: (state) => {
      state.status = "loading";
    },
    [getUsersRequests.fulfilled]: (state, { payload }) => {
      state.status = "success";
      state.data = payload;
      console.log("inside coooontact Slice: ", state.data);
      return state.data.filter((user) => {
        if (user.isActive == false && user.isVerified == false) {
          state.usersRequests = user;
        } else {
          state.users = user;
        }
      });
    },
    [getUsersRequests.rejected]: (state) => {
      state.status = "failed";
    },

});

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

答:
In a reducer created with createSlice, the state parameter is an Immer draft. Your reducer function must either modify the draft or return a new object, but not both. As you've implemented the reducer, the assignment of the status and data properties modify the draft, but then the value produced by state.data.filter is returned. This causes the error message you're seeing.

Instead, iterate through state.data and modify the two user properties, but do not explicitly return anything from the function. It might look something like this (extracted to a named function for demonstration):

function getUserRequestsFulfilled(state, { payload }) {
  state.status = "success";
  state.data = payload;
  state.data.forEach((user) => {
    if (user.isActive == false && user.isVerified == false) {
      state.usersRequests.push(user);
    } else {
      state.users.push(user);
    }
  });
}
```

Body:
I have this project, and I have api and through this api, the users in the Database are returned, but in the response, data is returned in addition to two variables, the first “isActive” and the second “isVerified”, and through these two values I can control the display, which means I can control the The data values that will be displayed on the interface,

If the value of the previous two variables is False, it means that the user has been rejected. Therefore, I save the rejected user in the "UsersRequests" array, and then I display the values in the "UsersRequests" array on the interface called "Users Requests"

And if the value of the previous two variables is true, then this means that the user has been accepted and has become a user of the site, so I save the user in the array “Users”,
Then I display the values in the "Users" array on the interface called "Users".

And based on the previous cases, I filtered the values coming from the backend

But I got this error:

[Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.

How can I solve the problem?

import {
  createSlice,
  createAsyncThunk,
  createEntityAdapter,
} from "@reduxjs/toolkit";
import axios from "axios";

export const getUsersRequests = createAsyncThunk(
  "usersRequests/getUsersRequests",
  async () => {
    const response = await axios
      .get("/users/for-admin")
      .catch((err) => console.log(err));
    const usersRequestsData = response.data.data;
    console.log("data inside Slice:", usersRequestsData);
    return usersRequestsData;
  }
);

// This is one of the keys 'slice name' which is 'usersRequests'
const contactsSlice = createSlice({
  name: "usersRequests",
  initialState: {
    data: [],
    usersRequests: [],
    status: null,
    approve: null,
    acceptedUsers: [],
  },
  reducers: {},
  extraReducers: {
    [getUsersRequests.pending]: (state) => {
      state.status = "loading";
    },
    [getUsersRequests.fulfilled]: (state, { payload }) => {
      state.status = "success";
      state.data = payload;
      console.log("inside coooontact Slice: ", state.data);
      return state.data.filter((user) => {
        if (user.isActive == false && user.isVerified == false) {
          state.usersRequests = user;
        } else {
          state.users = user;
        }
      });
    },
    [getUsersRequests.rejected]: (state) => {
      state.status = "failed";
    },

});

export default contactsSlice.reducer;


问:
getopt() function: purpose of addition of argv
code piece from book

I am reading getopt() funtion from a book and trying to make a program that takes command line arguments. But what is the purpose of adding optind to argv, and how to add an integer to pointer array? Full code:

```<code>#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[]){
    char *delivery = "";
    int thick = 0;
    int count = 0;
    char ch;

    while((ch = getopt(argc, argv, "td:")) != EOF)
        printf("%i\n", ch);
        switch(ch){
            case 'd':
                delivery = optarg;
                break;
            case 't':
                thick = 1;
                break;
            default:
                fprintf(stderr, "Unknown option: '%s'\n", optarg);
                return 1;
    argc -= optind;
    argv += optind;

    if(thick)
        puts("Thick crust.");

    if(delivery[0])
        printf("To be delivered %s.\n", delivery);

    puts("Ingredients:");

    for(count = 0 ; count < argc ; ++count)
        puts(argv[count]);
    return 0;
}
</code>```

答:
optind is the index of the next parameter to manage on the command line. In other words, it is the number of parameters managed so far. The goal of adding optind to argv is to make it point to the possible remaining parameters behind the already managed options on the command line. Hence, those additional parameters will be in argv[0], argv[1]... up to argv[argc - 1] since argc has been decremented with optind.

The following loop displays those additional parameters on the command line:

for(count = 0 ; count < argc ; ++count)
        puts(argv[count]);
```
<p>If you don't add <em>optind</em> to <em>argv</em> and don't decrement <em>argc</em> with it, the previous loop would have been:</p>
<pre class="lang-c prettyprint-override"><code>for(count = optind ; count < argc ; ++count)
        puts(argv[count]);
</code>```

N.B.: As argv is a pointer on a char *, adding to it some value like optind makes it be incremented by "optind x sizeof(char *)"

Body:
code piece from book

I am reading getopt() funtion from a book and trying to make a program that takes command line arguments. But what is the purpose of adding optind to argv, and how to add an integer to pointer array? Full code:

#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[]){
    char *delivery = "";
    int thick = 0;
    int count = 0;
    char ch;

    while((ch = getopt(argc, argv, "td:")) != EOF)
        printf("%i\n", ch);
        switch(ch){
            case 'd':
                delivery = optarg;
                break;
            case 't':
                thick = 1;
                break;
            default:
                fprintf(stderr, "Unknown option: '%s'\n", optarg);
                return 1;
    argc -= optind;
    argv += optind;

    if(thick)
        puts("Thick crust.");

    if(delivery[0])
        printf("To be delivered %s.\n", delivery);

    puts("Ingredients:");

    for(count = 0 ; count < argc ; ++count)
        puts(argv[count]);
    return 0;
}

Body:
optind is the index of the next parameter to manage on the command line. In other words, it is the number of parameters managed so far. The goal of adding optind to argv is to make it point to the possible remaining parameters behind the already managed options on the command line. Hence, those additional parameters will be in argv[0], argv[1]... up to argv[argc - 1] since argc has been decremented with optind.

The following loop displays those additional parameters on the command line:

for(count = 0 ; count < argc ; ++count)
        puts(argv[count]);

If you don't add optind to argv and don't decrement argc with it, the previous loop would have been:

for(count = optind ; count < argc ; ++count)
        puts(argv[count]);

N.B.: As argv is a pointer on a char *, adding to it some value like optind makes it be incremented by "optind x sizeof(char *)"


问:
How can I do not use constructor in MainActivity in Android Studio?
I'm a beginner.
I'm trying to make Locale project with Android Studio.
So I made a class regard with Context.
In MainActivity required a constructor.
But, I'm heard that MainActivity do not need constructor but onCreate.

Here is my code.

BaseContextWrapper

```<code>    public class BaseContextWrapper extends AppCompatActivity {
    //AppCompatActivity-FragmentActivity-ComponentActivity-Activity-ContextThemeWrapper-ContextWrapper-Context
    public BaseContextWrapper(Context base) {
        super.attachBaseContext(base);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @NonNull
    public static ContextWrapper wrap(Context context) {
        Resources resources = context.getResources();
        Configuration newConfig = new Configuration();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        newConfig.setToDefaults();

        newConfig.densityDpi = metrics.densityDpi;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            context = context.createConfigurationContext(newConfig);
        } else {
            resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
        }
        return new BaseContextWrapper(context);
    }
}
</code>```

MainActivity

```<code>    public class MainActivity extends BaseContextWrapper {
    public MainActivity(Context base) {
        super(base);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

答:
It all depends on what you inherit from. If from "extends Base ContextWrapper", then the constructor is required, it is included in the class. But if from "extends AppCompatActivity" then nothing but the onCreate() method is needed</p>
```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

Body:
I'm a beginner.
I'm trying to make Locale project with Android Studio.
So I made a class regard with Context.
In MainActivity required a constructor.
But, I'm heard that MainActivity do not need constructor but onCreate.

Here is my code.

BaseContextWrapper

    public class BaseContextWrapper extends AppCompatActivity {
    //AppCompatActivity-FragmentActivity-ComponentActivity-Activity-ContextThemeWrapper-ContextWrapper-Context
    public BaseContextWrapper(Context base) {
        super.attachBaseContext(base);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @NonNull
    public static ContextWrapper wrap(Context context) {
        Resources resources = context.getResources();
        Configuration newConfig = new Configuration();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        newConfig.setToDefaults();

        newConfig.densityDpi = metrics.densityDpi;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            context = context.createConfigurationContext(newConfig);
        } else {
            resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
        }
        return new BaseContextWrapper(context);
    }
}

MainActivity

    public class MainActivity extends BaseContextWrapper {
    public MainActivity(Context base) {
        super(base);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Body:
It all depends on what you inherit from. If from "extends Base ContextWrapper", then the constructor is required, it is included in the class. But if from "extends AppCompatActivity" then nothing but the onCreate() method is needed

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


答:
Two trouble for me :

One in the extraReducer you need to use builder like that :

```<code>extraReducers:(builder) => {
    builder.addCase(-typeAction-, state => {
     //doSomething...
      // state.value = newValue;
    });
  }
</code>```

See : https://redux-toolkit.js.org/api/createslice

Second trouble (less) :

```<code> return state.data.filter((user) => {
    if (user.isActive == false && user.isVerified == false) {
      state.usersRequests = user;
    } else {
      state.users = user;
    }
  });
</code>```

Try to change for :

```<code> state.data.forEach((user) => {
    ...
</code>```

D'après MozillaDev :
La méthode forEach() permet d'exécuter une fonction donnée sur chaque élément du tableau.
La méthode filter() crée et retourne un nouveau tableau contenant tous les éléments du tableau d'origine qui remplissent une condition déterminée par la fonction callback.

So you return a value on a Reducer with redux-toolkit, Immer don't like that.

Say me if it's good for you.

//edit

```<code>extraReducers: (builder) => {
builder
  .addCase(getUsersRequests.pending: (state) => {
  state.status = "loading";
}),
.addCase(getUsersRequests.fulfilled: (state, { payload }) => {
  state.status = "success";
  state.data = payload;
  console.log("inside coooontact Slice: ", state.data);
  state.data.forEach((user) => {
    if (user.isActive == false && user.isVerified == false) {
      state.usersRequests = user;
    } else {
      state.users = user;
    }
  });
}),
.addCase(getUsersRequests.rejected: (state) => {
  state.status = "failed";
}),
</code>```

Title: Filtering: An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft

Body:
Two trouble for me :

One in the extraReducer you need to use builder like that :

extraReducers:(builder) => {
    builder.addCase(-typeAction-, state => {
     //doSomething...
      // state.value = newValue;
    });
  }

See : https://redux-toolkit.js.org/api/createslice

Second trouble (less) :

 return state.data.filter((user) => {
    if (user.isActive == false && user.isVerified == false) {
      state.usersRequests = user;
    } else {
      state.users = user;
    }
  });

Try to change for :

 state.data.forEach((user) => {
    ...

D'après MozillaDev :
La méthode forEach() permet d'exécuter une fonction donnée sur chaque élément du tableau.
La méthode filter() crée et retourne un nouveau tableau contenant tous les éléments du tableau d'origine qui remplissent une condition déterminée par la fonction callback.

So you return a value on a Reducer with redux-toolkit, Immer don't like that.

Say me if it's good for you.

//edit

extraReducers: (builder) => {
builder
  .addCase(getUsersRequests.pending: (state) => {
  state.status = "loading";
}),
.addCase(getUsersRequests.fulfilled: (state, { payload }) => {
  state.status = "success";
  state.data = payload;
  console.log("inside coooontact Slice: ", state.data);
  state.data.forEach((user) => {
    if (user.isActive == false && user.isVerified == false) {
      state.usersRequests = user;
    } else {
      state.users = user;
    }
  });
}),
.addCase(getUsersRequests.rejected: (state) => {
  state.status = "failed";
}),