问:
React and Firebase - getting same photo id on clicking on different categories
Trying to build my first project using React and firebase. I have a Header.jsx component where I'm mapping names of all added categories like shown below:

```<code>const [data, setData] = useState([]);

// Getting all categories from firebase.
useEffect(() => {
    const fetchData = async () => {
        let list = []
        try{
            const categories = collection(db, 'category')
            let mquery = query(categories, orderBy('timeStamp', "desc"))
            const querySnapshot = await getDocs(mquery);
            querySnapshot.forEach((doc) => {
                list.push({ id: doc.id, ...doc.data()});
            });
            setData(list);
        } catch (err) {
            console.log(err)
        }
    };
    fetchData()
}, []);

// Mapping category names in the header
<ul className="absolute hidden text-white pt-1 group-hover:block items-center">
  {data.map((category, index) => {
    return (
     <Link to={`/categories/${category.name}`} key={category.id}>
       <li className='rounded-lg p-2 hover:text-white/80 hover:-translate-y-1 hover:scale-110 duration-300 transition ease-in-out delay-150'>
        <span>{category.name}</span>
       <li>
     </Link>
    )
  })}
</ul>
</code>```

When clicking on a category i get photos linked to a category. Photos listed in CategoryDetails.jsx page. I'm getting photos of a category from firebase as shown below. And passing props to a component namely CategoryDetailsHero.jsx where i'm rendering photo from Photos table and poem from category table.

```<code>// CategoryDetails.jsx page

const CategoryDetails = () => {

  const params = useParams();
  const [data, setData] = useState([]);
  const [filterCategory, setFilterCategory] = useState([]);

  // Get Photos from current category
  useEffect(() => {
    const fetchData = async () => {
        let list = []
        try{
          const q = query(collection(db, "Photos"), where("category", "==", params.categoryName, orderBy('timeStamp', "desc")));
          const querySnapshot = await getDocs(q);
          querySnapshot.forEach((doc) => {
              list.push({ id: doc.id, ...doc.data()});
          });
          setData(list);
        } catch (err) {
            console.log(err)
        }
    };
    fetchData()
  },[]);

   // Get all categories
   useEffect(() => {
      const fetchCategories = async () => {
          let list = []
          try{
              const categories = collection(db, 'category')
              let mquery = query(categories, orderBy('timeStamp', "desc"))
              const querySnapshot = await getDocs(mquery);
              querySnapshot.forEach((doc) => {
                  list.push({ id: doc.id, ...doc.data()});
              });
              setFilterCategory(list);
          } catch (err) {
              console.log(err)
          }
      };
      fetchCategories();
    },[]);

  return (
    <>
      <div className='w-full h-screen'>
        <CategoryDetailsHero heroImage={data} filterCateg={filterCategory} params={params} />
      </div>
    </>
  )
}

export default CategoryDetails

// CategoryDetailsHero.jsx

const CategoryDetailsHero = ({ heroImage, filterCateg, params }) => {

  return (
    <div className="mt-8 grid grid-cols-1 rounded-xl bg-[#121212] p-2 xl:grid-cols-2 md:grid-cols-2 sm:grid-cols:2 w-full h-full">
      {heroImage.filter(hero => hero.HeroImage == true).map((filteredImage) => {
        return (
          <div
           className='overflow-hidden relative inline-block xl:w-[480px]'
           key={filteredImage.id}>
           <img
            src={filteredImage.imageURL}
            alt="image"
            className='w-full h-auto box-border -rotate-3 rounded-xl'
           />
          </div>
         )
      })}
      <div className='justify-between mt-4'>
       <div className='flex flex-col flex-1'>
        {filterCateg.filter(item => item.name === params.categoryName).map((category) => {
       return (
        <p
         key={category.id}
         className='text-white md:max-w-[540px] leading-8 mb-4 text-[18px] tracking-wide flex-end lg:pl-[150px] md:pl-[100px]'
        >
         {category.poem}
       </p>
      )
     })}
    </div>
  </div>
</code>```

When i'm in CategoryDetails page and clicking (from Header.jsx) on a specific category category.poem is updated with the new category however image remains the same. It seems that i get same photo id.

It works only if i set [data] in useEffect hook like shown below, but in this case i get an infinite loop. How can i prevent infinite loop and get category.poem and photo.image for each category?

```<code>useEffect(() => {
    const fetchData = async () => {
        let list = []
        try{
          const q = query(collection(db, "Photos"), where("category", "==", params.categoryName, orderBy('timeStamp', "desc")));
          const querySnapshot = await getDocs(q);
          querySnapshot.forEach((doc) => {
              list.push({ id: doc.id, ...doc.data()});
          });
          setData(list);
        } catch (err) {
            console.log(err)
        }
    };
    fetchData()
  },[data]);
</code>```

Body:
Trying to build my first project using React and firebase. I have a Header.jsx component where I'm mapping names of all added categories like shown below:

const [data, setData] = useState([]);

// Getting all categories from firebase.
useEffect(() => {
    const fetchData = async () => {
        let list = []
        try{
            const categories = collection(db, 'category')
            let mquery = query(categories, orderBy('timeStamp', "desc"))
            const querySnapshot = await getDocs(mquery);
            querySnapshot.forEach((doc) => {
                list.push({ id: doc.id, ...doc.data()});
            });
            setData(list);
        } catch (err) {
            console.log(err)
        }
    };
    fetchData()
}, []);

// Mapping category names in the header

  {data.map((category, index) => {
    return (
     <Link to={`/categories/${category.name}`} key={category.id}>

        {category.name}

     </Link>
    )
  })}

When clicking on a category i get photos linked to a category. Photos listed in CategoryDetails.jsx page. I'm getting photos of a category from firebase as shown below. And passing props to a component namely CategoryDetailsHero.jsx where i'm rendering photo from Photos table and poem from category table.

// CategoryDetails.jsx page

const CategoryDetails = () => {

  const params = useParams();
  const [data, setData] = useState([]);
  const [filterCategory, setFilterCategory] = useState([]);

  // Get Photos from current category
  useEffect(() => {
    const fetchData = async () => {
        let list = []
        try{
          const q = query(collection(db, "Photos"), where("category", "==", params.categoryName, orderBy('timeStamp', "desc")));
          const querySnapshot = await getDocs(q);
          querySnapshot.forEach((doc) => {
              list.push({ id: doc.id, ...doc.data()});
          });
          setData(list);
        } catch (err) {
            console.log(err)
        }
    };
    fetchData()
  },[]);

   // Get all categories
   useEffect(() => {
      const fetchCategories = async () => {
          let list = []
          try{
              const categories = collection(db, 'category')
              let mquery = query(categories, orderBy('timeStamp', "desc"))
              const querySnapshot = await getDocs(mquery);
              querySnapshot.forEach((doc) => {
                  list.push({ id: doc.id, ...doc.data()});
              });
              setFilterCategory(list);
          } catch (err) {
              console.log(err)
          }
      };
      fetchCategories();
    },[]);

  return (
    <>

        <CategoryDetailsHero heroImage={data} filterCateg={filterCategory} params={params} />

    </>
  )
}

export default CategoryDetails

// CategoryDetailsHero.jsx

const CategoryDetailsHero = ({ heroImage, filterCateg, params }) => {

  return (

      {heroImage.filter(hero => hero.HeroImage == true).map((filteredImage) => {
        return (

         )
      })}

        {filterCateg.filter(item => item.name === params.categoryName).map((category) => {
       return (

         {category.poem}

      )
     })}

When i'm in CategoryDetails page and clicking (from Header.jsx) on a specific category category.poem is updated with the new category however image remains the same. It seems that i get same photo id.

It works only if i set [data] in useEffect hook like shown below, but in this case i get an infinite loop. How can i prevent infinite loop and get category.poem and photo.image for each category?

useEffect(() => {
    const fetchData = async () => {
        let list = []
        try{
          const q = query(collection(db, "Photos"), where("category", "==", params.categoryName, orderBy('timeStamp', "desc")));
          const querySnapshot = await getDocs(q);
          querySnapshot.forEach((doc) => {
              list.push({ id: doc.id, ...doc.data()});
          });
          setData(list);
        } catch (err) {
            console.log(err)
        }
    };
    fetchData()
  },[data]);


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Matplotlib Broken-barh set colors by attribute

Body:
To visualize the trips taken by a float, I want to create a broken barh plot using color schemes based on a Color column.

I have a dataset with the driver ID, the beginning and duration of each trip, and I defined a color column based on various trip characteristics.

I paste below the dictionary i made to create the graph, the driver IDs are 236, 888, and 922. The first number in parenthesis indicates the beginning of each trip, the second indicates its duration, and the third indicates its color.

trip_dict:

{236: [(19259.981458333332, 0.014930555555555556, '#F1EAC8')],
 888: [(19258.058530092592, 0.01596064814814815, '#D98994'),
  (19258.084953703703, 0.013449074074074073, '#D98994'),
  (19258.110277777778, 0.0353587962962963, '#90AAA1'),
  (19258.162974537037, 0.022881944444444444, '#D98994'),
  (19258.194444444445, 0.015601851851851851, '#90AAA1'),
  (19258.21078703704, 0.0241087962962963, '#F1EAC8'),
  (19258.253194444445, 0.014166666666666666, '#009291')],
 922: [(19258.01508101852, 0.012916666666666667, '#D0587E'),
  (19258.040173611113, 0.03238425925925926, '#F1EAC8'),
  (19258.07761574074, 0.01994212962962963, '#F1EAC8'),
  (19258.10462962963, 0.025868055555555557, '#F1EAC8'),
  (19258.133993055555, 0.021284722222222222, '#F1EAC8'),
  (19259.007013888888, 0.015335648148148147, '#F1EAC8'),
  (19259.032280092593, 0.046157407407407404, '#009291'),
  (19259.101365740742, 0.00912037037037037, '#D0587E'),
  (19259.11111111111, 0.01869212962962963, '#D98994'),
  (19259.14638888889, 0.019525462962962963, '#F1EAC8'),
  (19259.96574074074, 0.037986111111111116, '#90AAA1')]}

I want to see something like the figure i attached, however each green bar must have the determined color (dont worry about the grey bar, is based on each driver shift and it is not important for this problem).

I copy below the code i've written till now, which has trouble with the colour part

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

trip_list = sorted(trip_dict, reverse=True)
bar_size = 4

for i, id_driver, color in enumerate(trip_list):
    ax.broken_barh(trip_dict[id_driver],          # data
                   (10 * (i + 1), bar_size),      # (y position, bar size)
                   color= color,
                   alpha=1,
                   edgecolor='k',
                   linewidth=1.2)

#labels config

n=3  #count id_drivers

ax.set_yticks([2+ 10 * n for n in range(1, n + 1)])
ax.set_ylim(2, 2 + 10 * (n + 1))
ax.set_yticklabels(shift_list)

ax.xaxis.set_minor_locator(mdates.HourLocator(interval=4))   # every 4 hours
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))  # hours and minutes
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))    # every day
ax.xaxis.set_major_formatter(mdates.DateFormatter('\n\n\n %a %d-%m'))

plt.show()


问:
AWS Athena Decimal
I'm creating a new external table in AWS Athena. When I try to create a decimal(9,2) variable, the creation of the table is fine, but when I try to SELECT, I get the following error:

```<code>GENERIC_INTERNAL_ERROR: java.lang.String cannot be cast to org.apache.hadoop.hive.common.type.HiveDecimal
</code>```

Example of my DDL:

```<code>CREATE EXTERNAL TABLE IF NOT EXISTS `MY_DB`.`MY_NEW_TABLE` (
  `event_id` bigint
  ,`time_stamp` string
  ,`amount` decimal(9,2)
)
PARTITIONED BY (
  `year` smallint
  ,`month` tinyint
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
  'separatorChar' = ','
  ,'quoteChar' = '"'
  ,'escapeChar' = '\\'
)
STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION 's3://<BUCKETNAME>/<SUBFOLDER>/'
TBLPROPERTIES (
    'classification' = 'csv'
    ,'skip.header.line.count' = '1'
);
</code>```

If I define amount as a float, it works, and I can later CAST() it to a decimal(9,2) as I want, but I would prefer to have it in the table structure directly.

Title: AWS Athena Decimal

Body:
I'm creating a new external table in AWS Athena. When I try to create a decimal(9,2) variable, the creation of the table is fine, but when I try to SELECT, I get the following error:

GENERIC_INTERNAL_ERROR: java.lang.String cannot be cast to org.apache.hadoop.hive.common.type.HiveDecimal

Example of my DDL:

CREATE EXTERNAL TABLE IF NOT EXISTS `MY_DB`.`MY_NEW_TABLE` (
  `event_id` bigint
  ,`time_stamp` string
  ,`amount` decimal(9,2)
)
PARTITIONED BY (
  `year` smallint
  ,`month` tinyint
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
  'separatorChar' = ','
  ,'quoteChar' = '"'
  ,'escapeChar' = '\\'
)
STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION 's3://<BUCKETNAME>/<SUBFOLDER>/'
TBLPROPERTIES (
    'classification' = 'csv'
    ,'skip.header.line.count' = '1'
);

If I define amount as a float, it works, and I can later CAST() it to a decimal(9,2) as I want, but I would prefer to have it in the table structure directly.


问:
Web reverse - Can we trace javascript function calls from a button click?
I am trying to understand what happens after pressing a button on a web page (from an internal point of view, not the visible effects). In my case I know that everything happens on the browser side and yet from the developer tool (chrome) I can't find an entry point.

There are several scripts (which seem to be obfuscated) but I can't figure out which one is used during the actions I perform on the site, especially in my case when pressing one of the buttons.

I tried to use the recorder integrated to my browser (google chrome) but it details too much the calls and it did not allow me to understand what was going on.

I specify that it is not my site on which I would like to carry out tests.

Knowing that everything happens on the browser side, is it possible to trace the function calls from a button click?

Thank you.


问:
How do pass variables between two locally packaged functions while keeping default values in additional calls?
I packaged some plotting functions that I frequently use across several jupyter notebooks. One of the functions makes a pdf and calls other plotting functions in the same package with a changed default parameter to prevent from showing the plot.

```<code>def plot_data(data, show_plot=True):
    if not show_plot:
        plt.ioff()
    plt.plot(data)
    plt.savefig()

def make_pdf():
    plot_data(df, False)
    # other code to generate pdf
</code>```

When I call make_pdf() from the notebook, it changes show_plot and even if I pass show_plot=True afterwards it is not changing back and I get no plotting output. This is my first package and I am sure this has something to do with passing by reference vs passing by value, but I cannot figure out how to make it work the way I want to. I want to make the plot but not display it because I will save it locally, but don't want to see the plot when the pdf is being made.

How can I do this so that after I call make_pdf() I can call the other functions to show the plot again?

Body:
I packaged some plotting functions that I frequently use across several jupyter notebooks. One of the functions makes a pdf and calls other plotting functions in the same package with a changed default parameter to prevent from showing the plot.

def plot_data(data, show_plot=True):
    if not show_plot:
        plt.ioff()
    plt.plot(data)
    plt.savefig()

def make_pdf():
    plot_data(df, False)
    # other code to generate pdf

When I call make_pdf() from the notebook, it changes show_plot and even if I pass show_plot=True afterwards it is not changing back and I get no plotting output. This is my first package and I am sure this has something to do with passing by reference vs passing by value, but I cannot figure out how to make it work the way I want to. I want to make the plot but not display it because I will save it locally, but don't want to see the plot when the pdf is being made.

How can I do this so that after I call make_pdf() I can call the other functions to show the plot again?


问:
How to use regex capturing-group in custom US Address information in Office365
I'm trying to create a custom U.S Address classification label in Azure Information Protection  to match possible U.S Addresses

Regex (it works Java8 - e.g. https://regex101.com/):

```<code>^(\d+) ?(\w)? (.*?) ?((?<= )avenue|ave|court|ct|street|st|drive|dr|lane|ln|road|rd|blvd|plaza|parkway|pkwy)? ?((?<= )\d*)?$
</code>```

But when I try to set this code in Azure Information Protection I receive the error message below:

You cannot configure a pattern with groups or multiple match conditions like (.*, .+, .{0,n} or .{1,n}). Remove the group or the multiple match condition from the pattern to continue.

Is there a way to circumvent this situation? Is it possible to reach the same result in another way?

Sample Data to test:

66-4 Parkhurst Rd, Chelmsford MA 1824

591 Memorial Dr, Chicopee MA 1020

55 Brooksby Village Way, Danvers MA 1923

137 Teaticket Hwy, East Falmouth MA 2536

42 Fairhaven Commons Way, Fairhaven MA 2719

374 William S Canning Blvd, Fall River MA 2721

121 Worcester Rd, Framingham MA 1701

677 Timpany Blvd, Gardner MA 1440

337 Russell St, Hadley MA 1035

295 Plymouth Street, Halifax MA 2338

1775 Washington St, Hanover MA 2339

Body:
I'm trying to create a custom U.S Address classification label in Azure Information Protection  to match possible U.S Addresses

Regex (it works Java8 - e.g. https://regex101.com/):

^(\d+) ?(\w)? (.*?) ?((?<= )avenue|ave|court|ct|street|st|drive|dr|lane|ln|road|rd|blvd|plaza|parkway|pkwy)? ?((?<= )\d*)?$

But when I try to set this code in Azure Information Protection I receive the error message below:

You cannot configure a pattern with groups or multiple match conditions like (.*, .+, .{0,n} or .{1,n}). Remove the group or the multiple match condition from the pattern to continue.

Is there a way to circumvent this situation? Is it possible to reach the same result in another way?

Sample Data to test:

66-4 Parkhurst Rd, Chelmsford MA 1824

591 Memorial Dr, Chicopee MA 1020

55 Brooksby Village Way, Danvers MA 1923

137 Teaticket Hwy, East Falmouth MA 2536

42 Fairhaven Commons Way, Fairhaven MA 2719

374 William S Canning Blvd, Fall River MA 2721

121 Worcester Rd, Framingham MA 1701

677 Timpany Blvd, Gardner MA 1440

337 Russell St, Hadley MA 1035

295 Plymouth Street, Halifax MA 2338

1775 Washington St, Hanover MA 2339


问:
How to Delete a specific value in an array using Slicing?
I am making an array code in python using slicing and my problem is, how can I delete using a specific item code as its key to be deleted using slicing but if I input the item code it will not find the item code in the array and also it won't also delete its item description this is my expected output is...

```<code>code:     item       price  quantity   category

gsh3:     pencil     5.5       4        T
1sd2:     lipstick   12.3      2        W
12a2:     tools      123.3     5        M
</code>```

I need to input the code and the code will be the key to deleting its item and description.
my code is like this...

```<code>final = []
item = []
dis = []

#this is for the input i am using a online input
a, b, c, d, e = input("Input >> ").split(' ')
price = float(c)
quan = int(d)

item[len(item):] = [a]
dis[len(dis):] = [b]
dis[len(dis):] = [price]
dis[len(dis):] = [quan]
dis[len(dis):] = [e]
item[len(item):] = [dis]
final[:0] = [item]
print('   --Item successfully added!--\n')
</code>```
```<code>
itemCode = input("Item code to be deleted >> ")

for i in final:
    for x in i:
        if itemCode in x:
             for x in range(len(final)):
                 for z in range(len(final)):
                     final = final[:x] + final[x+1:]
                     print("item deleted!")
                     break
        else:
            print("item code does not exist")
            break
</code>```

#for the display

```<code>print("\n-- ITEM DIRECTORY --")
for i in final:
    print()
    print(')', str(i[0]), ':', end=" ")
    for x in i[1]:
        print(str(x), end=' | ')
print()
</code>```

Body:
I am making an array code in python using slicing and my problem is, how can I delete using a specific item code as its key to be deleted using slicing but if I input the item code it will not find the item code in the array and also it won't also delete its item description this is my expected output is...

code:     item       price  quantity   category

gsh3:     pencil     5.5       4        T
1sd2:     lipstick   12.3      2        W
12a2:     tools      123.3     5        M

I need to input the code and the code will be the key to deleting its item and description.
my code is like this...

final = []
item = []
dis = []

#this is for the input i am using a online input
a, b, c, d, e = input("Input >> ").split(' ')
price = float(c)
quan = int(d)

item[len(item):] = [a]
dis[len(dis):] = [b]
dis[len(dis):] = [price]
dis[len(dis):] = [quan]
dis[len(dis):] = [e]
item[len(item):] = [dis]
final[:0] = [item]
print('   --Item successfully added!--\n')

itemCode = input("Item code to be deleted >> ")

for i in final:
    for x in i:
        if itemCode in x:
             for x in range(len(final)):
                 for z in range(len(final)):
                     final = final[:x] + final[x+1:]
                     print("item deleted!")
                     break
        else:
            print("item code does not exist")
            break

#for the display

print("\n-- ITEM DIRECTORY --")
for i in final:
    print()
    print(')', str(i[0]), ':', end=" ")
    for x in i[1]:
        print(str(x), end=' | ')
print()


问:
how to change wifi password and ssid in blynk edgent
i recently changed my wifi ssid and password and i'm wondering how could i change the password i have already tried clearing the board with a flasher reuploading the code and nothing worked for it still tries to do it with the same credentials

```<code>#define BLYNK_TEMPLATE_ID "Template"
#define BLYNK_DEVICE_NAME "name"
//#define BLYNK_AUTH_TOKEN "token"

int DeskLampButtonAttempts = 0;
int DoorLampButtonAttempts = 0;

uint8_t DeskPin = 16;
uint8_t DoorPin = 5;

uint8_t DeskButtonPin = 4;
uint8_t DoorButtonPin = 0;

#define BLYNK_FIRMWARE_VERSION        "0.1.0"

#define BLYNK_PRINT Serial
//#define BLYNK_DEBUG

#define APP_DEBUG

// Uncomment your board, or configure a custom board in Settings.h
//#define USE_SPARKFUN_BLYNK_BOARD
#define USE_NODE_MCU_BOARD
//#define USE_WITTY_CLOUD_BOARD
//#define USE_WEMOS_D1_MINI

#include "BlynkEdgent.h"

BLYNK_WRITE(V0)
{
  int pinValue = param.asInt();
  digitalWrite(DeskPin, pinValue);
}
BLYNK_WRITE(V1)
{
  int pinValue = param.asInt();
  digitalWrite(DoorPin, pinValue);
}

void setup()
{
  Serial.begin(115200);
  delay(100);

  pinMode(DeskPin, OUTPUT);
  pinMode(DoorPin, OUTPUT);

  pinMode(DeskButtonPin, INPUT);
  pinMode(DoorButtonPin, INPUT);

  BlynkEdgent.begin();
}

void loop() {
  BlynkEdgent.run();
}
</code>```

note: the properties template ETC. are set correctly just don't want them leaked

Body:
i recently changed my wifi ssid and password and i'm wondering how could i change the password i have already tried clearing the board with a flasher reuploading the code and nothing worked for it still tries to do it with the same credentials

#define BLYNK_TEMPLATE_ID "Template"
#define BLYNK_DEVICE_NAME "name"
//#define BLYNK_AUTH_TOKEN "token"

int DeskLampButtonAttempts = 0;
int DoorLampButtonAttempts = 0;

uint8_t DeskPin = 16;
uint8_t DoorPin = 5;

uint8_t DeskButtonPin = 4;
uint8_t DoorButtonPin = 0;

#define BLYNK_FIRMWARE_VERSION        "0.1.0"

#define BLYNK_PRINT Serial
//#define BLYNK_DEBUG

#define APP_DEBUG

// Uncomment your board, or configure a custom board in Settings.h
//#define USE_SPARKFUN_BLYNK_BOARD
#define USE_NODE_MCU_BOARD
//#define USE_WITTY_CLOUD_BOARD
//#define USE_WEMOS_D1_MINI

#include "BlynkEdgent.h"

BLYNK_WRITE(V0)
{
  int pinValue = param.asInt();
  digitalWrite(DeskPin, pinValue);
}
BLYNK_WRITE(V1)
{
  int pinValue = param.asInt();
  digitalWrite(DoorPin, pinValue);
}

void setup()
{
  Serial.begin(115200);
  delay(100);

  pinMode(DeskPin, OUTPUT);
  pinMode(DoorPin, OUTPUT);

  pinMode(DeskButtonPin, INPUT);
  pinMode(DoorButtonPin, INPUT);

  BlynkEdgent.begin();
}

void loop() {
  BlynkEdgent.run();
}

note: the properties template ETC. are set correctly just don't want them leaked


问:
spring boot 3: Async Controller doesn't work when inherent async methods from interface
Using OpenApi to generate interfaces with "async : 'true'" to have asynchronous controller method handling, I tried to implement those interfaces but I get always 404. I checked also the '/actuator/mappings' method to see whether my endpoints but they don't appear in that list of mappings.
I tried also to have async method without inheriting from an interface and the mapping was correctly considered.Below are some examples:

Async from interface

```<code>public interface TestApi {

    @GetMapping(value = "/greeting-asnyc-api/{name}", produces = {"application/json", "application/xml"})
    CompletableFuture<ResponseEntity<String>> greetingAsync(@PathVariable("name") final String name);
}

// This example doesn't work and returns 404
@RestController
public class TestApiController implements TestApi {

    @Async
    @Override
    public CompletableFuture<ResponseEntity<String>> greetingAsync(final String name) {
        return CompletableFuture.completedFuture(ResponseEntity.ok("Greeting " + name));
    }
}

// This example works fine
@RestController
public class TestController {

    @Async
    @GetMapping(value = "/greeting/{name}", produces = {"application/json"})
    public CompletableFuture<ResponseEntity<String>> greeting(@PathVariable("name") final String name) {
        return CompletableFuture.completedFuture(ResponseEntity.ok("Greeting " + name));
    }

}

</code>```

The first example, i.e., TestApiController, doesn't work unfortunately and returns always 404 (also not found on '/actuator/mappings'), unlike the second example which works fine without any issues (can also be found on '/actuator/mappings')

Sync from interface

```<code>public interface TestApi {

    @GetMapping(value = "/greeting-sync/{name}", produces = {"application/json", "application/xml"})
    ResponseEntity<String> greeting(@PathVariable("name") final String name);
}

@RestController
public class TestApiController implements TestApi {

    @Override
    public ResponseEntity<String> greeting(final String name) {
        return ResponseEntity.ok("Greeting " + name);
    }
}

</code>```

The example above also works fine when inheriting synchronous method from interface.

Did anyone face similar issue? Thanks for helping

Body:
Using OpenApi to generate interfaces with "async : 'true'" to have asynchronous controller method handling, I tried to implement those interfaces but I get always 404. I checked also the '/actuator/mappings' method to see whether my endpoints but they don't appear in that list of mappings.
I tried also to have async method without inheriting from an interface and the mapping was correctly considered.Below are some examples:

Async from interface

public interface TestApi {

    @GetMapping(value = "/greeting-asnyc-api/{name}", produces = {"application/json", "application/xml"})
    CompletableFuture<ResponseEntity<String>> greetingAsync(@PathVariable("name") final String name);
}

// This example doesn't work and returns 404
@RestController
public class TestApiController implements TestApi {

    @Async
    @Override
    public CompletableFuture<ResponseEntity<String>> greetingAsync(final String name) {
        return CompletableFuture.completedFuture(ResponseEntity.ok("Greeting " + name));
    }
}

// This example works fine
@RestController
public class TestController {

    @Async
    @GetMapping(value = "/greeting/{name}", produces = {"application/json"})
    public CompletableFuture<ResponseEntity<String>> greeting(@PathVariable("name") final String name) {
        return CompletableFuture.completedFuture(ResponseEntity.ok("Greeting " + name));
    }

}

The first example, i.e., TestApiController, doesn't work unfortunately and returns always 404 (also not found on '/actuator/mappings'), unlike the second example which works fine without any issues (can also be found on '/actuator/mappings')

Sync from interface

public interface TestApi {

    @GetMapping(value = "/greeting-sync/{name}", produces = {"application/json", "application/xml"})
    ResponseEntity<String> greeting(@PathVariable("name") final String name);
}

@RestController
public class TestApiController implements TestApi {

    @Override
    public ResponseEntity<String> greeting(final String name) {
        return ResponseEntity.ok("Greeting " + name);
    }
}

The example above also works fine when inheriting synchronous method from interface.

Did anyone face similar issue? Thanks for helping


问:
MySQL: Return the highest number of the same table after making one query
We have these tables:_

table Groupmessages:

and table Groups (Called circles here):

If a user is new to a circle he or she will automatically create a message in the group message table with the content: ";;--;;!!IAMNEW". This is done for dataflow reasons, and will be sorted out when we query the table for the actual messages.

It does however tell us what user is in what group. In this example, user 216 and 215 both wrote 2 messages in circle ID 72. So 4 messages in total.

What we wanna do now is query those ables and find out if I am a part of this group and have written my IAMNEW message. This looks like this:

```<code>var sqlString1 = "SELECT a.*, b.smallPic \
FROM 10561_12865_tblGroupMessages  a \
LEFT JOIN 10561_12865_tblCircles b ON (a.fromCircles = b.tblCircleID) \
WHERE a.fromUser  = '" + userID + "' AND \
a.message = ';;--;;!IAMNEW'  \
LIMIT " + start + "," + count
</code>```

The result is fine, and will look something like this with the input being: userID: 216, start: 0, count: 10.

```<code>message->;;--;;!IAMNEW
fromUser->216
fromCircles->72
tblGroupMessageID->24
timeCreated->2022-12-23 13:27:23
timeUpdated->0000-00-00 00:00:00
unixCreated->1671805643
</code>```

It does also return us our own message with the content IAMNEW, and when it was written in UNIX time. But we also need something else inside this result:
As we wanna order the groupmessages by LAST message and not by our message we would need to add to the query something like:
And return the highest unixCreated from table Groupmessages where fromCircles is equal to (in this case) 72.
But the 72 is a result of the query above already.

Is there a way to query the table and then be returned the highest number from unixCreated from the same table inside the same query?

Best,

J

Body:
We have these tables:_

table Groupmessages:

and table Groups (Called circles here):

If a user is new to a circle he or she will automatically create a message in the group message table with the content: ";;--;;!!IAMNEW". This is done for dataflow reasons, and will be sorted out when we query the table for the actual messages.

It does however tell us what user is in what group. In this example, user 216 and 215 both wrote 2 messages in circle ID 72. So 4 messages in total.

What we wanna do now is query those ables and find out if I am a part of this group and have written my IAMNEW message. This looks like this:

var sqlString1 = "SELECT a.*, b.smallPic \
FROM 10561_12865_tblGroupMessages  a \
LEFT JOIN 10561_12865_tblCircles b ON (a.fromCircles = b.tblCircleID) \
WHERE a.fromUser  = '" + userID + "' AND \
a.message = ';;--;;!IAMNEW'  \
LIMIT " + start + "," + count

The result is fine, and will look something like this with the input being: userID: 216, start: 0, count: 10.

message->;;--;;!IAMNEW
fromUser->216
fromCircles->72
tblGroupMessageID->24
timeCreated->2022-12-23 13:27:23
timeUpdated->0000-00-00 00:00:00
unixCreated->1671805643

It does also return us our own message with the content IAMNEW, and when it was written in UNIX time. But we also need something else inside this result:
As we wanna order the groupmessages by LAST message and not by our message we would need to add to the query something like:
And return the highest unixCreated from table Groupmessages where fromCircles is equal to (in this case) 72.
But the 72 is a result of the query above already.

Is there a way to query the table and then be returned the highest number from unixCreated from the same table inside the same query?

Best,

J


问:
FlutteGray app bar problem when opening app
After clicking the application icon, the first screen I see while opening the application is not the splash screen, a gray appbar screen.

native splash screen should come first, then its own splash should come


问:
Can soot deal with java files can not be compiled?
For example, in the CallGraphs.java file below, the doStuff1 function is not defined, so the file can not be compiled. When I use the command
java -cp soot.jar soot.Main -cp .:soot.jar -pp -allow-phantom-refs -allow-phantom-elms -src-prec java CallGraphs, it throws soot.CompilationDeathException.

public class CallGraphs
{
    public static void main(String[] args) {
        doStuff1();
    }

    public static void doStuff() {
        new A().foo();
    }
}

class A
{
    public void foo() {
        bar();
    }

    public void bar() {
    }
}
```

Is there a way for soot to continue to analyse the file without throwing soot.CompilationDeathException? Moreover,if soot can not do this, is there a tool that can finish the task?

Body:
For example, in the CallGraphs.java file below, the doStuff1 function is not defined, so the file can not be compiled. When I use the command
java -cp soot.jar soot.Main -cp .:soot.jar -pp -allow-phantom-refs -allow-phantom-elms -src-prec java CallGraphs, it throws soot.CompilationDeathException.

public class CallGraphs
{
    public static void main(String[] args) {
        doStuff1();
    }

    public static void doStuff() {
        new A().foo();
    }
}

class A
{
    public void foo() {
        bar();
    }

    public void bar() {
    }
}

Is there a way for soot to continue to analyse the file without throwing soot.CompilationDeathException? Moreover,if soot can not do this, is there a tool that can finish the task?


问:
Django- error in if condition of django template language while cheking != condition
here the request.user = timon and user.username = timon so the if couldn't should not run for user timon but it does????

in the list of send message to the timon should not be included


问:
how to reflect changes that applied directly though database shell to django model?
We had to change the datatype of a table primary key from int to bigint but we did it manually through PSQL for many reasons and now we want that to be reflected in Django.

changing the id type like that
id = models.BigAutoField(primary_key=True)
will create a migration and it will be applied is there any way to mark migration as applied or edit Django tables to avoid migrations here?

As we have a really restricted pipeline and changing it to run migration with --fake is a really big hassle so I prefer code changes or database changes over running --fake


问:
Finding the correct generic type with Typescript
I'm trying to build an Adjacency Graph which I have written in JavaScript and convert it to typescript, but I am really struggling with the generic types that I would like to have. Sorry, I am probably in over my head, but seems like it would be super sweet. Here is what I have tried to start with, but cannot figure it out.

```<code>export type AdjacencyVertex<T> = {
  node: T;
  edges: number[];
};

export class AdjacencyGraph<T> {
  public adjList: Record<number, AdjacencyVertex<T>> = {};
  // public adjList: Partial<AdjacencyVertex<T>>;
  // public adjList: Record<string, any> = {};
  private key: keyof T;

  constructor(key: keyof T) {
    this.adjList = {};
    this.key = key;
  }

  addVertex(v: T): void {
    if (this.key) {
      if (!this.adjList[v[this.key]]) {
        this.adjList[v[this.key]] = {
          node: v,
          edges: [],
        };
      }
    } else {
      if (!this.adjList[v]) {
        this.adjList[v] = {
          node: v,
          edges: [],
        };
      }
    }
  }
}
</code>```

with this I am getting the error:

I guess I am just not really sure how to type this thing. Any help would be appreciated. Also an example usage, for reference would be something like this. these are the tests I wrote for the JavaScript version:

```<code>  test('should be able to add a vertex as an object', () => {
    const graph = new AdjacencyGraph('id');
    const node1 = { id: 1 };
    graph.addVertex(node1);
    let node = graph.adjList[node1.id];
    let result = { node: { id: 1 }, edges: [] };
    expect(node).toEqual(result);

    const node2 = { id: 2 };
    graph.addVertex(node2);
    node = graph.adjList[node2.id];
    result = { node: { id: 2 }, edges: [] };
    expect(node).toEqual(result);
  });
</code>```

This is the solution that I finally came up with. Any advice or recommendations are definitely appreciated. All my test are passing also by the way. This is supporting number and complex objects so far:

```<code>export type AdjacencyVertex<T> = {
  node: T;
  edges: number[];
};

/**
 * AdjacencyGraph<T>
 */
export class AdjacencyGraph<T> {
  public adjList = new Map<number, AdjacencyVertex<T>>();
  private key?: keyof T;

  constructor(key?: keyof T) {
    this.adjList = new Map<number, AdjacencyVertex<T>>();
    this.key = key;
  }

  addVertex(v: T): void {
    if (this.key) {
      if (!this.adjList.get(v[this.key] as number)) {
        this.adjList.set(v[this.key] as number, {
          node: v,
          edges: [],
        });
      }
    } else {
      if (!this.adjList.get(v as number)) {
        this.adjList.set(v as number, {
          node: v,
          edges: [],
        });
      }
    }
  }

  /**
   * add Edge
   * @param src{T}
   * @param dest{T}
   * @returns {void}
   */
  addEdge(src: T, dest: T): void {
    if (this.key) {
      if (!this.adjList.get(src[this.key] as number)) {
        this.addVertex(src);
      }
      if (!this.adjList.get(dest[this.key] as number)) {
        this.addVertex(dest);
      }
      if (
        !this.adjList
          .get(src[this.key] as number)
          ?.edges.includes(dest[this.key] as number)
      ) {
        this.adjList
          .get(src[this.key] as number)
          ?.edges.push(dest[this.key] as number);
      }
      if (
        !this.adjList
          .get(dest[this.key] as number)
          ?.edges.includes(src[this.key] as number)
      ) {
        this.adjList
          .get(dest[this.key] as number)
          ?.edges.push(src[this.key] as number);
      }
    } else {
      if (!this.adjList.get(src as number)) {
        this.addVertex(src);
      }
      if (!this.adjList.get(dest as number)) {
        this.addVertex(dest);
      }
      // make sure there are no duplicates
      if (!this.adjList.get(src as number)?.edges.includes(dest as number)) {
        this.adjList.get(src as number)?.edges.push(dest as number);
      }
      if (!this.adjList.get(dest as number)?.edges.includes(src as number)) {
        this.adjList.get(dest as number)?.edges.push(src as number);
      }
    }
  }

  /**
   *
   * @param src
   * @param dest
   */
  removeEdge(src: T, dest: T): void {
    if (this.key) {
      let obj = this.adjList.get(src[this.key] as number);
      if (obj) {
        const destKey = dest[this.key] as number;
        obj.edges = obj.edges.filter((v) => v != destKey);
      }
      obj = this.adjList.get(dest[this.key] as number);
      if (obj) {
        const srcKey = src[this.key] as number;
        obj.edges = obj.edges.filter((v) => v != srcKey);
      }
    } else {
      let obj = this.adjList.get(src as number);
      if (obj) {
        obj.edges = obj.edges.filter((v) => v != dest);
      }
      obj = this.adjList.get(dest as number);
      if (obj) {
        obj.edges = obj.edges.filter((v) => v != src);
      }
    }
  }

  /**
   *
   * @param v
   */
  removeVertex(v: T) {
    if (this.key) {
      const parent = this.adjList.get(v[this.key] as number);
      const edges = parent?.edges;
      edges?.forEach((edge) => {
        const child = this.adjList.get(edge);
        if (child) {
          if (this.key) {
            const childKey = v[this.key] as number;
            child.edges = child.edges.filter((x) => x != childKey);
          }
        }
      });
      this.adjList.delete(v[this.key] as number);
    } else {
      const parent = this.adjList.get(v as number);
      const edges = parent?.edges;
      edges?.forEach((edge) => {
        const child = this.adjList.get(edge);
        if (child) {
          child.edges = child?.edges.filter((x) => x != v);
        }
      });
      this.adjList.delete(v as number);
    }
  }

  /**
   *
   * @param start
   * @param func
   * @returns
   */
  depthFirstTraversal(start: T, func?: Function): T[] {
    const stack: T[] | number = [];
    if (this.key) {
      // @ts-ignore
      stack.push(this.adjList.get(start[this.key] as number));
    } else {
      // @ts-ignore
      stack.push(start as number);
    }

    const visited = new Map<number, boolean>();
    const result: T[] = [];
    if (this.key) {
      const startKey = start[this.key] as number;
      visited.set(startKey, true);
    } else {
      visited.set(start as number, true);
    }

    while (stack.length) {
      const current = stack.pop();
      if (func) {
        func(current);
      }
      if (current) {
        // @ts-ignore
        result.push(current);
        if (this.key) {
          const neighbors = this.adjList.get(
            // @ts-ignore
            current.node[this.key] as number
          )!.edges;
          neighbors.forEach((neighbor) => {
            if (!visited.get(neighbor)) {
              // @ts-ignore
              stack.push(this.adjList.get(neighbor));
              visited.set(neighbor, true);
            }
          });
        } else {
          if (current) {
            const neighbors = this.adjList.get(current as number)!.edges;
            neighbors.forEach((neighbor) => {
              if (!visited.get(neighbor)) {
                // @ts-ignore
                stack.push(neighbor);
                visited.set(neighbor, true);
              }
            });
          }
        }
      }
    }

    return result;
  }

  breadthFirstTraversal(start: T, func?: Function) {
    const queue = [];
    const visited = new Map<number, boolean>();
    const result = [];
    if (this.key) {
      const startKey = start[this.key] as number;
      visited.set(startKey, true);
      queue.push(this.adjList.get(startKey));
    } else {
      visited.set(start as number, true);
      queue.push(start);
    }

    while (queue.length) {
      const current = queue.shift();
      if (this.key) {
        // @ts-ignore
        const neighbors = this.adjList.get(
          // @ts-ignore
          current.node[this.key as number] as number
        )!.edges;
        if (func) {
          func(current);
        }
        // @ts-ignore
        result.push(this.adjList.get(current.node[this.key]));
        neighbors.forEach((neighbor) => {
          if (!visited.get(neighbor)) {
            visited.set(neighbor, true);
            queue.push(this.adjList.get(neighbor));
          }
        });
      } else {
        const neighbors = this.adjList.get(current as number)!.edges;
        if (func) {
          func(current);
        }
        result.push(current);
        neighbors.forEach((neighbor) => {
          if (!visited.get(neighbor)) {
            queue.push(neighbor);
            visited.set(neighbor, true);
          }
        });
      }
    }

    return result;
  }
}
</code>```

All test are passing:

```<code>import { AdjacencyGraph } from "../src/Structures/AdjacencyGraph";

describe("adjacencygraph tests", () => {
  test("should automatically add the first node", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addEdge(node1, node2);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    const graph1 = new AdjacencyGraph();
    graph1.addEdge(1, 2);
    expect(graph1.adjList.get(1)!.edges).toEqual([2]);
  });

  test("should be able to add a vertex as an object", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    graph.addVertex(node1);
    let node = graph.adjList.get(1);
    let result = { node: { id: 1 }, edges: [] };
    expect(node).toEqual(result);

    const node2 = { id: 2 };
    graph.addVertex(node2);
    node = graph.adjList.get(2);
    result = { node: { id: 2 }, edges: [] };
    expect(node).toEqual(result);
  });

  test("should be able to add vertex with a more complex object", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1, name: "mike", job: "developer" };
    graph.addVertex(node1);
    const node = graph.adjList.get(1);
    const result = {
      node: { id: 1, name: "mike", job: "developer" },
      edges: [],
    };
    expect(node).toEqual(result);
  });

  test("should be able to add vertex with simple numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    expect(graph.adjList.get(1)).toEqual({ node: 1, edges: [] });
    graph.addVertex(2);
    expect(graph.adjList.get(2)).toEqual({ node: 2, edges: [] });
    expect(graph.adjList.size).toEqual(2);
  });

  test("should be able to add edges with just numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addVertex(2);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    expect(graph.adjList.get(1)!.edges).toEqual([2, 5]);
  });

  test("should e able to add an edge with objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    expect(graph.adjList.size).toEqual(2);

    let edges = graph.adjList.get(1)!.edges;
    let result = [2];
    expect(edges).toEqual(result);
    const node5 = { id: 5 };
    graph.addEdge(node1, node5);
    edges = graph.adjList.get(1)!.edges;
    result = [2, 5];
    expect(edges).toEqual(result);
    expect(graph.adjList.size).toEqual(3);
  });

  // this is the structure this test is using
  // 1: [2,5]
  // 2: [1,5,3,4]
  // 3: [2,4]
  // 4: [2,5,3]
  // 5: [4,1,2]
  test("should not duplicate edges", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.addEdge(2, 1);
    graph.addEdge(2, 3);
    graph.addEdge(2, 3);
    graph.addEdge(2, 4);
    graph.addEdge(3, 2);
    graph.addEdge(3, 4);
    graph.addEdge(4, 2);
    graph.addEdge(4, 5);
    graph.addEdge(4, 3);
    graph.addEdge(5, 4);
    graph.addEdge(5, 1);
    graph.addEdge(5, 2);
    expect(graph.adjList.get(1)!.edges).toEqual([2, 5]);
    expect(graph.adjList.get(2)!.edges).toEqual([1, 3, 4, 5]);
    expect(graph.adjList.get(3)!.edges).toEqual([2, 4]);
    expect(graph.adjList.get(4)!.edges).toEqual([2, 3, 5]);
    expect(graph.adjList.get(5)!.edges).toEqual([1, 4, 2]);
  });

  test("should not duplicate edges with objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    const node3 = { id: 3 };
    const node4 = { id: 4 };
    const node5 = { id: 5 };
    graph.addVertex(node1);

    graph.addEdge(node1, node2);
    graph.addEdge(node1, node5);
    graph.addEdge(node2, node1);
    graph.addEdge(node2, node5);
    graph.addEdge(node2, node3);
    graph.addEdge(node2, node4);
    graph.addEdge(node3, node2);
    graph.addEdge(node3, node4);
    graph.addEdge(node4, node2);
    graph.addEdge(node4, node5);
    graph.addEdge(node4, node3);
    graph.addEdge(node5, node4);
    graph.addEdge(node5, node1);
    graph.addEdge(node5, node2);
    expect(graph.adjList.get(1)!.edges).toEqual([2, 5]);
    expect(graph.adjList.get(2)!.edges).toEqual([1, 5, 3, 4]);
    expect(graph.adjList.get(3)!.edges).toEqual([2, 4]);
    expect(graph.adjList.get(4)!.edges).toEqual([2, 3, 5]);
    expect(graph.adjList.get(5)!.edges).toEqual([1, 2, 4]);
  });

  test("should be able to remove an edge", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    const node5 = { id: 5 };
    graph.addEdge(node1, node5);
    graph.removeEdge(node1, node5);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    expect(graph.adjList.get(5)!.edges).toEqual([]);
  });

  test("should be able to remove an edge with just numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addVertex(2);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.removeEdge(1, 5);
    expect(graph.adjList.get(5)!.edges).toEqual([]);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
  });

  test("should be able to remove a vertex", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    const node5 = { id: 5 };
    graph.addEdge(node1, node5);
    graph.removeVertex(node5);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    expect(graph.adjList.size).toEqual(2);
  });

  test("should be able to remove a vertex with just numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.removeVertex(5);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    expect(graph.adjList.size).toEqual(2);
  });

  test("should return depth first traversal using only numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.addEdge(2, 1);
    graph.addEdge(2, 5);
    graph.addEdge(2, 3);
    graph.addEdge(2, 4);
    graph.addEdge(3, 2);
    graph.addEdge(3, 4);
    graph.addEdge(4, 2);
    graph.addEdge(4, 5);
    graph.addEdge(4, 3);
    graph.addEdge(5, 4);
    graph.addEdge(5, 1);
    graph.addEdge(5, 2);
    const result = graph.depthFirstTraversal(1, console.log);
    expect(result).toEqual([1, 5, 4, 3, 2]);
  });

  test("should return depth first traversal using objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    const node3 = { id: 3 };
    const node4 = { id: 4 };
    const node5 = { id: 5 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    graph.addEdge(node1, node5);
    graph.addEdge(node2, node1);
    const nodeResult1 = { node: { id: 1 }, edges: [2, 5] };
    const nodeResult2 = { node: { id: 5 }, edges: [1] };
    const nodeResult3 = { node: { id: 2 }, edges: [1] };
    const result = graph.depthFirstTraversal(node1, console.log);
    expect(result[0]).toEqual(nodeResult1);
    expect(result[1]).toEqual(nodeResult2);
    expect(result[2]).toEqual(nodeResult3);
  });

  test("should return breadth first traversal using objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    const node3 = { id: 3 };
    const node4 = { id: 4 };
    const node5 = { id: 5 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    graph.addEdge(node1, node5);
    graph.addEdge(node2, node1);
    const result = graph.breadthFirstTraversal(node1, console.log);
    const nodeResult1 = { node: { id: 1 }, edges: [2, 5] };
    expect(result[0]).toEqual(nodeResult1);
    const nodeResult2 = { node: { id: 2 }, edges: [1] };
    expect(result[1]).toEqual(nodeResult2);
    const nodeResult3 = { node: { id: 5 }, edges: [1] };
    expect(result[2]).toEqual(nodeResult3);
  });

  test("should return breadth first search on numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    const result = graph.breadthFirstTraversal(1, console.log);
    expect(result[0]).toEqual(1);
  });
});
</code>```

Body:
I'm trying to build an Adjacency Graph which I have written in JavaScript and convert it to typescript, but I am really struggling with the generic types that I would like to have. Sorry, I am probably in over my head, but seems like it would be super sweet. Here is what I have tried to start with, but cannot figure it out.

export type AdjacencyVertex<T> = {
  node: T;
  edges: number[];
};

export class AdjacencyGraph<T> {
  public adjList: Record<number, AdjacencyVertex<T>> = {};
  // public adjList: Partial<AdjacencyVertex<T>>;
  // public adjList: Record<string, any> = {};
  private key: keyof T;

  constructor(key: keyof T) {
    this.adjList = {};
    this.key = key;
  }

  addVertex(v: T): void {
    if (this.key) {
      if (!this.adjList[v[this.key]]) {
        this.adjList[v[this.key]] = {
          node: v,
          edges: [],
        };
      }
    } else {
      if (!this.adjList[v]) {
        this.adjList[v] = {
          node: v,
          edges: [],
        };
      }
    }
  }
}

with this I am getting the error:

I guess I am just not really sure how to type this thing. Any help would be appreciated. Also an example usage, for reference would be something like this. these are the tests I wrote for the JavaScript version:

  test('should be able to add a vertex as an object', () => {
    const graph = new AdjacencyGraph('id');
    const node1 = { id: 1 };
    graph.addVertex(node1);
    let node = graph.adjList[node1.id];
    let result = { node: { id: 1 }, edges: [] };
    expect(node).toEqual(result);

    const node2 = { id: 2 };
    graph.addVertex(node2);
    node = graph.adjList[node2.id];
    result = { node: { id: 2 }, edges: [] };
    expect(node).toEqual(result);
  });

This is the solution that I finally came up with. Any advice or recommendations are definitely appreciated. All my test are passing also by the way. This is supporting number and complex objects so far:

export type AdjacencyVertex<T> = {
  node: T;
  edges: number[];
};

/**
 * AdjacencyGraph<T>
 */
export class AdjacencyGraph<T> {
  public adjList = new Map<number, AdjacencyVertex<T>>();
  private key?: keyof T;

  constructor(key?: keyof T) {
    this.adjList = new Map<number, AdjacencyVertex<T>>();
    this.key = key;
  }

  addVertex(v: T): void {
    if (this.key) {
      if (!this.adjList.get(v[this.key] as number)) {
        this.adjList.set(v[this.key] as number, {
          node: v,
          edges: [],
        });
      }
    } else {
      if (!this.adjList.get(v as number)) {
        this.adjList.set(v as number, {
          node: v,
          edges: [],
        });
      }
    }
  }

  /**
   * add Edge
   * @param src{T}
   * @param dest{T}
   * @returns {void}
   */
  addEdge(src: T, dest: T): void {
    if (this.key) {
      if (!this.adjList.get(src[this.key] as number)) {
        this.addVertex(src);
      }
      if (!this.adjList.get(dest[this.key] as number)) {
        this.addVertex(dest);
      }
      if (
        !this.adjList
          .get(src[this.key] as number)
          ?.edges.includes(dest[this.key] as number)
      ) {
        this.adjList
          .get(src[this.key] as number)
          ?.edges.push(dest[this.key] as number);
      }
      if (
        !this.adjList
          .get(dest[this.key] as number)
          ?.edges.includes(src[this.key] as number)
      ) {
        this.adjList
          .get(dest[this.key] as number)
          ?.edges.push(src[this.key] as number);
      }
    } else {
      if (!this.adjList.get(src as number)) {
        this.addVertex(src);
      }
      if (!this.adjList.get(dest as number)) {
        this.addVertex(dest);
      }
      // make sure there are no duplicates
      if (!this.adjList.get(src as number)?.edges.includes(dest as number)) {
        this.adjList.get(src as number)?.edges.push(dest as number);
      }
      if (!this.adjList.get(dest as number)?.edges.includes(src as number)) {
        this.adjList.get(dest as number)?.edges.push(src as number);
      }
    }
  }

  /**
   *
   * @param src
   * @param dest
   */
  removeEdge(src: T, dest: T): void {
    if (this.key) {
      let obj = this.adjList.get(src[this.key] as number);
      if (obj) {
        const destKey = dest[this.key] as number;
        obj.edges = obj.edges.filter((v) => v != destKey);
      }
      obj = this.adjList.get(dest[this.key] as number);
      if (obj) {
        const srcKey = src[this.key] as number;
        obj.edges = obj.edges.filter((v) => v != srcKey);
      }
    } else {
      let obj = this.adjList.get(src as number);
      if (obj) {
        obj.edges = obj.edges.filter((v) => v != dest);
      }
      obj = this.adjList.get(dest as number);
      if (obj) {
        obj.edges = obj.edges.filter((v) => v != src);
      }
    }
  }

  /**
   *
   * @param v
   */
  removeVertex(v: T) {
    if (this.key) {
      const parent = this.adjList.get(v[this.key] as number);
      const edges = parent?.edges;
      edges?.forEach((edge) => {
        const child = this.adjList.get(edge);
        if (child) {
          if (this.key) {
            const childKey = v[this.key] as number;
            child.edges = child.edges.filter((x) => x != childKey);
          }
        }
      });
      this.adjList.delete(v[this.key] as number);
    } else {
      const parent = this.adjList.get(v as number);
      const edges = parent?.edges;
      edges?.forEach((edge) => {
        const child = this.adjList.get(edge);
        if (child) {
          child.edges = child?.edges.filter((x) => x != v);
        }
      });
      this.adjList.delete(v as number);
    }
  }

  /**
   *
   * @param start
   * @param func
   * @returns
   */
  depthFirstTraversal(start: T, func?: Function): T[] {
    const stack: T[] | number = [];
    if (this.key) {
      // @ts-ignore
      stack.push(this.adjList.get(start[this.key] as number));
    } else {
      // @ts-ignore
      stack.push(start as number);
    }

    const visited = new Map<number, boolean>();
    const result: T[] = [];
    if (this.key) {
      const startKey = start[this.key] as number;
      visited.set(startKey, true);
    } else {
      visited.set(start as number, true);
    }

    while (stack.length) {
      const current = stack.pop();
      if (func) {
        func(current);
      }
      if (current) {
        // @ts-ignore
        result.push(current);
        if (this.key) {
          const neighbors = this.adjList.get(
            // @ts-ignore
            current.node[this.key] as number
          )!.edges;
          neighbors.forEach((neighbor) => {
            if (!visited.get(neighbor)) {
              // @ts-ignore
              stack.push(this.adjList.get(neighbor));
              visited.set(neighbor, true);
            }
          });
        } else {
          if (current) {
            const neighbors = this.adjList.get(current as number)!.edges;
            neighbors.forEach((neighbor) => {
              if (!visited.get(neighbor)) {
                // @ts-ignore
                stack.push(neighbor);
                visited.set(neighbor, true);
              }
            });
          }
        }
      }
    }

    return result;
  }

  breadthFirstTraversal(start: T, func?: Function) {
    const queue = [];
    const visited = new Map<number, boolean>();
    const result = [];
    if (this.key) {
      const startKey = start[this.key] as number;
      visited.set(startKey, true);
      queue.push(this.adjList.get(startKey));
    } else {
      visited.set(start as number, true);
      queue.push(start);
    }

    while (queue.length) {
      const current = queue.shift();
      if (this.key) {
        // @ts-ignore
        const neighbors = this.adjList.get(
          // @ts-ignore
          current.node[this.key as number] as number
        )!.edges;
        if (func) {
          func(current);
        }
        // @ts-ignore
        result.push(this.adjList.get(current.node[this.key]));
        neighbors.forEach((neighbor) => {
          if (!visited.get(neighbor)) {
            visited.set(neighbor, true);
            queue.push(this.adjList.get(neighbor));
          }
        });
      } else {
        const neighbors = this.adjList.get(current as number)!.edges;
        if (func) {
          func(current);
        }
        result.push(current);
        neighbors.forEach((neighbor) => {
          if (!visited.get(neighbor)) {
            queue.push(neighbor);
            visited.set(neighbor, true);
          }
        });
      }
    }

    return result;
  }
}

All test are passing:

import { AdjacencyGraph } from "../src/Structures/AdjacencyGraph";

describe("adjacencygraph tests", () => {
  test("should automatically add the first node", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addEdge(node1, node2);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    const graph1 = new AdjacencyGraph();
    graph1.addEdge(1, 2);
    expect(graph1.adjList.get(1)!.edges).toEqual([2]);
  });

  test("should be able to add a vertex as an object", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    graph.addVertex(node1);
    let node = graph.adjList.get(1);
    let result = { node: { id: 1 }, edges: [] };
    expect(node).toEqual(result);

    const node2 = { id: 2 };
    graph.addVertex(node2);
    node = graph.adjList.get(2);
    result = { node: { id: 2 }, edges: [] };
    expect(node).toEqual(result);
  });

  test("should be able to add vertex with a more complex object", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1, name: "mike", job: "developer" };
    graph.addVertex(node1);
    const node = graph.adjList.get(1);
    const result = {
      node: { id: 1, name: "mike", job: "developer" },
      edges: [],
    };
    expect(node).toEqual(result);
  });

  test("should be able to add vertex with simple numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    expect(graph.adjList.get(1)).toEqual({ node: 1, edges: [] });
    graph.addVertex(2);
    expect(graph.adjList.get(2)).toEqual({ node: 2, edges: [] });
    expect(graph.adjList.size).toEqual(2);
  });

  test("should be able to add edges with just numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addVertex(2);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    expect(graph.adjList.get(1)!.edges).toEqual([2, 5]);
  });

  test("should e able to add an edge with objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    expect(graph.adjList.size).toEqual(2);

    let edges = graph.adjList.get(1)!.edges;
    let result = [2];
    expect(edges).toEqual(result);
    const node5 = { id: 5 };
    graph.addEdge(node1, node5);
    edges = graph.adjList.get(1)!.edges;
    result = [2, 5];
    expect(edges).toEqual(result);
    expect(graph.adjList.size).toEqual(3);
  });

  // this is the structure this test is using
  // 1: [2,5]
  // 2: [1,5,3,4]
  // 3: [2,4]
  // 4: [2,5,3]
  // 5: [4,1,2]
  test("should not duplicate edges", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.addEdge(2, 1);
    graph.addEdge(2, 3);
    graph.addEdge(2, 3);
    graph.addEdge(2, 4);
    graph.addEdge(3, 2);
    graph.addEdge(3, 4);
    graph.addEdge(4, 2);
    graph.addEdge(4, 5);
    graph.addEdge(4, 3);
    graph.addEdge(5, 4);
    graph.addEdge(5, 1);
    graph.addEdge(5, 2);
    expect(graph.adjList.get(1)!.edges).toEqual([2, 5]);
    expect(graph.adjList.get(2)!.edges).toEqual([1, 3, 4, 5]);
    expect(graph.adjList.get(3)!.edges).toEqual([2, 4]);
    expect(graph.adjList.get(4)!.edges).toEqual([2, 3, 5]);
    expect(graph.adjList.get(5)!.edges).toEqual([1, 4, 2]);
  });

  test("should not duplicate edges with objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    const node3 = { id: 3 };
    const node4 = { id: 4 };
    const node5 = { id: 5 };
    graph.addVertex(node1);

    graph.addEdge(node1, node2);
    graph.addEdge(node1, node5);
    graph.addEdge(node2, node1);
    graph.addEdge(node2, node5);
    graph.addEdge(node2, node3);
    graph.addEdge(node2, node4);
    graph.addEdge(node3, node2);
    graph.addEdge(node3, node4);
    graph.addEdge(node4, node2);
    graph.addEdge(node4, node5);
    graph.addEdge(node4, node3);
    graph.addEdge(node5, node4);
    graph.addEdge(node5, node1);
    graph.addEdge(node5, node2);
    expect(graph.adjList.get(1)!.edges).toEqual([2, 5]);
    expect(graph.adjList.get(2)!.edges).toEqual([1, 5, 3, 4]);
    expect(graph.adjList.get(3)!.edges).toEqual([2, 4]);
    expect(graph.adjList.get(4)!.edges).toEqual([2, 3, 5]);
    expect(graph.adjList.get(5)!.edges).toEqual([1, 2, 4]);
  });

  test("should be able to remove an edge", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    const node5 = { id: 5 };
    graph.addEdge(node1, node5);
    graph.removeEdge(node1, node5);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    expect(graph.adjList.get(5)!.edges).toEqual([]);
  });

  test("should be able to remove an edge with just numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addVertex(2);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.removeEdge(1, 5);
    expect(graph.adjList.get(5)!.edges).toEqual([]);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
  });

  test("should be able to remove a vertex", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    const node5 = { id: 5 };
    graph.addEdge(node1, node5);
    graph.removeVertex(node5);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    expect(graph.adjList.size).toEqual(2);
  });

  test("should be able to remove a vertex with just numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.removeVertex(5);
    expect(graph.adjList.get(1)!.edges).toEqual([2]);
    expect(graph.adjList.size).toEqual(2);
  });

  test("should return depth first traversal using only numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    graph.addEdge(1, 5);
    graph.addEdge(2, 1);
    graph.addEdge(2, 5);
    graph.addEdge(2, 3);
    graph.addEdge(2, 4);
    graph.addEdge(3, 2);
    graph.addEdge(3, 4);
    graph.addEdge(4, 2);
    graph.addEdge(4, 5);
    graph.addEdge(4, 3);
    graph.addEdge(5, 4);
    graph.addEdge(5, 1);
    graph.addEdge(5, 2);
    const result = graph.depthFirstTraversal(1, console.log);
    expect(result).toEqual([1, 5, 4, 3, 2]);
  });

  test("should return depth first traversal using objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    const node3 = { id: 3 };
    const node4 = { id: 4 };
    const node5 = { id: 5 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    graph.addEdge(node1, node5);
    graph.addEdge(node2, node1);
    const nodeResult1 = { node: { id: 1 }, edges: [2, 5] };
    const nodeResult2 = { node: { id: 5 }, edges: [1] };
    const nodeResult3 = { node: { id: 2 }, edges: [1] };
    const result = graph.depthFirstTraversal(node1, console.log);
    expect(result[0]).toEqual(nodeResult1);
    expect(result[1]).toEqual(nodeResult2);
    expect(result[2]).toEqual(nodeResult3);
  });

  test("should return breadth first traversal using objects", () => {
    const graph = new AdjacencyGraph("id");
    const node1 = { id: 1 };
    const node2 = { id: 2 };
    const node3 = { id: 3 };
    const node4 = { id: 4 };
    const node5 = { id: 5 };
    graph.addVertex(node1);
    graph.addEdge(node1, node2);
    graph.addEdge(node1, node5);
    graph.addEdge(node2, node1);
    const result = graph.breadthFirstTraversal(node1, console.log);
    const nodeResult1 = { node: { id: 1 }, edges: [2, 5] };
    expect(result[0]).toEqual(nodeResult1);
    const nodeResult2 = { node: { id: 2 }, edges: [1] };
    expect(result[1]).toEqual(nodeResult2);
    const nodeResult3 = { node: { id: 5 }, edges: [1] };
    expect(result[2]).toEqual(nodeResult3);
  });

  test("should return breadth first search on numbers", () => {
    const graph = new AdjacencyGraph();
    graph.addVertex(1);
    graph.addEdge(1, 2);
    const result = graph.breadthFirstTraversal(1, console.log);
    expect(result[0]).toEqual(1);
  });
});


问:
Material UI 4.0 Unable to Set Default Value in Autocomplete
Material UI 4.0 Unable to Set Default Value in Autocomplete, this the the following details i am using formick as well:

```<code>   <Autocomplete
            required
            options={Names}
            getOptionLabel={option => option.label}
            id='Name'
            aria-label='name'
            label='Name'
            name='name'
            clearOnEscape
            closeIcon={<SearchIcon />}
            className='name-action'
            renderInput={params => (
              <TextField
                {...params}
                required={true}
                label='Search Name'
              />
            )}
          />
</code>```

where the options is object of array

```<code>option= [
    { name: 'Air' },
    { name: 'Train' },
    { name: 'Surface' }]
</code>```

I tried placing the values as well in the above autocomplete but it did not worked for me

Body:
Material UI 4.0 Unable to Set Default Value in Autocomplete, this the the following details i am using formick as well:

   <Autocomplete
            required
            options={Names}
            getOptionLabel={option => option.label}
            id='Name'
            aria-label='name'
            label='Name'
            name='name'
            clearOnEscape
            closeIcon={<SearchIcon />}
            className='name-action'
            renderInput={params => (
              <TextField
                {...params}
                required={true}
                label='Search Name'
              />
            )}
          />

where the options is object of array

option= [
    { name: 'Air' },
    { name: 'Train' },
    { name: 'Surface' }]

I tried placing the values as well in the above autocomplete but it did not worked for me


问:
React Native - Run javascript function only if it is not currently running with the same parameters
I have a function called fetchGamesFromDatabase(date), which fetches the latest game info for all games on a given date.

This function can be called from daughter components, some of which share the same date. Now, if it is called by two components sharing the same date, I only want it to run once to avoid fetching the same data twice.

I tried to fix this by having a state keeping track of which dates are currently fetching, but since useState is async, many components manage to call the function before the state is updated.

I created a minimalistic Expo Snack to reproduce the behavior:

https://snack.expo.dev/yzkiU6rmc

As you can see in the logs (click Editor in the bottom bar and enable Panel), every child component calls the function before the state updates.

Any suggestions on how to make sure the fetchGamesFromDatabase function is only ran once per date, even though it will be called multiple times per date?

Thanks


问:
List hosts' private IP addresses by subnet ID using Ansible on AWS?
I have already running subnet with 2 instances on AWS.

I have completely new project and playbooks, but before all I wish to somehow obtain the info about that subnet (interested in Private and Public IP that are assigned of these instances inside that subnet), what I tried so for and had no success is:

```<code>- hosts: local
  gather_facts: no
  tasks:
  - name: Gather information about the VPC by subnet id
    amazon.aws.ec2_vpc_subnet_info:
      region: "eu-east-1"
      subnet_ids: subnet-2424a8dd88760911af
    register: subinfo

  - name: Debug...
    debug:
      msg: "{{ subinfo }}"
</code>```

On output I only get CIDR block of the subnet and other non-relevant info.

UPD: This may be handy for me, when, for example, I don't know how many instances in the subnet, but I wish to add one using Ansible (I create my own inventory file, where I describe existing subnets' parameters, but not hosts which are inside that subnet). So at the start Ansible should scan some existing network, obtain facts and then place my new one instance inside the subnet.

Body:
I have already running subnet with 2 instances on AWS.

I have completely new project and playbooks, but before all I wish to somehow obtain the info about that subnet (interested in Private and Public IP that are assigned of these instances inside that subnet), what I tried so for and had no success is:

- hosts: local
  gather_facts: no
  tasks:
  - name: Gather information about the VPC by subnet id
    amazon.aws.ec2_vpc_subnet_info:
      region: "eu-east-1"
      subnet_ids: subnet-2424a8dd88760911af
    register: subinfo

  - name: Debug...
    debug:
      msg: "{{ subinfo }}"

On output I only get CIDR block of the subnet and other non-relevant info.

UPD: This may be handy for me, when, for example, I don't know how many instances in the subnet, but I wish to add one using Ansible (I create my own inventory file, where I describe existing subnets' parameters, but not hosts which are inside that subnet). So at the start Ansible should scan some existing network, obtain facts and then place my new one instance inside the subnet.


问:
How do you change the current user control based on a ViewModel field in WPF MVVM?
I'm trying to code a dungeon crawler where a player navigates between set locations. Only the location where the player is will be displayed on screen, and will be changed whenever the player moves to a new location.

My GameView currently consists of a UserControl displaying inventory,stats and the location. I was hoping to add the location to the centre of the screen as a second UserControl inside the GameView, and change it to another UserControl whenever the View is notified that the player has moved locations.

This is what I am currently using to change between user controls inside the main window to navigate through menus:

```<code><ContentControl Content="{Binding CurrentViewModel}">
        <ContentControl.Resources>
            <DataTemplate DataType="{x:Type viewmodels:MenuViewModel}">
                <views:MenuView/>
            </DataTemplate>
             ...

        </ContentControl.Resources>
    </ContentControl>
</code>```

I was hoping to use something similar for the location, but for some reason the location doesn't display at the centre of the screen:

```<code>       <Viewbox Grid.Row="1" Grid.Column="1" Grid.RowSpan="2">
            <ContentControl Content="{Binding CurrentLocation}">
                <ContentControl.Resources>
                    <DataTemplate DataType="{x:Type locationModel:SmallRoom}">
                        <locationView:SmallRoomView/>
                    </DataTemplate>

                    <DataTemplate DataType="{x:Type locationModel:LargeRoom}">
                        <locationView:LargeRoomView/>
                    </DataTemplate>
                </ContentControl.Resources>
            </ContentControl>
        </Viewbox>
</code>```

I have checked and the CurrentLocation attribute is being updated and is of the type SmallRoom. I have also checked to see how the code runs without the data templates...

```<code>        <ContentControl>
            <locationView:SmallRoomView/>
        </ContentControl>
</code>```

...but not even this displays the UserControl in the centre of the screen. I've spent hours looking for bugs and have struggled to find any myself. Any suggestions of why my second UserControl is not displaying would be greatly appreciated. If there's any better way of doing this, advice would be appreciated. I'm fairly new to MVVM and WPF so go easy on me ;)

Body:
I'm trying to code a dungeon crawler where a player navigates between set locations. Only the location where the player is will be displayed on screen, and will be changed whenever the player moves to a new location.

My GameView currently consists of a UserControl displaying inventory,stats and the location. I was hoping to add the location to the centre of the screen as a second UserControl inside the GameView, and change it to another UserControl whenever the View is notified that the player has moved locations.

This is what I am currently using to change between user controls inside the main window to navigate through menus:

<ContentControl Content="{Binding CurrentViewModel}">
        <ContentControl.Resources>
            <DataTemplate DataType="{x:Type viewmodels:MenuViewModel}">
                <views:MenuView/>
            </DataTemplate>
             ...

        </ContentControl.Resources>
    </ContentControl>

I was hoping to use something similar for the location, but for some reason the location doesn't display at the centre of the screen:

       <Viewbox Grid.Row="1" Grid.Column="1" Grid.RowSpan="2">
            <ContentControl Content="{Binding CurrentLocation}">
                <ContentControl.Resources>
                    <DataTemplate DataType="{x:Type locationModel:SmallRoom}">
                        <locationView:SmallRoomView/>
                    </DataTemplate>

                    <DataTemplate DataType="{x:Type locationModel:LargeRoom}">
                        <locationView:LargeRoomView/>
                    </DataTemplate>
                </ContentControl.Resources>
            </ContentControl>
        </Viewbox>

I have checked and the CurrentLocation attribute is being updated and is of the type SmallRoom. I have also checked to see how the code runs without the data templates...

        <ContentControl>
            <locationView:SmallRoomView/>
        </ContentControl>

...but not even this displays the UserControl in the centre of the screen. I've spent hours looking for bugs and have struggled to find any myself. Any suggestions of why my second UserControl is not displaying would be greatly appreciated. If there's any better way of doing this, advice would be appreciated. I'm fairly new to MVVM and WPF so go easy on me ;)


问:
Pytest, Mocker and Patch Nested function not working
I am trying to run a unittest on Python, Pytest for my below function:

```<code>        some_obj= OBJ(db=db)  \\ Coverage done
        some_obj.create_obj_in_db(log=log)  \\ Coverage done
</code>```

Until this line the test is working, once it goes on the send_mail function, it doesn't work because mail credentials are not set.

```<code>        send_mail(changelog=changelog)  \\ Send Connection refused error
</code>```

I want to unit test send_mail also, I tried mock and patch, still connection error message

Need to cover send_mail also, but the function doesn't have the credentials so the test is failing with Connection Refused Error.

Body:
I am trying to run a unittest on Python, Pytest for my below function:

        some_obj= OBJ(db=db)  \\ Coverage done
        some_obj.create_obj_in_db(log=log)  \\ Coverage done

Until this line the test is working, once it goes on the send_mail function, it doesn't work because mail credentials are not set.

        send_mail(changelog=changelog)  \\ Send Connection refused error

I want to unit test send_mail also, I tried mock and patch, still connection error message

Need to cover send_mail also, but the function doesn't have the credentials so the test is failing with Connection Refused Error.


问:
How to let nginx log the ssl key log file?
My goal is capture the pcap file on my linux machine which is using nginx to connect and decrypt those packets using ssl key log file.but i am unable to find how to capture ssl key log file on nginx.
Could someone please help me how to capture ssl key log file ?

```<code>   log_format quic '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" "$http3"';

   access_log /var/log/nginx/access.log quic;

   server {
        # for better compatibility it's recommended
        # to use the same port for quic and https
        listen 8443 http3 reuseport;
        listen 8443 ssl;

        ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
        ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
        ssl_protocols       TLSv1.3;

        location / {
            # required for browsers to direct them into quic port
            add_header Alt-Svc 'h3=":8443"; ma=86400';
        }

</code>```

127.0.0.1 - - [23/Dec/2022:13:13:25 +0000] TLSv1.3/TLS_AES_128_GCM_SHA256 "GET / HTTP/3.0" 200 751 "-" "curl/7.87.1-DEV" "h3"

How do I configure nginx to log ssl key log information?

Body:
My goal is capture the pcap file on my linux machine which is using nginx to connect and decrypt those packets using ssl key log file.but i am unable to find how to capture ssl key log file on nginx.
Could someone please help me how to capture ssl key log file ?

   log_format quic '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" "$http3"';

   access_log /var/log/nginx/access.log quic;

   server {
        # for better compatibility it's recommended
        # to use the same port for quic and https
        listen 8443 http3 reuseport;
        listen 8443 ssl;

        ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
        ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
        ssl_protocols       TLSv1.3;

        location / {
            # required for browsers to direct them into quic port
            add_header Alt-Svc 'h3=":8443"; ma=86400';
        }

127.0.0.1 - - [23/Dec/2022:13:13:25 +0000] TLSv1.3/TLS_AES_128_GCM_SHA256 "GET / HTTP/3.0" 200 751 "-" "curl/7.87.1-DEV" "h3"

How do I configure nginx to log ssl key log information?


问:
How to know radio buttons of list-group not checked?
I am creating website to take test. In that I gave question & 4 radio buttons for options.
I am getting checked options using this snippet:

```<code>const formData = new FormData(document.getElementById('form'));
let checkvalues = []
for (const value of formData.values()) {
   checkvalues.push(value)
}
</code>```

But what happened is, suppose out of four radio buttons none of them is selected, then
I do not get any blank/null value for it.
So, how to know radio buttons of list-group not checked or is there any option like defaultvalue if not selected?

test.js

```<code>var data = [
    {
        "id" : 1,
        "question" : "jvm is____________",
        "options" : [
            "platform dependant",
            "platform lndepedent",
            "depends on jvm implementation",
            "Both b and c"
        ],
        "answer" : "platform dependant"
    },
    {
        "id" : 2,
        "question" : "return type of main method is______",
        "options" : [
            "int",
            "char",
            "void",
            "None of the above"
        ],
        "answer" : "void"
    }
]
</code>```

index.html

```<code><p id="result" class="m-3"></p>
<form id="form">
<div id="test" class="card-body"></div>

<div class="d-flex justify-content-center mb-5">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</code>```

Javascript

```<code><script>
        $("#form").submit((event) => {
            event.preventDefault();
            onTimesUp()
            submit()
        }
        )

        function submit() {
            $(".list-group-item").addClass('disabled')
            const formData = new FormData(document.getElementById('form'));
            let checkvalues = []
            let result = []
            for (const value of formData.values()) {
                checkvalues.push(value)
            }
            for (const key of formData.keys()) {
                console.log(key)
            }
            var i = 0;
            var sum = 0;
            data.map((que) => {
                if (que.answer === checkvalues[i]) {
                    sum += 1;
                    $(`#answer${i + 1}`).addClass('text-success').html('Right answer');
                }
                else {
                    $(`#answer${i + 1}`).addClass('text-danger').html(`Wrong answer.<p class='text-success mb-1'> Right answer : ${que.answer}</p>`);
                }
                i++
            })

            $("#result").html(`Your score : ${sum}/${data.length}`)
            $("#result").show()
        }

        $(window).on('load', function () {
            $("#result").hide()
            $("#answer").hide()
            data.map((que) => {
                $("#test").append(`
                <div class="card mb-3">
                    <div class="card-body">
                        <div class="card mb-2">
                            <div class="card-body">
                                <p>Q.${que.id} ${que.question}</p>
                            </div>
                        </div>
                        <ul class="list-group">
                            <li class="list-group-item">
                                <input class="form-check-input me-1" type="radio" name="listGroupRadio${que.id}" value="${que.options[0]}" id="firstRadio">
                                <label class="form-check-label" for="firstRadio">${que.options[0]}</label>
                            </li>
                            <li class="list-group-item">
                                <input class="form-check-input me-1" type="radio" name="listGroupRadio${que.id}" value="${que.options[1]}" id="secondRadio">
                                <label class="form-check-label" for="secondRadio">${que.options[1]}</label>
                            </li>
                            <li class="list-group-item">
                                <input class="form-check-input me-1" type="radio" name="listGroupRadio${que.id}" value="${que.options[2]}" id="thirdRadio">
                                <label class="form-check-label" for="secondRadio">${que.options[2]}</label>
                            </li>
                            <li class="list-group-item">
                                <input class="form-check-input me-1" type="radio" name="listGroupRadio${que.id}" value="${que.options[3]}" id="fourthRadio">
                                <label class="form-check-label" for="secondRadio">${que.options[3]}</label>
                            </li>
                        </ul>
                        <p id='answer${que.id}' class='mt-2 mb-1'></p>
                    </div>
                </div>
                `)
            })

        });

    </script>
</code>```

Body:
I am creating website to take test. In that I gave question & 4 radio buttons for options.
I am getting checked options using this snippet:

const formData = new FormData(document.getElementById('form'));
let checkvalues = []
for (const value of formData.values()) {
   checkvalues.push(value)
}

But what happened is, suppose out of four radio buttons none of them is selected, then
I do not get any blank/null value for it.
So, how to know radio buttons of list-group not checked or is there any option like defaultvalue if not selected?

test.js

var data = [
    {
        "id" : 1,
        "question" : "jvm is____________",
        "options" : [
            "platform dependant",
            "platform lndepedent",
            "depends on jvm implementation",
            "Both b and c"
        ],
        "answer" : "platform dependant"
    },
    {
        "id" : 2,
        "question" : "return type of main method is______",
        "options" : [
            "int",
            "char",
            "void",
            "None of the above"
        ],
        "answer" : "void"
    }
]

index.html

<form id="form">

<button class="btn btn-primary" type="submit">Submit</button>

</form>

Javascript


问:
Spring boot @Scheduled: parametrized task based on database record
I have a table whith 3 columns.

dateTimeStart

dateTimeEnd

refreshTimeInSeconds

In want my application for each record to run a scheduled task between dateTimeStart and dateTimeEnd for every refreshTimeInSeconds.

Example:

dateTimeStart - 2022/12/23 03:00:00 PM

dateTimeEnd - 2022/12/23 04:00:00 PM

refreshTimeInSeconds - 60

2022/12/23 03:00:00 PM - call some method

2022/12/23 03:01:00 PM - call some method (+ 60 seconds)

...

2022/12/23 04:00:00 PM - call some method

I have no idea how to solve this. Can I do this in spring using @Scheduled?


问:
allowable port numbers for chrome devtools
I am using chrome to perform some testing work. from my search on google I saw that most people make use of 9222 as the port i.e.
--remote-debugging-port=9222 but I need more than even 3 different numbers.

Is there any certain rule for the port number that I am to use?

Are there any range of port numbers that I am to use?

I am also concerned about security of my system, I am currently using windows, but would also use linux.


问:
Anylogic: Create text by Java with dynamic text content
I want to create text using Java so that I can use codes to control how many shapetext to create and auto position them, but I want to link the text content to a dynamic value that is changing (e.g. a variable storing a parameter that varies during runtime). I am using the code below to create the text, however, when I replace "Test" with a variable, the text captures the value at the initial instance and remains a static value.

Is there any way to make the content dynamic or I can only write a function to actively refresh the text content?

Also, using a function to actively update the value makes the model run slower right? I compared the runs and observe that the model runtime is significantly slower.

```<code>col_Label_EQ.add(new ShapeText(SHAPE_DRAW_2D,
               true,
               0,
               0,
               0,
               0,
               white,
               "Test",
               new Font("SansSerif",
                        Font.BOLD,
                        10),
               ALIGNMENT_CENTER));

</code>```

presentation.add(col_Label_EQ.get(0));

Body:
I want to create text using Java so that I can use codes to control how many shapetext to create and auto position them, but I want to link the text content to a dynamic value that is changing (e.g. a variable storing a parameter that varies during runtime). I am using the code below to create the text, however, when I replace "Test" with a variable, the text captures the value at the initial instance and remains a static value.

Is there any way to make the content dynamic or I can only write a function to actively refresh the text content?

Also, using a function to actively update the value makes the model run slower right? I compared the runs and observe that the model runtime is significantly slower.

col_Label_EQ.add(new ShapeText(SHAPE_DRAW_2D,
               true,
               0,
               0,
               0,
               0,
               white,
               "Test",
               new Font("SansSerif",
                        Font.BOLD,
                        10),
               ALIGNMENT_CENTER));

presentation.add(col_Label_EQ.get(0));


问:
Executing Command and Getting Output From C With MPI
I have an MPI C program, and I need to get the output of an executable. The executable does a complicated calculation and outputs the results.

The output of the executable is something like this:

```<code>0.0225873863659866,0.0000000000000000,0.0000000000000000,
</code>```

whithout a new line character at the end.

To execute and get the output of the command I tried:

```<code>double vals[3];
char command[256];
sprintf (command, "./a.out");

// Execute the command
FILE *cmd = popen(command, "r");

// Get the command output
char buf[256] = {0x0};
while (fgets(buf, sizeof(buf), cmd) != NULL) {
     // Output is separated with ,
     // separate the string
     char *token = strtok(buf, ",");
         for (int i = 0; i < 3; ++i) {
              // store integral value
              vals[i] = atof(token);
              token = strtok(NULL, ",");
          }
      }

printf("vals = (%g, %g, %g) pid = %d \n", vals[0], vals[1], vals[2], pid);

// Close file
pclose(cmd);
</code>```

In a serial test program, this works great. The problem is that with the MPI program, only PID 0 executes the command, and the rest of the processors don't do it. I also tried having each process call a different executable and different configurations of MPI_BARRIER, but nothing worked.

Why does this happen, and how can I fix it?

Body:
I have an MPI C program, and I need to get the output of an executable. The executable does a complicated calculation and outputs the results.

The output of the executable is something like this:

0.0225873863659866,0.0000000000000000,0.0000000000000000,

whithout a new line character at the end.

To execute and get the output of the command I tried:

double vals[3];
char command[256];
sprintf (command, "./a.out");

// Execute the command
FILE *cmd = popen(command, "r");

// Get the command output
char buf[256] = {0x0};
while (fgets(buf, sizeof(buf), cmd) != NULL) {
     // Output is separated with ,
     // separate the string
     char *token = strtok(buf, ",");
         for (int i = 0; i < 3; ++i) {
              // store integral value
              vals[i] = atof(token);
              token = strtok(NULL, ",");
          }
      }

printf("vals = (%g, %g, %g) pid = %d \n", vals[0], vals[1], vals[2], pid);

// Close file
pclose(cmd);

In a serial test program, this works great. The problem is that with the MPI program, only PID 0 executes the command, and the rest of the processors don't do it. I also tried having each process call a different executable and different configurations of MPI_BARRIER, but nothing worked.

Why does this happen, and how can I fix it?


问:
php bigquery get json value
I use sdk php bigquery for insert and select data and I add json properties but when I invoke json properties I found null value but in database content data.

this is screen for schema dataset

and this is code php for invoke data from dataset:

```<code>         $queryJobConfig = $bigQuery->query(
                    'SELECT id_sso,JSON_value(data) AS test FROM `gsoi-sandbox.users_profil.profil`'
                );
                $queryResults = $bigQuery->runQuery($queryJobConfig);
                foreach ($queryResults as $row) {
                    $result[] = ($row);
                }
</code>```

result of variable $result is:

my question how to get true data and not null , in dataset I have data and not null

Title: php bigquery get json value

Body:
I use sdk php bigquery for insert and select data and I add json properties but when I invoke json properties I found null value but in database content data.

this is screen for schema dataset

and this is code php for invoke data from dataset:

         $queryJobConfig = $bigQuery->query(
                    'SELECT id_sso,JSON_value(data) AS test FROM `gsoi-sandbox.users_profil.profil`'
                );
                $queryResults = $bigQuery->runQuery($queryJobConfig);
                foreach ($queryResults as $row) {
                    $result[] = ($row);
                }

result of variable $result is:

my question how to get true data and not null , in dataset I have data and not null