问:
What could I do to optimise this Minecraft Forge code in 1.19.2?
I'm pretty new to Minecraft modding and would like to know if there's a better way to test for a block in a radius around my player. my current implementation is the following:

```<code>if ((world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.TORCH

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.WALL_TORCH

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.FIRE

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.CAMPFIRE

                                            && world.getMaxLocalRawBrightness(new BlockPos(x + sx, y + sy, z + sz)) == 15

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.LANTERN

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.LAVA

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.LAVA_CAULDRON

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.FURNACE

                                            && world.getMaxLocalRawBrightness(new BlockPos(x + sx, y + sy, z + sz)) == 13)
</code>```

This basically loops through each block in a radius of 10 and returns true if a block is found. I know there is a way to optimise this code but I can't think how.

My implementation works, but is there anything else I could try which would be less taxing on the cpu?

Body:
I'm pretty new to Minecraft modding and would like to know if there's a better way to test for a block in a radius around my player. my current implementation is the following:

if ((world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.TORCH

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.WALL_TORCH

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.FIRE

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.CAMPFIRE

                                            && world.getMaxLocalRawBrightness(new BlockPos(x + sx, y + sy, z + sz)) == 15

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.LANTERN

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.LAVA

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.LAVA_CAULDRON

                                    || (world.getBlockState(new BlockPos(x + sx, y + sy, z + sz))).getBlock() == Blocks.FURNACE

                                            && world.getMaxLocalRawBrightness(new BlockPos(x + sx, y + sy, z + sz)) == 13)

This basically loops through each block in a radius of 10 and returns true if a block is found. I know there is a way to optimise this code but I can't think how.

My implementation works, but is there anything else I could try which would be less taxing on the cpu?


来源: stackexchange

问:
Python class body scope rule is confusing, why?

x = 1

class Girl:
    x = 2
    print([i * x for i in (1, 2, 3)])
```

The output is [1, 2, 3].

So class does not have its own scope; someone told me that according to the LEGB rule, class body != closure, so Python looks for the global x.

I still have trouble understanding this. Are class bodies actually function bodies? You can actually run any code (if - else, for loop, etc) in that body, why? I'm so confused

ContentLicense: CC BY-SA 4.0

Body:
x = 1

class Girl:
    x = 2
    print([i * x for i in (1, 2, 3)])

The output is [1, 2, 3].

So class does not have its own scope; someone told me that according to the LEGB rule, class body != closure, so Python looks for the global x.

I still have trouble understanding this. Are class bodies actually function bodies? You can actually run any code (if - else, for loop, etc) in that body, why? I'm so confused


问:
Show data in Excel by columns when selecting a checkbox
I am new to programming and I am creating a website where the user chooses through a checkbox the data he wants to see and that is stored in my database. Example, if the client only wants to see the Car and price data, he selects them and when he presses a button, the data he requested is downloaded in an Excel file.

The problem is that it doesn't show by columns but it puts all the data in the same column and I can't put everything in the same array because each checkbox has to be independent.

The data looks like this

```<code>Car
Ford
Chevrolete
Tesla

Price
2000
3000
4000

And i want each one to be in a different column

</code>```

This is my code

```<code>
if(isset($_POST['respuesta'])){
        if(isset ($_POST['checkbox'])){
            foreach($_POST ['checkbox'] as $checkbox);

        $Auto = $_POST['checkbox'];
         $Color= $_POST['checkbox'];
         $Precio = $_POST['checkbox'];
         $Año = $_POST['checkbox'];

         header('Content-Type:text/csv; charset-latin1');
         header('Content-Disposition: attachment; filename="Reporte.csv"');

         $salida=fopen('php://output', 'W');

         if (in_array('Auto',$_POST['checkbox'])){
            fputcsv($salida, array ('Auto'));

            $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
            $resultados=mysqli_query($enlace, $query);
            while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Auto']));

    }
        ?>

        <?PHP
         if (in_array('Color',$_POST['checkbox'])){
            fputcsv($salida, array ('Color'));

           $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
           $resultados=mysqli_query($enlace, $query);
           while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Color']));

    }

        ?>

         <?PHP
          if (in_array('Precio',$_POST['checkbox'])){
         fputcsv($salida, array ('Precio'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array($filaR['Precio']));
         }

         ?>

        <?PHP
        if (in_array('Año', $_POST['checkbox'])){
        fputcsv($salida, array ('Año'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array ($filaR['Año']));
        }

        ?>

</code>```

Body:
I am new to programming and I am creating a website where the user chooses through a checkbox the data he wants to see and that is stored in my database. Example, if the client only wants to see the Car and price data, he selects them and when he presses a button, the data he requested is downloaded in an Excel file.

The problem is that it doesn't show by columns but it puts all the data in the same column and I can't put everything in the same array because each checkbox has to be independent.

The data looks like this

Car
Ford
Chevrolete
Tesla

Price
2000
3000
4000

And i want each one to be in a different column

This is my code

if(isset($_POST['respuesta'])){
        if(isset ($_POST['checkbox'])){
            foreach($_POST ['checkbox'] as $checkbox);

        $Auto = $_POST['checkbox'];
         $Color= $_POST['checkbox'];
         $Precio = $_POST['checkbox'];
         $Año = $_POST['checkbox'];

         header('Content-Type:text/csv; charset-latin1');
         header('Content-Disposition: attachment; filename="Reporte.csv"');

         $salida=fopen('php://output', 'W');

         if (in_array('Auto',$_POST['checkbox'])){
            fputcsv($salida, array ('Auto'));

            $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
            $resultados=mysqli_query($enlace, $query);
            while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Auto']));

    }
        ?>

        <?PHP
         if (in_array('Color',$_POST['checkbox'])){
            fputcsv($salida, array ('Color'));

           $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
           $resultados=mysqli_query($enlace, $query);
           while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Color']));

    }

        ?>

         <?PHP
          if (in_array('Precio',$_POST['checkbox'])){
         fputcsv($salida, array ('Precio'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array($filaR['Precio']));
         }

         ?>

        <?PHP
        if (in_array('Año', $_POST['checkbox'])){
        fputcsv($salida, array ('Año'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array ($filaR['Año']));
        }

        ?>


问:
Alignment Issues and Counting Diagnosis issues. This is my first post, Sorry if anything is incorrectly formatted

Programming Project 3F

Vital signs of hospital patients are monitored and reported automatically. While each monitor has alarms which go off when a reading is out of range, combinations of readings are also important. Common vital signs and normal range is given below.

The use of functions is encouraged.  If you create your own header file, name it Project3.h.  This common name will allow me to easily include your header in the report I grade.

Write a program to read a series of patient records from the file PATIENTS.TXT. Use the Priming Read logic to process all records in the file. Each record (line of the file) contains the following fields delimited by a space: first name, lastname, pulse, respiration, oxygen, room. The file contains and unknown number of records. Unlike Program #2, simple stream input using >> from the file should suffice to read this file. You do not need to parse the file as you did in Project #2.

A sample file with one record per line might resemble the following

Buster Leggs 88 44 88 120
Charlie Horse 56 15 95 011
Wilma Moneylast 132 18 98 200
Willie Makit 75 30 94 121
Betty Wont 50 10 90 000
Eaton Buggs 79 16 97 111
Freda Spirit 110 23 90 220

Categorize each reading as Low, Normal or High. Print the result in the report detailed below. Normal range for each reading is as follows

Pulse 60-100

Respiration 12-20

Oxygen Level 92-100

Tag each record as according to the following and print any needed messages in the report for each record

CHECK – one indicator out of range
ALERT*** – two indicators out of range
CRITICAL***** – three indicators out of range

Room Name                  Pulse  Respir  Oxygen

120  Leggs, Buster            88 High=44  Low=88 ALERT***
011  Horse, Charlie      Low= 56      15      95 CHECK
200  Moneylast, Wilma   High=132      18      98 CHECK
111  Makit, Willie            75      20      94
000  Wont, Betty         Low= 50  Low=10  Low=90 CRITICAL****
111  Buggs, Eaton             79      16      97
220  Spirit, Freda      High=110 High=23  Low=90 CRITICAL****

Totals
2 Normal
1 ALERT
2 CHECK
2 CRITICAL

The Code I Currently have is:

```<code></code>```
```<code>\`#include "stdafx.h"
\#include \<iostream\>
\#include \<fstream\>
\#include \<string\>
\#include \<iomanip\>

using namespace std;

void Pause()
{
char junk;
cin.ignore(100,'\\n');
cout \<\< "\\n\\nPress enter to continue...";
cin.get(junk);
} // Pause()
</code>```
```<code>int main()
{

//File Variables
ifstream PATIENTS_IN;
ofstream PATIENTS_LOG;

//Declare Variables and Constants
string Info, diag;
int pulseint, respint, O2int;
int count,count1, count2, count3,check, alert, critical;
string FirstName, LastName, Pulse, Resp, O2Lvl, RoomNum;
</code>```
```<code>//Initalize Variables
count=0;
count1=1;
count2=0;
count3=0;
check=0;
alert=0;
critical=0;
Info= "no name read";
FirstName= "no name read";
LastName= "no name read";

//               \*\* Open Data Files \*\*
</code>```
```<code>PATIENTS_LOG.open("D:\\PATIENTS.log");
if(PATIENTS_LOG)
{//Last file operation was successful
}
else
{//last file operation FAILED!
cout \<\< "PATIENTS_LOG open FAILED!" \<\< endl;
</code>```
```<code>}
PATIENTS_IN.open("D:\\PATIENTS.txt");
if (PATIENTS_IN)
{//last file operation was successful
PATIENTS_LOG \<\< "PATIENTS_IN file open successful" \<\< endl;
}
else
{//last file operation FAILED!
cout \<\< "PATIENTS_IN file FAILED!" \<\< endl;
}
</code>```
```<code>
    getline(PATIENTS_IN, Info); //Priming read
    if(PATIENTS_IN)
    {//last file peration was successful

    }
    else
    {PATIENTS_LOG << "Input file Priming read FAILED" << endl;
    }
    count=1;

//Header
cout \<\<   "Room Name                  Pulse  Respir  Oxygen" \<\< endl;
cout \<\<"-----------------------------------------------------" \<\< endl;

while (!PATIENTS_IN.eof())
{PATIENTS_IN \>\> FirstName \>\>
LastName \>\> Pulse \>\> Resp \>\> O2Lvl \>\> RoomNum;
//Conversion
pulseint=stoi(Pulse);
respint=stoi(Resp);
O2int=stoi(O2Lvl);

if(pulseint\>100)
{Pulse="High=" + Pulse;
}
else if(pulseint\<60)
{Pulse="Low="+ Pulse;
}
else
{}//Do Nothing

if(respint\>20)
{Resp="High=" + Resp;
}
else if(respint\<12)
{Resp="Low="+ Resp;
}
else
{
}
if(O2int\>100)
{O2Lvl="High=" + O2Lvl;
}
else if(O2int\<92)
{O2Lvl="Low="+ O2Lvl;
}
else
{
}

if(pulseint\>100||pulseint\<60)
{count1++;
}
if(respint\>20||respint\<12)
{count2++;
}
if(O2int\>100||O2int\<92)
{count3++;
}

    if(count1==1)

{diag="CHECK--";
check++;}
if(count1==2)
{diag= "ALERT ***";
alert++;}
if(count1==3)
{diag= "CRITICAL***\*\*";
critical++;}
else
{diag="";
}
</code>```
```<code>cout << left <<RoomNum << "  " << LastName << ", " << FirstName<< "";
cout << right <<""<<setw(12)<<Pulse <<right
cout << ""<<setw(10) <<Resp <<""<< right<<setw(10) << O2Lvl<<"\n";
</code>```
```<code>
}//End While
Pause();
return (0);
}

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

I have tried messing with the counters, others say they are having run time errors while trying to run the code while I don't get them, as well as alignment issues. I feel like Albert  Einstein's definition of insanity.

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

Body:
Programming Project 3F

Vital signs of hospital patients are monitored and reported automatically. While each monitor has alarms which go off when a reading is out of range, combinations of readings are also important. Common vital signs and normal range is given below.

The use of functions is encouraged.  If you create your own header file, name it Project3.h.  This common name will allow me to easily include your header in the report I grade.

Write a program to read a series of patient records from the file PATIENTS.TXT. Use the Priming Read logic to process all records in the file. Each record (line of the file) contains the following fields delimited by a space: first name, lastname, pulse, respiration, oxygen, room. The file contains and unknown number of records. Unlike Program #2, simple stream input using >> from the file should suffice to read this file. You do not need to parse the file as you did in Project #2.

A sample file with one record per line might resemble the following

Buster Leggs 88 44 88 120
Charlie Horse 56 15 95 011
Wilma Moneylast 132 18 98 200
Willie Makit 75 30 94 121
Betty Wont 50 10 90 000
Eaton Buggs 79 16 97 111
Freda Spirit 110 23 90 220

Categorize each reading as Low, Normal or High. Print the result in the report detailed below. Normal range for each reading is as follows

Pulse 60-100

Respiration 12-20

Oxygen Level 92-100

Tag each record as according to the following and print any needed messages in the report for each record

CHECK – one indicator out of range
ALERT*** – two indicators out of range
CRITICAL***** – three indicators out of range

Room Name                  Pulse  Respir  Oxygen

120  Leggs, Buster            88 High=44  Low=88 ALERT***
011  Horse, Charlie      Low= 56      15      95 CHECK
200  Moneylast, Wilma   High=132      18      98 CHECK
111  Makit, Willie            75      20      94
000  Wont, Betty         Low= 50  Low=10  Low=90 CRITICAL****
111  Buggs, Eaton             79      16      97
220  Spirit, Freda      High=110 High=23  Low=90 CRITICAL****

Totals
2 Normal
1 ALERT
2 CHECK
2 CRITICAL

The Code I Currently have is:

\`#include "stdafx.h"
\#include \<iostream\>
\#include \<fstream\>
\#include \<string\>
\#include \<iomanip\>

using namespace std;

void Pause()
{
char junk;
cin.ignore(100,'\\n');
cout \<\< "\\n\\nPress enter to continue...";
cin.get(junk);
} // Pause()

int main()
{

//File Variables
ifstream PATIENTS_IN;
ofstream PATIENTS_LOG;

//Declare Variables and Constants
string Info, diag;
int pulseint, respint, O2int;
int count,count1, count2, count3,check, alert, critical;
string FirstName, LastName, Pulse, Resp, O2Lvl, RoomNum;

//Initalize Variables
count=0;
count1=1;
count2=0;
count3=0;
check=0;
alert=0;
critical=0;
Info= "no name read";
FirstName= "no name read";
LastName= "no name read";

//               \*\* Open Data Files \*\*

PATIENTS_LOG.open("D:\\PATIENTS.log");
if(PATIENTS_LOG)
{//Last file operation was successful
}
else
{//last file operation FAILED!
cout \<\< "PATIENTS_LOG open FAILED!" \<\< endl;

}
PATIENTS_IN.open("D:\\PATIENTS.txt");
if (PATIENTS_IN)
{//last file operation was successful
PATIENTS_LOG \<\< "PATIENTS_IN file open successful" \<\< endl;
}
else
{//last file operation FAILED!
cout \<\< "PATIENTS_IN file FAILED!" \<\< endl;
}

    getline(PATIENTS_IN, Info); //Priming read
    if(PATIENTS_IN)
    {//last file peration was successful

    }
    else
    {PATIENTS_LOG << "Input file Priming read FAILED" << endl;
    }
    count=1;

//Header
cout \<\<   "Room Name                  Pulse  Respir  Oxygen" \<\< endl;
cout \<\<"-----------------------------------------------------" \<\< endl;

while (!PATIENTS_IN.eof())
{PATIENTS_IN \>\> FirstName \>\>
LastName \>\> Pulse \>\> Resp \>\> O2Lvl \>\> RoomNum;
//Conversion
pulseint=stoi(Pulse);
respint=stoi(Resp);
O2int=stoi(O2Lvl);

if(pulseint\>100)
{Pulse="High=" + Pulse;
}
else if(pulseint\<60)
{Pulse="Low="+ Pulse;
}
else
{}//Do Nothing

if(respint\>20)
{Resp="High=" + Resp;
}
else if(respint\<12)
{Resp="Low="+ Resp;
}
else
{
}
if(O2int\>100)
{O2Lvl="High=" + O2Lvl;
}
else if(O2int\<92)
{O2Lvl="Low="+ O2Lvl;
}
else
{
}

if(pulseint\>100||pulseint\<60)
{count1++;
}
if(respint\>20||respint\<12)
{count2++;
}
if(O2int\>100||O2int\<92)
{count3++;
}

    if(count1==1)

{diag="CHECK--";
check++;}
if(count1==2)
{diag= "ALERT ***";
alert++;}
if(count1==3)
{diag= "CRITICAL***\*\*";
critical++;}
else
{diag="";
}

cout << left <<RoomNum << "  " << LastName << ", " << FirstName<< "";
cout << right <<""<<setw(12)<<Pulse <<right
cout << ""<<setw(10) <<Resp <<""<< right<<setw(10) << O2Lvl<<"\n";

}//End While
Pause();
return (0);
}

I have tried messing with the counters, others say they are having run time errors while trying to run the code while I don't get them, as well as alignment issues. I feel like Albert  Einstein's definition of insanity.


问:
Firebase Hosting copy and paste dynamic url not working
I'm stuck on where to search / what to search for regarding this issue, so I'm looking for some help.

I have a site that has user-generated posts with uid's. When someone navigates through the site, everything works totally fine, but when the url is copied and pasted into a new tab, I get a blank screen and a tab that won't load.

My routes go from "/" to

```<code><Route path="/listings" element={<ListingsPage />} />
</code>```

then to

```<code><Route path="/listings/:id" element={<ListingDetailPage />} />
</code>```

once the post is clicked on.

I'm not sure if this is a routing issue, or a dynamic link issue, or some type of issue that can be fixed with SSR / cloud functions.

Any help would be greatly appreciated. I know Firebase's open source cloud function github example is about 4 years old now, wondering if that's still applicable.

Body:
I'm stuck on where to search / what to search for regarding this issue, so I'm looking for some help.

I have a site that has user-generated posts with uid's. When someone navigates through the site, everything works totally fine, but when the url is copied and pasted into a new tab, I get a blank screen and a tab that won't load.

My routes go from "/" to

<Route path="/listings" element={<ListingsPage />} />

then to

<Route path="/listings/:id" element={<ListingDetailPage />} />

once the post is clicked on.

I'm not sure if this is a routing issue, or a dynamic link issue, or some type of issue that can be fixed with SSR / cloud functions.

Any help would be greatly appreciated. I know Firebase's open source cloud function github example is about 4 years old now, wondering if that's still applicable.


问:
SPARQL hanging when asked about two values
When I try to query what geographical areas two cities belong Wikidata SparQL query hangs. It works fine for each of the cites.

Any ideas what's going on and whether a workaround is needed?

```<code># This works:
# select ?z ?i where {
#   select ?z ?i where {
#     values ?z { wd:Q936768 }
#     ?z wdt:P131+ ?i.
#   }
# }

# This hangs:
select ?z ?i where {
  select ?z ?i where {
    values ?z { wd:Q936768 wd:Q159288 }
    ?z wdt:P131+ ?i.
  }
}

</code>```

Body:
When I try to query what geographical areas two cities belong Wikidata SparQL query hangs. It works fine for each of the cites.

Any ideas what's going on and whether a workaround is needed?

# This works:
# select ?z ?i where {
#   select ?z ?i where {
#     values ?z { wd:Q936768 }
#     ?z wdt:P131+ ?i.
#   }
# }

# This hangs:
select ?z ?i where {
  select ?z ?i where {
    values ?z { wd:Q936768 wd:Q159288 }
    ?z wdt:P131+ ?i.
  }
}


问:
Why one entity extratcted different values in different forms in one intent
I have my Dialogflow es agent working weid now.
Previously, I was training one intent understanding how many bedrooms the enduser mentioned, so I have an entity relating to that called $sc_bed It should be a list as a checked the "is list" in action and parameters

action and parametes I have for this Intent

Also I have 3 output contexts with this intent and store the key parameters mentioned
contexts

For my understanding, the sc_bed entity should be stored in all 3 contexts I mentioned above, with same value and format(which should be list rather than string)

However, the log shows that the entity in different contexts are different in both format and value, I will shoe the log here.

```<code>"name": "projects/xxxx/locations/global/agent/sessions/f4xxxxxxxx/contexts/search_criteria",
        "lifespanCount": 49,
        "parameters": {
          "is_visitor": "yes",
          "lead_first_name": "Test Lead",
          "sc_location": [],
          "clarify_renter.original": "",
          "lead_email.original": "",
          "buyer_reply_message2": "I’d like to get a little more information from you if that's ok.",
          "sc_timeframe.original": [],
          "buyer_interested_listing.original": "",
          "conversation.original": "",
          "lead_type": "renter",
          "buyer_reply_message": "I've got your preferences down here and I'll set up a search for places you might like.",
          "seller_market_snapshot.original": "",
          "lead_first_name.original": "",
          "assigned_agent_name.original": "",
          **"sc_bed": {
            "amount": 3
          },**
          "assigned_agent_name": "Test Assigned Agent",
          "reply_message_timeframe": "We would love to assist you with the renting process!",
          "sc_maxPrice.original": [],
          "reminder_price_reduced_link": "chime.me/pricereduced",
          "sc_timeframe_range": [],
          "search_listing_result.original": "",
          "sc_propertyType": [],
          "sc_priceRange": [],
          "sc_maxPrice": [],
        }
      },
      {
        "name": "projects/newagent-mxiwbg/locations/global/agent/sessions/f47970c6-49b2-c8a9-7aff-60316c185007/contexts/general_info",
        "lifespanCount": 49,
        "parameters": {
          "chime_action_add_tag": "AI: Interested",
          "buyer_reply_message2.original": "",
          "follow_up_event.original": "",
          "conversation": "renter_home_search",
          "conversation.original": "",
          "sc_feature.original": [],
          "sc_location": [],
          "lead_type": "renter",
          "reply_message_timeframe.original": "",
          "sc_priceRange": [],
          "buyer_reply_message.original": "",
          "sc_approxPrice": "",
          "sc_propertyType": [],
          "sc_propertyType.original": [],
          "clarify_renter.original": "",
          "sc_timeframe_range": [],
          "clarify_renter": "Yes",
          "sc_maxPrice.original": [],
          **"sc_bed": [
            {
              "amount.original": [
                "2",
                "3"
              ],
              "amount": [
                2,
                3
              ]
            }
          ],
          "sc_bed.original": [
            "2 or 3 bedroom"
          ],**
        }
      },
</code>```

What I am expecting are 2 points:

The entity in different contexts should be the same one at least for the entity extracted in this exactly same one intent

The entity info should keep the format I checked which is a list not a string.

Body:
I have my Dialogflow es agent working weid now.
Previously, I was training one intent understanding how many bedrooms the enduser mentioned, so I have an entity relating to that called $sc_bed It should be a list as a checked the "is list" in action and parameters

action and parametes I have for this Intent

Also I have 3 output contexts with this intent and store the key parameters mentioned
contexts

For my understanding, the sc_bed entity should be stored in all 3 contexts I mentioned above, with same value and format(which should be list rather than string)

However, the log shows that the entity in different contexts are different in both format and value, I will shoe the log here.

"name": "projects/xxxx/locations/global/agent/sessions/f4xxxxxxxx/contexts/search_criteria",
        "lifespanCount": 49,
        "parameters": {
          "is_visitor": "yes",
          "lead_first_name": "Test Lead",
          "sc_location": [],
          "clarify_renter.original": "",
          "lead_email.original": "",
          "buyer_reply_message2": "I’d like to get a little more information from you if that's ok.",
          "sc_timeframe.original": [],
          "buyer_interested_listing.original": "",
          "conversation.original": "",
          "lead_type": "renter",
          "buyer_reply_message": "I've got your preferences down here and I'll set up a search for places you might like.",
          "seller_market_snapshot.original": "",
          "lead_first_name.original": "",
          "assigned_agent_name.original": "",
          **"sc_bed": {
            "amount": 3
          },**
          "assigned_agent_name": "Test Assigned Agent",
          "reply_message_timeframe": "We would love to assist you with the renting process!",
          "sc_maxPrice.original": [],
          "reminder_price_reduced_link": "chime.me/pricereduced",
          "sc_timeframe_range": [],
          "search_listing_result.original": "",
          "sc_propertyType": [],
          "sc_priceRange": [],
          "sc_maxPrice": [],
        }
      },
      {
        "name": "projects/newagent-mxiwbg/locations/global/agent/sessions/f47970c6-49b2-c8a9-7aff-60316c185007/contexts/general_info",
        "lifespanCount": 49,
        "parameters": {
          "chime_action_add_tag": "AI: Interested",
          "buyer_reply_message2.original": "",
          "follow_up_event.original": "",
          "conversation": "renter_home_search",
          "conversation.original": "",
          "sc_feature.original": [],
          "sc_location": [],
          "lead_type": "renter",
          "reply_message_timeframe.original": "",
          "sc_priceRange": [],
          "buyer_reply_message.original": "",
          "sc_approxPrice": "",
          "sc_propertyType": [],
          "sc_propertyType.original": [],
          "clarify_renter.original": "",
          "sc_timeframe_range": [],
          "clarify_renter": "Yes",
          "sc_maxPrice.original": [],
          **"sc_bed": [
            {
              "amount.original": [
                "2",
                "3"
              ],
              "amount": [
                2,
                3
              ]
            }
          ],
          "sc_bed.original": [
            "2 or 3 bedroom"
          ],**
        }
      },

What I am expecting are 2 points:

The entity in different contexts should be the same one at least for the entity extracted in this exactly same one intent

The entity info should keep the format I checked which is a list not a string.


问:
Can I use Gitlab Personal token in Jenkins Global Pipeline Libraries?
I want to use Gitlab personal token in Jenkins Global Pipeline Libraries.
When I add a global gitlab api token kind, it is not visiable at credentials meum

What should I do?

My jenkins version is 2.319.3, git plugin version is 4.11.5


问:
Training accuracy not improve in CNN
My model is a SegNet with cross-entrophy loss. It is for liver and liver vessel medical segmentation.
And my problem is, when I use 725 cases for input, the accuracy increase normally.
The result of liver is good, but the result of vessel still need to be improve.
But when I increase my input data to 34,868 cases, the accuracy doesn't increase at the beginning, and then  jump up to about 95% accuracy.
Even the accuracy is about 95%, the result of my segmentation is very poor.
The result got no liver nor liver vessel, but full of background.
The training process with input 725 cases
The training process with input 34,868 cases

I am wondering if my model is too complicated, or I should modified the loss function.
I have change my loss function to focal loss and dice+focal loss, but they doesn't solve the problem or improve the result.

Title: Training accuracy not improve in CNN


问:
@nomiclabs/hardhat-etherscan: The address provided as argument contains a contract, but its bytecode doesn't match any of your local contracts
I deployed a contract with proxy implementation with hardhat:

This is the hardhat/script:

const { ethers, upgrades } = require("hardhat");

```<code>async function main() {
  const Test = await ethers.getContractFactory("Test");
  console.log("Deploying Test...");
  const box = await upgrades.deployProxy(Test, [10], {
    initializer: "initialize",
  });
  await box.deployed();
}

main();
</code>```

When you run a transaction to deploy a contract, we actually deploy 3 contracts:

Implementation Contract, in this case my simple custom Test conract

Proxy Admin contract

TransparentUpgradeableProxy

I successfully verified "Implementation" and "TransparentUpgradeableProxy" contract. That means my hardhat config and script are correct. But I get the error when I verify the ProxyAdmin contract.

```<code>// I load the environment variables from .env
env $(cat .env) npx hardhat verify --network goerli 0x45a87e0E632a4C269De0FEE6a6FbABF7B4f8b92d
</code>```

This is the error:

Error in plugin @nomiclabs/hardhat-etherscan: The address provided as
argument contains a contract, but its bytecode doesn't match any of
your local contracts.

Possible causes are:

Contract code changed after the deployment was executed. This includes code for seemingly unrelated contracts.

A solidity file was added, moved, deleted or renamed after the deployment was executed. This includes files for seemingly unrelated
contracts.

Solidity compiler settings were modified after the deployment was executed (like the optimizer, target EVM, etc.).

The given address is wrong.

The selected network (goerli) is wrong.

Since it says "its bytecode doesn't match any of your local contracts", I added this contract into the contracts directory

```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";

// Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
    constructor(
        address logic,
        address admin,
        bytes memory data
    ) payable TransparentUpgradeableProxy(logic, admin, data) {}
}
</code>```

But still same error:

Body:
I deployed a contract with proxy implementation with hardhat:

This is the hardhat/script:

const { ethers, upgrades } = require("hardhat");

async function main() {
  const Test = await ethers.getContractFactory("Test");
  console.log("Deploying Test...");
  const box = await upgrades.deployProxy(Test, [10], {
    initializer: "initialize",
  });
  await box.deployed();
}

main();

When you run a transaction to deploy a contract, we actually deploy 3 contracts:

Implementation Contract, in this case my simple custom Test conract

Proxy Admin contract

TransparentUpgradeableProxy

I successfully verified "Implementation" and "TransparentUpgradeableProxy" contract. That means my hardhat config and script are correct. But I get the error when I verify the ProxyAdmin contract.

// I load the environment variables from .env
env $(cat .env) npx hardhat verify --network goerli 0x45a87e0E632a4C269De0FEE6a6FbABF7B4f8b92d

This is the error:

Error in plugin @nomiclabs/hardhat-etherscan: The address provided as
argument contains a contract, but its bytecode doesn't match any of
your local contracts.

Possible causes are:

Contract code changed after the deployment was executed. This includes code for seemingly unrelated contracts.

A solidity file was added, moved, deleted or renamed after the deployment was executed. This includes files for seemingly unrelated
contracts.

Solidity compiler settings were modified after the deployment was executed (like the optimizer, target EVM, etc.).

The given address is wrong.

The selected network (goerli) is wrong.

Since it says "its bytecode doesn't match any of your local contracts", I added this contract into the contracts directory

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";

// Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
    constructor(
        address logic,
        address admin,
        bytes memory data
    ) payable TransparentUpgradeableProxy(logic, admin, data) {}
}

But still same error:


问:
Debug Failure. False expression: parameter should have errors when reporting errors
this is my first time building a Next JS app with typescript and experiencing this error which is not helpful to me. "Debug Failure. False expression: parameter should have errors when reporting errors"

when I saw the errors I think this has something to do with node modules so I tried to delete and install the node modules, still the same error happening

your text


问:
How to generate two war files using maven 1. full war file including all 3rd party dependencies jars 2. lightweight war without 3rd part jars
I have a requirement to generate 2 binaries

with all dependencies

with only my project code.

Can anyone please suggest a solution

exploring a plugin which helps for various applications


问:
SQL: Selecting 1 ROW from a TABLE where 3 COLUMNS have repeating values
Trying to select a single row from a table where 2 different columns have repeating values.  I'm trying to left join to a different table with unique values.  However this table causes duplicate values.

COLUMN1
Column2
COLUMN 3

NAME1
ID Numb1
DESCR1

NAME1
ID Numb1
DESCR2

NAME1
ID Numb2
DESCR1

NAME1
ID Numb3
DESCR1

NAME2
ID Numb3
DESCR3

NAME2
ID Numb3
DESCR1

NAME2
ID Numb4
DESCR1

NAME4
ID Numb4
DESCR1

I don't care which values for DESCR or ID Numb I get.

All I need one single row for each name with the corresponding ID Numb and DESCR attached to it.

I'm trying to join this to another table which already has unique values for NAME.

Help?


问:
Fail to load react nodejs app in AKS(Azure Kubenetics Service) but successfully in local docker container
I have a react nodejs application and it works fine running in local in the docker container, however, I am having trouble deploying it to AKS. I am not sure where my configuration gets wrong in AKS manifest file and I would appreciate your help!

I have one dockerfile for frontend(react) and one dockerfile for backend(nodejs). I also have a docker-compose.yml file. The file structure looks like below:

```<code>--api(dir for backend)
 --dockerfile
--my-app(dir for frontend)
 --dockerfile
--dockercompose.yml
</code>```

My docker file for frontend is as below:

```<code>FROM node:10
WORKDIR /my-app
COPY . .
RUN npm install && npm run build
EXPOSE 3000

CMD ["npm", "start"]
</code>```

My dockerfile for the backend is as below:

```<code>FROM node:10
WORKDIR /api
COPY ./package*.json .
RUN npm install
COPY . .
EXPOSE 3080

CMD ["node", "--require",  "./tracing.js",  "./server.js"]
</code>```

My docker-compose file is as below:

```<code>version: '3'
services:
  app-backend:
    build: ./api
    container_name: app-backend
    ports:
        - "3080:3080"

  app-frontend:
    depends_on:
      - app-backend
    build: ./my-app
    container_name: app-frontend
    ports:
        - "3000:3000"
    tty: true
</code>```

This is how my frontend package.json look like:

```<code>{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.5.0",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://app-backend:3080",
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

My AKS manifest file look like below:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app-backend
  template:
    metadata:
      labels:
        app: app-backend
    spec:
      containers:
      - name: app-backend
        image: danpoc0acr.azurecr.io/react-nodejs-aks-app-backend:v1
        ports:
        - containerPort: 3080

---
apiVersion: v1
kind: Service
metadata:
  name: app-backend
spec:
  ports:
  - port: 3080
  selector:
    app: app-backend
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-frontend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app-frontend
  template:
    metadata:
      labels:
        app: app-frontend
    spec:
      containers:
      - name: app-frontend
        image: danpoc0acr.azurecr.io/react-nodejs-aks-app-frontend:v1
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: app-frontend
spec:
  type: LoadBalancer
  ports:
  - port: 3000
  selector:
    app: app-frontend
</code>```

After I ran kubectl apply -f manifest.yml, it shows me below in CLI.

I can also see below in AKS, but if I try to load external IP in browser with or without port 3000, it never loads. I wonder if my manifest file is missing something. Or is there a way to debug where goes wrong?

Body:
I have a react nodejs application and it works fine running in local in the docker container, however, I am having trouble deploying it to AKS. I am not sure where my configuration gets wrong in AKS manifest file and I would appreciate your help!

I have one dockerfile for frontend(react) and one dockerfile for backend(nodejs). I also have a docker-compose.yml file. The file structure looks like below:

--api(dir for backend)
 --dockerfile
--my-app(dir for frontend)
 --dockerfile
--dockercompose.yml

My docker file for frontend is as below:

FROM node:10
WORKDIR /my-app
COPY . .
RUN npm install && npm run build
EXPOSE 3000

CMD ["npm", "start"]

My dockerfile for the backend is as below:

FROM node:10
WORKDIR /api
COPY ./package*.json .
RUN npm install
COPY . .
EXPOSE 3080

CMD ["node", "--require",  "./tracing.js",  "./server.js"]

My docker-compose file is as below:

version: '3'
services:
  app-backend:
    build: ./api
    container_name: app-backend
    ports:
        - "3080:3080"

  app-frontend:
    depends_on:
      - app-backend
    build: ./my-app
    container_name: app-frontend
    ports:
        - "3000:3000"
    tty: true

This is how my frontend package.json look like:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.5.0",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://app-backend:3080",
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

My AKS manifest file look like below:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app-backend
  template:
    metadata:
      labels:
        app: app-backend
    spec:
      containers:
      - name: app-backend
        image: danpoc0acr.azurecr.io/react-nodejs-aks-app-backend:v1
        ports:
        - containerPort: 3080

---
apiVersion: v1
kind: Service
metadata:
  name: app-backend
spec:
  ports:
  - port: 3080
  selector:
    app: app-backend
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-frontend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app-frontend
  template:
    metadata:
      labels:
        app: app-frontend
    spec:
      containers:
      - name: app-frontend
        image: danpoc0acr.azurecr.io/react-nodejs-aks-app-frontend:v1
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: app-frontend
spec:
  type: LoadBalancer
  ports:
  - port: 3000
  selector:
    app: app-frontend

After I ran kubectl apply -f manifest.yml, it shows me below in CLI.

I can also see below in AKS, but if I try to load external IP in browser with or without port 3000, it never loads. I wonder if my manifest file is missing something. Or is there a way to debug where goes wrong?


问:
Formik not setting initial value
I expect the input to have a default value of "default value" in the field but nothing shows up.</p>
```<code>import * as React from 'react';
import {Form, Formik} from "formik";

export default function CreateEvent() {
    return <Formik validate={() => alert("hooo")} initialValues={{
        name: 'default value'
    }} onSubmit={() => alert("hi")}>
        <Form>
            <input type="text" name="name"/>
        </Form>
    </Formik>
}
</code>```

Title: Formik not setting initial value

Body:
I expect the input to have a default value of "default value" in the field but nothing shows up.

import * as React from 'react';
import {Form, Formik} from "formik";

export default function CreateEvent() {
    return <Formik validate={() => alert("hooo")} initialValues={{
        name: 'default value'
    }} onSubmit={() => alert("hi")}>
        <Form>
            <input type="text" name="name"/>
        </Form>
    </Formik>
}


问:
Append new line of string in specific line in the 3-layer hierarchical structured text file with Python
For example the content in 3-layer hierarchical structured text file (component, valueX and Value_X) is like this:

```<code>Component_X
   Value1
      Value_A

      Value_B
      #Here is where i want to append the new string#

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_Y
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_X
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B
      #Here is where i want to append the new string#

      Value_C
</code>```

My question is, how can I append a new string at the specific component and specific Value1 or Value2 such as I want to append new string in the Value_B of Value1 of the Component_X by using Python? Hopefully anybody can help this out.

This is the code that works for now with the helps from one of the stackoverflow user here, but this code only work for two layer, what should I add for it to find one-by-one layer which is start from  Component first, then search for valueX (Value1 or Value2), lastly search and append new under value_X (Value_A, Value_B or Value_C).

```<code>def insert_after(filename, component, after_this, value):
    in_component = False
    with open(filename, 'r+') as text:
        out_lines = []
        for line in text.readlines():
            if not line[0].isspace():
                in_component = line.startswith(component)
            out_lines.append(line)
            if in_component and line.strip() == after_this:
                pad = ' ' * (len(line) - len(line.lstrip()))
                out_lines.append(f"{pad}{value}\n")
        text.seek(0)
        text.writelines(out_lines)

insert_after('foo.txt', 'Component_X', 'Value_B', 'true')
</code>```

My expected output after write the new string into the text file is:

```<code>Component_X
   Value1
      Value_A

      Value_B
      true

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_Y
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_X
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B
      true

      Value_C

</code>```

Body:
For example the content in 3-layer hierarchical structured text file (component, valueX and Value_X) is like this:

Component_X
   Value1
      Value_A

      Value_B
      #Here is where i want to append the new string#

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_Y
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_X
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B
      #Here is where i want to append the new string#

      Value_C

My question is, how can I append a new string at the specific component and specific Value1 or Value2 such as I want to append new string in the Value_B of Value1 of the Component_X by using Python? Hopefully anybody can help this out.

This is the code that works for now with the helps from one of the stackoverflow user here, but this code only work for two layer, what should I add for it to find one-by-one layer which is start from  Component first, then search for valueX (Value1 or Value2), lastly search and append new under value_X (Value_A, Value_B or Value_C).

def insert_after(filename, component, after_this, value):
    in_component = False
    with open(filename, 'r+') as text:
        out_lines = []
        for line in text.readlines():
            if not line[0].isspace():
                in_component = line.startswith(component)
            out_lines.append(line)
            if in_component and line.strip() == after_this:
                pad = ' ' * (len(line) - len(line.lstrip()))
                out_lines.append(f"{pad}{value}\n")
        text.seek(0)
        text.writelines(out_lines)

insert_after('foo.txt', 'Component_X', 'Value_B', 'true')

My expected output after write the new string into the text file is:

Component_X
   Value1
      Value_A

      Value_B
      true

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_Y
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B

      Value_C

Component_X
   Value1
      Value_A

      Value_B

      Value_C

   Value2
      Value_A

      Value_B
      true

      Value_C


问:
How to get the data of the cell below as the header just in case the header is merged?
I am dealing with a lot of excel data files. There are some files with merged headers (each file has different data and has a different header). Is there a way I can handle the case: if the header is merged, will the data of the cell below to compensate for the merged part and and put it in the dataframe?
Below is an illustration
enter image description here

```<code>
danhSach = list(df.columns)

df.columns = danhSach

for i in range(len(danhSach)):

    if "A certain fixed keyword" in str(danhSach[i]):
        danhSach[i] = str(df[danhSach[i]][0])

        danhSach[i + 1] = str(df[danhSach[i+1]][0])

df.columns = danhSach

</code>```

I tried doing it with A certain fixed keyword , but it's not optimal

Get the data of the cell below as the header just in case the header is merged

Body:
I am dealing with a lot of excel data files. There are some files with merged headers (each file has different data and has a different header). Is there a way I can handle the case: if the header is merged, will the data of the cell below to compensate for the merged part and and put it in the dataframe?
Below is an illustration
enter image description here

danhSach = list(df.columns)

df.columns = danhSach

for i in range(len(danhSach)):

    if "A certain fixed keyword" in str(danhSach[i]):
        danhSach[i] = str(df[danhSach[i]][0])

        danhSach[i + 1] = str(df[danhSach[i+1]][0])

df.columns = danhSach

I tried doing it with A certain fixed keyword , but it's not optimal

Get the data of the cell below as the header just in case the header is merged


问:
When I try to dispose of than remote side TRACK_REMOVED event is not called
I am trying to remove the desktop track for all participants who joined the meeting but when I try to dispose of the track than not called the TRACK_REMOVED event listener.

If have some ideas please reply.

```<code>room.on(JitsiMeetJS.events.conference.TRACK_REMOVED, (track) => {
    console.log("TRACK_REMOVED", track)
  })
</code>```
```<code>oldTrack.dispose();
</code>```

My expectation is when I dispose of the track that time TRACK_REMOVED called for every participant's side also.

Body:
I am trying to remove the desktop track for all participants who joined the meeting but when I try to dispose of the track than not called the TRACK_REMOVED event listener.

If have some ideas please reply.

room.on(JitsiMeetJS.events.conference.TRACK_REMOVED, (track) => {
    console.log("TRACK_REMOVED", track)
  })

oldTrack.dispose();

My expectation is when I dispose of the track that time TRACK_REMOVED called for every participant's side also.


问:
Failed to save modifications to the server. Error returned: 'OLE DB or ODBC error: [DataSource.Error]
I am using the SSAS to develop the tabular model. I am able to extract the data from the database. However, when I try to deploy I keep on getting this error.

Failed to save modifications to the server. Error returned: 'OLE DB or ODBC error: [DataSource.Error] An error happened while reading data from the provider: 'Object reference not set to an instance of an object.'.  '.

I have tried many solution like:

Check my database connection

Check the datatype in the table

However, none of the solution works.

Is there a way to find the issue with the Object reference not set to an instance of an object error?


问:
HTTPS certificate error while running ASP.Net Core application in docker container
I have created an ASP.Net Core application and compiled it using a YAML Pipeline. I am publishing the output in docker image and pushed in Azure Container Registry.
The endpoint URL for the application is https . But I am getting below error when I try to run the container locally.

```<code>crit: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to start Kestrel.
System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date.
To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
   at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions, Action`1 configureOptions)
   at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func`2 createBinding)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
</code>```

Below is the Docker file content. In the YAM pipeline I have published the compiled result in Output folder.

```<code>FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base

EXPOSE 8080
ENV ASPNETCORE_URLS=https://*:8080
FROM base AS final

WORKDIR /app
COPY ./Output/ /app
RUN ls

RUN addgroup --group t--gid 2000 \
&& adduser \
--uid 1000 \
--gid 2000 \
"tst"
RUN chown tst:tstgr /app
USER tst:tstgr

ENTRYPOINT ["dotnet", "testsite.dll"]
</code>```

Here is the code for

```<code> public static ConnectionMultiplexer _redis;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

                services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, (OpenIdConnectOptions options) =>
                {
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;

                });

                var redisConnectionString = Environment.GetEnvironmentVariable("CacheConnection");

                if (string.IsNullOrEmpty(redisConnectionString))
                {
                    throw new Exception($"App setting RTC:CacheConnection is either empty or missing");
                }

                _redis = ConnectionMultiplexer.Connect(redisConnectionString);
                services.AddHttpContextAccessor();
                services.AddControllersWithViews(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                    options.Filters.Add(new AuthorizeFilter(policy));
                }).AddJsonOptions(jsonOptions => jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null);

                // Add the Kendo UI services to the services container.
                services.AddKendo();
                services.AddRazorPages();
                services.AddScoped<ICacheService, CacheService>();
                services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseHttpsRedirection();

            app.UseRouting();
            // Configure Kendo UI
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(name: "Ins",
                pattern: "Ins/{*Manage}",
                defaults: new { controller = "Ins", action = "Manage" });
            });s
        }
        private async static Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext ctx)
        {
            var claims = new ClaimsPrincipal();
            const string AZUREADGRAPH_RESOURCE = @"https://graph.windows.net/";
            var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

            string userId = ctx.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var cache = new adowebhub.Controllers.RedisTokenCache(ctx.Options.ClientId, userId);
            var authContext = new AuthenticationContext(ctx.Options.Authority, cache);
            var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                ctx.ProtocolMessage.Code, new Uri(ctx.TokenEndpointRequest.RedirectUri), credential, resource: AZUREADGRAPH_RESOURCE);
            ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
</code>```

It seems like I need to attach a certificate to make it run but I am unclear on how to do that. When I run the application without docker it works fine.
Please suggest.

Body:
I have created an ASP.Net Core application and compiled it using a YAML Pipeline. I am publishing the output in docker image and pushed in Azure Container Registry.
The endpoint URL for the application is https . But I am getting below error when I try to run the container locally.

crit: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to start Kestrel.
System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date.
To generate a developer certificate run 'dotnet dev-certs https'. To trust the certificate (Windows and macOS only) run 'dotnet dev-certs https --trust'.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
   at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions, Action`1 configureOptions)
   at Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseHttps(ListenOptions listenOptions)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func`2 createBinding)
   at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)

Below is the Docker file content. In the YAM pipeline I have published the compiled result in Output folder.

FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base

EXPOSE 8080
ENV ASPNETCORE_URLS=https://*:8080
FROM base AS final

WORKDIR /app
COPY ./Output/ /app
RUN ls

RUN addgroup --group t--gid 2000 \
&& adduser \
--uid 1000 \
--gid 2000 \
"tst"
RUN chown tst:tstgr /app
USER tst:tstgr

ENTRYPOINT ["dotnet", "testsite.dll"]

Here is the code for

 public static ConnectionMultiplexer _redis;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

                services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, (OpenIdConnectOptions options) =>
                {
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;

                });

                var redisConnectionString = Environment.GetEnvironmentVariable("CacheConnection");

                if (string.IsNullOrEmpty(redisConnectionString))
                {
                    throw new Exception($"App setting RTC:CacheConnection is either empty or missing");
                }

                _redis = ConnectionMultiplexer.Connect(redisConnectionString);
                services.AddHttpContextAccessor();
                services.AddControllersWithViews(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                    options.Filters.Add(new AuthorizeFilter(policy));
                }).AddJsonOptions(jsonOptions => jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null);

                // Add the Kendo UI services to the services container.
                services.AddKendo();
                services.AddRazorPages();
                services.AddScoped<ICacheService, CacheService>();
                services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseHttpsRedirection();

            app.UseRouting();
            // Configure Kendo UI
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(name: "Ins",
                pattern: "Ins/{*Manage}",
                defaults: new { controller = "Ins", action = "Manage" });
            });s
        }
        private async static Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext ctx)
        {
            var claims = new ClaimsPrincipal();
            const string AZUREADGRAPH_RESOURCE = @"https://graph.windows.net/";
            var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

            string userId = ctx.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var cache = new adowebhub.Controllers.RedisTokenCache(ctx.Options.ClientId, userId);
            var authContext = new AuthenticationContext(ctx.Options.Authority, cache);
            var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                ctx.ProtocolMessage.Code, new Uri(ctx.TokenEndpointRequest.RedirectUri), credential, resource: AZUREADGRAPH_RESOURCE);
            ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }

It seems like I need to attach a certificate to make it run but I am unclear on how to do that. When I run the application without docker it works fine.
Please suggest.


问:
docker container stops after docker run
I have a docker file which when built and run stops. I am trying to run both client and server in one docker container. If there is any solution to use docker-compose, then that is already in place and working fine. Please advise how to keep the container up and running using docker run. Thanks!

Here is my docker file, package.json and screenshot of folder structure.

DockerFile contents:

```<code>FROM node:14.14.0-alpine
RUN apk update && apk add bash
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
WORKDIR /app
EXPOSE 3000
EXPOSE 4565
CMD ["npm","run","prebuild"]
</code>```

docker build: command:

```<code>docker build -t sample .
</code>```

docker run command:

```<code>docker run -d -it --name sm -v `pwd`:/app sample
</code>```

Package.json:

Title: docker container stops after docker run

Body:
I have a docker file which when built and run stops. I am trying to run both client and server in one docker container. If there is any solution to use docker-compose, then that is already in place and working fine. Please advise how to keep the container up and running using docker run. Thanks!

Here is my docker file, package.json and screenshot of folder structure.

DockerFile contents:

FROM node:14.14.0-alpine
RUN apk update && apk add bash
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
WORKDIR /app
EXPOSE 3000
EXPOSE 4565
CMD ["npm","run","prebuild"]

docker build: command:

docker build -t sample .

docker run command:

docker run -d -it --name sm -v `pwd`:/app sample

Package.json:


问:
Not able to take the MongoDB backup/dump using node js
When executing the written script, it exit with code 'one' while it should save the dump of the database

const cron = require('node-cron');
const { exit } = require('process');
const spawn = require('child_process').spawn;

    let backupProcess = spawn('mongodump', [
        '--host=localhost',
        '--port=27017',
        '--out=.',
        '--db=testdb',
    ], {shell: true});

    backupProcess.on('exit', (code, signal) => {
        console.log('Function called');
        if(code)
            console.log('Backup process exited with code ', code);
        else if (signal)
            console.error('Backup process was killed with singal ', signal);
        else
            console.log('Successfully backedup the database')
    });
```
<p>while executing the same through VS code terminal, getting following error,</p>
```Function called
Backup process exited with code  1 while should  save the dump at given location`your text`
```

Actual Result : Backup process exited with code  1

Expected result : Must dump the database

Body:
When executing the written script, it exit with code 'one' while it should save the dump of the database

const cron = require('node-cron');
const { exit } = require('process');
const spawn = require('child_process').spawn;

    let backupProcess = spawn('mongodump', [
        '--host=localhost',
        '--port=27017',
        '--out=.',
        '--db=testdb',
    ], {shell: true});

    backupProcess.on('exit', (code, signal) => {
        console.log('Function called');
        if(code)
            console.log('Backup process exited with code ', code);
        else if (signal)
            console.error('Backup process was killed with singal ', signal);
        else
            console.log('Successfully backedup the database')
    });

while executing the same through VS code terminal, getting following error,

Function called
Backup process exited with code  1 while should  save the dump at given location`your text`

Actual Result : Backup process exited with code  1

Expected result : Must dump the database


问:
Error during compilation stating undefined references in C++
Sorry for the code dump

The code is being typed into a command line.

Graph.cpp

```<code>#ifndef GRAPH_CPP
#define GRAPH_CPP
#include <map>
#include <set>
#include <queue>
#include "Graph.h"
#include <iostream>

using namespace std;

template <typename T>
Graph<T>::Graph(){

}
//check if an edge exists between v and w
template <typename T>
bool Graph<T>::hasEdge(T v, T w) const
{
if (adjMap.find(v) == adjMap.end())
return false;
if (adjMap.at(v).find(w) != adjMap.at(v).end())
return true;
else
return false;
}

template <typename T>
void Graph<T>::addEdge(T v, T w) {
adjMap[v].insert(w);
adjMap[w].insert(v);
}

template <typename T>
int Graph<T>::BFS(T s, T t, map<T,int>& distance, map<T,T>& go_through) const
{
if (adjMap.find(s) == adjMap.end() || adjMap.find(t) == adjMap.end())
{
cout << "Invalid source vertex or/and destination vertex!" << endl;
return INVALID_VERTEX;
}
//Mark all the vertices with current distance to s: -1
for (auto it = adjMap.begin(); it != adjMap.end(); it++) {
distance[it->first] = NOPATH;
}

//Create queue for bfs
queue<T> bfs;
bfs.push(s);
//mark distance from source s to s:0
distance[s] = 0;
//mark shortest path to given source s going through s
go_through[s] = s;
T current = bfs.front();
while (!bfs.empty() && current != t) {
current = bfs.front();
set<T> adjVertices = adjMap.at(current);
for (auto i = adjVertices.begin(); i != adjVertices.end(); i++) {
if (distance[*i] == NOPATH) {
distance[*i] = distance[current] + 1;
go_through[*i] = current;
bfs.push(*i);
}
}
bfs.pop();
}
return distance[t];

}

#endif
</code>```

Graph.h

```<code>#ifndef GRAPH_H
#define GRAPH_H

#include <map>
#include <set>

using namespace std;

const int NOPATH = -1;
const int INVALID_VERTEX = -2;

template <class T>
class Graph
{
   public:
    // default constructor
    Graph();

    // to check if an edge exists between v and w
    bool hasEdge(T v, T w) const;

    // to add an edge beween v and w to the graph
    void addEdge(T v, T w);

    // Apply BFS traversal to find the shortest path from the given source s to destination t
    // return the distnace from s to t
    // if s or t does not exist, return INVALID_VERTEX (=-2)
    // if there is no path from s to t, return NOPATH (=-1)
    // store the shortest path distance from the given source s  to vertex w in distance map<w, distance>
    // store which next vertex to go through on the shortest path to the given source s in go_through map<w, v>.
    // Here a pair <w, v> in go_through map represents on the shortest path from w to the given source s, it needs to take the path: w-->v...-->s
    int BFS(T s, T t, map<T, int>& distance, map<T, T>& go_through) const;

   private:
    //represent the mapping from a Vertex, say u (key) to a set of vertices (value) which directly connect to u
    map<T, set<T> > adjMap;
};

#endif   /* GRAPH_H */
</code>```

PA3Part2.cpp

```<code>#include <vector>
#include <iostream>
#include <string>
#include <fstream>
#include <stack>
#include <algorithm>     // for transform() function
#include "Graph.h"

using namespace std;

// declare global variable (constant only)
const int ARGUMENTS = 2;   // define the required command line arguments

// define a function to decide the collection of edges for a graph
// using "Word Buckets Approach"
Graph<string> WordBuckets_addEdges(const vector<string>& words);

int main(int argc, char* argv[])
{
    // Check whether the number of command line arguments match the required one
    if (argc != ARGUMENTS)
    {
        cout << "Warning: need exactly " << ARGUMENTS-1 << " command line argument." << endl;
        cout << "Usage: " << argv[0] << " inputfile_name" << endl;
        return 1;
    }

    ifstream in_file;
    in_file.open(argv[1]);
    // Check whether the input file can be open successfully or not
    if (!in_file.good())
    {
        cout << "Warning: cannot open file named " << argv[1] << "!" << endl;
        return 2;
    }

    // Read data from the input file, assume "good data" from the input file
    // each line of the input file constains one word from English dictionary
    string word;
    vector<string> words;

    while (in_file >> word)
    {
        // convert word to all lower-case letters
        // if assume that each word from the input file is in lower-case letters, this step can be ignored
        transform(word.begin(), word.end(), word.begin(), ::tolower);
        words.push_back(word);
    }
    // close the input file
    in_file.close();

    // build the graph based on the collection of words
    // each word in the collection represents a Vertex in the graph
    // there is an edge from one word to another if these two words are only different by a single letter
    Graph<string> wordsG = WordBuckets_addEdges(words);

    string word1, word2;

    while (true)
    {
        cout << endl << endl;
        cout << "Welcome to CS216 Word Ladder!" << endl;
        cout << "Please give me two English words, and I will convert the first into the second by modifying one letter at a time." << endl;
        cout << "For the Demo purpose, let us try four-letter words only." << endl;
        cout << "Please type the FIRST four-letter word (or type Enter to quit): " << endl;
        getline(cin, word1);

        if (word1 == "")
            break;

        cout << "Please type the SECOND four-letter word (or type Enter to quit): " << endl;
        getline(cin, word2);

        if (word2 == "")
            break;

        // convert both word1 and word2 to all lower-case letters
        transform(word1.begin(), word1.end(), word1.begin(), ::tolower);
        transform(word2.begin(), word2.end(), word2.begin(), ::tolower);

        map<string,int> distance;
            map<string, string> go_through;
        int dis = wordsG.BFS(word1, word2, distance, go_through);
        // Display the ladder distance from word1 to word2
        // Display the shortest path on the word ladder from word1 to word2
        // the ladder distance is defined as the number of edges on the shortest path from one vertex to another
        // the ladder distance of the same vertex to itself is 0
        // if word1 and word2 are the same word, your program should display "Two words should be different."
        // there is no path from word1 to word2 if its ladder distance is -1
        // there is no path from word1 to word2 if its ladder distance is -2, which means either word1 or/and word2 is invalid
        if ( dis == NOPATH || dis == INVALID_VERTEX)
            cout << "There is no path from [" << word1 << "] to [" << word2 << "]" << endl;
        else if ( dis == 0)
        {
            cout << "Two words should be different." << endl;
        }
        else
        {
            cout << "The ladder distance from [" << word1 << "] to [" << word2 << "] is " << dis << "-step away." << endl;
            cout << "A ladder from [" << word1 << "] to [" << word2 << "]:" << endl;
        string nextVertex = word2;
            cout << word2;
            while (go_through[nextVertex] != word1)
            {
                cout << " ---> " << go_through[nextVertex];
                nextVertex = go_through[nextVertex];
            }
            cout << " ---> " << word1 << endl;
        }
    }

    cout << "Thank you for using this program, bye..." << endl;
    return 0;
}

/* define a function to decide the collection of edges for a graph
 * using "Word Buckets Approach"
 * Purpose: build a graph based on the collection of vertices
 *          each word stored in the vector, represents a Vertex in the graph
 *          there is an edge from one word to another
 *          if these two words are only different by a single letter
 *@param words vector<string>: representing the collection of vertices, each string stored in the vector forms a vertex
 *@return Graph<string>: representing the graph built by
 *                       (1) the collection of vertices from words;
 *                       (2) the collection of edges are decided by if any two words are only different by a single letter
 *                         e.g. there is an edge between "cool" and "pool", but there is no edge between "cool" and "poll"
 *
 */
Graph<string> WordBuckets_addEdges(const vector<string>& words)
{
    // build the graph
    // there is an edge from one word to another if the two words are only different by a single letter.
    // use "Word Bucket" solution described in Lab11 to efficiently decide whether an edge between two vertices
    Graph<string> wordsG;

    // provide your code here
    // implement "Word Buckets Approach" to decide if you need to call addEdge() member function between two vertices
    map<string, vector<string> > bucket;
    for (int i = 0; i < words.size(); i++) {
        for (int j = 0; j < words[i].length(); j++) {
            string key = words[i];
            key[j] = '?';
            bucket[key].push_back(words[i]);
        }
    }

    for (auto k = bucket.begin(); k != bucket.end(); k++) {
        for (int s = 0; k->second.size(); s++) {
            for (int m = 0; m<k->second.size(); m++) {
                if (k->second[s] != k->second[m]) {
                    wordsG.addEdge(k->second[s],k->second[m]);
                }
            }
        }
    }
    return wordsG;
}
</code>```

So after I completed the code and fixed all the errors, I tried compiling PA3Part2.cpp and Graph.cpp together into an executable program, which gave me this error below.

Error when attempting to compile:

/usr/bin/ld: /tmp/ccHsDrH9.o: in function main': PA3Part2.cpp:(.text+0x4ef): undefined reference to Graph<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >::BFS(std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::map<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, int, std::less<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits, std::allocator > const, int> > >&, std::map<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::less<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits, std::allocator > const, std::__cxx11::basic_string<char, std::char_traits, std::allocator > > > >&) const' /usr/bin/ld: /tmp/ccHsDrH9.o: in function WordBuckets_addEdges(std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&)': PA3Part2.cpp:(.text+0x9f0): undefined reference to Graph<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >::Graph()' /usr/bin/ld: PA3Part2.cpp:(.text+0xcca): undefined reference to `Graph<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >::addEdge(std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::__cxx11::basic_string<char, std::char_traits, std::allocator >)' collect2: error: ld returned 1 exit status

I'm stuck on what to do here, please help and thank you.

I recall having this problem before and not having as much trouble as I am with this.

Body:
Sorry for the code dump

The code is being typed into a command line.

Graph.cpp

#ifndef GRAPH_CPP
#define GRAPH_CPP
#include <map>
#include <set>
#include <queue>
#include "Graph.h"
#include <iostream>

using namespace std;

template <typename T>
Graph<T>::Graph(){

}
//check if an edge exists between v and w
template <typename T>
bool Graph<T>::hasEdge(T v, T w) const
{
if (adjMap.find(v) == adjMap.end())
return false;
if (adjMap.at(v).find(w) != adjMap.at(v).end())
return true;
else
return false;
}

template <typename T>
void Graph<T>::addEdge(T v, T w) {
adjMap[v].insert(w);
adjMap[w].insert(v);
}

template <typename T>
int Graph<T>::BFS(T s, T t, map<T,int>& distance, map<T,T>& go_through) const
{
if (adjMap.find(s) == adjMap.end() || adjMap.find(t) == adjMap.end())
{
cout << "Invalid source vertex or/and destination vertex!" << endl;
return INVALID_VERTEX;
}
//Mark all the vertices with current distance to s: -1
for (auto it = adjMap.begin(); it != adjMap.end(); it++) {
distance[it->first] = NOPATH;
}

//Create queue for bfs
queue<T> bfs;
bfs.push(s);
//mark distance from source s to s:0
distance[s] = 0;
//mark shortest path to given source s going through s
go_through[s] = s;
T current = bfs.front();
while (!bfs.empty() && current != t) {
current = bfs.front();
set<T> adjVertices = adjMap.at(current);
for (auto i = adjVertices.begin(); i != adjVertices.end(); i++) {
if (distance[*i] == NOPATH) {
distance[*i] = distance[current] + 1;
go_through[*i] = current;
bfs.push(*i);
}
}
bfs.pop();
}
return distance[t];

}

#endif

Graph.h

#ifndef GRAPH_H
#define GRAPH_H

#include <map>
#include <set>

using namespace std;

const int NOPATH = -1;
const int INVALID_VERTEX = -2;

template <class T>
class Graph
{
   public:
    // default constructor
    Graph();

    // to check if an edge exists between v and w
    bool hasEdge(T v, T w) const;

    // to add an edge beween v and w to the graph
    void addEdge(T v, T w);

    // Apply BFS traversal to find the shortest path from the given source s to destination t
    // return the distnace from s to t
    // if s or t does not exist, return INVALID_VERTEX (=-2)
    // if there is no path from s to t, return NOPATH (=-1)
    // store the shortest path distance from the given source s  to vertex w in distance map<w, distance>
    // store which next vertex to go through on the shortest path to the given source s in go_through map<w, v>.
    // Here a pair <w, v> in go_through map represents on the shortest path from w to the given source s, it needs to take the path: w-->v...-->s
    int BFS(T s, T t, map<T, int>& distance, map<T, T>& go_through) const;

   private:
    //represent the mapping from a Vertex, say u (key) to a set of vertices (value) which directly connect to u
    map<T, set<T> > adjMap;
};

#endif   /* GRAPH_H */

PA3Part2.cpp

#include <vector>
#include <iostream>
#include <string>
#include <fstream>
#include <stack>
#include <algorithm>     // for transform() function
#include "Graph.h"

using namespace std;

// declare global variable (constant only)
const int ARGUMENTS = 2;   // define the required command line arguments

// define a function to decide the collection of edges for a graph
// using "Word Buckets Approach"
Graph<string> WordBuckets_addEdges(const vector<string>& words);

int main(int argc, char* argv[])
{
    // Check whether the number of command line arguments match the required one
    if (argc != ARGUMENTS)
    {
        cout << "Warning: need exactly " << ARGUMENTS-1 << " command line argument." << endl;
        cout << "Usage: " << argv[0] << " inputfile_name" << endl;
        return 1;
    }

    ifstream in_file;
    in_file.open(argv[1]);
    // Check whether the input file can be open successfully or not
    if (!in_file.good())
    {
        cout << "Warning: cannot open file named " << argv[1] << "!" << endl;
        return 2;
    }

    // Read data from the input file, assume "good data" from the input file
    // each line of the input file constains one word from English dictionary
    string word;
    vector<string> words;

    while (in_file >> word)
    {
        // convert word to all lower-case letters
        // if assume that each word from the input file is in lower-case letters, this step can be ignored
        transform(word.begin(), word.end(), word.begin(), ::tolower);
        words.push_back(word);
    }
    // close the input file
    in_file.close();

    // build the graph based on the collection of words
    // each word in the collection represents a Vertex in the graph
    // there is an edge from one word to another if these two words are only different by a single letter
    Graph<string> wordsG = WordBuckets_addEdges(words);

    string word1, word2;

    while (true)
    {
        cout << endl << endl;
        cout << "Welcome to CS216 Word Ladder!" << endl;
        cout << "Please give me two English words, and I will convert the first into the second by modifying one letter at a time." << endl;
        cout << "For the Demo purpose, let us try four-letter words only." << endl;
        cout << "Please type the FIRST four-letter word (or type Enter to quit): " << endl;
        getline(cin, word1);

        if (word1 == "")
            break;

        cout << "Please type the SECOND four-letter word (or type Enter to quit): " << endl;
        getline(cin, word2);

        if (word2 == "")
            break;

        // convert both word1 and word2 to all lower-case letters
        transform(word1.begin(), word1.end(), word1.begin(), ::tolower);
        transform(word2.begin(), word2.end(), word2.begin(), ::tolower);

        map<string,int> distance;
            map<string, string> go_through;
        int dis = wordsG.BFS(word1, word2, distance, go_through);
        // Display the ladder distance from word1 to word2
        // Display the shortest path on the word ladder from word1 to word2
        // the ladder distance is defined as the number of edges on the shortest path from one vertex to another
        // the ladder distance of the same vertex to itself is 0
        // if word1 and word2 are the same word, your program should display "Two words should be different."
        // there is no path from word1 to word2 if its ladder distance is -1
        // there is no path from word1 to word2 if its ladder distance is -2, which means either word1 or/and word2 is invalid
        if ( dis == NOPATH || dis == INVALID_VERTEX)
            cout << "There is no path from [" << word1 << "] to [" << word2 << "]" << endl;
        else if ( dis == 0)
        {
            cout << "Two words should be different." << endl;
        }
        else
        {
            cout << "The ladder distance from [" << word1 << "] to [" << word2 << "] is " << dis << "-step away." << endl;
            cout << "A ladder from [" << word1 << "] to [" << word2 << "]:" << endl;
        string nextVertex = word2;
            cout << word2;
            while (go_through[nextVertex] != word1)
            {
                cout << " ---> " << go_through[nextVertex];
                nextVertex = go_through[nextVertex];
            }
            cout << " ---> " << word1 << endl;
        }
    }

    cout << "Thank you for using this program, bye..." << endl;
    return 0;
}

/* define a function to decide the collection of edges for a graph
 * using "Word Buckets Approach"
 * Purpose: build a graph based on the collection of vertices
 *          each word stored in the vector, represents a Vertex in the graph
 *          there is an edge from one word to another
 *          if these two words are only different by a single letter
 *@param words vector<string>: representing the collection of vertices, each string stored in the vector forms a vertex
 *@return Graph<string>: representing the graph built by
 *                       (1) the collection of vertices from words;
 *                       (2) the collection of edges are decided by if any two words are only different by a single letter
 *                         e.g. there is an edge between "cool" and "pool", but there is no edge between "cool" and "poll"
 *
 */
Graph<string> WordBuckets_addEdges(const vector<string>& words)
{
    // build the graph
    // there is an edge from one word to another if the two words are only different by a single letter.
    // use "Word Bucket" solution described in Lab11 to efficiently decide whether an edge between two vertices
    Graph<string> wordsG;

    // provide your code here
    // implement "Word Buckets Approach" to decide if you need to call addEdge() member function between two vertices
    map<string, vector<string> > bucket;
    for (int i = 0; i < words.size(); i++) {
        for (int j = 0; j < words[i].length(); j++) {
            string key = words[i];
            key[j] = '?';
            bucket[key].push_back(words[i]);
        }
    }

    for (auto k = bucket.begin(); k != bucket.end(); k++) {
        for (int s = 0; k->second.size(); s++) {
            for (int m = 0; m<k->second.size(); m++) {
                if (k->second[s] != k->second[m]) {
                    wordsG.addEdge(k->second[s],k->second[m]);
                }
            }
        }
    }
    return wordsG;
}

So after I completed the code and fixed all the errors, I tried compiling PA3Part2.cpp and Graph.cpp together into an executable program, which gave me this error below.

Error when attempting to compile:

/usr/bin/ld: /tmp/ccHsDrH9.o: in function main': PA3Part2.cpp:(.text+0x4ef): undefined reference to Graph<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >::BFS(std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::map<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, int, std::less<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits, std::allocator > const, int> > >&, std::map<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::less<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits, std::allocator > const, std::__cxx11::basic_string<char, std::char_traits, std::allocator > > > >&) const' /usr/bin/ld: /tmp/ccHsDrH9.o: in function WordBuckets_addEdges(std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&)': PA3Part2.cpp:(.text+0x9f0): undefined reference to Graph<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >::Graph()' /usr/bin/ld: PA3Part2.cpp:(.text+0xcca): undefined reference to `Graph<std::__cxx11::basic_string<char, std::char_traits, std::allocator > >::addEdge(std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::__cxx11::basic_string<char, std::char_traits, std::allocator >)' collect2: error: ld returned 1 exit status

I'm stuck on what to do here, please help and thank you.

I recall having this problem before and not having as much trouble as I am with this.


问:
Content-Disposition utf8 encoding (golang)
It is implementing a file download API

The problem is that the Korean file name is broken

text: "AWS자산.svg"

my code ↓

```<code>
import (
    "github.com/gin-gonic/gin"
    "net/url"
)

 func FileDownload(c *gin.Context) {
    result, infos := fileDownload(c)
    if result.Code == 200 {
        c.Writer.Header().Set("Content-Type", infos.FileType)
        /* infos.FileOgName = AWS자산.svg */
        c.FileAttachment(infos.FilePath, infos.FileOgName) // 1 image
        c.FileAttachment(infos.FilePath, url.QueryEscape(infos.FileOgName)) // 2 image
    } else {
        c.JSON(result.Code, result)
    }
}
</code>```
```<code>// 3 image
func (c \*Context) FileAttachment(filepath, filename string) {
    c.Writer.Header().Set("content-disposition", fmt.Sprintf(attachment; filename\*="UTF-8''%s", filename))
    http.ServeFile(c.Writer, c.Request, filepath)
}
</code>```

I conducted three tests

I sent you a pure file name.
test 1 image

url encoding
test 2 image

Apply by referring to the Internet (filename*="UTF-8''%s")
test 3 image

The problem has not been solved.

I need help from good developers

----------2022-12-09 update-----------

[go gin 1.8.1]
The module update has been completed, but the problem remains.

```<code>// FileAttachment writes the specified file into the body stream in an efficient way
// On the client side, the file will typically be downloaded with the given filename
func (c *Context) FileAttachment(filepath, filename string) {
    if isASCII(filename) {
        c.Writer.Header().Set("Content-Disposition", `attachment; filename="`+filename+`"`)
    } else {
        c.Writer.Header().Set("Content-Disposition", `attachment; filename*=UTF-8''`+url.QueryEscape(filename))
    }
    http.ServeFile(c.Writer, c.Request, filepath)
}
</code>```

test 4 image

Body:
It is implementing a file download API

The problem is that the Korean file name is broken

text: "AWS자산.svg"

my code ↓

import (
    "github.com/gin-gonic/gin"
    "net/url"
)

 func FileDownload(c *gin.Context) {
    result, infos := fileDownload(c)
    if result.Code == 200 {
        c.Writer.Header().Set("Content-Type", infos.FileType)
        /* infos.FileOgName = AWS자산.svg */
        c.FileAttachment(infos.FilePath, infos.FileOgName) // 1 image
        c.FileAttachment(infos.FilePath, url.QueryEscape(infos.FileOgName)) // 2 image
    } else {
        c.JSON(result.Code, result)
    }
}

// 3 image
func (c \*Context) FileAttachment(filepath, filename string) {
    c.Writer.Header().Set("content-disposition", fmt.Sprintf(attachment; filename\*="UTF-8''%s", filename))
    http.ServeFile(c.Writer, c.Request, filepath)
}

I conducted three tests

I sent you a pure file name.
test 1 image

url encoding
test 2 image

Apply by referring to the Internet (filename*="UTF-8''%s")
test 3 image

The problem has not been solved.

I need help from good developers

----------2022-12-09 update-----------

[go gin 1.8.1]
The module update has been completed, but the problem remains.

// FileAttachment writes the specified file into the body stream in an efficient way
// On the client side, the file will typically be downloaded with the given filename
func (c *Context) FileAttachment(filepath, filename string) {
    if isASCII(filename) {
        c.Writer.Header().Set("Content-Disposition", `attachment; filename="`+filename+`"`)
    } else {
        c.Writer.Header().Set("Content-Disposition", `attachment; filename*=UTF-8''`+url.QueryEscape(filename))
    }
    http.ServeFile(c.Writer, c.Request, filepath)
}

test 4 image


问:
C++ concurrent functions?
I'm trying to stop randomFunction() when i == 5 in the main function. I do know that the current code for randomFunction() will only stop if counter equals 1000 and counter++ gets run 1000 times.

```<code>class A{
counter = 0;
public:

    void randomFunction()
    {
        while(counter != 1000)
        {
            counter++;
            cout << counter << endl;
        }
        cout << "Task Complete!" << endl;
    }

    void stopFunction()
    {
        counter = 1000;
    }
};

int main()
{
    A o;
    o.randomFunction();
    for (int i = 0; i < 6; i++)
    {
        if (i == 5)
        {
            o.stopFunction();
        }

    }
    return 0;
}

</code>```

Is there a way to run stopFunction() while randomFunction is running?
I'm looking for:

```<code>1
2
3
4
5
Task Complete!
</code>```

And not:

```<code>1
...
1000
Task Complete!
</code>```

I'm thinking the solution has to do with library thread and future or mutex, but I do not know where to start.

Title: C++ concurrent functions?

Body:
I'm trying to stop randomFunction() when i == 5 in the main function. I do know that the current code for randomFunction() will only stop if counter equals 1000 and counter++ gets run 1000 times.

class A{
counter = 0;
public:

    void randomFunction()
    {
        while(counter != 1000)
        {
            counter++;
            cout << counter << endl;
        }
        cout << "Task Complete!" << endl;
    }

    void stopFunction()
    {
        counter = 1000;
    }
};

int main()
{
    A o;
    o.randomFunction();
    for (int i = 0; i < 6; i++)
    {
        if (i == 5)
        {
            o.stopFunction();
        }

    }
    return 0;
}

Is there a way to run stopFunction() while randomFunction is running?
I'm looking for:

1
2
3
4
5
Task Complete!

And not:

1
...
1000
Task Complete!

I'm thinking the solution has to do with library thread and future or mutex, but I do not know where to start.