问:
React loader's state doesn't change
I am trying to implement a loading spinner into my React app, but I have a problem with changing its state. It is supposed to appear when the data to display is being downloaded through Axios (once the function getProjectDetails gets the data, see componentDidMount) and then disappear. But right now it's just spinning forever. What am I doing wrong?</p>
```<code>export function StyledTabs(props) {
    const [value, setValue] = React.useState(0);
    const [loading, setLoading] = useState(true);

    const handleChange = (event, newValue) => {
        console.log(props)
        setValue(newValue);
    };

    function tabProps(index) {
        return {
            id: `vertical-tab-${index}`,
            'aria-controls': `vertical-tabpanel-${index}`,
        };
    }

    return loading ? <LoadingComponent /> : (
        <div>
            <AppBar position="static" color="transparent">
                <Tabs
                    value={value}
                    onChange={handleChange}
                    variant="scrollable"
                    scrollButtons="on">
                    <Tab label="Project Information" {...tabProps(0)} />
                    <Tab label="Group Procurement Information" {...tabProps(1)} />
                    <Tab label="Other Information" {...tabProps(2)} />
                    <Tab label="Improvement Calculation* (Absolute Number)" {...tabProps(3)} />
                    <Tab label="Project Description" {...tabProps(4)} />
                </Tabs>
              </AppBar>
             </div>

   export default class ProjectDetails extends React.Component {
    state = {
        projectDetails: {
            additionalEntities: "a5ff008e-eb77-4f4a-9ee7-0d863ffed1ed",
            additionalEntityName: "",
            businessCFO: 0,
            businessController: 0,
            businessOwner: 0,
            categoryName: "Technical Marine (Strategic)",
            contractEndDate: "2021-08-26T00:00:00",
            contractStartDate: "2021-08-26T00:00:00",
            description: "Test Desctription",
            descriptionId: 1,
            ebitda: 0,
            gpCategory: "fb6028e5-4273-4176-8cdb-978de1fd2e99",
            gpSubCategory: "e3a22c6e-6ffa-43e4-867d-0f51e90540e3",
            legalEntity: "4af62e99-abb4-41c5-835e-063a5f4eaa46",
            nameOfSuplier: "string",
            OverallImprovementTypeId: 1,
            overallImprovementTypeName: "OPEX",
            projectId: "351b2f09-d879-4db1-02b1-08d968707193",
            projectName: "Test Project",
            FullProjectNumber: "000.00",
            projectResponsible: 0,
            subCategoryName: "Terminal Equipment",
            valueImprovementTypeId: 1,
            valueImprovementTypeName: "EBIT"
        }
    }

    componentDidMount() {
        this.getProjectDetails();
        this.setState(() => {
          return  {loading: false}
        })
    }

    getProjectDetails() {
        customInstance.get('Project/' + this.id).then((response) => {
            const projectDetails = response.data;
            this.setState((state) => {
                state = response.data;
                this.state.projectDetails = response.data;
                return state;
            });
        });
        console.log(this.state.projectDetails);
    }
</code>```

答: componentDidMount is for class components but you are using function component you should use useEffect instead and you should change the state with useState like this : setLoading(false) otherwise the loading will be always true and always spinning. also you dont need "this" in function component

Title: React loader's state doesn't change

Body:
I am trying to implement a loading spinner into my React app, but I have a problem with changing its state. It is supposed to appear when the data to display is being downloaded through Axios (once the function getProjectDetails gets the data, see componentDidMount) and then disappear. But right now it's just spinning forever. What am I doing wrong?

export function StyledTabs(props) {
    const [value, setValue] = React.useState(0);
    const [loading, setLoading] = useState(true);

    const handleChange = (event, newValue) => {
        console.log(props)
        setValue(newValue);
    };

    function tabProps(index) {
        return {
            id: `vertical-tab-${index}`,
            'aria-controls': `vertical-tabpanel-${index}`,
        };
    }

    return loading ? <LoadingComponent /> : (

            <AppBar position="static" color="transparent">
                <Tabs
                    value={value}
                    onChange={handleChange}
                    variant="scrollable"
                    scrollButtons="on">
                    <Tab label="Project Information" {...tabProps(0)} />
                    <Tab label="Group Procurement Information" {...tabProps(1)} />
                    <Tab label="Other Information" {...tabProps(2)} />
                    <Tab label="Improvement Calculation* (Absolute Number)" {...tabProps(3)} />
                    <Tab label="Project Description" {...tabProps(4)} />
                </Tabs>
              </AppBar>

   export default class ProjectDetails extends React.Component {
    state = {
        projectDetails: {
            additionalEntities: "a5ff008e-eb77-4f4a-9ee7-0d863ffed1ed",
            additionalEntityName: "",
            businessCFO: 0,
            businessController: 0,
            businessOwner: 0,
            categoryName: "Technical Marine (Strategic)",
            contractEndDate: "2021-08-26T00:00:00",
            contractStartDate: "2021-08-26T00:00:00",
            description: "Test Desctription",
            descriptionId: 1,
            ebitda: 0,
            gpCategory: "fb6028e5-4273-4176-8cdb-978de1fd2e99",
            gpSubCategory: "e3a22c6e-6ffa-43e4-867d-0f51e90540e3",
            legalEntity: "4af62e99-abb4-41c5-835e-063a5f4eaa46",
            nameOfSuplier: "string",
            OverallImprovementTypeId: 1,
            overallImprovementTypeName: "OPEX",
            projectId: "351b2f09-d879-4db1-02b1-08d968707193",
            projectName: "Test Project",
            FullProjectNumber: "000.00",
            projectResponsible: 0,
            subCategoryName: "Terminal Equipment",
            valueImprovementTypeId: 1,
            valueImprovementTypeName: "EBIT"
        }
    }

    componentDidMount() {
        this.getProjectDetails();
        this.setState(() => {
          return  {loading: false}
        })
    }

    getProjectDetails() {
        customInstance.get('Project/' + this.id).then((response) => {
            const projectDetails = response.data;
            this.setState((state) => {
                state = response.data;
                this.state.projectDetails = response.data;
                return state;
            });
        });
        console.log(this.state.projectDetails);
    }


来源: stackexchange

问:
C equivalent x-macro defined enum in Rust
I have been a C/C++ developer for more years than I care to remember. I am now starting out in Rust. Based on reading the documentation, I believe it will be able to address most, if not all, of my needs directly. However, I want to make sure that I can understand the Rust equivalent syntax for the following C++ syntax (I skipped error checking code for simplicity)

#include <iostream>
#include <map>

#define MY_ENUM \
  X(AA, 17) \
  X(BB, 42)

enum my_enum {
#define X(name, val) name = val,
  MY_ENUM
#undef X
};

std::string enum_to_str(my_enum x)
{
  static std::map<int, std::string> lookup = {
#define X(name, val) {val, #name},
  MY_ENUM
#undef X
  };
  return lookup.at(x);
}

my_enum str_to_enum(const std::string &x)
{
  static std::map<std::string, my_enum> lookup = {
#define X(name, val) {#name, my_enum(val)},
  MY_ENUM
#undef X
  };
  return lookup.at(x);
}

int main()
{
  my_enum x = AA;
  const std::string bb("BB");
  std::cout << "x=" << x << " which is " << enum_to_str(x) << std::endl;
  std::cout << bb << " is " << str_to_enum(bb) << std::endl;
}
```
<p>I believe I can achieve the <code>to_string()</code> functionality using either the <code>Display</code> or <code>Debug</code> trait in Rust, like so.</p>
<pre class="lang-rust prettyprint-override"><code>#[derive(Debug)]
enum MyEnum {
    AA = 17,
}

//use std::fmt;
//impl fmt::Display for MyEnum {
//    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//       write!(f, "{:?}", self)
//    }
//}

fn main() {
    let x = MyEnum::AA;
    println!("x={:?}", x);
}
</code>```

What would be a way to do the string_to_enum() in Rust?

答:
In rust, the normal way to convert strings into other types is by using the FromStr trait. However, FromStr can, by default, not be derived.

I thought I could recommend you the derive_more crate. Using this crate you can derive more traits, as the name implies. Unfortunately it does not support enums at this moment. I think that would be a fun addition to the library.

I think you can solve this problem with macros, but the clearest, cleanest, and most idiomatic way is just implementing FromStr yourself. You can use a match statement, matching on each of the strings and producing an enum variant. Doing this, you can also change the format of the strings which produce certain variants. For example, your enum variants might have capitalized names, but you may not want the strings to be capitalized as well. You could also add aliasses this way. An example:

enum MyEnum {
   A,
   B
}

struct FromStrError;

impl FromStr for MyEnum {
    type Err = FromStrError;

    fn from_str(v: &str) -> Result<Self, Self::Err> {
        match v {
            "a" => Ok(Self::A),
            "b" => Ok(Self::B),
            _ => Err(FromStrError),
        }
    }

}

fn main() {
    let parsed: MyEnum = "a".parse()?
}

```
<p>I understand this may not be an answer to your exact question: You wanted something equialent to the X macro. I think this is the way you will want to implement this, but if you really prefer a macro solution please let me know. Your question feels to me a bit like an X-Y problem. "how can I do X in rust", while what you actually want may be Y. Anyway, let me know if I can help you further.</p>
<p>NOTE: the to_string functionality you definitely can achieve with <code>derive_more</code>! See here</p>
<p>EDIT: if you really want a macro solution, and I want to stress again that I don't think this is the right solution, you can do something like this:</p>
<pre class="lang-rust prettyprint-override"><code>// define a macro generating both FromStr and Display implementations
macro_rules! stringy_enum {
    (enum $name: ident {
        $($variant: ident = $value: literal),* $(,)?
    }) => {
        #[derive(Debug, PartialEq)] // for tests, no need if you don't want it
        enum $name {
            $($variant = $value),*
        }

        impl std::str::FromStr for $name {
            type Err = String;

            fn from_str(value: &str) -> Result<Self, Self::Err> {
                match value {
                    $(
                        stringify!($variant) => {Ok(Self::$variant)}
                    )*
                    _ => {
                        Err(format!("couldn't parse to {}", stringify!($name)))
                    }
                }
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                match self {
                    $(
                        Self::$variant => {write!(f, stringify!($variant))}
                    )*
                }
            }
        }
    };
}

stringy_enum!(
    enum MyEnum {
        A = 3,
        B = 4,
    }
);

#[test]
fn example() {
    // strings can be parsed into enums
    assert_eq!(Ok(MyEnum::A), "A".parse());
    // enums can be converted into strings
    assert_eq!(MyEnum::A.to_string(), "A");
}

</code>```

note that this solution does not accept custom derives on the enum (the macro doesn't parse those), it doesn't accept anything other than variant = name pairs, it does not accept a pub keyword or other visibility attribues (though that's easy to add), it does not accept any other custom attributes other than derive, it does not support variants with values, etc. This is just an example. Don't literally use it.

ContentLicense: CC BY-SA 4.0

Body:
I have been a C/C++ developer for more years than I care to remember. I am now starting out in Rust. Based on reading the documentation, I believe it will be able to address most, if not all, of my needs directly. However, I want to make sure that I can understand the Rust equivalent syntax for the following C++ syntax (I skipped error checking code for simplicity)

#include <iostream>
#include <map>

#define MY_ENUM \
  X(AA, 17) \
  X(BB, 42)

enum my_enum {
#define X(name, val) name = val,
  MY_ENUM
#undef X
};

std::string enum_to_str(my_enum x)
{
  static std::map<int, std::string> lookup = {
#define X(name, val) {val, #name},
  MY_ENUM
#undef X
  };
  return lookup.at(x);
}

my_enum str_to_enum(const std::string &x)
{
  static std::map<std::string, my_enum> lookup = {
#define X(name, val) {#name, my_enum(val)},
  MY_ENUM
#undef X
  };
  return lookup.at(x);
}

int main()
{
  my_enum x = AA;
  const std::string bb("BB");
  std::cout << "x=" << x << " which is " << enum_to_str(x) << std::endl;
  std::cout << bb << " is " << str_to_enum(bb) << std::endl;
}

I believe I can achieve the to_string() functionality using either the Display or Debug trait in Rust, like so.

#[derive(Debug)]
enum MyEnum {
    AA = 17,
}

//use std::fmt;
//impl fmt::Display for MyEnum {
//    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//       write!(f, "{:?}", self)
//    }
//}

fn main() {
    let x = MyEnum::AA;
    println!("x={:?}", x);
}

What would be a way to do the string_to_enum() in Rust?

Body:
In rust, the normal way to convert strings into other types is by using the FromStr trait. However, FromStr can, by default, not be derived.

I thought I could recommend you the derive_more crate. Using this crate you can derive more traits, as the name implies. Unfortunately it does not support enums at this moment. I think that would be a fun addition to the library.

I think you can solve this problem with macros, but the clearest, cleanest, and most idiomatic way is just implementing FromStr yourself. You can use a match statement, matching on each of the strings and producing an enum variant. Doing this, you can also change the format of the strings which produce certain variants. For example, your enum variants might have capitalized names, but you may not want the strings to be capitalized as well. You could also add aliasses this way. An example:

enum MyEnum {
   A,
   B
}

struct FromStrError;

impl FromStr for MyEnum {
    type Err = FromStrError;

    fn from_str(v: &str) -> Result<Self, Self::Err> {
        match v {
            "a" => Ok(Self::A),
            "b" => Ok(Self::B),
            _ => Err(FromStrError),
        }
    }

}

fn main() {
    let parsed: MyEnum = "a".parse()?
}

I understand this may not be an answer to your exact question: You wanted something equialent to the X macro. I think this is the way you will want to implement this, but if you really prefer a macro solution please let me know. Your question feels to me a bit like an X-Y problem. "how can I do X in rust", while what you actually want may be Y. Anyway, let me know if I can help you further.

NOTE: the to_string functionality you definitely can achieve with derive_more! See here

EDIT: if you really want a macro solution, and I want to stress again that I don't think this is the right solution, you can do something like this:

// define a macro generating both FromStr and Display implementations
macro_rules! stringy_enum {
    (enum $name: ident {
        $($variant: ident = $value: literal),* $(,)?
    }) => {
        #[derive(Debug, PartialEq)] // for tests, no need if you don't want it
        enum $name {
            $($variant = $value),*
        }

        impl std::str::FromStr for $name {
            type Err = String;

            fn from_str(value: &str) -> Result<Self, Self::Err> {
                match value {
                    $(
                        stringify!($variant) => {Ok(Self::$variant)}
                    )*
                    _ => {
                        Err(format!("couldn't parse to {}", stringify!($name)))
                    }
                }
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                match self {
                    $(
                        Self::$variant => {write!(f, stringify!($variant))}
                    )*
                }
            }
        }
    };
}

stringy_enum!(
    enum MyEnum {
        A = 3,
        B = 4,
    }
);

#[test]
fn example() {
    // strings can be parsed into enums
    assert_eq!(Ok(MyEnum::A), "A".parse());
    // enums can be converted into strings
    assert_eq!(MyEnum::A.to_string(), "A");
}

note that this solution does not accept custom derives on the enum (the macro doesn't parse those), it doesn't accept anything other than variant = name pairs, it does not accept a pub keyword or other visibility attribues (though that's easy to add), it does not accept any other custom attributes other than derive, it does not support variants with values, etc. This is just an example. Don't literally use it.


问:
AttributeError: 'NoneType' object has no attribute 'build_absolute_uri' Django Rest Framework
I've got this Serializer translating path to url, and it works on its own, but when i try to nest this serializer inside another serializer, i get this error. Do you have any idea why? I need to have this function, because otherwise it just shows the paths to the image in this main SpecialistSerializer.

```<code>class EntityPhotosSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField('get_file_abs_url')

    class Meta:
        model = EntityPhoto
        fields = ('user', 'entity', 'image',)

    def get_file_abs_url(self, obj):
        request = self.context.get('request')
        return request.build_absolute_uri(obj.image.url)

</code>```
```<code>class SpecialistSerializer(serializers.ModelSerializer):
    reviews_quantity = serializers.IntegerField(source="get_reviews_quantity")

    class Meta:
        model = Entity
        fields = '__all__'

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['photos'] = EntityPhotosSerializer(many=True, instance=instance.entityphoto_set.all()).data
        return data
</code>```

Traceback:

```<code>Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 282, in get
    return self.retrieve(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 56, in retrieve
    return Response(serializer.data)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 548, in data
    ret = super().data
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 246, in data
    self._data = self.to_representation(self.instance)
  File "/Users/jakubstrawa/programming/PythonKuba/api/specialists/serializers.py", line 35, in to_representation
    data['photos'] = EntityPhotosSerializer(many=True, instance=instance.entityphoto_set.all()).data
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 745, in data
    ret = super().data
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 246, in data
    self._data = self.to_representation(self.instance)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 664, in to_representation
    self.child.to_representation(item) for item in iterable
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 664, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 515, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/fields.py", line 1870, in to_representation
    return method(value)
  File "/Users/jakubstrawa/programming/PythonKuba/api/specialists/serializers.py", line 23, in get_file_abs_url
    return request.build_absolute_uri(obj.image.url)
AttributeError: 'NoneType' object has no attribute 'build_absolute_uri'
</code>```
```<code></code>```

答:
In to_representation, you access to the EntityPhotosSerializer. And in that serializer, you are trying to access to the context. If you want to do that, you need to pass the current context to EntityPhotosSerializer in SpecialistSerializer.

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['photos'] = EntityPhotosSerializer(many=True, context=self.context, instance=instance.entityphoto_set.all()).data
        return data
```

Body:
I've got this Serializer translating path to url, and it works on its own, but when i try to nest this serializer inside another serializer, i get this error. Do you have any idea why? I need to have this function, because otherwise it just shows the paths to the image in this main SpecialistSerializer.

class EntityPhotosSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField('get_file_abs_url')

    class Meta:
        model = EntityPhoto
        fields = ('user', 'entity', 'image',)

    def get_file_abs_url(self, obj):
        request = self.context.get('request')
        return request.build_absolute_uri(obj.image.url)

class SpecialistSerializer(serializers.ModelSerializer):
    reviews_quantity = serializers.IntegerField(source="get_reviews_quantity")

    class Meta:
        model = Entity
        fields = '__all__'

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['photos'] = EntityPhotosSerializer(many=True, instance=instance.entityphoto_set.all()).data
        return data

Traceback:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 282, in get
    return self.retrieve(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 56, in retrieve
    return Response(serializer.data)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 548, in data
    ret = super().data
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 246, in data
    self._data = self.to_representation(self.instance)
  File "/Users/jakubstrawa/programming/PythonKuba/api/specialists/serializers.py", line 35, in to_representation
    data['photos'] = EntityPhotosSerializer(many=True, instance=instance.entityphoto_set.all()).data
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 745, in data
    ret = super().data
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 246, in data
    self._data = self.to_representation(self.instance)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 664, in to_representation
    self.child.to_representation(item) for item in iterable
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 664, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 515, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/fields.py", line 1870, in to_representation
    return method(value)
  File "/Users/jakubstrawa/programming/PythonKuba/api/specialists/serializers.py", line 23, in get_file_abs_url
    return request.build_absolute_uri(obj.image.url)
AttributeError: 'NoneType' object has no attribute 'build_absolute_uri'


问:
React Carousel memory leak issue (I cannot get first selected value from list)
In my project, I listed map images through react carousel component and show its name in motion div to add some animation.

I have an problem about getting displayName value from map list.

When I remove motion.div, it works. It also works when I add this div during run time.

When I refresh the page, I get an error message.

Here is my error message shown below.

```<code>Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
</code>```

How can I fix my issue?

Here is my MapList Component shown below.

```<code>const MapList = () => {
  const { maps } = useContext(APIContext);

  const [selected, setSelected] = useState(0);

  const handleChange = (selectedIndex) => {
    setSelected(selectedIndex);
  };

  useEffect(()=>{
    handleChange(selected)
  }, [selected])

  const variants = {
    show: {
      opacity: 1,
      y: 0,
      transition: {
        ease: "easeOut",
        duration: 0.5,
      },
    },
    hide: {
      y: 50,
      opacity: 0,
    },
  };

  return (
    <div className={styles.mapList}>
      <Carousel
            infiniteLoop
            showStatus={false}
            showThumbs={false}
            dynamicHeight={false}
            swipeable={true}
            onChange={handleChange}
          >
            {maps?.map((map, index) => (
              <img className='carouselImage' src={map.splash} alt='carouselImage' key={index}></img>
            ))}
      </Carousel>
      <motion.div
        className={styles.mapInfo}
        key={selected}
        variants={variants}
        animate={"show"}
        initial="hide"
      >
        <p className={styles.mapName}>{maps?.[selected].displayName}</p>
      </motion.div>
    </div>
  )
}

export default MapList;
</code>```

答:
You should clean up your useEffect.

const MapList = () => {
  const { maps } = useContext(APIContext);

  const [selected, setSelected] = useState(0);

  const handleChange = (selectedIndex) => {
    setSelected(selectedIndex);
  };

  useEffect(()=>{
  let isMounted = false;
  if(!isMounted){
  handleChange(selected)
  }
    return () => (isMounted=true)
  }, [selected])

  const variants = {
    show: {
      opacity: 1,
      y: 0,
      transition: {
        ease: "easeOut",
        duration: 0.5,
      },
    },
    hide: {
      y: 50,
      opacity: 0,
    },
  };

  return (

      <Carousel
            infiniteLoop
            showStatus={false}
            showThumbs={false}
            dynamicHeight={false}
            swipeable={true}
            onChange={handleChange}
          >
            {maps?.map((map, index) => (

            ))}
      </Carousel>
      <motion.div
        className={styles.mapInfo}
        key={selected}
        variants={variants}
        animate={"show"}
        initial="hide"
      >

{maps?.[selected].displayName}

      </motion.div>

  )
}

export default MapList;```

Body:
In my project, I listed map images through react carousel component and show its name in motion div to add some animation.

I have an problem about getting displayName value from map list.

When I remove motion.div, it works. It also works when I add this div during run time.

When I refresh the page, I get an error message.

Here is my error message shown below.

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

How can I fix my issue?

Here is my MapList Component shown below.

const MapList = () => {
  const { maps } = useContext(APIContext);

  const [selected, setSelected] = useState(0);

  const handleChange = (selectedIndex) => {
    setSelected(selectedIndex);
  };

  useEffect(()=>{
    handleChange(selected)
  }, [selected])

  const variants = {
    show: {
      opacity: 1,
      y: 0,
      transition: {
        ease: "easeOut",
        duration: 0.5,
      },
    },
    hide: {
      y: 50,
      opacity: 0,
    },
  };

  return (

      <Carousel
            infiniteLoop
            showStatus={false}
            showThumbs={false}
            dynamicHeight={false}
            swipeable={true}
            onChange={handleChange}
          >
            {maps?.map((map, index) => (

            ))}
      </Carousel>
      <motion.div
        className={styles.mapInfo}
        key={selected}
        variants={variants}
        animate={"show"}
        initial="hide"
      >

{maps?.[selected].displayName}

      </motion.div>

  )
}

export default MapList;

Body:
You should clean up your useEffect.

const MapList = () => {
  const { maps } = useContext(APIContext);

  const [selected, setSelected] = useState(0);

  const handleChange = (selectedIndex) => {
    setSelected(selectedIndex);
  };

  useEffect(()=>{
  let isMounted = false;
  if(!isMounted){
  handleChange(selected)
  }
    return () => (isMounted=true)
  }, [selected])

  const variants = {
    show: {
      opacity: 1,
      y: 0,
      transition: {
        ease: "easeOut",
        duration: 0.5,
      },
    },
    hide: {
      y: 50,
      opacity: 0,
    },
  };

  return (
    <div className={styles.mapList}>
      <Carousel
            infiniteLoop
            showStatus={false}
            showThumbs={false}
            dynamicHeight={false}
            swipeable={true}
            onChange={handleChange}
          >
            {maps?.map((map, index) => (
              <img className='carouselImage' src={map.splash} alt='carouselImage' key={index}></img>
            ))}
      </Carousel>
      <motion.div
        className={styles.mapInfo}
        key={selected}
        variants={variants}
        animate={"show"}
        initial="hide"
      >
        <p className={styles.mapName}>{maps?.[selected].displayName}</p>
      </motion.div>
    </div>
  )
}

export default MapList;


问:
OOP PHP and 'Get-Set'
I'm wondering is there anyway to create 'Get-Set' method only once that can be use to every attribute

The following code is not correct. Just to make sure you know what I'm looking for

```<code>class someClass {
    private $attrA;
    private $attrB;
    private $attrC;

    public function get($attr){
        return $this->$attr;
    }

    public function set($attr, $value){
        $this->$attr = $value;
    }
}
</code>```

答:
Yes, you can use the magic methods __get() and __set() in the exact way you describe.

More info on the official web site.

ContentLicense: CC BY-SA 3.0

Title: OOP PHP and 'Get-Set'

Body:
I'm wondering is there anyway to create 'Get-Set' method only once that can be use to every attribute

The following code is not correct. Just to make sure you know what I'm looking for

class someClass {
    private $attrA;
    private $attrB;
    private $attrC;

    public function get($attr){
        return $this->$attr;
    }

    public function set($attr, $value){
        $this->$attr = $value;
    }
}


问:
Add resources and config files to your JAR using Gradle
How do I add config files or any other resources into my jar using gradle?

My project structure:

src/main/java/com/perseus/.. --- Java packages (source files)

src/main/java/config/*.xml --- Spring config files

Expected jar structure:

com/perseus/.. --- Java packages (class files)

config/*.xml --- Spring config files

答:
This is for Kotlin DSL (build.gradle.kts).

Add the following code to your subproject or app build.gradle.kts file:

sourceSets {
    main {
        resources {
            srcDirs("src/main/configs", "src/main/misc")
        }
    }
    // OR another notation
    // main.get().resources.srcDirs("src/main/configs", "src/main/misc")
}
```

As mentioned by other answers, files in src/main/resources/ are automatically added to JAR. The srcDirs() function in above code adds its given paths to that existing path so files in those directories will be included in the JAR as well. You can add as many entries as you want.

Note that after adding the above code and syncing your changes with the IDE, some IDEs like IntelliJ IDEA and Android Studio show a helpful icon for those directories to indicate they are resources root directories:

Body:
This is for Kotlin DSL (build.gradle.kts).

Add the following code to your subproject or app build.gradle.kts file:

sourceSets {
    main {
        resources {
            srcDirs("src/main/configs", "src/main/misc")
        }
    }
    // OR another notation
    // main.get().resources.srcDirs("src/main/configs", "src/main/misc")
}

As mentioned by other answers, files in src/main/resources/ are automatically added to JAR. The srcDirs() function in above code adds its given paths to that existing path so files in those directories will be included in the JAR as well. You can add as many entries as you want.

Note that after adding the above code and syncing your changes with the IDE, some IDEs like IntelliJ IDEA and Android Studio show a helpful icon for those directories to indicate they are resources root directories:


问:
MongoDB - Update an object from a nested array
```<code>{ _id: 1, first : "Maria",
    travel : [
    { country: "Canada", visits: 3, rating: 7 },
    { country: "Poland", visits: 1, rating: 8 },
    { country: "Thailand", visits: 2, rating: 9 } ] },

{ _id: 2, first : "Chen",
    travel : [
    { country: "Thailand", visits: 3, rating: 7 },
    { country: "Canada", visits: 2, rating: 9 },
    { country: "Costa Rica", visits: 4, rating: 8 } ] },

{ _id: 3, first : "Gladys",
    travel : [
    { country: "Canada", visits: 1, rating: 8 },
    { country: "Thailand", visits: 2, rating: 9 },
    { country: "Australia", visits: 3, rating: 10 } ]}
])
</code>```

I need to update the visits Maria made to Canada to 5, so I have to use some sort of "double filter" (?) But I'm not sure how to do that

答:
Okay, I got how to make that "double filter" : Array filters and $[identifier]
Here</p>
```<code>db.viajeros.updateOne(  { first: "Maria"},
                        { $set: {"travel.$[elem].visits": 5}},
                        { arrayFilters: [{"elem.country": "Canada"}]}   )
</code>```

Body:
{ _id: 1, first : "Maria",
    travel : [
    { country: "Canada", visits: 3, rating: 7 },
    { country: "Poland", visits: 1, rating: 8 },
    { country: "Thailand", visits: 2, rating: 9 } ] },

{ _id: 2, first : "Chen",
    travel : [
    { country: "Thailand", visits: 3, rating: 7 },
    { country: "Canada", visits: 2, rating: 9 },
    { country: "Costa Rica", visits: 4, rating: 8 } ] },

{ _id: 3, first : "Gladys",
    travel : [
    { country: "Canada", visits: 1, rating: 8 },
    { country: "Thailand", visits: 2, rating: 9 },
    { country: "Australia", visits: 3, rating: 10 } ]}
])

I need to update the visits Maria made to Canada to 5, so I have to use some sort of "double filter" (?) But I'm not sure how to do that

Body:
Okay, I got how to make that "double filter" : Array filters and $[identifier]
Here

db.viajeros.updateOne(  { first: "Maria"},
                        { $set: {"travel.$[elem].visits": 5}},
                        { arrayFilters: [{"elem.country": "Canada"}]}   )


问:
KoinApplication has not been started on another activity
My app has a splash activity where i check for login and start Koin.

The problem is, when i go to another activity, put my app on recents (so android basicaly kills it) and go back, android try to open the activity again but Koin is not started so it crashes.

Am i doing something wrong or should i try to start Koin on every activity that uses it?

Here is how i'm starting Koin:

    onCreate......
    KoinApplication koin = KoinAndroidApplication.create(SplashActivity.this)
                .printLogger(Level.ERROR)
                .modules(
                        NetworkModule.getNetworkModule(),
                        MainModule.getMainModule()
                );
    startKoin(koin);
```

答:
Am i doing something wrong or should i try to start Koin on every activity that uses it?

You should start koin in your app's Application class like mentioned in the documentation - the Application will be created before any activity or other component is launched.


问:
I'm trying to print one letter after another
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:</p>
```<code>    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }
</code>```

答:
Note that setTimeout does not actually delay the running of the code that comes after; it just schedules for something to happen in the future. So all the letters are added at the same time, after 100 milliseconds.

The most straightforward way to fix it is to make each subsequent timeout wait a bit longer, by multiplying the delay with the index of the letter (i * 100):

const welcome = document.getElementById('welcome');
const welcText = 'Welcome!';

for (let i = 0; i < welcText.length; i++) {
    setTimeout(() => {
        welcome.innerText += welcText[i];
    }, i * 100);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="welcome"></div></code>```

Body:
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:

    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }

Body:
Note that setTimeout does not actually delay the running of the code that comes after; it just schedules for something to happen in the future. So all the letters are added at the same time, after 100 milliseconds.

The most straightforward way to fix it is to make each subsequent timeout wait a bit longer, by multiplying the delay with the index of the letter (i * 100):

const welcome = document.getElementById('welcome');
const welcText = 'Welcome!';

for (let i = 0; i < welcText.length; i++) {
    setTimeout(() => {
        welcome.innerText += welcText[i];
    }, i * 100);
}

<div id="welcome"></div>


问:
Removing columns from pandas dataframe based on function output
I have the following dataframe:

```<code>d = {'col1': ['challenging', 'swimming', ',', 'it', 'my', 'there!'], 'col2': [3, 4,5,6,7,8]}
df = pd.DataFrame(data=d)
          col1  col2
0  challenging     3
1     swimming     4
2            ,     5
3           it     6
4           my     7
5       there!     8
</code>```

I have defined this function that removes punctuations and stopwords:

```<code>from nltk.corpus import stopwords
import string
stop_words = set(stopwords.words('english'))

def remove_stopwords_punc(sent_words):
   # print(sent_words)
    return [ww for ww in sent_words
            if ww.lower() not in stop_words and ww not in string.punctuation]
from nltk.tokenize import word_tokenize
remove_stopwords_punc(word_tokenize('challenging swimming , it my there!'))

['challenging', 'swimming']
</code>```

I want to run this function on the col1 and only keep the rows that are not deemed at stopwords or punctuation, in this example leaving this output:

```<code>          col1  col2
0  challenging     3
1     swimming     4
</code>```

答:
If you preprocess the list of acceptable words, it would likely be faster (I haven't tested though):</p>
```<code>valid_words = set(remove_stopwords_punc(word_tokenize(" ".join(df['col1']))))
df = df[df['col1'] in valid_words]
</code>```

Body:
I have the following dataframe:

d = {'col1': ['challenging', 'swimming', ',', 'it', 'my', 'there!'], 'col2': [3, 4,5,6,7,8]}
df = pd.DataFrame(data=d)
          col1  col2
0  challenging     3
1     swimming     4
2            ,     5
3           it     6
4           my     7
5       there!     8

I have defined this function that removes punctuations and stopwords:

from nltk.corpus import stopwords
import string
stop_words = set(stopwords.words('english'))

def remove_stopwords_punc(sent_words):
   # print(sent_words)
    return [ww for ww in sent_words
            if ww.lower() not in stop_words and ww not in string.punctuation]
from nltk.tokenize import word_tokenize
remove_stopwords_punc(word_tokenize('challenging swimming , it my there!'))

['challenging', 'swimming']

I want to run this function on the col1 and only keep the rows that are not deemed at stopwords or punctuation, in this example leaving this output:

          col1  col2
0  challenging     3
1     swimming     4

Body:
If you preprocess the list of acceptable words, it would likely be faster (I haven't tested though):

valid_words = set(remove_stopwords_punc(word_tokenize(" ".join(df['col1']))))
df = df[df['col1'] in valid_words]


问:
How to check if a list exist inside another list
So I have a list a that contain the string "ab" and another list b that contain a list that contain the string "ab". So it look something like this:

```<code>var a = ["ab"]
var b = [["ab"]]
</code>```

How can I check if a is in b. I have try using b.includes(a) that result in a false and I also have try b.indexOf(a) which also return false. The way that I currently use is this:

```<code>var flag = false
var a = ["ab"]
var b = [["ab"]]

b.forEach((i) => {
    if (i.join("") == a.join("")) flag = true
})
console.log(flag)
</code>```

Is there like a shorter way?

Thanks y'all.

答:
Little trick for you. You can compare two array if you use toString() method.

const a = ["ab"];
const b = [["ab"]];
const result = b.some(p => p.toString().includes(a));

console.log(result);```

Body:
So I have a list a that contain the string "ab" and another list b that contain a list that contain the string "ab". So it look something like this:

var a = ["ab"]
var b = [["ab"]]

How can I check if a is in b. I have try using b.includes(a) that result in a false and I also have try b.indexOf(a) which also return false. The way that I currently use is this:

var flag = false
var a = ["ab"]
var b = [["ab"]]

b.forEach((i) => {
    if (i.join("") == a.join("")) flag = true
})
console.log(flag)

Is there like a shorter way?

Thanks y'all.


问:
FindFirst with Date value
I'm using a splitform to navigate information and I have a command button that selects a record based on today's date.

Private Sub FindDate_Click()
  TodayDate = DateTime.Date
     Me![Start Date].SetFocus
     DoCmd.FindRecord TodayDate
End Sub
```
<p>I discovered that wouldn't work if the date didn't exist in my recordset.</p>
<p>I modified the code but I get</p>
<blockquote>
<p>"Run-time error '3251': Operation is not supported for this type of
object."</p>
</blockquote>
<p>The new line of code is</p>
<pre class="lang-vb prettyprint-override"><code>Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date

StrSQl = "[Start Date] = #" & TodayDate & "#"

CurrRec.FindFirst (StrSQl)
</code>```

I'm trying to use that FindFirst function to tell me if there is a record that matches my criteria and if not I was going to -1 to TodayDate and check again until I get a record to lock onto.

答:
We create a loop with an an "on error GoTo" which will simply skip the line recording success. We then remove a day from the date variable and try again.</p>
```<code>Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date
Dim Success as Boolean
Success = false
While (Success = false)
    StrSQl = "[Start Date] = #" & TodayDate & "#"
    On Error GoTo target
    CurrRec.FindFirst (StrSQl)
    Success = true
    target
    TodayDate = DateAdd("d", -1,TodayDate)
Wend

</code>```

Title: FindFirst with Date value

Body:
I'm using a splitform to navigate information and I have a command button that selects a record based on today's date.

Private Sub FindDate_Click()
  TodayDate = DateTime.Date
     Me![Start Date].SetFocus
     DoCmd.FindRecord TodayDate
End Sub

I discovered that wouldn't work if the date didn't exist in my recordset.

I modified the code but I get

"Run-time error '3251': Operation is not supported for this type of
object."

The new line of code is

Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date

StrSQl = "[Start Date] = #" & TodayDate & "#"

CurrRec.FindFirst (StrSQl)

I'm trying to use that FindFirst function to tell me if there is a record that matches my criteria and if not I was going to -1 to TodayDate and check again until I get a record to lock onto.

Body:
We create a loop with an an "on error GoTo" which will simply skip the line recording success. We then remove a day from the date variable and try again.

Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date
Dim Success as Boolean
Success = false
While (Success = false)
    StrSQl = "[Start Date] = #" & TodayDate & "#"
    On Error GoTo target
    CurrRec.FindFirst (StrSQl)
    Success = true
    target
    TodayDate = DateAdd("d", -1,TodayDate)
Wend


问:
How can I replace a tab with four spaces in JTextArea?
I'm using a JTextArea in a JFrame. I would like the tab key to insert four spaces instead of a tab.

The method setTabSize does not work, as it puts a tab ('\t') in the contents of the text area.

How can I have JTextArea insert four spaces instead of a tab whenever I press the tab key? That way the getText() method will return indentations of four spaces for every tab.

答:
I would avoid using KeyListeners (as a general rule with JTextComponents) and even Key Bindings, since while Key Bindings would work for keyboard input, it wouldn't work for copy-and-paste.

In my mind, the best way is to use a DocumentFilter set on the JTextArea's Document (which is a PlainDocument, by the way). This way, even if you copy and paste text into the JTextAreas, one with tabs, then all the tabs will automatically be converted to 4 spaces on insertion.

For example:

```<code>import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class TestTextArea {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JTextArea textArea = new JTextArea(20, 50);
            JScrollPane scrollPane = new JScrollPane(textArea);

            int spaceCount = 4;
            ((PlainDocument) textArea.getDocument()).setDocumentFilter(new ChangeTabToSpacesFilter(spaceCount));

            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(scrollPane);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

    private static class ChangeTabToSpacesFilter extends DocumentFilter {
        private int spaceCount;
        private String spaces = "";

        public ChangeTabToSpacesFilter(int spaceCount) {
            this.spaceCount = spaceCount;
            for (int i = 0; i < spaceCount; i++) {
                spaces += " ";
            }
        }

        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            string = string.replace("\t", spaces);
            super.insertString(fb, offset, string, attr);
        }

        @Override
        public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
            super.remove(fb, offset, length);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            text = text.replace("\t", spaces);
            super.replace(fb, offset, length, text, attrs);
        }

    }

}
</code>```

So now, even if I copy and paste a document with tabs within it, into the JTextArea, all tabs will be automatically replaced with spaceCount spaces.

Body:
I would avoid using KeyListeners (as a general rule with JTextComponents) and even Key Bindings, since while Key Bindings would work for keyboard input, it wouldn't work for copy-and-paste.

In my mind, the best way is to use a DocumentFilter set on the JTextArea's Document (which is a PlainDocument, by the way). This way, even if you copy and paste text into the JTextAreas, one with tabs, then all the tabs will automatically be converted to 4 spaces on insertion.

For example:

import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class TestTextArea {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JTextArea textArea = new JTextArea(20, 50);
            JScrollPane scrollPane = new JScrollPane(textArea);

            int spaceCount = 4;
            ((PlainDocument) textArea.getDocument()).setDocumentFilter(new ChangeTabToSpacesFilter(spaceCount));

            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(scrollPane);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

    private static class ChangeTabToSpacesFilter extends DocumentFilter {
        private int spaceCount;
        private String spaces = "";

        public ChangeTabToSpacesFilter(int spaceCount) {
            this.spaceCount = spaceCount;
            for (int i = 0; i < spaceCount; i++) {
                spaces += " ";
            }
        }

        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            string = string.replace("\t", spaces);
            super.insertString(fb, offset, string, attr);
        }

        @Override
        public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
            super.remove(fb, offset, length);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            text = text.replace("\t", spaces);
            super.replace(fb, offset, length, text, attrs);
        }

    }

}

So now, even if I copy and paste a document with tabs within it, into the JTextArea, all tabs will be automatically replaced with spaceCount spaces.


问:
how can ı handle react with firebase authentication problem?
I am trying develop user authentication page in react with firebase.
I can sign in but then sign in doesn't change to sign out.
what is the problem?</p>
```<code>
    const handleAuthentication = () => {
    if(user){
        auth.signOut();
    }
   }
</code>```
```<code>  <div onClick={handleAuthentication}
            className="header_option">
                <span
                className="header_optionLineOne" >Hello, Guest</span>
                <span
                className="header_optionLineTwo" >{user ?
                'Sign Out': 'Sign In'}</span>
   </div>
</code>```

答:
Probably the user is actually signed out, but the UI is not rerendering as it doesn't know about the change.

To fix this, you'll want to store the user in the component's state, with either setState or a useState hook:

```<code>const [user, setUser] = useState(null);

auth.onAuthStateChanged((user) => {
  setUser(user);
});
</code>```

With the user being part of the state, the call to setUser(user) will cause the component to rerender and thus show the updated (lack of) user information.

Also see the first code snippet in the Firebase documentation on getting the current user.

Body:
I am trying develop user authentication page in react with firebase.
I can sign in but then sign in doesn't change to sign out.
what is the problem?

    const handleAuthentication = () => {
    if(user){
        auth.signOut();
    }
   }

                Hello, Guest
                {user ?
                'Sign Out': 'Sign In'}

Body:
Probably the user is actually signed out, but the UI is not rerendering as it doesn't know about the change.

To fix this, you'll want to store the user in the component's state, with either setState or a useState hook:

const [user, setUser] = useState(null);

auth.onAuthStateChanged((user) => {
  setUser(user);
});

With the user being part of the state, the call to setUser(user) will cause the component to rerender and thus show the updated (lack of) user information.

Also see the first code snippet in the Firebase documentation on getting the current user.


问:
The difference between two dates
I have been writing some queries about SQL Server in order to learn.

I wonder that how can I get the difference of today between 90 days ago in a SQL query?

答:
This will round correctly to midnight on the day 3 months ago (not 90 days ago) which seems to be what you want (08-18 -> 05-18 is 92 days since there were two 31sts in there).</p>

```<code>...
WHERE column >= DATEADD(MONTH, -3,
    DATEADD(DAY, DATEDIFF(DAY, '20000101', CURRENT_TIMESTAMP), '20000101'));
</code>```

Title: The difference between two dates

Body:
This will round correctly to midnight on the day 3 months ago (not 90 days ago) which seems to be what you want (08-18 -> 05-18 is 92 days since there were two 31sts in there).

...
WHERE column >= DATEADD(MONTH, -3,
    DATEADD(DAY, DATEDIFF(DAY, '20000101', CURRENT_TIMESTAMP), '20000101'));


答:
Not quiet sure what exactly you want to check but here are 2 examples:

var a = ["ab"];
var b = [["ab"]];
var flag = false;

//Example 1: search for "ab" in the nested array
b.forEach(el=>{
el.forEach(innerEl=>{
  if(innerEl === "ab") flag = true;
});
});

console.log(`Result 1 ${flag}`);

//Example 1: seach for the exact array ["ab"]
b.forEach(el=>{
 if(el == a)flag = true;
});

console.log(`Result 2 ${flag}`);```

Title: How to check if a list exist inside another list


问:
Spring Batch conditionnal database call
I'm a spring batch beginner, I'm a working on an app that needs to make a call to TWO different DB depending on a condition.

Here's what's the app does:
Read a flat file that contains credit and debit card numbers, then depending if the number is credit or debit I have to make a call to a database to get some info, then make csv file with that info. The thing is that there are two DB one for debit cards and another for credit cards.

My problem is that I'm having difficulty to configure the batch job for the conditional call to the DB. If there was only one database to call I could've done it easily but this is confusing me.

For now, I have done a card reader, that read the flat file, a processor that retrieves info from DB and a writer for the final csv. I don't really see how I could configure the processor to call a different DB since spring batch seems to use only one data source.

Edit: I have successfully been able to make the DB calls, just needed to make two data source beans (use one as primary) with two different JdbcTemplate beans.

答:
you have to configure two different Datasources Beans and inject them both in your batch processor.

Then the rest is simple (if credit use the first bean, or use the second one)

see this link for multiple datasources.

And don't forget to annotate one of them as Primary. Spring Batch will generate all its SQL tables in the Primary datasource by default.

Title: Spring Batch conditionnal database call


问:
Vectorize string operation in Python
Having two lists of strings, my goal is to apply a function f on cross product of these two vectors as

```<code>a = ['red dwarf', 'smart cat']
b = ['red car', 'black hole', 'cat']

[[f(x,y) for x in a] for y in b]
</code>```

in a more efficient way.

What options are actually available for

a general (custom) Python function f

pre-defined string distance metric?

In 2), I am looking for something similar to scipy.spatial.distance.cdist (distance metrics) that can be applied on strings.
In 1), I tried to look on Cython and Numba, but I was not able to perform better than the nested Python for loop - note that I tested a function

```<code>def f(a, b):
    v1 =  set(a)
    v2 = set(b)
    return len(v1.intersection(v2)) / (len(v1)+len(v2))
</code>```

答:
You could use itertools.product (the shape wouldn't be the same as your output though):

```<code>from itertools import product
out = [f(*tup) for tup in product(a,b)]
</code>```

Or as suggested by @Andrej and @Kelly, modify f by mapping each list to sets first then do the operations on the sets:

```<code>out = [len(v1 & v2) / (len(v1) + len(v2)) for v1, v2 in product(map(set, a), map(set, b))]
</code>```

Output:

```<code>[0.38461538461538464, 0.1875, 0.1, 0.3076923076923077, 0.1875, 0.3]
</code>```

That being said, I think your approach is plenty efficient imo.

Title: Vectorize string operation in Python

Body:
Having two lists of strings, my goal is to apply a function f on cross product of these two vectors as

a = ['red dwarf', 'smart cat']
b = ['red car', 'black hole', 'cat']

[[f(x,y) for x in a] for y in b]

in a more efficient way.

What options are actually available for

a general (custom) Python function f

pre-defined string distance metric?

In 2), I am looking for something similar to scipy.spatial.distance.cdist (distance metrics) that can be applied on strings.
In 1), I tried to look on Cython and Numba, but I was not able to perform better than the nested Python for loop - note that I tested a function

def f(a, b):
    v1 =  set(a)
    v2 = set(b)
    return len(v1.intersection(v2)) / (len(v1)+len(v2))

Body:
You could use itertools.product (the shape wouldn't be the same as your output though):

from itertools import product
out = [f(*tup) for tup in product(a,b)]

Or as suggested by @Andrej and @Kelly, modify f by mapping each list to sets first then do the operations on the sets:

out = [len(v1 & v2) / (len(v1) + len(v2)) for v1, v2 in product(map(set, a), map(set, b))]

Output:

[0.38461538461538464, 0.1875, 0.1, 0.3076923076923077, 0.1875, 0.3]

That being said, I think your approach is plenty efficient imo.


问:
What recursive function can I use to substitute the characters in a string by the greatest character on its right?
I got this exercise (it's not homework or an assignment, just practice) that asks for a program that replaces the characters in a string by the greatest character on the right using recursive functions, no loops allowed.

If I have a string acbcba the function has to return ccccba.

One thing I've tried with the loops for the string is this, to maybe try to turn it into a recursion if it worked:

```<code>void nextGreatest(char *str, int size)
{
  int max_from_right =  str[size-1];

  str[size-1] = -1;
  for(int i = size-2; i >= 0; i--)
  {
    int temp = str[i];
    str[i] = max_from_right;
    if(max_from_right < temp)
       max_from_right = temp;
  }
}

Output: cccba
</code>```

I think the issue is that it doesn't count the characters that don't have to be replaced.

There was also another example using python I found and tried to change to C (MAX is a macro from here):

```<code>void nextGreatest(char *arr, int rev_i, int maxnum){
        if (rev_i == strlen(arr) - 1){
            arr[0] = maxnum;
            return;
        }
        int i = strlen(arr) - 1 - rev_i;
        arr[i], maxnum = maxnum, MAX(maxnum, arr[i]);
        return nextGreatest(arr, rev_i + 1, maxnum);
}

Output: ~bccba
</code>```

答:
It does not need to be hard:

```<code>char nextGreatest(char *s)
{
    char n;
    if (!*s) return 0;
    n = nextGreatest(s + 1);
    return *s = MAX(*s, n);
}
</code>```

If a character is \0 then we've reached the end of the string. Otherwise, we have more characters to the right, and we want the current character to be the greatest of its own value and all values to the right. But since we call the function in this order, you only will need to call it for its direct right neighbour, because it will in turn do the same first.

Body:
I got this exercise (it's not homework or an assignment, just practice) that asks for a program that replaces the characters in a string by the greatest character on the right using recursive functions, no loops allowed.

If I have a string acbcba the function has to return ccccba.

One thing I've tried with the loops for the string is this, to maybe try to turn it into a recursion if it worked:

void nextGreatest(char *str, int size)
{
  int max_from_right =  str[size-1];

  str[size-1] = -1;
  for(int i = size-2; i >= 0; i--)
  {
    int temp = str[i];
    str[i] = max_from_right;
    if(max_from_right < temp)
       max_from_right = temp;
  }
}

Output: cccba

I think the issue is that it doesn't count the characters that don't have to be replaced.

There was also another example using python I found and tried to change to C (MAX is a macro from here):

void nextGreatest(char *arr, int rev_i, int maxnum){
        if (rev_i == strlen(arr) - 1){
            arr[0] = maxnum;
            return;
        }
        int i = strlen(arr) - 1 - rev_i;
        arr[i], maxnum = maxnum, MAX(maxnum, arr[i]);
        return nextGreatest(arr, rev_i + 1, maxnum);
}

Output: ~bccba

Body:
It does not need to be hard:

char nextGreatest(char *s)
{
    char n;
    if (!*s) return 0;
    n = nextGreatest(s + 1);
    return *s = MAX(*s, n);
}

If a character is \0 then we've reached the end of the string. Otherwise, we have more characters to the right, and we want the current character to be the greatest of its own value and all values to the right. But since we call the function in this order, you only will need to call it for its direct right neighbour, because it will in turn do the same first.


问:
What function to I need to plot in MATLAB to get the reflection of this graph?
I have confused myself slightly. I have plotted 1 - 0.95^(x) in MATLAB and got this graph.

However I want the reflection of this about '50' on the x axis whereby I can get a near 1 penalty for low x values and then the penalty starts to decrease as x increases.
Does anyone have any suggestions on the function I would need for this I appear to be having a mind blank!

Thanks

答: You mean like this? Just cut the "1-".

Body: You mean like this? Just cut the "1-".


问:
Difference Between Data Driven and Keyword Driven Testing?
I searched already to see differences between data and keyword driven testing on Google but I did not find an enough answer for me.</p>

答:
In 8 days, i got something that want to write here:

First thing, kdt is so expensive (for time and people). because of this, almost all automated testing tools uses a hibrit (ddt and kdt) approach. And like Dabowhekk said before, kdt also include test scenarios, actions&events.


问:
Why does Rust try to borrow *self as mutable again, when it already holds a mutable borrow?
Why does the program below produce the following error? Is there anything I can do to fix the error without changing the program flow?

```<code>error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:10:39
   |
9  |         for bar in &mut self.bars {
   |                    --------------
   |                    |
   |                    first mutable borrow occurs here
   |                    first borrow later used here
10 |             bar.add_foo_value_and_inc(self);
   |                                       ^^^^ second mutable borrow occurs here
</code>```

The program:

#[derive(Debug)]
struct Foo {
    add_value: u32,
    bars: Vec<Bar>,
}

impl Foo {
    fn add_value_to_bars(&mut self) {
        for bar in &mut self.bars {
            bar.add_foo_value_and_inc(self);
        }
    }
}

#[derive(Debug)]
struct Bar {
    value: u32,
}

impl Bar {
    fn add_foo_value_and_inc(&mut self, foo: &mut Foo) {
        self.value += foo.add_value;
        foo.add_value += 1;
    }
}

fn main() {
    let mut foo = Foo{add_value: 1, bars: vec![Bar{value:2}, Bar{value:3}]};
    foo.add_value_to_bars();
}
```
<p>It seems to me that function <code>add_value_to_bars</code> already holds a mutable reference to <code>self</code> (this is the parameter of the function). So, why does it try to borrow <code>self</code> as mutable <em>again</em> when it calls <code>bar.add_foo_value_and_inc</code>?</p>
<p>Note: this is a minimal program to reproduce the problem, so it isn't intended to be sensible.</p>
<p>Edit: @Herohtar comments that "It is add_foo_value_and_inc that is trying to mutably borrow self
while add_value_to_bars already holds a mutable reference, thus it is being borrowed a second time."</p>
<p>If that is the cause, then why does the following code compile an run without any problems?</p>
<p>Function <code>add_three</code> already holds a mutable reference to <code>x</code>. Function <code>add_two</code> takes a mutable
reference to <code>x</code> <em>again</em> but in this case it does not cause any problem</p>
<pre class="lang-rust prettyprint-override"><code>fn main() {
    let mut x: u32 = 1234;
    add_three(&mut x);
}

fn add_three(x: &mut u32) {
    add_two(x);
    add_one(x);
}

fn add_two(x: &mut u32) {
    *x += 2;
}

fn add_one(x: &mut u32) {
    *x += 1;
}
</code>```

答:
This is Rust doing what Rust is designed to do: prevent you from using memory in an unsafe way.

A mutable reference to self.bars was borrowed and given to an implicitly-created std::slice::IterMut value (the iterator the loop is using).  Because of this, self can't be mutably borrowed within the loop -- it contains self.bars, which is already borrowed.

If Rust allowed this to happen, there would be two concurrently-existing mutable references through which self.bars could be changed, which is exactly what the borrow checker is designed to prevent.

There is a solution, however: you can borrow a different part of self within the loop.  If you change Bar::add_foo_value_and_inc to accept &mut u32 instead of &mut Foo then you can borrow self.add_value, which is the only field this method modifies anyway.

```<code>#[derive(Debug)]
struct Foo {
    add_value: u32,
    bars: Vec<Bar>,
}

impl Foo {
    fn add_value_to_bars(&mut self) {
        for bar in &mut self.bars {
            bar.add_foo_value_and_inc(&mut self.add_value);
        }
    }
}

#[derive(Debug)]
struct Bar {
    value: u32,
}

impl Bar {
    fn add_foo_value_and_inc(&mut self, foo_value: &mut u32) {
        self.value += *foo_value;
        *foo_value += 1;
    }
}

fn main() {
    let mut foo = Foo{add_value: 1, bars: vec![Bar{value:2}, Bar{value:3}]};
    foo.add_value_to_bars();
}
</code>```

Body:
Why does the program below produce the following error? Is there anything I can do to fix the error without changing the program flow?

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:10:39
   |
9  |         for bar in &mut self.bars {
   |                    --------------
   |                    |
   |                    first mutable borrow occurs here
   |                    first borrow later used here
10 |             bar.add_foo_value_and_inc(self);
   |                                       ^^^^ second mutable borrow occurs here

The program:

#[derive(Debug)]
struct Foo {
    add_value: u32,
    bars: Vec<Bar>,
}

impl Foo {
    fn add_value_to_bars(&mut self) {
        for bar in &mut self.bars {
            bar.add_foo_value_and_inc(self);
        }
    }
}

#[derive(Debug)]
struct Bar {
    value: u32,
}

impl Bar {
    fn add_foo_value_and_inc(&mut self, foo: &mut Foo) {
        self.value += foo.add_value;
        foo.add_value += 1;
    }
}

fn main() {
    let mut foo = Foo{add_value: 1, bars: vec![Bar{value:2}, Bar{value:3}]};
    foo.add_value_to_bars();
}

It seems to me that function add_value_to_bars already holds a mutable reference to self (this is the parameter of the function). So, why does it try to borrow self as mutable again when it calls bar.add_foo_value_and_inc?

Note: this is a minimal program to reproduce the problem, so it isn't intended to be sensible.

Edit: @Herohtar comments that "It is add_foo_value_and_inc that is trying to mutably borrow self
while add_value_to_bars already holds a mutable reference, thus it is being borrowed a second time."

If that is the cause, then why does the following code compile an run without any problems?

Function add_three already holds a mutable reference to x. Function add_two takes a mutable
reference to x again but in this case it does not cause any problem

fn main() {
    let mut x: u32 = 1234;
    add_three(&mut x);
}

fn add_three(x: &mut u32) {
    add_two(x);
    add_one(x);
}

fn add_two(x: &mut u32) {
    *x += 2;
}

fn add_one(x: &mut u32) {
    *x += 1;
}

Body:
This is Rust doing what Rust is designed to do: prevent you from using memory in an unsafe way.

A mutable reference to self.bars was borrowed and given to an implicitly-created std::slice::IterMut value (the iterator the loop is using).  Because of this, self can't be mutably borrowed within the loop -- it contains self.bars, which is already borrowed.

If Rust allowed this to happen, there would be two concurrently-existing mutable references through which self.bars could be changed, which is exactly what the borrow checker is designed to prevent.

There is a solution, however: you can borrow a different part of self within the loop.  If you change Bar::add_foo_value_and_inc to accept &mut u32 instead of &mut Foo then you can borrow self.add_value, which is the only field this method modifies anyway.

#[derive(Debug)]
struct Foo {
    add_value: u32,
    bars: Vec<Bar>,
}

impl Foo {
    fn add_value_to_bars(&mut self) {
        for bar in &mut self.bars {
            bar.add_foo_value_and_inc(&mut self.add_value);
        }
    }
}

#[derive(Debug)]
struct Bar {
    value: u32,
}

impl Bar {
    fn add_foo_value_and_inc(&mut self, foo_value: &mut u32) {
        self.value += *foo_value;
        *foo_value += 1;
    }
}

fn main() {
    let mut foo = Foo{add_value: 1, bars: vec![Bar{value:2}, Bar{value:3}]};
    foo.add_value_to_bars();
}


问:
HTML - Disable Password Manager
Our security team requires us to disable the password manager for protected fields on the HTML form. As an example, here's an over simplified HTML form below. When I click the submit button, firefox (version 51.0.1) pops up the password manager.

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
    <form name="testform" action="disable-pwd-mgr.htm" method="post"
        autocomplete="off">

        <label for="protected-input">Protected Input</label>
        <input type="password" size="16" maxlength="16" id="protected-input"  name="protected-input" accept="numbers" />
        <input type="password" id="disable-pwd-mgr-1" style="display: none;" value="stop-pwd-mgr-1"/>
        <input type="password" id="disable-pwd-mgr-2" style="display: none;" value="stop-pwd-mgr-2"/>

        <button name="next" id="next" type="submit" value="Next">
            NEXT
        </button>

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

Note that all alternatives suggested here didn't work.

autocomplete=off didn't work.

Having another hidden input field of
type password didn't work.

Using the two separate additional hidden password inputs, each with different dummy values seems to work for the case when the user actually inputs a value into the protected field and clicks submit. But if the field is left blank and the submit button is clicked, the password manager pops up again. Interestingly chrome (Version 55) doesn't pop up the password manager at all, which is good. Does anyone have a better solution to this problem?

答:
Simple hack (Feb 2022)

I tried many solutions nothing worked, simple hack is

Use text-security-disc as font-family to display font of text
field as disc

Use webkit-text-security CSS property (for now it's
only for Chrome, we can use that as fallback of text-security-disc font)

Example

```<code><input type="text" name="password" class="password">

<style>
@font-face{
  font-family: text-security-disc;
  src: url("https://raw.githubusercontent.com/noppa/text-security/master/dist/text-security-disc.woff");
}
.password{
  -webkit-text-security: disc;
  font-family: text-security-disc;
}
</style>
</code>```

In above example -webkit-text-security: disc; is used as fallback of font-family: text-security-disc. So in case text-security-disc is unavailable then -webkit-text-security: disc; will work.

Good Luck

Title: HTML - Disable Password Manager

Body:
Our security team requires us to disable the password manager for protected fields on the HTML form. As an example, here's an over simplified HTML form below. When I click the submit button, firefox (version 51.0.1) pops up the password manager.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

    <form name="testform" action="disable-pwd-mgr.htm" method="post"
        autocomplete="off">

        Protected Input
        <input type="password" size="16" maxlength="16" id="protected-input"  name="protected-input" accept="numbers" />
        <input type="password" id="disable-pwd-mgr-1" style="display: none;" value="stop-pwd-mgr-1"/>
        <input type="password" id="disable-pwd-mgr-2" style="display: none;" value="stop-pwd-mgr-2"/>

        <button name="next" id="next" type="submit" value="Next">
            NEXT
        </button>

    </form>

Note that all alternatives suggested here didn't work.

autocomplete=off didn't work.

Having another hidden input field of
type password didn't work.

Using the two separate additional hidden password inputs, each with different dummy values seems to work for the case when the user actually inputs a value into the protected field and clicks submit. But if the field is left blank and the submit button is clicked, the password manager pops up again. Interestingly chrome (Version 55) doesn't pop up the password manager at all, which is good. Does anyone have a better solution to this problem?

Body:
Simple hack (Feb 2022)

I tried many solutions nothing worked, simple hack is

Use text-security-disc as font-family to display font of text
field as disc

Use webkit-text-security CSS property (for now it's
only for Chrome, we can use that as fallback of text-security-disc font)

Example

<input type="text" name="password" class="password">

<style>
@font-face{
  font-family: text-security-disc;
  src: url("https://raw.githubusercontent.com/noppa/text-security/master/dist/text-security-disc.woff");
}
.password{
  -webkit-text-security: disc;
  font-family: text-security-disc;
}
</style>

In above example -webkit-text-security: disc; is used as fallback of font-family: text-security-disc. So in case text-security-disc is unavailable then -webkit-text-security: disc; will work.

Good Luck


答:
You have sets, just compile a set of all words to remove:</p>
```<code>remove = stop_words|set(string.punctuation)

df[~(df['col1'].str.lower().isin(remove))]
</code>```

Title: Removing columns from pandas dataframe based on function output

Body:
I have the following dataframe:

d = {'col1': ['challenging', 'swimming', ',', 'it', 'my', 'there!'], 'col2': [3, 4,5,6,7,8]}
df = pd.DataFrame(data=d)
          col1  col2
0  challenging     3
1     swimming     4
2            ,     5
3           it     6
4           my     7
5       there!     8

I have defined this function that removes punctuations and stopwords:

from nltk.corpus import stopwords
import string
stop_words = set(stopwords.words('english'))

def remove_stopwords_punc(sent_words):
   # print(sent_words)
    return [ww for ww in sent_words
            if ww.lower() not in stop_words and ww not in string.punctuation]
from nltk.tokenize import word_tokenize
remove_stopwords_punc(word_tokenize('challenging swimming , it my there!'))

['challenging', 'swimming']

I want to run this function on the col1 and only keep the rows that are not deemed at stopwords or punctuation, in this example leaving this output:

          col1  col2
0  challenging     3
1     swimming     4

Body:
You have sets, just compile a set of all words to remove:

remove = stop_words|set(string.punctuation)

df[~(df['col1'].str.lower().isin(remove))]


问:
How to remove TypeScript warning: property 'length' does not exist on type '{}'
In a TypeScript file, I have defined a 3D array:

```<code>var myArr = ['one', [[19, 1], [13, 1], [86, 1], [12, 2]],
             'two',    [[83, 1], [72, 1], [16, 2]],
             'three',  [[4, 1]]];

function testArray(){
    console.log(myArr[1].length);
}
</code>```

I get a warning under the length property:

Property 'length' does not exist on type '{}'

Is there something I can do to remove this warning?

答:
for those who already have a interface/type/class configured and would like it to have a length or something else i have a suggestion that i use. Inside the class, interface, type put the code below. It will set unknown only on undefined attributes. It is not necessary to put it at the end, I also suggest that you create a separate interface and extend it to your objects if you prefer

```<code>export interface x {
...
[props: string]: unknown
...
}
</code>```

This will make it possible for you to use any attribute name in your object, as bad as it sounds, it actually isn't. That's because for each unknown attribute you will be forced(T.S 4.4+) to do a forced conversion to some other type when you use, eg

```<code>(object.length as number).
</code>```

When analyzing the possible type of the attribute you will be more careful and will not try to access something that does not exist. Don't worry about your object auto-completion, it will keep working normally

Body:
In a TypeScript file, I have defined a 3D array:

var myArr = ['one', [[19, 1], [13, 1], [86, 1], [12, 2]],
             'two',    [[83, 1], [72, 1], [16, 2]],
             'three',  [[4, 1]]];

function testArray(){
    console.log(myArr[1].length);
}

I get a warning under the length property:

Property 'length' does not exist on type '{}'

Is there something I can do to remove this warning?

Body:
for those who already have a interface/type/class configured and would like it to have a length or something else i have a suggestion that i use. Inside the class, interface, type put the code below. It will set unknown only on undefined attributes. It is not necessary to put it at the end, I also suggest that you create a separate interface and extend it to your objects if you prefer

export interface x {
...
[props: string]: unknown
...
}

This will make it possible for you to use any attribute name in your object, as bad as it sounds, it actually isn't. That's because for each unknown attribute you will be forced(T.S 4.4+) to do a forced conversion to some other type when you use, eg

(object.length as number).

When analyzing the possible type of the attribute you will be more careful and will not try to access something that does not exist. Don't worry about your object auto-completion, it will keep working normally


问:
Vue project cannot resolve '@'
My vue-cli version is 4.5.15, but it cannot resolve @ as ./src and all paths using '@' are not found. Why did this happen and how could I solve it?

答:
It is not possible to import a folder, you will have to import a single file from the layout folder:

```<code>import Footer from "@/Layout/Footer.vue"
import Header from "@/Layout/Header.vue"
import Index from "@/Layout/Index.vue"
import Sidebar from "@/Layout/Sidebar.vue"
import Sidebar2 from "@/Layout/Sidebar2.vue"
</code>```

If you want to import every file, you will have to this all manually, because you cannot import a folder.

Hope this will work for you!

Title: Vue project cannot resolve '@'

Body:
It is not possible to import a folder, you will have to import a single file from the layout folder:

import Footer from "@/Layout/Footer.vue"
import Header from "@/Layout/Header.vue"
import Index from "@/Layout/Index.vue"
import Sidebar from "@/Layout/Sidebar.vue"
import Sidebar2 from "@/Layout/Sidebar2.vue"

If you want to import every file, you will have to this all manually, because you cannot import a folder.

Hope this will work for you!


问:
Unable to install NPM
I am trying to install NPM on a repository that I have locally cloned from GitHub. This is the error that I receive. Please let me know what I should do to resolve this.

Thank You!

```<code>npm ERR! path D:\Avin Dev\portfolio\node_modules\fibers
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node build.js || nodejs build.js
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@3.8.0
npm ERR! gyp info using node@16.14.0 | win32 | x64
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Command failed: C:\Program Files\Python38\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
npm ERR! gyp ERR! stack   File "<string>", line 1
npm ERR! gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
npm ERR! gyp ERR! stack                       ^
npm ERR! gyp ERR! stack SyntaxError: invalid syntax
npm ERR! gyp ERR! stack
npm ERR! gyp ERR! stack     at ChildProcess.exithandler (node:child_process:399:12)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:520:28)
npm ERR! gyp ERR! stack     at maybeClose (node:internal/child_process:1092:16)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5)
npm ERR! gyp ERR! System Windows_NT 10.0.22000
npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Avin Dev\\portfolio\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--release"
npm ERR! gyp ERR! cwd D:\Avin Dev\portfolio\node_modules\fibers
npm ERR! gyp ERR! node -v v16.14.0
npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! gyp ERR! not ok
npm ERR! node-gyp exited with code: 1
npm ERR! Please make sure you are using a supported platform and node version. If you
npm ERR! would like to compile fibers on this machine please make sure you have setup your
npm ERR! build environment--
npm ERR! Windows + OS X instructions here: https://github.com/nodejs/node-gyp
npm ERR! Ubuntu users please run: `sudo apt-get install g++ build-essential`
npm ERR! RHEL users please run: `yum install gcc-c++` and `yum groupinstall 'Development Tools'`
npm ERR! Alpine users please run: `sudo apk add python make g++`
npm ERR! 'nodejs' is not recognized as an internal or external command,
npm ERR! operable program or batch file.

npm ERR! A complete log of this run can be found in:
</code>```

答:
When a binary package is used in compatible environment, usually a precompiled binary is installed. That NPM tries to compile it is a sign that a combination Node version, CPU architecture and OS isn't supported by specified version of a binary package. fibers is a binary package known to be incompatible with Node 16.

One option is to modify the project to not depend on fibers. In the context of Vue it's likely node-sass that depends on fibers and  it needs to be migrated to sass.

Another option is to downgrade to Node 14 and install the project as is.

Title: Unable to install NPM

Body:
I am trying to install NPM on a repository that I have locally cloned from GitHub. This is the error that I receive. Please let me know what I should do to resolve this.

Thank You!

npm ERR! path D:\Avin Dev\portfolio\node_modules\fibers
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node build.js || nodejs build.js
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@3.8.0
npm ERR! gyp info using node@16.14.0 | win32 | x64
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Command failed: C:\Program Files\Python38\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
npm ERR! gyp ERR! stack   File "<string>", line 1
npm ERR! gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
npm ERR! gyp ERR! stack                       ^
npm ERR! gyp ERR! stack SyntaxError: invalid syntax
npm ERR! gyp ERR! stack
npm ERR! gyp ERR! stack     at ChildProcess.exithandler (node:child_process:399:12)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:520:28)
npm ERR! gyp ERR! stack     at maybeClose (node:internal/child_process:1092:16)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5)
npm ERR! gyp ERR! System Windows_NT 10.0.22000
npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Avin Dev\\portfolio\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--release"
npm ERR! gyp ERR! cwd D:\Avin Dev\portfolio\node_modules\fibers
npm ERR! gyp ERR! node -v v16.14.0
npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! gyp ERR! not ok
npm ERR! node-gyp exited with code: 1
npm ERR! Please make sure you are using a supported platform and node version. If you
npm ERR! would like to compile fibers on this machine please make sure you have setup your
npm ERR! build environment--
npm ERR! Windows + OS X instructions here: https://github.com/nodejs/node-gyp
npm ERR! Ubuntu users please run: `sudo apt-get install g++ build-essential`
npm ERR! RHEL users please run: `yum install gcc-c++` and `yum groupinstall 'Development Tools'`
npm ERR! Alpine users please run: `sudo apk add python make g++`
npm ERR! 'nodejs' is not recognized as an internal or external command,
npm ERR! operable program or batch file.

npm ERR! A complete log of this run can be found in:


问:
How do I persist to local storage with easy-peasy redux
I'm building a react ecommerce website and I am using easy-peasy redux. I want to persist to localStorage when I add to cart. I can't find anything on their documentation about how to persist to localStorage. easy-peasy  is configured to persist to sessionStorage; although there is a mention that it can be configured to localStorage.

I can currently add to cart but I can't set to localStorage.

Below  is my store.js and product page

```<code>    import { createStore, action } from 'easy-peasy';

    const store = createStore({
    cartItems: JSON.parse(localStorage.getItem('cartItems')) ?? [],
    addToCart: action((state, payload) => {
    return {
    ...state,
    cartItems: [...state.cartItems, payload],
   };
   }),
   });

   export default store;
</code>```

//Home (product page)

```<code>   import { collection, addDoc, getDocs } from 'firebase/firestore';
   import { db } from '../../firebase/config';
   import { products } from '../../figsofeden-products';
   import { Card, Row, Container, Col } from 'react-bootstrap';
   import { Link, useNavigate } from 'react-router-dom';
   import { useState, useEffect } from 'react';
   import { useStoreActions, useStore } from 'easy-peasy';

 const Home = () => {
 const [products, setProducts] = useState([]);
 const navigate = useNavigate();

 useEffect(() => {
 getData();
 }, []);

async function getData() {
try {
  const products = await getDocs(collection(db, 'products'));
  const productsArray = [];
  products.forEach((doc) => {

    const obj = {
      id: doc.id,
      ...doc.data(),
    };

    productsArray.push(obj);
  });

  setProducts(productsArray);
} catch (error) {
  console.log(error);
  }
 }

const addToCart = useStoreActions((actions) => actions.addToCart);

return (
<Layout>
  <Container fluid className="product-directory mx-auto">
    <Row xs={1} md={2} lg={3} className="g-2">
      {products.map((product, index) => {
        return (
          <Col key={product.id} className="g-2">
            <Card>
              <div className="product-wrapper position-relative">
                <div className="product-content">
                  <Card.Img
                    variant="top"
                    src={product.imageURL}
                    alt="img"
                  />
                  <Card.Body>
                    <Card.Text>{product.name}</Card.Text>
                    <Card.Text>NGN {product.price}</Card.Text>
                  </Card.Body>
                </div>
                <div className="product-actions">
                  <h3> NGN {product.price}</h3>
                  <div className="d-flex">
                    <button
                      className="mx-2"
                      disabled={product.quantity === 0 ? 'true' : ''}
                      onClick={() => addToCart(product)}
                    >
                      ADD TO CART
                    </button>
                    <button
                      onClick={() => {
                        navigate(`/productinfo/${product.id}`);
                      }}
                    >
                      VIEW
                    </button>
                  </div>
                  <div className="outofstock">
                    <p>
                      <em>{product.quantity > 0 ? '' : 'Out Of Stock'}</em>
                    </p>
                  </div>
                </div>
              </div>
            </Card>
          </Col>
        );
      })}
    </Row>
  </Container>
 </Layout>
  );
 };

export default Home;
</code>```

答:
```<code>addToCart: action((state, payload) => {

// define cartItems with needed state values
const cartItems = [...state.cartItems, payload]

// after set it to local storage
window.localStorage.setItem("cartItems", JSON.stringfy(cartItems))

// and return the new state
return {
   ...state,
   cartItems
};
</code>```

Body:
I'm building a react ecommerce website and I am using easy-peasy redux. I want to persist to localStorage when I add to cart. I can't find anything on their documentation about how to persist to localStorage. easy-peasy  is configured to persist to sessionStorage; although there is a mention that it can be configured to localStorage.

I can currently add to cart but I can't set to localStorage.

Below  is my store.js and product page

    import { createStore, action } from 'easy-peasy';

    const store = createStore({
    cartItems: JSON.parse(localStorage.getItem('cartItems')) ?? [],
    addToCart: action((state, payload) => {
    return {
    ...state,
    cartItems: [...state.cartItems, payload],
   };
   }),
   });

   export default store;

//Home (product page)

   import { collection, addDoc, getDocs } from 'firebase/firestore';
   import { db } from '../../firebase/config';
   import { products } from '../../figsofeden-products';
   import { Card, Row, Container, Col } from 'react-bootstrap';
   import { Link, useNavigate } from 'react-router-dom';
   import { useState, useEffect } from 'react';
   import { useStoreActions, useStore } from 'easy-peasy';

 const Home = () => {
 const [products, setProducts] = useState([]);
 const navigate = useNavigate();

 useEffect(() => {
 getData();
 }, []);

async function getData() {
try {
  const products = await getDocs(collection(db, 'products'));
  const productsArray = [];
  products.forEach((doc) => {

    const obj = {
      id: doc.id,
      ...doc.data(),
    };

    productsArray.push(obj);
  });

  setProducts(productsArray);
} catch (error) {
  console.log(error);
  }
 }

const addToCart = useStoreActions((actions) => actions.addToCart);

return (
<Layout>
  <Container fluid className="product-directory mx-auto">
    <Row xs={1} md={2} lg={3} className="g-2">
      {products.map((product, index) => {
        return (
          <Col key={product.id} className="g-2">
            <Card>

                  <Card.Img
                    variant="top"
                    src={product.imageURL}
                    alt="img"
                  />
                  <Card.Body>
                    <Card.Text>{product.name}</Card.Text>
                    <Card.Text>NGN {product.price}</Card.Text>
                  </Card.Body>

 NGN {product.price}

                    <button
                      className="mx-2"
                      disabled={product.quantity === 0 ? 'true' : ''}
                      onClick={() => addToCart(product)}
                    >
                      ADD TO CART
                    </button>
                    <button
                      onClick={() => {
                        navigate(`/productinfo/${product.id}`);
                      }}
                    >
                      VIEW
                    </button>

                      {product.quantity > 0 ? '' : 'Out Of Stock'}

            </Card>
          </Col>
        );
      })}
    </Row>
  </Container>
 </Layout>
  );
 };

export default Home;