问:
python class function append on all instance of an object
I wanted to make a script in order to manage my friends and I, walkie talkies. so I created 4 classes:
a Range is a modification that can upgrade the walkie talkie
a Walkie Talkie describe the radio and its possible mods(Range)
a Person describe me or my friends and their radios
a TalkieRangeData is a class to handle all of this

Here is my code:

import json
import base64
import os

def is_base64(s):
    """Check if a parameter is encoded in base64."""
    try:
        base64.b64decode(s)
        return True and s[-1] == "="
    except:
        return False

def to_base64(s):
    """Encode a parameter in base64 if it is not already encoded."""
    if not is_base64(s):
        s = base64.b64encode(s.encode()).decode()
    return s

def from_base64(s):
    """Decode a parameter from base64 if it is encoded."""
    if is_base64(s):
        s = base64.b64decode(s).decode()
    return s

class Range:
    def __init__(self, mod, minrange, maxrange, commentary):
        self.mod = mod
        self.minrange = minrange
        self.maxrange = maxrange
        self.commentary = to_base64(commentary)

    def update_range(
        self, new_mod=None, new_min=None, new_max=None, new_commentary=None
    ):
        if new_mod:
            self.mod = new_mod
        if new_min:
            self.minrange = new_min
        if new_max:
            self.maxrange = new_max
        if new_commentary:
            self.commentary = to_base64(new_commentary)

    def __repr__(self):
        return f"Mod: {self.mod}\n\tMin: {self.minrange}\n\tMax: {self.maxrange}\n\tCommentary: {from_base64(self.commentary)} "

    def toJSON(self):
        return {
            "mod": self.mod,
            "minrange": self.minrange,
            "maxrange": self.maxrange,
            "commentary": self.commentary,
        }

class WalkieTalkie:
    def __init__(self, model, general_commentary, ranges=list()):
        self.model = model
        self.generalCommentary = to_base64(general_commentary)
        self.ranges = list()
        for r in ranges:
            if isinstance(r, Range):
                self.ranges.append(r)
            else:
                self.ranges.append(Range(*r))

    def add_range(self, mod, minrange, maxrange, commentary):
        self.ranges.append(Range(mod, minrange, maxrange, to_base64(commentary)))

    def update_range(
        self, mod, new_mod=None, new_min=None, new_max=None, new_commentary=None
    ):
        range = next((r for r in self.ranges if r.mod == mod), None)
        if range:
            range.update_range(new_mod, new_min, new_max, new_commentary)
        else:
            raise ValueError("No range with that mod name was found.")

    def delete_range(self, mod):
        range = next((r for r in self.ranges if r.mod == mod), None)
        if range:
            self.ranges.remove(range)
        else:
            raise ValueError("No range with that mod name was found.")

    def __repr__(self):
        ranges_str = "\n".join([f"{range}" for range in self.ranges])
        return f"Model: {self.model}\nGeneral Commentary: {from_base64(self.generalCommentary)}\nRanges:\n{ranges_str}"

    def toJSON(self):
        return {
            "model": self.model,
            "generalCommentary": self.generalCommentary,
            "ranges": [r.toJSON() for r in self.ranges],
        }

class Person:
    def __init__(self, name, color, latitude, longitude, walkie_talkies=list()):
        self.name = name
        self.color = color
        self.location = {"latitude": latitude, "longitude": longitude}
        self.walkie_talkies = walkie_talkies

    def add_walkie_talkie(self, model, general_commentary, ranges=list()):
        wt = WalkieTalkie(model, general_commentary, ranges)
        self.walkie_talkies.append(wt)

    def add_walkie_talkie2(self, walkie_talkie: WalkieTalkie):
        self.walkie_talkies.append(walkie_talkie)

    def update_walkie_talkie(
        self, model, new_model=None, new_general_commentary=None, new_ranges=None
    ):
        wt_to_update = next(wt for wt in self.walkie_talkies if wt.model == model)
        if new_model:
            wt_to_update.model = new_model
        if new_general_commentary:
            wt_to_update.generalCommentary = to_base64(new_general_commentary)
        if new_ranges:
            wt_to_update.ranges = new_ranges

    def delete_walkie_talkie(self, model):
        self.walkie_talkies = [wt for wt in self.walkie_talkies if wt.model != model]

    def __repr__(self):
        walkie_talkies_str = "\n".join(
            [f"{walkie_talkie}" for walkie_talkie in self.walkie_talkies]
        )
        return (
            f"Name: {self.name}\nLocation: ({self.location['latitude']}, {self.location['longitude']})\nWalkie "
            f"Talkies:\n{walkie_talkies_str} "
        )

class TalkieRangeData:
    def __init__(self, filepath):
        self.filepath = filepath
        self.people = self.read_data()

    def read_data(self):
        # if file path does not exist, create it
        if not os.path.exists(self.filepath):
            with open(self.filepath, "w") as f:
                f.write('\{"people": []\}')

        with open(self.filepath, "r") as f:
            try:
                data = json.load(f)
                return [
                    Person(
                        person["name"],
                        person["color"],
                        person["location"]["latitude"],
                        person["location"]["longitude"],
                        [
                            WalkieTalkie(
                                wt["model"],
                                from_base64(wt["generalCommentary"]),
                                [
                                    Range(
                                        r["mod"],
                                        r["minrange"],
                                        r["maxrange"],
                                        from_base64(r["commentary"]),
                                    )
                                    for r in wt["ranges"]
                                ],
                            )
                            for wt in person["walkieTalkies"]
                        ],
                    )
                    for person in data["people"]
                ]
            except json.decoder.JSONDecodeError:
                return list()

    def add_person(self, name, color, latitude, longitude, overwrite=False):
        if not overwrite:
            existing_person = next(
                (person for person in self.people if person.name == name), None
            )
            if existing_person:
                raise ValueError(
                    "A person with that name already exists. Set `overwrite` to True if you want to update the existing person."
                )
        person = Person(name, color, latitude, longitude)
        self.people.append(person)
        self.update_json()

    def add_person2(self, pperson: Person, overwrite=False):
        if not overwrite:
            existing_person = next(
                (person for person in self.people if person.name == pperson.name), None
            )
            if existing_person:
                raise ValueError(
                    "A person with that name already exists. Set `overwrite` to True if you want to update the existing person."
                )
        self.people.append(pperson)
        self.update_json()

    def update_json(self):
        data = {
            "people": [
                {
                    "name": person.name,
                    "color": person.color,
                    "location": person.location,
                    "walkieTalkies": [wt.toJSON() for wt in person.walkie_talkies],
                }
                for person in self.people
            ]
        }
        with open(self.filepath, "w") as f:
            json.dump(data, f, indent=2)

    def update_person(
        self,
        name,
        new_name=None,
        new_latitude=None,
        new_longitude=None,
        new_walkie_talkies=None,
    ):
        person_to_update = next(person for person in self.people if person.name == name)
        if new_name:
            person_to_update.name = new_name
        if new_latitude:
            person_to_update.location["latitude"] = new_latitude
        if new_longitude:
            person_to_update.location["longitude"] = new_longitude
        if new_walkie_talkies:
            person_to_update.walkie_talkies = new_walkie_talkies
        self.update_json()

    def delete_person(self, name):
        self.people = [person for person in self.people if person.name != name]
        self.update_json()

    def __repr__(self):
        return f"TalkieRangeData"

```
<p>and here is my main.py file that I use to generate a kml file from input data</p>
<pre class="lang-py prettyprint-override"><code>import json
import os
import simplekml

from TalkieRangeData import (
    TalkieRangeData,
    to_base64,
    from_base64,
    Person,
    WalkieTalkie,
    Range,
)
from polycircles import polycircles

def load_data():
    if os.path.exists("talkies.json"):
        trd = TalkieRangeData("talkies.json")
    else:
        print(
            "talkies.json does not exist. Let's create it.First we need to create at least one user."
        )
        name = input("Enter the name of the person: ")
        color = input("Enter the color of the person: ")
        latitude = input("Enter the latitude of the person: ")
        longitude = input("Enter the longitude of the person: ")
        model = input("Enter the model of the walkie talkie: ")
        general_commentary = input(
            "Enter the general commentary of the walkie talkie: "
        )
        mod = input("Enter the mod of the range: ")
        rangemin = input("Enter the min of the range: ")
        rangemax = input("Enter the max of the range: ")
        commentary = input("Enter the commentary of the range: ")
        json_data = {
            "people": [
                {
                    "name": name,
                    "location": {"latitude": latitude, "longitude": longitude},
                    "walkieTalkies": [
                        {
                            "model": model,
                            "generalCommentary": to_base64(general_commentary),
                            "ranges": [
                                {
                                    "mod": mod,
                                    "min": rangemin,
                                    "max": rangemax,
                                    "commentary": to_base64(commentary),
                                }
                            ],
                        }
                    ],
                }
            ]
        }
        with open("talkies.json", "w") as f:
            json.dump(json_data, f)
        trd = TalkieRangeData("talkies.json")
    return trd

def main():
    j = Person("J", "00ff00", 0.956131, 0.587348)
    t = Person("T", "ff0080", 0.943916, 0.609007)
    a = Person("A", "ff00ff", 0.961872, 0.596557)
    l = Person("L", "0000ff", 0.942723, 0.740706)

    bf888s = WalkieTalkie(
        "BF-888S",
        "This is a BF-888S",
        [Range("antenne normal", 1000, 2000, "antenne standard")],
    )
    uv5r = WalkieTalkie(
        "UV-5R",
        "This is a UV-55R",
        [Range("antenne normal", 5000, 7000, "antenne standard")],
    )
    thuv88 = WalkieTalkie(
        "TH-UV88",
        "This is a TH-UV88",
        [
            Range("antenne normal", 3000, 5000, "antenne standard"),
            Range("antenne longue", 6000, 13000, "antenne longue"),
        ],
    )

    # we all have a BF-888S
    j.add_walkie_talkie2(bf888s)
    t.add_walkie_talkie2(bf888s)
    a.add_walkie_talkie2(bf888s)
    l.add_walkie_talkie2(bf888s)

    j.add_walkie_talkie2(uv5r)

    l.add_walkie_talkie2(thuv88)

    # trd = load_data()
    trd = TalkieRangeData("talkies.json")
    trd.add_person2(j, overwrite=True)
    trd.add_person2(t, overwrite=True)
    trd.add_person2(a, overwrite=True)
    trd.add_person2(l, overwrite=True)

    kml = simplekml.Kml()
    # Create a folder for each person
    for person in trd.people:
        folder = kml.newfolder(name=person.name)
        for walkie_talkie in person.walkie_talkies:
            # Create a folder for each walkie talkie
            wt_folder = folder.newfolder(
                name=walkie_talkie.model,
                description=from_base64(walkie_talkie.generalCommentary),
            )
            for mod in walkie_talkie.ranges:
                # Create a folder for each mod
                mod_folder = wt_folder.newfolder(
                    name=mod.mod, description=from_base64(mod.commentary)
                )

                # create two series of points for the ranges
                polygon = polycircles.Polycircle(
                    latitude=person.location["latitude"],
                    longitude=person.location["longitude"],
                    radius=mod.minrange,
                    number_of_vertices=100,
                )

                polygon2 = polycircles.Polycircle(
                    latitude=person.location["latitude"],
                    longitude=person.location["longitude"],
                    radius=mod.maxrange,
                    number_of_vertices=100,
                )

                # add the points to the kml using polygons in order
                bottomcircle = mod_folder.newpolygon(
                    name="{}-{}-{} max range".format(
                        person.name, walkie_talkie.model, mod.mod
                    ),
                    outerboundaryis=polygon2.to_kml(),
                )

                topcircle = mod_folder.newpolygon(
                    name="{}-{}-{} min range".format(
                        person.name, walkie_talkie.model, mod.mod
                    ),
                    outerboundaryis=polygon.to_kml(),
                )

                # set the color of the polygons

                bottomcircle.style.labelstyle.scale = 1
                bottomcircle.style.labelstyle.color = simplekml.Color.hexa(
                    person.color + "33"
                )
                bottomcircle.style.polystyle.color = simplekml.Color.hexa(
                    person.color + "33"
                )

                topcircle.style.labelstyle.scale = 1
                topcircle.style.labelstyle.color = simplekml.Color.hexa(
                    person.color + "80"
                )
                topcircle.style.polystyle.color = simplekml.Color.hexa(
                    person.color + "80"
                )

    kml.save("talkies.kml")

if __name__ == "__main__":
    main()

</code>```

I'm very new to python oop and here is the issue I fall onto. My code create a json file the format seems to be correct but it gave all my Person the same talkies so it look like this:

j

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

l

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

a

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

t

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

By running in debug mod I found out that each time I call add_walkie_talkie2(wt) it appends the wt to all my Person, does anyone knows why this occurs ?

Body:
I wanted to make a script in order to manage my friends and I, walkie talkies. so I created 4 classes:
a Range is a modification that can upgrade the walkie talkie
a Walkie Talkie describe the radio and its possible mods(Range)
a Person describe me or my friends and their radios
a TalkieRangeData is a class to handle all of this

Here is my code:

import json
import base64
import os

def is_base64(s):
    """Check if a parameter is encoded in base64."""
    try:
        base64.b64decode(s)
        return True and s[-1] == "="
    except:
        return False

def to_base64(s):
    """Encode a parameter in base64 if it is not already encoded."""
    if not is_base64(s):
        s = base64.b64encode(s.encode()).decode()
    return s

def from_base64(s):
    """Decode a parameter from base64 if it is encoded."""
    if is_base64(s):
        s = base64.b64decode(s).decode()
    return s

class Range:
    def __init__(self, mod, minrange, maxrange, commentary):
        self.mod = mod
        self.minrange = minrange
        self.maxrange = maxrange
        self.commentary = to_base64(commentary)

    def update_range(
        self, new_mod=None, new_min=None, new_max=None, new_commentary=None
    ):
        if new_mod:
            self.mod = new_mod
        if new_min:
            self.minrange = new_min
        if new_max:
            self.maxrange = new_max
        if new_commentary:
            self.commentary = to_base64(new_commentary)

    def __repr__(self):
        return f"Mod: {self.mod}\n\tMin: {self.minrange}\n\tMax: {self.maxrange}\n\tCommentary: {from_base64(self.commentary)} "

    def toJSON(self):
        return {
            "mod": self.mod,
            "minrange": self.minrange,
            "maxrange": self.maxrange,
            "commentary": self.commentary,
        }

class WalkieTalkie:
    def __init__(self, model, general_commentary, ranges=list()):
        self.model = model
        self.generalCommentary = to_base64(general_commentary)
        self.ranges = list()
        for r in ranges:
            if isinstance(r, Range):
                self.ranges.append(r)
            else:
                self.ranges.append(Range(*r))

    def add_range(self, mod, minrange, maxrange, commentary):
        self.ranges.append(Range(mod, minrange, maxrange, to_base64(commentary)))

    def update_range(
        self, mod, new_mod=None, new_min=None, new_max=None, new_commentary=None
    ):
        range = next((r for r in self.ranges if r.mod == mod), None)
        if range:
            range.update_range(new_mod, new_min, new_max, new_commentary)
        else:
            raise ValueError("No range with that mod name was found.")

    def delete_range(self, mod):
        range = next((r for r in self.ranges if r.mod == mod), None)
        if range:
            self.ranges.remove(range)
        else:
            raise ValueError("No range with that mod name was found.")

    def __repr__(self):
        ranges_str = "\n".join([f"{range}" for range in self.ranges])
        return f"Model: {self.model}\nGeneral Commentary: {from_base64(self.generalCommentary)}\nRanges:\n{ranges_str}"

    def toJSON(self):
        return {
            "model": self.model,
            "generalCommentary": self.generalCommentary,
            "ranges": [r.toJSON() for r in self.ranges],
        }

class Person:
    def __init__(self, name, color, latitude, longitude, walkie_talkies=list()):
        self.name = name
        self.color = color
        self.location = {"latitude": latitude, "longitude": longitude}
        self.walkie_talkies = walkie_talkies

    def add_walkie_talkie(self, model, general_commentary, ranges=list()):
        wt = WalkieTalkie(model, general_commentary, ranges)
        self.walkie_talkies.append(wt)

    def add_walkie_talkie2(self, walkie_talkie: WalkieTalkie):
        self.walkie_talkies.append(walkie_talkie)

    def update_walkie_talkie(
        self, model, new_model=None, new_general_commentary=None, new_ranges=None
    ):
        wt_to_update = next(wt for wt in self.walkie_talkies if wt.model == model)
        if new_model:
            wt_to_update.model = new_model
        if new_general_commentary:
            wt_to_update.generalCommentary = to_base64(new_general_commentary)
        if new_ranges:
            wt_to_update.ranges = new_ranges

    def delete_walkie_talkie(self, model):
        self.walkie_talkies = [wt for wt in self.walkie_talkies if wt.model != model]

    def __repr__(self):
        walkie_talkies_str = "\n".join(
            [f"{walkie_talkie}" for walkie_talkie in self.walkie_talkies]
        )
        return (
            f"Name: {self.name}\nLocation: ({self.location['latitude']}, {self.location['longitude']})\nWalkie "
            f"Talkies:\n{walkie_talkies_str} "
        )

class TalkieRangeData:
    def __init__(self, filepath):
        self.filepath = filepath
        self.people = self.read_data()

    def read_data(self):
        # if file path does not exist, create it
        if not os.path.exists(self.filepath):
            with open(self.filepath, "w") as f:
                f.write('\{"people": []\}')

        with open(self.filepath, "r") as f:
            try:
                data = json.load(f)
                return [
                    Person(
                        person["name"],
                        person["color"],
                        person["location"]["latitude"],
                        person["location"]["longitude"],
                        [
                            WalkieTalkie(
                                wt["model"],
                                from_base64(wt["generalCommentary"]),
                                [
                                    Range(
                                        r["mod"],
                                        r["minrange"],
                                        r["maxrange"],
                                        from_base64(r["commentary"]),
                                    )
                                    for r in wt["ranges"]
                                ],
                            )
                            for wt in person["walkieTalkies"]
                        ],
                    )
                    for person in data["people"]
                ]
            except json.decoder.JSONDecodeError:
                return list()

    def add_person(self, name, color, latitude, longitude, overwrite=False):
        if not overwrite:
            existing_person = next(
                (person for person in self.people if person.name == name), None
            )
            if existing_person:
                raise ValueError(
                    "A person with that name already exists. Set `overwrite` to True if you want to update the existing person."
                )
        person = Person(name, color, latitude, longitude)
        self.people.append(person)
        self.update_json()

    def add_person2(self, pperson: Person, overwrite=False):
        if not overwrite:
            existing_person = next(
                (person for person in self.people if person.name == pperson.name), None
            )
            if existing_person:
                raise ValueError(
                    "A person with that name already exists. Set `overwrite` to True if you want to update the existing person."
                )
        self.people.append(pperson)
        self.update_json()

    def update_json(self):
        data = {
            "people": [
                {
                    "name": person.name,
                    "color": person.color,
                    "location": person.location,
                    "walkieTalkies": [wt.toJSON() for wt in person.walkie_talkies],
                }
                for person in self.people
            ]
        }
        with open(self.filepath, "w") as f:
            json.dump(data, f, indent=2)

    def update_person(
        self,
        name,
        new_name=None,
        new_latitude=None,
        new_longitude=None,
        new_walkie_talkies=None,
    ):
        person_to_update = next(person for person in self.people if person.name == name)
        if new_name:
            person_to_update.name = new_name
        if new_latitude:
            person_to_update.location["latitude"] = new_latitude
        if new_longitude:
            person_to_update.location["longitude"] = new_longitude
        if new_walkie_talkies:
            person_to_update.walkie_talkies = new_walkie_talkies
        self.update_json()

    def delete_person(self, name):
        self.people = [person for person in self.people if person.name != name]
        self.update_json()

    def __repr__(self):
        return f"TalkieRangeData"

and here is my main.py file that I use to generate a kml file from input data

import json
import os
import simplekml

from TalkieRangeData import (
    TalkieRangeData,
    to_base64,
    from_base64,
    Person,
    WalkieTalkie,
    Range,
)
from polycircles import polycircles

def load_data():
    if os.path.exists("talkies.json"):
        trd = TalkieRangeData("talkies.json")
    else:
        print(
            "talkies.json does not exist. Let's create it.First we need to create at least one user."
        )
        name = input("Enter the name of the person: ")
        color = input("Enter the color of the person: ")
        latitude = input("Enter the latitude of the person: ")
        longitude = input("Enter the longitude of the person: ")
        model = input("Enter the model of the walkie talkie: ")
        general_commentary = input(
            "Enter the general commentary of the walkie talkie: "
        )
        mod = input("Enter the mod of the range: ")
        rangemin = input("Enter the min of the range: ")
        rangemax = input("Enter the max of the range: ")
        commentary = input("Enter the commentary of the range: ")
        json_data = {
            "people": [
                {
                    "name": name,
                    "location": {"latitude": latitude, "longitude": longitude},
                    "walkieTalkies": [
                        {
                            "model": model,
                            "generalCommentary": to_base64(general_commentary),
                            "ranges": [
                                {
                                    "mod": mod,
                                    "min": rangemin,
                                    "max": rangemax,
                                    "commentary": to_base64(commentary),
                                }
                            ],
                        }
                    ],
                }
            ]
        }
        with open("talkies.json", "w") as f:
            json.dump(json_data, f)
        trd = TalkieRangeData("talkies.json")
    return trd

def main():
    j = Person("J", "00ff00", 0.956131, 0.587348)
    t = Person("T", "ff0080", 0.943916, 0.609007)
    a = Person("A", "ff00ff", 0.961872, 0.596557)
    l = Person("L", "0000ff", 0.942723, 0.740706)

    bf888s = WalkieTalkie(
        "BF-888S",
        "This is a BF-888S",
        [Range("antenne normal", 1000, 2000, "antenne standard")],
    )
    uv5r = WalkieTalkie(
        "UV-5R",
        "This is a UV-55R",
        [Range("antenne normal", 5000, 7000, "antenne standard")],
    )
    thuv88 = WalkieTalkie(
        "TH-UV88",
        "This is a TH-UV88",
        [
            Range("antenne normal", 3000, 5000, "antenne standard"),
            Range("antenne longue", 6000, 13000, "antenne longue"),
        ],
    )

    # we all have a BF-888S
    j.add_walkie_talkie2(bf888s)
    t.add_walkie_talkie2(bf888s)
    a.add_walkie_talkie2(bf888s)
    l.add_walkie_talkie2(bf888s)

    j.add_walkie_talkie2(uv5r)

    l.add_walkie_talkie2(thuv88)

    # trd = load_data()
    trd = TalkieRangeData("talkies.json")
    trd.add_person2(j, overwrite=True)
    trd.add_person2(t, overwrite=True)
    trd.add_person2(a, overwrite=True)
    trd.add_person2(l, overwrite=True)

    kml = simplekml.Kml()
    # Create a folder for each person
    for person in trd.people:
        folder = kml.newfolder(name=person.name)
        for walkie_talkie in person.walkie_talkies:
            # Create a folder for each walkie talkie
            wt_folder = folder.newfolder(
                name=walkie_talkie.model,
                description=from_base64(walkie_talkie.generalCommentary),
            )
            for mod in walkie_talkie.ranges:
                # Create a folder for each mod
                mod_folder = wt_folder.newfolder(
                    name=mod.mod, description=from_base64(mod.commentary)
                )

                # create two series of points for the ranges
                polygon = polycircles.Polycircle(
                    latitude=person.location["latitude"],
                    longitude=person.location["longitude"],
                    radius=mod.minrange,
                    number_of_vertices=100,
                )

                polygon2 = polycircles.Polycircle(
                    latitude=person.location["latitude"],
                    longitude=person.location["longitude"],
                    radius=mod.maxrange,
                    number_of_vertices=100,
                )

                # add the points to the kml using polygons in order
                bottomcircle = mod_folder.newpolygon(
                    name="{}-{}-{} max range".format(
                        person.name, walkie_talkie.model, mod.mod
                    ),
                    outerboundaryis=polygon2.to_kml(),
                )

                topcircle = mod_folder.newpolygon(
                    name="{}-{}-{} min range".format(
                        person.name, walkie_talkie.model, mod.mod
                    ),
                    outerboundaryis=polygon.to_kml(),
                )

                # set the color of the polygons

                bottomcircle.style.labelstyle.scale = 1
                bottomcircle.style.labelstyle.color = simplekml.Color.hexa(
                    person.color + "33"
                )
                bottomcircle.style.polystyle.color = simplekml.Color.hexa(
                    person.color + "33"
                )

                topcircle.style.labelstyle.scale = 1
                topcircle.style.labelstyle.color = simplekml.Color.hexa(
                    person.color + "80"
                )
                topcircle.style.polystyle.color = simplekml.Color.hexa(
                    person.color + "80"
                )

    kml.save("talkies.kml")

if __name__ == "__main__":
    main()

I'm very new to python oop and here is the issue I fall onto. My code create a json file the format seems to be correct but it gave all my Person the same talkies so it look like this:

j

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

l

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

a

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

t

bf888s

bf888s

bf888s

bf888s

uv5r

thuv88

By running in debug mod I found out that each time I call add_walkie_talkie2(wt) it appends the wt to all my Person, does anyone knows why this occurs ?


来源: stackexchange

问:
Input-Device missing in PyAudio when running as root (Raspberry Pi | Debian Bullseye)
First of all some Information about my Setup:
System: Raspberry Pi, Running Debian Bullseye
USB-Microphone with HW-ID: 3|0.

I used following script to set up my USB-Microphone:

Content of /home/pi/.asoundrc

```<code>pcm.!default {
  type asym
  capture.pcm "mic"
}
pcm.mic {
  type plug
  slave {
    pcm "hw:3,0"
  }
}
</code>```

Note that Bullseye uses Alsamixer.

Short Story:
I have following Python Script that searches for an PyAudio Device ID:

```<code>import pyaudio

p = pyaudio.PyAudio()
info = p.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')

for i in range(0, numdevices):
    if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
        print("Input Device id ", i, " - ", p.get_device_info_by_host_api_device_index(0, i).get('name'))
</code>```

When I run this script as the standard pi user, without root, it outputs what I expect it to do:

Input Device id 1 - USB PnP Sound Device: Audio (hw:3,0)
Input Device id 6 - pulse
Input Device id 13 - default

But when I run the script as root, it only detects Input Device id 1.
Why, and how can I change it, so the "default" device is also listed for scripts running with root privileges?

Long Story:
I'm running a Python-Script that utilizes that DeviceID Script.
If I start it from shell or Desktop mode without root privileges, it works perfectly.
I had to choose the "default" Input Device, because if I choose "USB PNP..." PyAudio throws me a WrongChannels-Error. (Yes, I tried changing the Channels Parameter)
My Problems start when I want to run my Main-Python Script at System-Startup.

I tried to make that happen with crontab -e (without sudo):

```<code>@reboot /home/pi/Software/MyScript.py
</code>```

But my logs show that I run into the same problem as when running "get_device_info_by_host_api_device_index" as root. Only 1 Audio Device gets detected. "default" is missing. So my Main-Python-Script runs into an error.
The Problem only occurs when running the script in @reboot in crontab.
I'm not 100% if it's a user-problem.

Thanks for Help.

I tried running a Bash-Script from Crontab that sleeps for 5 seconds before calling my Python-Script. Everything without Sudo.

I also added time.sleep(5) to the start of my Python Script, just to make sure some background audio stuff needs to initialize first.

I also tried working with the USB PNP AUdio device, instead of "default" but couldn't work it out.
Another way to solve my problem would be to make that work.
if I use it with PyAudio it either throws an WrongChannels Error or doesnt detect any Audio Input.
(Yes, the Volume is turned up in Alsamixer)
But thats another Question, and I want to focus on getting the default device working with root first.

ContentLicense: CC BY-SA 4.0

Body:
First of all some Information about my Setup:
System: Raspberry Pi, Running Debian Bullseye
USB-Microphone with HW-ID: 3|0.

I used following script to set up my USB-Microphone:

Content of /home/pi/.asoundrc

pcm.!default {
  type asym
  capture.pcm "mic"
}
pcm.mic {
  type plug
  slave {
    pcm "hw:3,0"
  }
}

Note that Bullseye uses Alsamixer.

Short Story:
I have following Python Script that searches for an PyAudio Device ID:

import pyaudio

p = pyaudio.PyAudio()
info = p.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')

for i in range(0, numdevices):
    if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
        print("Input Device id ", i, " - ", p.get_device_info_by_host_api_device_index(0, i).get('name'))

When I run this script as the standard pi user, without root, it outputs what I expect it to do:

Input Device id 1 - USB PnP Sound Device: Audio (hw:3,0)
Input Device id 6 - pulse
Input Device id 13 - default

But when I run the script as root, it only detects Input Device id 1.
Why, and how can I change it, so the "default" device is also listed for scripts running with root privileges?

Long Story:
I'm running a Python-Script that utilizes that DeviceID Script.
If I start it from shell or Desktop mode without root privileges, it works perfectly.
I had to choose the "default" Input Device, because if I choose "USB PNP..." PyAudio throws me a WrongChannels-Error. (Yes, I tried changing the Channels Parameter)
My Problems start when I want to run my Main-Python Script at System-Startup.

I tried to make that happen with crontab -e (without sudo):

@reboot /home/pi/Software/MyScript.py

But my logs show that I run into the same problem as when running "get_device_info_by_host_api_device_index" as root. Only 1 Audio Device gets detected. "default" is missing. So my Main-Python-Script runs into an error.
The Problem only occurs when running the script in @reboot in crontab.
I'm not 100% if it's a user-problem.

Thanks for Help.

I tried running a Bash-Script from Crontab that sleeps for 5 seconds before calling my Python-Script. Everything without Sudo.

I also added time.sleep(5) to the start of my Python Script, just to make sure some background audio stuff needs to initialize first.

I also tried working with the USB PNP AUdio device, instead of "default" but couldn't work it out.
Another way to solve my problem would be to make that work.
if I use it with PyAudio it either throws an WrongChannels Error or doesnt detect any Audio Input.
(Yes, the Volume is turned up in Alsamixer)
But thats another Question, and I want to focus on getting the default device working with root first.


问:
Tailwind @applying custom classes generates incorrect styles
In one file, I have typography.css:

.p.xl {
  font-size: 1.375rem;
}

.p.lg {
  font-size: 1.25rem;
}

.p {
  font-size: 1.125rem;
}

.p.sm {
  font-size: 0.875rem;
}

```
<p>And in another file, I want to apply <code>.p.lg</code> to my <code>.link</code>s:</p>
<pre class="lang-css prettyprint-override"><code>.link {
  @apply p lg;
}
</code>```

The following code is generated and shipped to the front end:

.link {
    font-size: 1.125rem;
}
```
<p>Even if I change the order of <code>lg</code> and <code>p</code> and even if I inline it in the link itself with <code>class="p lg"</code>.</p>
<hr />
<p>Hell, even if I specify for the <code>p</code> styles to explicitly NOT target the <code>lg</code> elements it STILL generates the incorrect CSS:</p>
<p>Input:</p>
<pre class="lang-css prettyprint-override"><code>.p.xl {
  font-size: 1.375rem;
}

.p.lg {
  font-size: 1.25rem;
}

.p:not(.xxl):not(.xl):not(.lg):not(.sm):not(.xs):not(.xxs) {
  font-size: 1.125rem;
}

.p.sm {
  font-size: 0.875rem;
}
</code>```

Output:

```<code>.link:not(.xxl):not(.xl):not(.lg):not(.sm):not(.xs):not(.xxs) {
    font-size: 1.125rem;
}
</code>```

It's just stupidly copying and pasting the rest of the paragraph selector rather than running the selector logic and determining whether or not to apply the styles.

I have this exact same problem hundreds of times in my project with seemingly no solution other than to completely abandon Tailwind for half the project or to install tailwind-plugins and then enter every single combination of every class I want to apply in my tailwind.config.js.

Help is greatly appreciated. I've searched online for a while without finding anyone even having the same problem; I only found people who don't know how @apply works (well perhaps I'm one of them...). Thanks in advance.

UPDATE:

I also have:

.p {
  @apply font-light;
}

.p.subheading {
  @apply font-normal;
}
```
<p>And of course the same issue with applying <code>p subheading</code> where it applies the wrong font weight and even using <code>.p:not(.subheading)</code> still generates the wrong styles. Will I really have no way whatsoever of styling <code>p</code> font-weights without also giving every single <code>.p</code> ANOTHER class to tell it to use one font weight? In other words, are default styles impossible?</p>
<hr />
<h3>UPDATE 2</h3>
<p>Even when using <code>!important</code> it still fails to override...</p>
<pre class="lang-css prettyprint-override"><code>  .p {
    @apply font-light;
  }

  .p.subheading {
    @apply !font-normal;
  }
</code>```

and

  .p.xl {
    font-size: 1.375rem !important;
  }

  .p.lg {
    font-size: 1.25rem !important;
  }

  .p {
    font-size: 1.125rem;
  }

  .p.sm {
    font-size: 0.875rem !important;
  }
```
<p>I STILL get the wrong font sizes and font weights generated:</p>
<pre class="lang-css prettyprint-override"><code>.link {
    font-size: 1.125rem;
}
.link {
    font-weight: 300;
}
</code>```

Body:
In one file, I have typography.css:

.p.xl {
  font-size: 1.375rem;
}

.p.lg {
  font-size: 1.25rem;
}

.p {
  font-size: 1.125rem;
}

.p.sm {
  font-size: 0.875rem;
}

And in another file, I want to apply .p.lg to my .links:

.link {
  @apply p lg;
}

The following code is generated and shipped to the front end:

.link {
    font-size: 1.125rem;
}

Even if I change the order of lg and p and even if I inline it in the link itself with class="p lg".

Hell, even if I specify for the p styles to explicitly NOT target the lg elements it STILL generates the incorrect CSS:

Input:

.p.xl {
  font-size: 1.375rem;
}

.p.lg {
  font-size: 1.25rem;
}

.p:not(.xxl):not(.xl):not(.lg):not(.sm):not(.xs):not(.xxs) {
  font-size: 1.125rem;
}

.p.sm {
  font-size: 0.875rem;
}

Output:

.link:not(.xxl):not(.xl):not(.lg):not(.sm):not(.xs):not(.xxs) {
    font-size: 1.125rem;
}

It's just stupidly copying and pasting the rest of the paragraph selector rather than running the selector logic and determining whether or not to apply the styles.

I have this exact same problem hundreds of times in my project with seemingly no solution other than to completely abandon Tailwind for half the project or to install tailwind-plugins and then enter every single combination of every class I want to apply in my tailwind.config.js.

Help is greatly appreciated. I've searched online for a while without finding anyone even having the same problem; I only found people who don't know how @apply works (well perhaps I'm one of them...). Thanks in advance.

UPDATE:

I also have:

.p {
  @apply font-light;
}

.p.subheading {
  @apply font-normal;
}

And of course the same issue with applying p subheading where it applies the wrong font weight and even using .p:not(.subheading) still generates the wrong styles. Will I really have no way whatsoever of styling p font-weights without also giving every single .p ANOTHER class to tell it to use one font weight? In other words, are default styles impossible?

UPDATE 2

Even when using !important it still fails to override...

  .p {
    @apply font-light;
  }

  .p.subheading {
    @apply !font-normal;
  }

and

  .p.xl {
    font-size: 1.375rem !important;
  }

  .p.lg {
    font-size: 1.25rem !important;
  }

  .p {
    font-size: 1.125rem;
  }

  .p.sm {
    font-size: 0.875rem !important;
  }

I STILL get the wrong font sizes and font weights generated:

.link {
    font-size: 1.125rem;
}
.link {
    font-weight: 300;
}


问:
Getting error undefined reference to `getaddrinfo' on Linux
When I try to compile my small C program, I get the error msg:
: undefined reference to `getaddrinfo'. I have included the netdb.h and socket.h header files too. But the error is in linker.

I see a query already on stackoverflow, but that was on Windows. I am trying it on a Linux machine.
How do I make the compilation succeed ?

Thanks !

Here is the code:

```<code>   #include <stdlib.h>
   #include <stdio.h>
   #include <sys/socket.h>
   #include <sys/types.h>
   #include <netdb.h>

   int main() {
   int status;
   struct addrinfo hints;
  struct addrinfo *servinfo; // will point to the results

  memset(&hints, 0, sizeof hints); // make sure the struct is empty
  hints.ai_family = AF_UNSPEC;    // don't care IPv4 or IPv6
  hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
  hints.ai_flags = AI_PASSIVE;    // fill in my IP for me
  if ((status = getaddrinfo(NULL, "80", &hints, &servinfo)) != 0)
  {

     fprintf(stderr, "getaddrinfo error: \n");
      exit(1);
  }
  printf("\n %d %d %d %d %d %s",servinfo->ai_flags, servinfo->ai_family, servi    nfo->ai_socktype, servinfo->ai_protocol, servinfo->ai_addrlen, servinfo->ai_canonname);
  return 0;
 }
</code>```

gcc test5.c
/tmp/ccrFX43l.o(.text+0x4c): In function main':
: undefined reference togetaddrinfo'
collect2: ld returned 1 exit status

ContentLicense: CC BY-SA 3.0

Body:
When I try to compile my small C program, I get the error msg:
: undefined reference to `getaddrinfo'. I have included the netdb.h and socket.h header files too. But the error is in linker.

I see a query already on stackoverflow, but that was on Windows. I am trying it on a Linux machine.
How do I make the compilation succeed ?

Thanks !

Here is the code:

   #include <stdlib.h>
   #include <stdio.h>
   #include <sys/socket.h>
   #include <sys/types.h>
   #include <netdb.h>

   int main() {
   int status;
   struct addrinfo hints;
  struct addrinfo *servinfo; // will point to the results

  memset(&hints, 0, sizeof hints); // make sure the struct is empty
  hints.ai_family = AF_UNSPEC;    // don't care IPv4 or IPv6
  hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
  hints.ai_flags = AI_PASSIVE;    // fill in my IP for me
  if ((status = getaddrinfo(NULL, "80", &hints, &servinfo)) != 0)
  {

     fprintf(stderr, "getaddrinfo error: \n");
      exit(1);
  }
  printf("\n %d %d %d %d %d %s",servinfo->ai_flags, servinfo->ai_family, servi    nfo->ai_socktype, servinfo->ai_protocol, servinfo->ai_addrlen, servinfo->ai_canonname);
  return 0;
 }

gcc test5.c
/tmp/ccrFX43l.o(.text+0x4c): In function main':
: undefined reference togetaddrinfo'
collect2: ld returned 1 exit status


问:
Should I use Shorter field names in firestore document fields to reduce cost?
Q1:
I wanted to know, using shorter field name in a document in firestore have benifit for saving cost ?

suppose I have:

```<code>first_name : "a"
last_name : "b"
</code>```

And then I have:

```<code>fn : "a"
ln : "b"
</code>```

here I am clearly saving 8 + 7 = 15 bytes. This may be small for one document, but suppose there are 1 million of this docs than this will be almost 14 MB saved ?

I feel I can save on both side :

storage cost

bandwidth cost if this docs updates frequenctly ?

Q2 :
Suppose my document size is 20 bytes and collection have 10 such docs will collection size be 200 bytes of firebase uses any short of key mapping mechanism and all field names will be stored at collection level ?

Body:
Q1:
I wanted to know, using shorter field name in a document in firestore have benifit for saving cost ?

suppose I have:

first_name : "a"
last_name : "b"

And then I have:

fn : "a"
ln : "b"

here I am clearly saving 8 + 7 = 15 bytes. This may be small for one document, but suppose there are 1 million of this docs than this will be almost 14 MB saved ?

I feel I can save on both side :

storage cost

bandwidth cost if this docs updates frequenctly ?

Q2 :
Suppose my document size is 20 bytes and collection have 10 such docs will collection size be 200 bytes of firebase uses any short of key mapping mechanism and all field names will be stored at collection level ?


问:
Custom tensorflow model unable to process inputs (should be string) properly DURING TRAINING
I'm building a custom model in tensorflow with a custom layer (fasttext embedding layer) via subclassing and I've got the current setup here so far:

(p.s. the simple_preprocess function is simply imported from gensim library -> from gensim.utils import simple_preprocess)

class FastTextEmbedding(tf.keras.layers.Layer):
    def __init__(self, trained_ft_model_dir:str) -> None:
        super(FastTextEmbedding, self).__init__()
        self.trained_ft_model = FastText.load(trained_ft_model_dir)

    # INPUT IS A STRING : "Hey my name is Anas"
    def call(self, input):
        # print(type(input))
        # input = tf.constant(input)
        # assert type(input) == str
        out = np.zeros(shape=(1,60))
        sent_tokenized = simple_preprocess(input)

        # we'll use mean pooling
        for word in sent_tokenized:
            out[:,:] += self.trained_ft_model.wv[word]

        print(len(sent_tokenized))
        return tf.convert_to_tensor(out / len(sent_tokenized))
        # return tf.convert_to_tensor(out / len(sent_tokenized))

    # def call(self, input):
    #     # print(type(input))
    #     # input = tf.constant(input)
    #     # assert type(input) == str
    #     out = np.zeros(shape=(60,))
    #     sent_tokenized = simple_preprocess(input)

    #     # we'll use mean pooling
    #     for word in sent_tokenized:
    #         out += self.trained_ft_model.wv[word]

    #     print(len(sent_tokenized))
    #     return tf.expand_dims(tf.convert_to_tensor(out / len(sent_tokenized)), axis=1)
    #     # return tf.convert_to_tensor(out / len(sent_tokenized))
```
<pre class="lang-py prettyprint-override"><code>class FastTextModel(tf.keras.Model):
    def __init__(self, trained_ft_model_dir, num_classes:int=16) -> None:
        super(FastTextModel, self).__init__(name='FT')
        self.fasttext_embeddings = FastTextEmbedding(trained_ft_model_dir)
        self.relu = tf.keras.layers.Activation('relu')
        self.softmax = tf.keras.layers.Activation('softmax')
        self.dense1 = tf.keras.layers.Dense(units=60)
        self.do = tf.keras.layers.Dropout(rate=0.35)
        self.dense2 = tf.keras.layers.Dense(units=num_classes)
        self.bn = tf.keras.layers.BatchNormalization()

    def call(self, input):
        x = self.fasttext_embeddings(input,training=False)
        x = self.dense1(x, training=True)
        print(x.shape)
        x = self.bn(x, training=True)
        print(x.shape)
        x = self.relu(x)
        x = self.do(x, training=False)
        print(x.shape)
        x = self.dense2(x, training=True)
        print(x.shape)
        return self.softmax(x)
</code>```

So I've made a custom layer FastTextEmbedding and built that layer into my model FastTextModel

My issue is that when I go to build the model via the following line:
_ = model.build("Hey my name is Anas")
it builds successfully with the current setup I've got. FYI the model is intended to take in string and get the fasttext embeddings for the words, combine via mean pooling and pass that through some layers to make a decision. Now when I go to train my model I get this weird error:

```<code>output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[150], line 1
----> 1 history = model.fit(X_train,
      2                     y_train,
      3                     batch_size=128,
      4                     validation_data=(X_val, y_val),
      5                     validation_batch_size=128,
      6                     epochs=15)

File ~/Desktop/Winterproj/emojify/lib/python3.9/site-packages/keras/utils/traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     67     filtered_tb = _process_traceback_frames(e.__traceback__)
     68     # To get the full stack trace, call:
     69     # `tf.debugging.disable_traceback_filtering()`
---> 70     raise e.with_traceback(filtered_tb) from None
     71 finally:
     72     del filtered_tb

File /var/folders/07/1yqf9lq93hb3l2f96cqmmv9c0000gn/T/__autograph_generated_filerg_dksj0.py:15, in outer_factory.<locals>.inner_factory.<locals>.tf__train_function(iterator)
     13 try:
     14     do_return = True
---> 15     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
     16 except:
     17     do_return = False

Call arguments received by layer 'FT' (type FastTextModel):
  • input=tf.Tensor(shape=(None,), dtype=string)
</code>```

My training data is of this format:

```<code>Training data (X_train, a np array of string tweets):
['chick fil hicksville finally open'
 'accidental twinning with my favorites'
 'one of my favorite people in this world love you mrs andrews' ...
 'of your fav artists takin on hoco' 'welcome to the studio' 'the boys']

shape of training data: (204073,)

Labels for data(categorically encoded, there are 16 total classes):
[[0. 0. 0. ... 0. 0. 0.]
 [1. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]

shape of labels for training: (204073, 16)
</code>```

I tried expanding the dimensions for my call method in my custom layer, that worked to get past a few problems but still I'm stuck here because I need the model to train as it takes in all the inputs and use batches of like 128 or so to train the model.

At the end I want to be able to take a single line of text such as "Hey my name is Anas" and apply my model to it to output one of the 16 classes (they are emoji labels).

This is my first time building out a model like this, I've been stuck for some time now and would appreciate any suggestions / advice. Thanks

Body:
I'm building a custom model in tensorflow with a custom layer (fasttext embedding layer) via subclassing and I've got the current setup here so far:

(p.s. the simple_preprocess function is simply imported from gensim library -> from gensim.utils import simple_preprocess)

class FastTextEmbedding(tf.keras.layers.Layer):
    def __init__(self, trained_ft_model_dir:str) -> None:
        super(FastTextEmbedding, self).__init__()
        self.trained_ft_model = FastText.load(trained_ft_model_dir)

    # INPUT IS A STRING : "Hey my name is Anas"
    def call(self, input):
        # print(type(input))
        # input = tf.constant(input)
        # assert type(input) == str
        out = np.zeros(shape=(1,60))
        sent_tokenized = simple_preprocess(input)

        # we'll use mean pooling
        for word in sent_tokenized:
            out[:,:] += self.trained_ft_model.wv[word]

        print(len(sent_tokenized))
        return tf.convert_to_tensor(out / len(sent_tokenized))
        # return tf.convert_to_tensor(out / len(sent_tokenized))

    # def call(self, input):
    #     # print(type(input))
    #     # input = tf.constant(input)
    #     # assert type(input) == str
    #     out = np.zeros(shape=(60,))
    #     sent_tokenized = simple_preprocess(input)

    #     # we'll use mean pooling
    #     for word in sent_tokenized:
    #         out += self.trained_ft_model.wv[word]

    #     print(len(sent_tokenized))
    #     return tf.expand_dims(tf.convert_to_tensor(out / len(sent_tokenized)), axis=1)
    #     # return tf.convert_to_tensor(out / len(sent_tokenized))

class FastTextModel(tf.keras.Model):
    def __init__(self, trained_ft_model_dir, num_classes:int=16) -> None:
        super(FastTextModel, self).__init__(name='FT')
        self.fasttext_embeddings = FastTextEmbedding(trained_ft_model_dir)
        self.relu = tf.keras.layers.Activation('relu')
        self.softmax = tf.keras.layers.Activation('softmax')
        self.dense1 = tf.keras.layers.Dense(units=60)
        self.do = tf.keras.layers.Dropout(rate=0.35)
        self.dense2 = tf.keras.layers.Dense(units=num_classes)
        self.bn = tf.keras.layers.BatchNormalization()

    def call(self, input):
        x = self.fasttext_embeddings(input,training=False)
        x = self.dense1(x, training=True)
        print(x.shape)
        x = self.bn(x, training=True)
        print(x.shape)
        x = self.relu(x)
        x = self.do(x, training=False)
        print(x.shape)
        x = self.dense2(x, training=True)
        print(x.shape)
        return self.softmax(x)

So I've made a custom layer FastTextEmbedding and built that layer into my model FastTextModel

My issue is that when I go to build the model via the following line:
_ = model.build("Hey my name is Anas")
it builds successfully with the current setup I've got. FYI the model is intended to take in string and get the fasttext embeddings for the words, combine via mean pooling and pass that through some layers to make a decision. Now when I go to train my model I get this weird error:

output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[150], line 1
----> 1 history = model.fit(X_train,
      2                     y_train,
      3                     batch_size=128,
      4                     validation_data=(X_val, y_val),
      5                     validation_batch_size=128,
      6                     epochs=15)

File ~/Desktop/Winterproj/emojify/lib/python3.9/site-packages/keras/utils/traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     67     filtered_tb = _process_traceback_frames(e.__traceback__)
     68     # To get the full stack trace, call:
     69     # `tf.debugging.disable_traceback_filtering()`
---> 70     raise e.with_traceback(filtered_tb) from None
     71 finally:
     72     del filtered_tb

File /var/folders/07/1yqf9lq93hb3l2f96cqmmv9c0000gn/T/__autograph_generated_filerg_dksj0.py:15, in outer_factory.<locals>.inner_factory.<locals>.tf__train_function(iterator)
     13 try:
     14     do_return = True
---> 15     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
     16 except:
     17     do_return = False

Call arguments received by layer 'FT' (type FastTextModel):
  • input=tf.Tensor(shape=(None,), dtype=string)

My training data is of this format:

Training data (X_train, a np array of string tweets):
['chick fil hicksville finally open'
 'accidental twinning with my favorites'
 'one of my favorite people in this world love you mrs andrews' ...
 'of your fav artists takin on hoco' 'welcome to the studio' 'the boys']

shape of training data: (204073,)

Labels for data(categorically encoded, there are 16 total classes):
[[0. 0. 0. ... 0. 0. 0.]
 [1. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]

shape of labels for training: (204073, 16)

I tried expanding the dimensions for my call method in my custom layer, that worked to get past a few problems but still I'm stuck here because I need the model to train as it takes in all the inputs and use batches of like 128 or so to train the model.

At the end I want to be able to take a single line of text such as "Hey my name is Anas" and apply my model to it to output one of the 16 classes (they are emoji labels).

This is my first time building out a model like this, I've been stuck for some time now and would appreciate any suggestions / advice. Thanks


问:
set_major_formatter resets x axis origin to 1970-01-01
The code below generates a plot with a properly-labeled x axis.  But I don't want the full YYYY-MM-DD HH:MM:SS date format.  No problem, a bunch of googling finally turned up the locator / formatter utilities.  But if I uncomment the last line with the set_major_formatter, with no other changes, it formats the date as requested -- but now the x axis starts at the epoch (1970-01-01).  !??

```<code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter

dates = pd.date_range(start="2021-01-01", end="2022-12-01")
data = [d.day for d in dates]
df = pd.DataFrame(index=dates, columns=[ "Data" ], data=data)
df.plot(kind="bar")
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 4, 7, 10)))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
date_form = DateFormatter("%Y-%m")
# ax.xaxis.set_major_formatter(date_form)
</code>```

Body:
The code below generates a plot with a properly-labeled x axis.  But I don't want the full YYYY-MM-DD HH:MM:SS date format.  No problem, a bunch of googling finally turned up the locator / formatter utilities.  But if I uncomment the last line with the set_major_formatter, with no other changes, it formats the date as requested -- but now the x axis starts at the epoch (1970-01-01).  !??

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter

dates = pd.date_range(start="2021-01-01", end="2022-12-01")
data = [d.day for d in dates]
df = pd.DataFrame(index=dates, columns=[ "Data" ], data=data)
df.plot(kind="bar")
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 4, 7, 10)))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
date_form = DateFormatter("%Y-%m")
# ax.xaxis.set_major_formatter(date_form)


问:
Run an async function from a sync function... without knowing whether there is already a running event loop?
So it is a common question for someone first coming to python's async to ask, "how do I run an async function from a sync function?" Hopefully if you're here you already know that the answer to that question is asyncio.run().

But this is not really the answer. Because suppose I want to write an ad hoc set of scripts in which, in a few places within it, I want to call a few coroutines. asyncio.run "should ideally only be called once" and "cannot be called when another asyncio event loop is running in the same thread." In general you cannot have two event loops running in the same thread.

In the ad hoc scenario I imagine I would like an idiom which is "block execution of this non-async function, and its event loop if there is one, until this coroutine finishes". It must tolerate being run whether an event loop exists or not and whether it is running or not. If there is no running event loop this easy. If there is, it should have the same effect as creating another event loop, calling run_until_complete on that, then resuming execution of the calling function (which, eventually, will pass control back to the original loop, though since it's not async, that might not be for a while.)

For example:

async def coro1():
  pass

def function1():
  better_asyncio_run(coro1())

def function2():
  function1()
  better_asyncio_run(coro1())

async def coro2():
  function2()

if __name__ == '__main__':
  better_asyncio_run(coro2())
```

One might be tempted to answer, "rewrite your code to all be async" which is I guess giving in to the nightmare. It surely shouldn't be necessary for the rapid prototyping we love python for. If there is some fundamental reason why it can't work, I haven't spotted it and would love to know what it is.

Body:
So it is a common question for someone first coming to python's async to ask, "how do I run an async function from a sync function?" Hopefully if you're here you already know that the answer to that question is asyncio.run().

But this is not really the answer. Because suppose I want to write an ad hoc set of scripts in which, in a few places within it, I want to call a few coroutines. asyncio.run "should ideally only be called once" and "cannot be called when another asyncio event loop is running in the same thread." In general you cannot have two event loops running in the same thread.

In the ad hoc scenario I imagine I would like an idiom which is "block execution of this non-async function, and its event loop if there is one, until this coroutine finishes". It must tolerate being run whether an event loop exists or not and whether it is running or not. If there is no running event loop this easy. If there is, it should have the same effect as creating another event loop, calling run_until_complete on that, then resuming execution of the calling function (which, eventually, will pass control back to the original loop, though since it's not async, that might not be for a while.)

For example:

async def coro1():
  pass

def function1():
  better_asyncio_run(coro1())

def function2():
  function1()
  better_asyncio_run(coro1())

async def coro2():
  function2()

if __name__ == '__main__':
  better_asyncio_run(coro2())

One might be tempted to answer, "rewrite your code to all be async" which is I guess giving in to the nightmare. It surely shouldn't be necessary for the rapid prototyping we love python for. If there is some fundamental reason why it can't work, I haven't spotted it and would love to know what it is.


问:
Swift UI: Cannot load files via JS fetch in Webview HTML
I was trying to load some existing website code into web view. One example html would be like:

```<code><!doctype html>
<html>
  <head>
    <title>This is the title of the webpage!</title>
    <script>
        const url = "/somefolder/model.txt"
        fetch(url)
           .then( r => r.text() )
           .then( t => console.log(t))
    </script>
  </head>
  <body>
    <p>This is an example paragraph.</p>
  </body>
</html>
</code>```

I am using WKWebview for this:

```<code>    struct SwiftUIWebview: UIViewRepresentable{
    func makeUIView(context: Context) -> WKWebView {
        let prefs = WKWebpagePreferences();
        prefs.allowsContentJavaScript=true;
        let config = WKWebViewConfiguration();
        config.defaultWebpagePreferences = prefs;
        config.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        let browser = WKWebView(frame: .zero, configuration: config)
        return browser
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let url = Bundle.main.url(forResource: "index", withExtension: "html")!
        uiView.loadFileURL(url, allowingReadAccessTo: url)
        let request = URLRequest(url: url)
        uiView.load(request)
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            SwiftUIWebview()
        }
    }
}
</code>```

I am getting errors while fetching the file. Looks like the URL is not considering the whole path for the app. I manually made the URL and fetched it from safari mobile browser of the device while app was running, It worked.

Need a solution that would consider the complete URL path for the file to be loaded.

Body:
I was trying to load some existing website code into web view. One example html would be like:

<!doctype html>

    <title>This is the title of the webpage!</title>

This is an example paragraph.

I am using WKWebview for this:

    struct SwiftUIWebview: UIViewRepresentable{
    func makeUIView(context: Context) -> WKWebView {
        let prefs = WKWebpagePreferences();
        prefs.allowsContentJavaScript=true;
        let config = WKWebViewConfiguration();
        config.defaultWebpagePreferences = prefs;
        config.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        let browser = WKWebView(frame: .zero, configuration: config)
        return browser
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let url = Bundle.main.url(forResource: "index", withExtension: "html")!
        uiView.loadFileURL(url, allowingReadAccessTo: url)
        let request = URLRequest(url: url)
        uiView.load(request)
    }
}

struct ContentView: View {
    var body: some View {
        VStack {
            SwiftUIWebview()
        }
    }
}

I am getting errors while fetching the file. Looks like the URL is not considering the whole path for the app. I manually made the URL and fetched it from safari mobile browser of the device while app was running, It worked.

Need a solution that would consider the complete URL path for the file to be loaded.


问:
ModelMapper throws an exception while mapping from List to Map
I am using ModelMapper to map 3 classes describing Doctor: DoctorEntity, Doctor and
DoctorDto

```<code>@Entity
public class DoctorEntity {

    private List<AppointmentEntity> appointmentEntities
    ...
}
</code>```
```<code>public class Doctor {

    private Map<Long, AppointmentInterface> appointments;
    ...
}
</code>```
```<code>public class DoctorDTO {

    private List<AppointmentDto> appointments;
    ...
}
</code>```

To map fields with 'List' type to 'Map' type I've implemented 2 methods:

```<code>@Override
protected void mapSpecificFieldsToModelFromDto(DoctorDto source, Doctor destination) {

    if (source.getAppointments() != null)
        destination.setAppointments(source.getAppointments()
                .stream()
                .collect(Collectors.toMap(AppointmentDto::getId,
                        elem -> mapper.map(elem, Appointment.class))));
}
</code>```
```<code>@Override
protected void mapSpecificFieldsToModelFromEntity(DoctorEntity source, Doctor destination) {

    if (source.getAppointmentEntities() != null)
        destination.setAppointments(source.getAppointmentEntities()
                .stream()
                .collect(Collectors.toMap(AppointmentEntity::getId,
                        elem -> mapper.map(elem, Appointment.class))));
}
</code>```

These methods configure DoctorMapper by this method in DoctorMapper class, where I'm setting the TypeMaps and PostConverters:

```<code>@PostConstruct
public void setupMapper() {
    mapper.createTypeMap(DoctorEntity.class, Doctor.class)
            .setPostConverter(toModelFromEntityConverter());
    mapper.createTypeMap(Doctor.class, DoctorEntity.class)
            .setPostConverter(toEntityFromModelConverter());
    mapper.createTypeMap(Doctor.class, DoctorDto.class)
            .setPostConverter(toDtoFromModelConverter());
    mapper.createTypeMap(DoctorDto.class, Doctor.class)
            .setPostConverter(toModelFromDtoConverter());
}
</code>```

DoctorMapper is inherited from the AbstractMapper class and it also inherit toFromConverter() methods from an abstract class:

```<code>protected Converter<E, M> toModelFromEntityConverter() {
    return context -> {
        E source = context.getSource();
        M destination = context.getDestination();
        mapSpecificFieldsToModelFromEntity(source, destination);
        return context.getDestination();
    };
}

protected Converter<M, E> toEntityFromModelConverter() {
    return context -> {
        M source = context.getSource();
        E destination = context.getDestination();
        mapSpecificFieldsToEntityFromModel(source, destination);
        return context.getDestination();
    };
}

protected Converter<M, D> toDtoFromModelConverter() {
    return context -> {
        M source = context.getSource();
        D destination = context.getDestination();
        mapSpecificFieldsToDtoFromModel(source, destination);
        return context.getDestination();
    };
}

protected Converter<D, M> toModelFromDtoConverter() {
    return context -> {
        D source = context.getSource();
        M destination = context.getDestination();
        mapSpecificFieldsToModelFromDto(source, destination);
        return context.getDestination();
    };
}
</code>```

I've written two test to check the mapping proccess works as I expect. But the first one is passing and another one is falling:

```<code>@Autowired
private Mapper<DoctorEntity, Doctor, DoctorDto> doctorMapper;

@Test
void mapEntityToModel() {
    DoctorEntity doctorEntity = new DoctorEntity(1L,
            ...
            List.of(new AppointmentEntity(1L,
                            LocalDate.now(),
                            AppointmentState.OPEN,
                            null,
                            null,
                            null)
            ));

    Doctor doctor = doctorMapper.toModelFromEntity(doctorEntity);

    doctorEntity.getAppointments().forEach(a -> assertTrue(doctor.getAppointments().containsKey(a.getId())));
}
</code>```
```<code>@Autowired
private Mapper<DoctorEntity, Doctor, DoctorDto> doctorMapper;

void mapDtoToModel() {
        DoctorDto doctorDto = new DoctorDto(1L,
                ...
                List.of(new AppointmentDto(1L,
                                LocalDate.now(),
                                AppointmentState.OPEN,
                                null,
                                null,
                                null)
                ));

        Doctor doctor = doctorMapper.toModelFromDto(doctorDto);

        doctorDto.getAppointments().forEach(a -> assertTrue(doctor.getAppointments().containsKey(a.getId())));
    }
</code>```

So, the issue occurs when ModelMapper tries to map DoctorDTO to Doctor

```<code>1) Failed to instantiate instance of destination java.util.Map. Ensure that java.util.Map has a non-private no-argument constructor.
</code>```

Surprisingly for me, DoctorMapper maps Entity to Model correctly.

So, after I've read an exception, I've changed the Map type to the HashMap in the Doctor class and it worked.

But I have no ideas why it works and why ModelMapper can't use the HashMap implementation to construct field with Map type in Doctor class.
As I understood from official ModelMapper's repository on GitHub the issues related to this was marked as solved long ago, but I've tried to do everything from the solutions of these issues and it didn't help me.

Body:
I am using ModelMapper to map 3 classes describing Doctor: DoctorEntity, Doctor and
DoctorDto

@Entity
public class DoctorEntity {

    private List<AppointmentEntity> appointmentEntities
    ...
}

public class Doctor {

    private Map<Long, AppointmentInterface> appointments;
    ...
}

public class DoctorDTO {

    private List<AppointmentDto> appointments;
    ...
}

To map fields with 'List' type to 'Map' type I've implemented 2 methods:

@Override
protected void mapSpecificFieldsToModelFromDto(DoctorDto source, Doctor destination) {

    if (source.getAppointments() != null)
        destination.setAppointments(source.getAppointments()
                .stream()
                .collect(Collectors.toMap(AppointmentDto::getId,
                        elem -> mapper.map(elem, Appointment.class))));
}

@Override
protected void mapSpecificFieldsToModelFromEntity(DoctorEntity source, Doctor destination) {

    if (source.getAppointmentEntities() != null)
        destination.setAppointments(source.getAppointmentEntities()
                .stream()
                .collect(Collectors.toMap(AppointmentEntity::getId,
                        elem -> mapper.map(elem, Appointment.class))));
}

These methods configure DoctorMapper by this method in DoctorMapper class, where I'm setting the TypeMaps and PostConverters:

@PostConstruct
public void setupMapper() {
    mapper.createTypeMap(DoctorEntity.class, Doctor.class)
            .setPostConverter(toModelFromEntityConverter());
    mapper.createTypeMap(Doctor.class, DoctorEntity.class)
            .setPostConverter(toEntityFromModelConverter());
    mapper.createTypeMap(Doctor.class, DoctorDto.class)
            .setPostConverter(toDtoFromModelConverter());
    mapper.createTypeMap(DoctorDto.class, Doctor.class)
            .setPostConverter(toModelFromDtoConverter());
}

DoctorMapper is inherited from the AbstractMapper class and it also inherit toFromConverter() methods from an abstract class:

protected Converter<E, M> toModelFromEntityConverter() {
    return context -> {
        E source = context.getSource();
        M destination = context.getDestination();
        mapSpecificFieldsToModelFromEntity(source, destination);
        return context.getDestination();
    };
}

protected Converter<M, E> toEntityFromModelConverter() {
    return context -> {
        M source = context.getSource();
        E destination = context.getDestination();
        mapSpecificFieldsToEntityFromModel(source, destination);
        return context.getDestination();
    };
}

protected Converter<M, D> toDtoFromModelConverter() {
    return context -> {
        M source = context.getSource();
        D destination = context.getDestination();
        mapSpecificFieldsToDtoFromModel(source, destination);
        return context.getDestination();
    };
}

protected Converter<D, M> toModelFromDtoConverter() {
    return context -> {
        D source = context.getSource();
        M destination = context.getDestination();
        mapSpecificFieldsToModelFromDto(source, destination);
        return context.getDestination();
    };
}

I've written two test to check the mapping proccess works as I expect. But the first one is passing and another one is falling:

@Autowired
private Mapper<DoctorEntity, Doctor, DoctorDto> doctorMapper;

@Test
void mapEntityToModel() {
    DoctorEntity doctorEntity = new DoctorEntity(1L,
            ...
            List.of(new AppointmentEntity(1L,
                            LocalDate.now(),
                            AppointmentState.OPEN,
                            null,
                            null,
                            null)
            ));

    Doctor doctor = doctorMapper.toModelFromEntity(doctorEntity);

    doctorEntity.getAppointments().forEach(a -> assertTrue(doctor.getAppointments().containsKey(a.getId())));
}

@Autowired
private Mapper<DoctorEntity, Doctor, DoctorDto> doctorMapper;

void mapDtoToModel() {
        DoctorDto doctorDto = new DoctorDto(1L,
                ...
                List.of(new AppointmentDto(1L,
                                LocalDate.now(),
                                AppointmentState.OPEN,
                                null,
                                null,
                                null)
                ));

        Doctor doctor = doctorMapper.toModelFromDto(doctorDto);

        doctorDto.getAppointments().forEach(a -> assertTrue(doctor.getAppointments().containsKey(a.getId())));
    }

So, the issue occurs when ModelMapper tries to map DoctorDTO to Doctor

1) Failed to instantiate instance of destination java.util.Map. Ensure that java.util.Map has a non-private no-argument constructor.

Surprisingly for me, DoctorMapper maps Entity to Model correctly.

So, after I've read an exception, I've changed the Map type to the HashMap in the Doctor class and it worked.

But I have no ideas why it works and why ModelMapper can't use the HashMap implementation to construct field with Map type in Doctor class.
As I understood from official ModelMapper's repository on GitHub the issues related to this was marked as solved long ago, but I've tried to do everything from the solutions of these issues and it didn't help me.


问:
Multivaraible Regression Performca Metrics are Good but Plot is Broken
I built m model as:

```<code>X = alldata.drop(columns= ['S&P 500 Price','Date'])
y = alldata['S&P 500 Price']
X_train,X_test,y_train,y_test= train_test_split(X,y,test_size=0.25,random_state=0)
LR_model = LinearRegression()
LR_model.fit(X_train,y_train)
y_pred = LR_model.predict(X_test)
</code>```

When I plot my predict and actual data as below:

```<code>plt.plot(y_pred,color='red', alpha=0.6, label =' Predicted Data')
plt.plot(y_test,color='green', alpha=0.6, label='Actual Data')
plt.title('Actual and Predicted Data for S&P 500 Prediction')
plt.show()
</code>```

My output come like this. As you can see my test actual data test values goes up to like 4000 ish in reality it is 1055 just like predicted data I don't understand that my y_test values seems like over 4000 values in it when I plot it in reality it is not. And I can't udnerstand anything with this plot picture but my performance metrics is really good fo example r2 score 0.97 and validation is good also. Is there any way I can fix this plot?

Body:
I built m model as:

X = alldata.drop(columns= ['S&P 500 Price','Date'])
y = alldata['S&P 500 Price']
X_train,X_test,y_train,y_test= train_test_split(X,y,test_size=0.25,random_state=0)
LR_model = LinearRegression()
LR_model.fit(X_train,y_train)
y_pred = LR_model.predict(X_test)

When I plot my predict and actual data as below:

plt.plot(y_pred,color='red', alpha=0.6, label =' Predicted Data')
plt.plot(y_test,color='green', alpha=0.6, label='Actual Data')
plt.title('Actual and Predicted Data for S&P 500 Prediction')
plt.show()

My output come like this. As you can see my test actual data test values goes up to like 4000 ish in reality it is 1055 just like predicted data I don't understand that my y_test values seems like over 4000 values in it when I plot it in reality it is not. And I can't udnerstand anything with this plot picture but my performance metrics is really good fo example r2 score 0.97 and validation is good also. Is there any way I can fix this plot?


问:
How to deploy/publish on GitHub pages of another repository?
I have an enterprise GitHub repository (let’s name it Repo-A) and its GitHub pages is already occupied. Meaning it is already used. So I have created another repository within the same organisation in which my Repo-A exists ( let’s call this one Repo-B). How can I publish static html present in Repo-A to GitHub pages of Repo-B?


问:
Search with fusejs using different words parameters
I'm moving from algolia autocomplete and I'm trying to use fusejs to search through a json file using a query like "Shirt Dodgers" but I'm not able to get these results, insted I'm getting back no data

```<code>[
    {
        "Active": true,
        "Brand": "FEXPRO",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2FMLBHD52001BLU%2FMLBHD52001BLU.jpg?alt=media",
        "Images": {},
        "Name": "LOS ANGELES DODGERS MLB PRIMARY LOGO HOODIE",
        "Price": 999,
        "Priority": 7,
        "SKU_Parent": "MLBHD52001BLU",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "SUDADERA",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/FEXPRO",
        "Type": "TEXTIL",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "FEXPRO",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2FMLBSH520201NVY%2FMLBSH520201NVY.jpg?alt=media",
        "Images": {},
        "Name": "LOS ANGELES DODGERS MLB BASIC CASUAL SHORT",
        "Price": 699,
        "Priority": 7,
        "SKU_Parent": "MLBSH520201NVY",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "SHORT",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/FEXPRO",
        "Type": "TEXTIL",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "FEXPRO",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2FMLBTS520200BLU2%2FMLBTS520200BLU2.jpg?alt=media",
        "Images": {},
        "Name": "LOS ANGELES DODGERS MLB PRIMARY LOGO TSHIRT",
        "Price": 349,
        "Priority": 7,
        "SKU_Parent": "MLBTS520200BLU2",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "PLAYERA M/C",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/FEXPRO",
        "Type": "TEXTIL",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "STANCE",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2FA545A22DOD%2FA545A22DOD.jpg?alt=media",
        "Images": {},
        "Name": "STANCE LOS ANGELES DODGERS SPLIT CREW",
        "Price": 329,
        "Priority": 7,
        "SKU_Parent": "A545A22DOD",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "TIN MEDIO",
        "SpecialPrice": 230,
        "SpecialPrice_DateFrom": "2022-11-27T06:00:00.000Z",
        "SpecialPrice_DateTo": "2031-01-01T05:59:59.000Z",
        "Special_Price_Label": "30%",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/STANCE",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "STANCE",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2FA556A22DOD%2FA556A22DOD.jpg?alt=media",
        "Images": {},
        "Name": "STANCE LOS ANGELES DODGERS TWIST CREW",
        "Price": 329,
        "Priority": 7,
        "SKU_Parent": "A556A22DOD",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "TIN MEDIO",
        "SpecialPrice": 230,
        "SpecialPrice_DateFrom": "2022-11-27T06:00:00.000Z",
        "SpecialPrice_DateTo": "2031-01-01T05:59:59.000Z",
        "Special_Price_Label": "30%",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/STANCE",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Banner_Desktop": "%2F10975815%2Fbanner_desktop.jpg?alt=media",
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2F10975815%2F10975815.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA LOS ANGELES DODGERS BASICS 39THIRTY",
        "Price": 799,
        "Priority": 3,
        "SKU_Parent": "10975815",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "3930",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/NEW ERA",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Banner_Desktop": "%2F70428987%2Fbanner_desktop.jpg?alt=media",
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2F70428987%2F70428987.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA LOS ANGELES DODGERS BASICS 39THIRTY",
        "Price": 799,
        "Priority": 3,
        "SKU_Parent": "70428987",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "3930",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/NEW ERA",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Banner_Desktop": "%2F70331962%2Fbanner_desktop.jpg?alt=media",
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2F70331962%2F70331962.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA LOS ANGELES DODGERS AUTHENTIC COLLECTION 59FIFTY",
        "Price": 999,
        "Priority": 3,
        "SKU_Parent": "70331962",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "5950",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/NEW ERA",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2F11204002%2F11204002.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA PLAYERA LOS ANGELES DODGERS HOMBRE",
        "Price": 599,
        "Priority": 20,
        "SKU_Parent": "11204002",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "PLAYERA M/C",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/NEW ERA",
        "Type": "TEXTIL",
        "Variants": {}
    }
]

</code>```

is there a way to refine the search with the options fuse has and give me back results like these?

I used this configurations and query but I got no success

```<code>const query = "shirt dodgers";
const path = './dict.json';
const content = fs.readFileSync(path, { encoding: 'utf-8' });
const json = JSON.parse(content)
const workingCatalog = Object.values(json.Catalog)

//Create the FuseJS index
const keys = [
    { name: 'Name', weight: 1 },
    { name: 'Description', weight: 0.1 },
    { name: 'Brand', weight: 1 },
    'SKU_Parent',
    'Sport',
    'Type',
    'Silueta',
]
const index = new Fuse(workingCatalog, {
    keys: keys,
    threshold: .3,
    isCaseSensitive: false,
    shouldSort: true,
    minMatchCharLength: 3,
    includeScore: true,
});
const results = index.search(query).map(x => {
    let item = x.item;
    item.Images = {}
    item.Variants = {};
    return item;
});
console.log(JSON.stringify(results, null, 4));
</code>```

Body:
I'm moving from algolia autocomplete and I'm trying to use fusejs to search through a json file using a query like "Shirt Dodgers" but I'm not able to get these results, insted I'm getting back no data

[
    {
        "Active": true,
        "Brand": "FEXPRO",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2FMLBHD52001BLU%2FMLBHD52001BLU.jpg?alt=media",
        "Images": {},
        "Name": "LOS ANGELES DODGERS MLB PRIMARY LOGO HOODIE",
        "Price": 999,
        "Priority": 7,
        "SKU_Parent": "MLBHD52001BLU",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "SUDADERA",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/FEXPRO",
        "Type": "TEXTIL",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "FEXPRO",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2FMLBSH520201NVY%2FMLBSH520201NVY.jpg?alt=media",
        "Images": {},
        "Name": "LOS ANGELES DODGERS MLB BASIC CASUAL SHORT",
        "Price": 699,
        "Priority": 7,
        "SKU_Parent": "MLBSH520201NVY",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "SHORT",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/FEXPRO",
        "Type": "TEXTIL",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "FEXPRO",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2FMLBTS520200BLU2%2FMLBTS520200BLU2.jpg?alt=media",
        "Images": {},
        "Name": "LOS ANGELES DODGERS MLB PRIMARY LOGO TSHIRT",
        "Price": 349,
        "Priority": 7,
        "SKU_Parent": "MLBTS520200BLU2",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "PLAYERA M/C",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/FEXPRO",
        "Type": "TEXTIL",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "STANCE",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2FA545A22DOD%2FA545A22DOD.jpg?alt=media",
        "Images": {},
        "Name": "STANCE LOS ANGELES DODGERS SPLIT CREW",
        "Price": 329,
        "Priority": 7,
        "SKU_Parent": "A545A22DOD",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "TIN MEDIO",
        "SpecialPrice": 230,
        "SpecialPrice_DateFrom": "2022-11-27T06:00:00.000Z",
        "SpecialPrice_DateTo": "2031-01-01T05:59:59.000Z",
        "Special_Price_Label": "30%",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/STANCE",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "STANCE",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2FA556A22DOD%2FA556A22DOD.jpg?alt=media",
        "Images": {},
        "Name": "STANCE LOS ANGELES DODGERS TWIST CREW",
        "Price": 329,
        "Priority": 7,
        "SKU_Parent": "A556A22DOD",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "TIN MEDIO",
        "SpecialPrice": 230,
        "SpecialPrice_DateFrom": "2022-11-27T06:00:00.000Z",
        "SpecialPrice_DateTo": "2031-01-01T05:59:59.000Z",
        "Special_Price_Label": "30%",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/STANCE",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Banner_Desktop": "%2F10975815%2Fbanner_desktop.jpg?alt=media",
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2F10975815%2F10975815.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA LOS ANGELES DODGERS BASICS 39THIRTY",
        "Price": 799,
        "Priority": 3,
        "SKU_Parent": "10975815",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "3930",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/NEW ERA",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Banner_Desktop": "%2F70428987%2Fbanner_desktop.jpg?alt=media",
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2F70428987%2F70428987.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA LOS ANGELES DODGERS BASICS 39THIRTY",
        "Price": 799,
        "Priority": 3,
        "SKU_Parent": "70428987",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "3930",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/NEW ERA",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Banner_Desktop": "%2F70331962%2Fbanner_desktop.jpg?alt=media",
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "ACCESORIOS",
        "Gender": "HOMBRES",
        "Image_Main": "%2F70331962%2F70331962.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA LOS ANGELES DODGERS AUTHENTIC COLLECTION 59FIFTY",
        "Price": 999,
        "Priority": 3,
        "SKU_Parent": "70331962",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "5950",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/ACCESORIOS/NEW ERA",
        "Type": "ACCESORIOS",
        "Variants": {}
    },
    {
        "Active": true,
        "Brand": "NEW ERA",
        "Description": "",
        "Description_Short": "TEXTIL",
        "Gender": "HOMBRES",
        "Image_Main": "%2F11204002%2F11204002.jpg?alt=media",
        "Images": {},
        "Name": "NEW ERA PLAYERA LOS ANGELES DODGERS HOMBRE",
        "Price": 599,
        "Priority": 20,
        "SKU_Parent": "11204002",
        "Silo": "LOS ANGELES DODGERS",
        "Silueta": "PLAYERA M/C",
        "Sport": "CASUAL",
        "Suggested": "CASUAL/HOMBRES/TEXTIL/NEW ERA",
        "Type": "TEXTIL",
        "Variants": {}
    }
]

is there a way to refine the search with the options fuse has and give me back results like these?

I used this configurations and query but I got no success

const query = "shirt dodgers";
const path = './dict.json';
const content = fs.readFileSync(path, { encoding: 'utf-8' });
const json = JSON.parse(content)
const workingCatalog = Object.values(json.Catalog)

//Create the FuseJS index
const keys = [
    { name: 'Name', weight: 1 },
    { name: 'Description', weight: 0.1 },
    { name: 'Brand', weight: 1 },
    'SKU_Parent',
    'Sport',
    'Type',
    'Silueta',
]
const index = new Fuse(workingCatalog, {
    keys: keys,
    threshold: .3,
    isCaseSensitive: false,
    shouldSort: true,
    minMatchCharLength: 3,
    includeScore: true,
});
const results = index.search(query).map(x => {
    let item = x.item;
    item.Images = {}
    item.Variants = {};
    return item;
});
console.log(JSON.stringify(results, null, 4));