问:
Selecting a row in Treeview Tkinter
i'm facing a problem that i don't really understand.
I'm using twice Treeview. The first time to 'buy' an item from a catalog display in treeview. And the second time i'm using treeview to display the bought item.

In the first Treeview, everythink workds fine, as i can buy the selected row.
But in the second Treeview, when i click on an item, it keeps showing the last added.

Picture 1

as you can see in the picture, eventhough the first row is selected, it keeps showing the vines of the last row.

Here's the code:

```<code>def open_land(self, event):
    item = self.tree.identify('item', event.x, event.y)
    self.tree.selection_set(item)
    self.tree.focus_set()
    self.tree.focus(item)
    if item:
        # Open the selected land in a new frame
        self.land_frame = ttk.Frame(self)
        self.land_frame.grid(row=2, column=2)
        # add code here to display information about the selected land in the new frame
        for field in Player._lands:
            if field['Trellising'] < field['Max_Vines']:
                self.planting_label = ttk.Label(self.land_frame, text=f"{field['Planting']}/{field['Max_Vines']}")
                self.trellising_label = ttk.Label(self.land_frame, text=f"{field['Trellising']}/{field['Max_Vines']}")
                planting_button = ttk.Button(self.land_frame, text='Planting', command=self.planting)
                trellising_button_2 = ttk.Button(self.land_frame, text="Trellising", command=self.trellising) #Supporting the vines as they grow by attaching them to a trellis or other support structure.
                self.planting_label.grid(row=0, column=0)
                self.trellising_label.grid(row=0, column=1)
                planting_button.grid(row=1, column=0)
                trellising_button_2.grid(row=1, column=1)
</code>```

Title: Selecting a row in Treeview Tkinter

Body:
i'm facing a problem that i don't really understand.
I'm using twice Treeview. The first time to 'buy' an item from a catalog display in treeview. And the second time i'm using treeview to display the bought item.

In the first Treeview, everythink workds fine, as i can buy the selected row.
But in the second Treeview, when i click on an item, it keeps showing the last added.

Picture 1

as you can see in the picture, eventhough the first row is selected, it keeps showing the vines of the last row.

Here's the code:

def open_land(self, event):
    item = self.tree.identify('item', event.x, event.y)
    self.tree.selection_set(item)
    self.tree.focus_set()
    self.tree.focus(item)
    if item:
        # Open the selected land in a new frame
        self.land_frame = ttk.Frame(self)
        self.land_frame.grid(row=2, column=2)
        # add code here to display information about the selected land in the new frame
        for field in Player._lands:
            if field['Trellising'] < field['Max_Vines']:
                self.planting_label = ttk.Label(self.land_frame, text=f"{field['Planting']}/{field['Max_Vines']}")
                self.trellising_label = ttk.Label(self.land_frame, text=f"{field['Trellising']}/{field['Max_Vines']}")
                planting_button = ttk.Button(self.land_frame, text='Planting', command=self.planting)
                trellising_button_2 = ttk.Button(self.land_frame, text="Trellising", command=self.trellising) #Supporting the vines as they grow by attaching them to a trellis or other support structure.
                self.planting_label.grid(row=0, column=0)
                self.trellising_label.grid(row=0, column=1)
                planting_button.grid(row=1, column=0)
                trellising_button_2.grid(row=1, column=1)


来源: stackexchange

问:
Transformer BOS token when breaking sequence into sub-sequences
I need to apply a Transformer to a task where sequences can be much longer than the time dependency between timesteps.

For example, a sequence might be 1000 tokens long, but to predict x[i+1] only x[i-50] to x[i] are necessary. This induces me to train the transformer by breaking each sequence of 1000 tokens into 20 sequences of 50 steps each, which would be more efficient.

How should I deal with the BOS (beginning-of-sentence) token that shifts targets right? Should I use it in each subsequence, or should I instead use the token that comes immediately before the beginning of each subsequence?

For example, given a subsequence x[50:100], should the targets be [BOS, x[50], x[51], ... x[100]] or should they be [x[49], x[50], x[51], ... x[100]]?

ContentLicense: CC BY-SA 4.0


问:
UI Testing for Power Platform on Azure DevOps
Tester on our team has created automated testing via Visual Studio, which uses chrome in order to perform tasks on an environment on Power Platform. The tests work successfully locally. This is EASYREPO.

I have created the following pipeline with YAML.

This Pipeline fails with "Chrome driver does not exist".

I've followed Classic, and YAML based Microsoft Documents, and i cannot get anywhere with it.

##[error] [ERROR] The file D:\a_temp\PROJECTNAMEchromedriver.exe does not exist. The driver can be downloaded at http://chromedriver.storage.googleapis.com/index.html

I can confirm that the solution does have chrome driver exactly in the file it says it is not in....

```<code>trigger:
- none

pool:
vmImage: 'windows-latest'
parameters:
- name: BrowserType
displayName: "Test on Chrome"
type: string
default: Chrome
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
Invoke-WebRequest -Uri "https://chromedriver.storage.googleapis.com/75.0.3770.90/chromedriver_win32.zip" -OutFile $(System.DefaultWorkingDirectory)/chromedriver_win32.zip;
Expand-Archive -Path $(System.DefaultWorkingDirectory)/chromedriver_win32.zip -DestinationPath $(System.DefaultWorkingDirectory)/chromedriver;
$env:webdriverpath = "$(System.DefaultWorkingDirectory)/chromedriver"
$env:path += ";$env:webdriverpath"
displayName: 'Download and install ChromeDriver'

- powershell: |
# Set agent screen resolution to 1920x1080 to avoid sizing issues with Portal
Set-DisplayResolution -Width 1920 -Height 1080 -Force

# Wait 10 seconds
Start-Sleep -s 10

# Verify Screen Resolution is set to 1920x1080
Get-DisplayResolution
ignoreLASTEXITCODE: true
displayName: "Agent Screen Size"
- task: NuGetCommand@2
displayName: 'Restore NuGet Packages'
inputs:
restoreSolution: '**\*.sln'
- task: VSBuild@1
displayName: 'Build Power Apps Test Automation Solution'
inputs:
solution: '**\*.sln'
- task: VSTest@2
displayName: 'Run Power Apps Test Automation Tests via Chrome'
condition: or(eq('${{ parameters.BrowserType }}', 'Chrome'), eq('${{ parameters.BrowserType }}', 'All'))
inputs:
testSelector: 'testAssemblies'
testAssemblyVer2: 'DLL HERE'
searchFolder: '$(System.DefaultWorkingDirectory)'
uiTests: true
</code>```

Body:
Tester on our team has created automated testing via Visual Studio, which uses chrome in order to perform tasks on an environment on Power Platform. The tests work successfully locally. This is EASYREPO.

I have created the following pipeline with YAML.

This Pipeline fails with "Chrome driver does not exist".

I've followed Classic, and YAML based Microsoft Documents, and i cannot get anywhere with it.

##[error] [ERROR] The file D:\a_temp\PROJECTNAMEchromedriver.exe does not exist. The driver can be downloaded at http://chromedriver.storage.googleapis.com/index.html

I can confirm that the solution does have chrome driver exactly in the file it says it is not in....

trigger:
- none

pool:
vmImage: 'windows-latest'
parameters:
- name: BrowserType
displayName: "Test on Chrome"
type: string
default: Chrome
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
Invoke-WebRequest -Uri "https://chromedriver.storage.googleapis.com/75.0.3770.90/chromedriver_win32.zip" -OutFile $(System.DefaultWorkingDirectory)/chromedriver_win32.zip;
Expand-Archive -Path $(System.DefaultWorkingDirectory)/chromedriver_win32.zip -DestinationPath $(System.DefaultWorkingDirectory)/chromedriver;
$env:webdriverpath = "$(System.DefaultWorkingDirectory)/chromedriver"
$env:path += ";$env:webdriverpath"
displayName: 'Download and install ChromeDriver'

- powershell: |
# Set agent screen resolution to 1920x1080 to avoid sizing issues with Portal
Set-DisplayResolution -Width 1920 -Height 1080 -Force

# Wait 10 seconds
Start-Sleep -s 10

# Verify Screen Resolution is set to 1920x1080
Get-DisplayResolution
ignoreLASTEXITCODE: true
displayName: "Agent Screen Size"
- task: NuGetCommand@2
displayName: 'Restore NuGet Packages'
inputs:
restoreSolution: '**\*.sln'
- task: VSBuild@1
displayName: 'Build Power Apps Test Automation Solution'
inputs:
solution: '**\*.sln'
- task: VSTest@2
displayName: 'Run Power Apps Test Automation Tests via Chrome'
condition: or(eq('${{ parameters.BrowserType }}', 'Chrome'), eq('${{ parameters.BrowserType }}', 'All'))
inputs:
testSelector: 'testAssemblies'
testAssemblyVer2: 'DLL HERE'
searchFolder: '$(System.DefaultWorkingDirectory)'
uiTests: true


问:
Starting a URI in the background
I can't seem to figure out how to open a URI from a batch-file, whilst keeping the running Command Prompt window in the foreground and in focus.

I've tried using start "" /b "www.google.com" but it still moves my browser on top of the Command Prompt.

Title: Starting a URI in the background


问:
How can I host a a website with a firestore database?
I have the frontend already deployed on Vercel and I have the backend deployed on Heroku. How can I deploy the firestore database so that I can access the data from the frontend. If someone can give a step by step procedure, that would be great!</p>


问:
How to mock ipcRenderer EventListeners for electron
I'm struggeling to understand how to test the renderer - main interactions for my electron app.

I setup my electron App using the electron-react-template. In my preload.ts file I define a callback, so I can tell the component can listen when some data was loaded

```<code>contextBridge.exposeInMainWorld("api", {
    file: {
        wasOpened: (callback) => { return ipcRenderer.on('api-file-wasOpened') }
    }
})
</code>```

In my component I listen to the event like this

```<code>function App(){
    const [isStorageOpen, setIsStorageOpen] = useState(false);

    api.file.wasOpened((event, value) => {
        setIsStorageOpen(true);
    })

    return (
        <div>Storage is open: {isStorageOpen}</div>
    )
}
</code>```

My testfile is just a very simple check if the component renders for now

```<code>describe('App', () => {
    it('should render', () => {
        expect(render(<App />)).toBeTruthy();
    });
});
</code>```

When I start the App (npm run start) it does not throw any errors, and the api is defined. However, when I run it as a test (with jest) I get the error that api is undefined (ReferenceError: api is not defined).

My question is, do I need to do something special to have the api loaded during testing or should I just mock it? If so, how would I mock the functions that I use to communicate from main to the renderer, and how would I send the ipcRenderer.invoke signal?

Body:
I'm struggeling to understand how to test the renderer - main interactions for my electron app.

I setup my electron App using the electron-react-template. In my preload.ts file I define a callback, so I can tell the component can listen when some data was loaded

contextBridge.exposeInMainWorld("api", {
    file: {
        wasOpened: (callback) => { return ipcRenderer.on('api-file-wasOpened') }
    }
})

In my component I listen to the event like this

function App(){
    const [isStorageOpen, setIsStorageOpen] = useState(false);

    api.file.wasOpened((event, value) => {
        setIsStorageOpen(true);
    })

    return (

Storage is open: {isStorageOpen}

    )
}

My testfile is just a very simple check if the component renders for now

describe('App', () => {
    it('should render', () => {
        expect(render(<App />)).toBeTruthy();
    });
});

When I start the App (npm run start) it does not throw any errors, and the api is defined. However, when I run it as a test (with jest) I get the error that api is undefined (ReferenceError: api is not defined).

My question is, do I need to do something special to have the api loaded during testing or should I just mock it? If so, how would I mock the functions that I use to communicate from main to the renderer, and how would I send the ipcRenderer.invoke signal?


问:
why ethereum.utils.privtoaddr(priv) generates an address
so i was looking at this script
ethercheck

and i gave it a private key...some crap i came out with

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

and to my surprize it came out with and address

```<code>0x6813eb9362372eef6200f3b1dbc3f819671cba69
</code>```

everything else  seems to work fine. any ideea on why it works with this?

no address at all, an error

LE: so my question is why does it generate and actual address if the private key is invalid?

Body:
so i was looking at this script
ethercheck

and i gave it a private key...some crap i came out with

FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364144

and to my surprize it came out with and address

0x6813eb9362372eef6200f3b1dbc3f819671cba69

everything else  seems to work fine. any ideea on why it works with this?

no address at all, an error

LE: so my question is why does it generate and actual address if the private key is invalid?


问:
Is there a way to get the file import dependencies for different files in a Python project?
I'm working with a Python project consisting of multiple files and nested directories. I want to get a dictionary consisting of all existing files and their references to other files (nesting not required), for example:

```<code>dependencies = {
    "file1.py": ["file2.py","file4.py"],
    "file2.py": ["file3.py","file4.py",
    "file3.py": ["file1.py"],
    "file4.py": []
}
</code>```

Is there a module or an existing approach already out there to accomplish this?

My current plan is to write a program to read each line in every file and just track what comes after any from or import statement, but I'm not sure if that method's airtight.

Pseudocode:

```<code>dependencies = {}
for file in directory:
    for line in file:
        if line begins with "import" or "from":
            dependencies[file] += everything_after_from_import(line)
return dependencies
</code>```

I looked at modules like pipdeptree, but those only seem to track pip dependencies, rather than imports from file-to-file. I also don't need to worry about performance or scalability, as this is for generating an offline report for my own reference.

Is my current approach the best, or are there better ways out there?

Body:
I'm working with a Python project consisting of multiple files and nested directories. I want to get a dictionary consisting of all existing files and their references to other files (nesting not required), for example:

dependencies = {
    "file1.py": ["file2.py","file4.py"],
    "file2.py": ["file3.py","file4.py",
    "file3.py": ["file1.py"],
    "file4.py": []
}

Is there a module or an existing approach already out there to accomplish this?

My current plan is to write a program to read each line in every file and just track what comes after any from or import statement, but I'm not sure if that method's airtight.

Pseudocode:

dependencies = {}
for file in directory:
    for line in file:
        if line begins with "import" or "from":
            dependencies[file] += everything_after_from_import(line)
return dependencies

I looked at modules like pipdeptree, but those only seem to track pip dependencies, rather than imports from file-to-file. I also don't need to worry about performance or scalability, as this is for generating an offline report for my own reference.

Is my current approach the best, or are there better ways out there?


问:
Flutter - Package Tutorial not working when passing StreamBuilder in body
I will be very direct, I use package Tutorial link: https://pub.dev/packages/tutorial
But I'm having trouble making it work with StreamBuilder.

Example that works:

```<code>import 'package:flutter/material.dart';
import 'package:tutorial/tutorial.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<TutorialItem> itens = [];
  final _keyDrawer = GlobalKey();
  final _keyAccount = GlobalKey();
  final _keyContainer = GlobalKey();

  @override
  void initState() {
    itens.addAll({
      TutorialItem(
          globalKey: _keyDrawer,
          touchScreen: true,
          top: 200,
          left: 50,
          children: [
            const Text(
              "Ali é nosso menu , você consegue ver varias coisas nele",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
            const SizedBox(
              height: 100,
            )
          ],
          widgetNext: const Text(
            "Toque para continuar",
            style: TextStyle(
              color: Colors.purple,
              fontWeight: FontWeight.bold,
            ),
          ),
          shapeFocus: ShapeFocus.oval),
      TutorialItem(
        globalKey: _keyAccount,
        touchScreen: true,
        top: 200,
        left: 50,
        children: [
          const Text(
            "Qualquer duvida que aparecer , entre no nosso chat , estamos prontos para ajudar",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          const SizedBox(
            height: 100,
          )
        ],
        widgetNext: const Text(
          "Toque para continuar",
          style: TextStyle(
            color: Colors.purple,
            fontWeight: FontWeight.bold,
          ),
        ),
        shapeFocus: ShapeFocus.oval,
      ),
      TutorialItem(
        globalKey: _keyContainer,
        touchScreen: true,
        top: 200,
        left: 50,
        children: [
          const Text(
            "Aqui veremos todo container",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          const SizedBox(
            height: 100,
          )
        ],
        widgetNext: const Text(
          "Toque para continuar",
          style: TextStyle(
            color: Colors.purple,
            fontWeight: FontWeight.bold,
          ),
        ),
        shapeFocus: ShapeFocus.square,
      ),
    });

    ///FUNÇÃO QUE EXIBE O TUTORIAL.
    Future.delayed(const Duration(microseconds: 200)).then((value) {
      Tutorial.showTutorial(context, itens);
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Teste tutorial"),
        leading: Builder(builder: (context) {
          return IconButton(
            key: _keyDrawer,
            onPressed: () {
              Scaffold.of(context).openDrawer();
            },
            icon: const Icon(
              Icons.menu,
              color: Colors.white,
            ),
            tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
          );
        }),
        actions: [
          IconButton(
              key: _keyAccount,
              onPressed: () {},
              icon: const Icon(Icons.account_circle_outlined))
        ],
      ),
      body: Stack(
        children: <Widget>[
          createListView(
            context,
          )
        ],
      ),
      drawer: const Drawer(),
    );
  }

  final List<String> entries = <String>['A', 'B', 'C'];
  final List<int> colorCodes = <int>[600, 500, 100];

  Widget createListView(
    BuildContext context,
  ) {
    return ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: entries.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            key: index == 0 ? _keyContainer : null,
            height: 50,
            color: Colors.blue[colorCodes[index]],
            child: Center(child: Text('Entry ${entries[index]}')),
          );
        });
  }
}

</code>```

expected result and working in the first example

What is not working is when my body is passed a StreamBuilder that returns a CreateListView:

```<code>body: Stack(
        children: <Widget>[
          _buildBodyBack(),
          StreamBuilder<bool>(
            stream: _syncservice.outLoading,
            initialData: false,
            builder: (context, snapshot) {
              if (snapshot.data == true)
                return loading(title: "Sync Data...");

              return StreamBuilder<bool>(
                stream: _propertyService.outLoading,
                initialData: false,
                builder: (context, snapshot) {
                  if (snapshot.data == true)
                    return loading(title: "Loading Property...");

                  return StreamBuilder<List<Property>>(
                      stream: _propertyService.outProperty,
                      initialData: null,
                      builder: (context, snapshot) {
                        if (snapshot.data == null) return Container();
                        return createListView(
                          context,
                          snapshot,
                        );
                      });
                },
              );
            },
          ),
        ],
      ),
</code>```

Using the stream builder and passing my createListView widget the key like this:

key: _keyExampleName (Key name example)

Even passing the key correctly it doesn't work as the first example

Body:
I will be very direct, I use package Tutorial link: https://pub.dev/packages/tutorial
But I'm having trouble making it work with StreamBuilder.

Example that works:

import 'package:flutter/material.dart';
import 'package:tutorial/tutorial.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<TutorialItem> itens = [];
  final _keyDrawer = GlobalKey();
  final _keyAccount = GlobalKey();
  final _keyContainer = GlobalKey();

  @override
  void initState() {
    itens.addAll({
      TutorialItem(
          globalKey: _keyDrawer,
          touchScreen: true,
          top: 200,
          left: 50,
          children: [
            const Text(
              "Ali é nosso menu , você consegue ver varias coisas nele",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
            const SizedBox(
              height: 100,
            )
          ],
          widgetNext: const Text(
            "Toque para continuar",
            style: TextStyle(
              color: Colors.purple,
              fontWeight: FontWeight.bold,
            ),
          ),
          shapeFocus: ShapeFocus.oval),
      TutorialItem(
        globalKey: _keyAccount,
        touchScreen: true,
        top: 200,
        left: 50,
        children: [
          const Text(
            "Qualquer duvida que aparecer , entre no nosso chat , estamos prontos para ajudar",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          const SizedBox(
            height: 100,
          )
        ],
        widgetNext: const Text(
          "Toque para continuar",
          style: TextStyle(
            color: Colors.purple,
            fontWeight: FontWeight.bold,
          ),
        ),
        shapeFocus: ShapeFocus.oval,
      ),
      TutorialItem(
        globalKey: _keyContainer,
        touchScreen: true,
        top: 200,
        left: 50,
        children: [
          const Text(
            "Aqui veremos todo container",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          const SizedBox(
            height: 100,
          )
        ],
        widgetNext: const Text(
          "Toque para continuar",
          style: TextStyle(
            color: Colors.purple,
            fontWeight: FontWeight.bold,
          ),
        ),
        shapeFocus: ShapeFocus.square,
      ),
    });

    ///FUNÇÃO QUE EXIBE O TUTORIAL.
    Future.delayed(const Duration(microseconds: 200)).then((value) {
      Tutorial.showTutorial(context, itens);
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Teste tutorial"),
        leading: Builder(builder: (context) {
          return IconButton(
            key: _keyDrawer,
            onPressed: () {
              Scaffold.of(context).openDrawer();
            },
            icon: const Icon(
              Icons.menu,
              color: Colors.white,
            ),
            tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
          );
        }),
        actions: [
          IconButton(
              key: _keyAccount,
              onPressed: () {},
              icon: const Icon(Icons.account_circle_outlined))
        ],
      ),
      body: Stack(
        children: <Widget>[
          createListView(
            context,
          )
        ],
      ),
      drawer: const Drawer(),
    );
  }

  final List<String> entries = <String>['A', 'B', 'C'];
  final List<int> colorCodes = <int>[600, 500, 100];

  Widget createListView(
    BuildContext context,
  ) {
    return ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: entries.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            key: index == 0 ? _keyContainer : null,
            height: 50,
            color: Colors.blue[colorCodes[index]],
            child: Center(child: Text('Entry ${entries[index]}')),
          );
        });
  }
}

expected result and working in the first example

What is not working is when my body is passed a StreamBuilder that returns a CreateListView:

body: Stack(
        children: <Widget>[
          _buildBodyBack(),
          StreamBuilder<bool>(
            stream: _syncservice.outLoading,
            initialData: false,
            builder: (context, snapshot) {
              if (snapshot.data == true)
                return loading(title: "Sync Data...");

              return StreamBuilder<bool>(
                stream: _propertyService.outLoading,
                initialData: false,
                builder: (context, snapshot) {
                  if (snapshot.data == true)
                    return loading(title: "Loading Property...");

                  return StreamBuilder<List<Property>>(
                      stream: _propertyService.outProperty,
                      initialData: null,
                      builder: (context, snapshot) {
                        if (snapshot.data == null) return Container();
                        return createListView(
                          context,
                          snapshot,
                        );
                      });
                },
              );
            },
          ),
        ],
      ),

Using the stream builder and passing my createListView widget the key like this:

key: _keyExampleName (Key name example)

Even passing the key correctly it doesn't work as the first example


问:
Number of days between two Instants doesn't change when changing a specific end date
I have a class that I use to get the number of days between 2 Instants :

```<code>public static Long getDaysBetween(final Instant startInstant, final Instant endInstant) {
    final ZonedDateTime startDate = startInstant.atZone(ZoneId.systemDefault());
    final ZonedDateTime endDate = endInstant.atZone(ZoneId.systemDefault());
    return ChronoUnit.DAYS.between(startDate, endDate);
}
</code>```

And the corresponding test class

```<code>class WeekCalculatorTest {

    @Test
    void givenStartAndEndInstant_whenCalculatingTheNumberOfDaysBetween_thenTheResultShouldBe() {
        final String start = "2022-09-01T00:00:00Z";
        final String end = "2022-10-31T00:00:00Z";
        final Instant startInstant = Instant.parse(start);
        final Instant endInstant = Instant.parse(end);
        assertThat(WeekCalculator.getDaysBetween(startInstant, endInstant), is(59L));
    }
}
</code>```

I don't understand why when I change the end variable to final String end = "2022-10-30T00:00:00Z";, my test is still passing.

Body:
I have a class that I use to get the number of days between 2 Instants :

public static Long getDaysBetween(final Instant startInstant, final Instant endInstant) {
    final ZonedDateTime startDate = startInstant.atZone(ZoneId.systemDefault());
    final ZonedDateTime endDate = endInstant.atZone(ZoneId.systemDefault());
    return ChronoUnit.DAYS.between(startDate, endDate);
}

And the corresponding test class

class WeekCalculatorTest {

    @Test
    void givenStartAndEndInstant_whenCalculatingTheNumberOfDaysBetween_thenTheResultShouldBe() {
        final String start = "2022-09-01T00:00:00Z";
        final String end = "2022-10-31T00:00:00Z";
        final Instant startInstant = Instant.parse(start);
        final Instant endInstant = Instant.parse(end);
        assertThat(WeekCalculator.getDaysBetween(startInstant, endInstant), is(59L));
    }
}

I don't understand why when I change the end variable to final String end = "2022-10-30T00:00:00Z";, my test is still passing.


问:
GraphQL schema returns null for nested items. AWS AppSync & HTTP DataSources
I'm deploying a REST api to integrate with some partners. Some of these endpoints are passed through to a GraphQL query (via AppSync) to give read only access to the data and allow partner devs to pick which fields they want back. This was all fairly straight forward until I hooked up a HTTP DataSource to our internal calendar api. GraphQL is new to me and I can't figure out how to properly define a variable inside the schema.

Api response is structured like this: (with a lot more key value pairs)

```<code>{
    "site_id": "0000-1111-2222-3333-4444",
    "start_date": "2023-01-19",
    "end_date": "2023-01-20",
    "calendar": {
        "2023-01-19": {
            "a": true,
            "dow": 4,
            "h": false,
            "min": 2,
            "nr": 150,
            "s": "available"
        },
        "2023-01-20": {
            "a": true,
            "dow": 5,
            "h": false,
            "min": 2,
            "nr": 150,
            "s": "available"
        }
    },
    "is_active": true
}
</code>```

GraphQL schema:

```<code>type Calendar {
    site_id: ID!
    start_date: String!
    end_date: String!
    is_active: Boolean
    calendar: CalendarDate
}

type CalendarDate {
    date: Avails
}

type Avails {
    a: Boolean
    s: String
    nr: Int
}
</code>```

Query:

```<code>query {
getCalendar(end_date: "2023-01-20", site_id: "0000-1111-2222-3333-4444", start_date: "2023-01-19") {
    is_active
    site_id
    calendar {
        date {
            a
            nr
            s
        }
    }
    }
}
</code>```

Response:

```<code>{
  "data": {
    "getCalendar": {
      "is_active": true,
      "site_id": "0000-1111-2222-3333-4444",
      "calendar": {
        "date": null
      }
    }
  }
}
</code>```

I know the issue is in the CalendarDate type, since it's looking for the key "date" and not finding it. Does someone know how I can turn that field in the schema into what I need?

Body:
I'm deploying a REST api to integrate with some partners. Some of these endpoints are passed through to a GraphQL query (via AppSync) to give read only access to the data and allow partner devs to pick which fields they want back. This was all fairly straight forward until I hooked up a HTTP DataSource to our internal calendar api. GraphQL is new to me and I can't figure out how to properly define a variable inside the schema.

Api response is structured like this: (with a lot more key value pairs)

{
    "site_id": "0000-1111-2222-3333-4444",
    "start_date": "2023-01-19",
    "end_date": "2023-01-20",
    "calendar": {
        "2023-01-19": {
            "a": true,
            "dow": 4,
            "h": false,
            "min": 2,
            "nr": 150,
            "s": "available"
        },
        "2023-01-20": {
            "a": true,
            "dow": 5,
            "h": false,
            "min": 2,
            "nr": 150,
            "s": "available"
        }
    },
    "is_active": true
}

GraphQL schema:

type Calendar {
    site_id: ID!
    start_date: String!
    end_date: String!
    is_active: Boolean
    calendar: CalendarDate
}

type CalendarDate {
    date: Avails
}

type Avails {
    a: Boolean
    s: String
    nr: Int
}

Query:

query {
getCalendar(end_date: "2023-01-20", site_id: "0000-1111-2222-3333-4444", start_date: "2023-01-19") {
    is_active
    site_id
    calendar {
        date {
            a
            nr
            s
        }
    }
    }
}

Response:

{
  "data": {
    "getCalendar": {
      "is_active": true,
      "site_id": "0000-1111-2222-3333-4444",
      "calendar": {
        "date": null
      }
    }
  }
}

I know the issue is in the CalendarDate type, since it's looking for the key "date" and not finding it. Does someone know how I can turn that field in the schema into what I need?


问:
DAX : Average of Cumulative Durations
I need a little help with this one that seems very simple but I cant write the right DAX for it.

Context

I have a table of insurance claims and the days they were assigned and unassigned to adjusters, and the duration of this assignments in days.

ClaimID
Another header
A header
Another header

1
10/31/2022
11/30/2022
30

1
1/1/2023
1/4/2023
3

2
10/29/2022
12/28/2022
60

2
12/28/2022
1/6/2023
9

I need a measure (CycleTime) that calculates a monthly cumulative duration for each claim, and then take an average. All this based on the UnAssignedDate.

Desired output.

The measure will be plotted by month-year and this is how it needs to calculate CycleTime:

November 2022 : We only have one unassigned claim (1), so the cycletime equals to that single duration (30).

December 2022 : Again, we only have one unassigned claim (2), so the cycletime equals to that single duration (60).

January 2022 :  For this month, both claims were unassigned, so we need to calculate the cumulative duration for each one and then take the average:

Claim 1 : 30 + 3 = 33

Claim 2 : 60+9 = 69

CycleTime = (33 + 69)/2 = 51

The measure should work for multiple claims and multiple unassignments per claim.

Any help would be greatly appreciated. Thank you for reading!

Title: DAX : Average of Cumulative Durations


问:
I have a problem using two setState method in flutter
Hello Stack Community I need some help with this flutter/dart code

I need to use both functionalities at the same time (change interest/category color and enable start button)
whit my currently code I can only use one functionality or change color or enable button but I cant use the two functionalities at the same time
thanks for your time and help

choose_interest_screen.dart

```<code>
import 'package:flutter/material.dart';
import '../widget/category_button.dart';

class ChooseInterestScreen extends StatefulWidget {
  static const routeName = "/choose_interest";
  List<String> _listCategoriesId = [];
  bool _isAdded = false;
  @override
  State<ChooseInterestScreen> createState() => _ChooseInterestScreenState();
}

class _ChooseInterestScreenState extends State<ChooseInterestScreen> {
  @override
  Widget build(BuildContext context) {
    void handleCategory(String idCategory) {
      if (widget._listCategoriesId.contains(idCategory)) {
        widget._listCategoriesId.remove(idCategory);
        if (widget._listCategoriesId.isEmpty) {
          setState(() {
            widget._isAdded = false;
          });
        }
      } else {
        setState(() {
          widget._isAdded = true;
        });
        widget._listCategoriesId.add(idCategory);
      }
    }

    final List<Widget> listCategories = [
      CategoryButton(
        label: 'Tech',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Finance',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Design',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'File',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Music',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Movie',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Cars',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Bike',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'ASMR',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Stories',
        selected: false,
        onPressCallback: handleCategory,
      ),
    ];
    final mediaQuery = MediaQuery.of(context);
    return Scaffold(
      body: Container(
        color: const Color.fromARGB(255, 0, 0, 0),
        alignment: Alignment.topCenter,
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.only(top: 30),
              alignment: Alignment.topRight,
              child: TextButton(
                child: const Text("Later"),
                onPressed: () {},
              ),
            ),
            Container(
              margin: const EdgeInsets.only(left: 10, right: 10),
              alignment: Alignment.topLeft,
              child: const Text(
                "Select your interest",
                textAlign: TextAlign.start,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(
                  left: 10, right: 10, top: 5, bottom: 20),
              child: const Text(
                "Will show all content than you like",
                textAlign: TextAlign.start,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
            Container(
              height: mediaQuery.size.height * 0.7,
              child: GridView.count(
                childAspectRatio: 3,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20,
                crossAxisCount: 3,
                children: listCategories,
              ),
            ),
            Expanded(
                child: Align(
              alignment: Alignment.bottomCenter,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size.fromHeight(50),
                ),
                onPressed: !widget._isAdded
                    ? null
                    : () {
                        print("Work");
                      },
                child: const Text(
                  'Start',
                  style: TextStyle(fontSize: 24),
                ),
              ),
            )),
          ],
        ),
      ),
    );
  }
}
</code>```

category_button.dart

```<code>
`> import 'dart:math';

>
> import 'package:flutter/material.dart';
>
> class CategoryButton extends StatefulWidget {   CategoryButton({
>     super.key,
>     required this.label,
>     required this.selected,
>     required this.onPressCallback,   });
>
>   final void Function(String) onPressCallback;   final String label;
> bool selected;
>
>   @override   State<CategoryButton> createState() =>
> _CategoryButtonState(); }
>
> class _CategoryButtonState extends State<CategoryButton> {   @override
> Widget build(BuildContext context) {
>     return GestureDetector(
>       key: ValueKey((Random().nextInt(10)).toString()),
>       onTap: () {
>         print(widget.selected);
>         setState(
>           () {
>             widget.selected = !widget.selected;
>             widget.onPressCallback(widget.label);
>           },
>         );
>       },
>       child: Container(
>         decoration: BoxDecoration(
>           color: widget.selected ? Colors.blue : Colors.black,
>           borderRadius: BorderRadius.circular(40),
>         ),
>         child: Column(
>           crossAxisAlignment: CrossAxisAlignment.center,
>           mainAxisAlignment: MainAxisAlignment.center,
>           children: [
>             Text(
>               widget.label,
>               style: TextStyle(
>                 color: Colors.white,
>                 fontSize: 25,
>                 fontWeight: FontWeight.w500,
>               ),
>
>
>

</code>```

Edit 1: More detail

when I click in category button inside gridView

```<code>    onTap: () {
            print(widget.selected);
            setState(
              () {
                widget.selected = !widget.selected;
              },
            );
            widget.onPressCallback(widget.label);

</code>```

This part of code works randomly (sometimes change category button color and sometimes doesn´t change)
and widget.onPressCallback(widget.label);
calls this method

```<code>

void handleCategory(String idCategory) {
  if (widget._listCategoriesId.contains(idCategory)) {
    widget._listCategoriesId.remove(idCategory);
    if (widget._listCategoriesId.isEmpty) {
      setState(() {
        widget._isAdded = false;
      });
    }
  } else {
    setState(() {
      widget._isAdded = true;
    });
    widget._listCategoriesId.add(idCategory);
  }
}

</code>```

this method also works randomly enabling and disabling Start button

```<code>
      Expanded(
            child: Align(
          alignment: Alignment.bottomCenter,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size.fromHeight(50),
            ),
            onPressed: !widget._isAdded
                ? null
                : () {
                    print("funciono");
                  },
            child: const Text(
              'Empezar',
              style: TextStyle(fontSize: 24),
            ),
          ),
        )),

</code>```

When this 2 functions change color of category and enable/disable start button
work together, sometimes works fine sometimes nop but if this 2 functions are working alone works fine
I need this 2 functions work fine

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

Body:
Hello Stack Community I need some help with this flutter/dart code

I need to use both functionalities at the same time (change interest/category color and enable start button)
whit my currently code I can only use one functionality or change color or enable button but I cant use the two functionalities at the same time
thanks for your time and help

choose_interest_screen.dart

import 'package:flutter/material.dart';
import '../widget/category_button.dart';

class ChooseInterestScreen extends StatefulWidget {
  static const routeName = "/choose_interest";
  List<String> _listCategoriesId = [];
  bool _isAdded = false;
  @override
  State<ChooseInterestScreen> createState() => _ChooseInterestScreenState();
}

class _ChooseInterestScreenState extends State<ChooseInterestScreen> {
  @override
  Widget build(BuildContext context) {
    void handleCategory(String idCategory) {
      if (widget._listCategoriesId.contains(idCategory)) {
        widget._listCategoriesId.remove(idCategory);
        if (widget._listCategoriesId.isEmpty) {
          setState(() {
            widget._isAdded = false;
          });
        }
      } else {
        setState(() {
          widget._isAdded = true;
        });
        widget._listCategoriesId.add(idCategory);
      }
    }

    final List<Widget> listCategories = [
      CategoryButton(
        label: 'Tech',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Finance',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Design',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'File',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Music',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Movie',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Cars',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Bike',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'ASMR',
        selected: false,
        onPressCallback: handleCategory,
      ),
      CategoryButton(
        label: 'Stories',
        selected: false,
        onPressCallback: handleCategory,
      ),
    ];
    final mediaQuery = MediaQuery.of(context);
    return Scaffold(
      body: Container(
        color: const Color.fromARGB(255, 0, 0, 0),
        alignment: Alignment.topCenter,
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.only(top: 30),
              alignment: Alignment.topRight,
              child: TextButton(
                child: const Text("Later"),
                onPressed: () {},
              ),
            ),
            Container(
              margin: const EdgeInsets.only(left: 10, right: 10),
              alignment: Alignment.topLeft,
              child: const Text(
                "Select your interest",
                textAlign: TextAlign.start,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(
                  left: 10, right: 10, top: 5, bottom: 20),
              child: const Text(
                "Will show all content than you like",
                textAlign: TextAlign.start,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
            Container(
              height: mediaQuery.size.height * 0.7,
              child: GridView.count(
                childAspectRatio: 3,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20,
                crossAxisCount: 3,
                children: listCategories,
              ),
            ),
            Expanded(
                child: Align(
              alignment: Alignment.bottomCenter,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size.fromHeight(50),
                ),
                onPressed: !widget._isAdded
                    ? null
                    : () {
                        print("Work");
                      },
                child: const Text(
                  'Start',
                  style: TextStyle(fontSize: 24),
                ),
              ),
            )),
          ],
        ),
      ),
    );
  }
}

category_button.dart

`> import 'dart:math';

>
> import 'package:flutter/material.dart';
>
> class CategoryButton extends StatefulWidget {   CategoryButton({
>     super.key,
>     required this.label,
>     required this.selected,
>     required this.onPressCallback,   });
>
>   final void Function(String) onPressCallback;   final String label;
> bool selected;
>
>   @override   State<CategoryButton> createState() =>
> _CategoryButtonState(); }
>
> class _CategoryButtonState extends State<CategoryButton> {   @override
> Widget build(BuildContext context) {
>     return GestureDetector(
>       key: ValueKey((Random().nextInt(10)).toString()),
>       onTap: () {
>         print(widget.selected);
>         setState(
>           () {
>             widget.selected = !widget.selected;
>             widget.onPressCallback(widget.label);
>           },
>         );
>       },
>       child: Container(
>         decoration: BoxDecoration(
>           color: widget.selected ? Colors.blue : Colors.black,
>           borderRadius: BorderRadius.circular(40),
>         ),
>         child: Column(
>           crossAxisAlignment: CrossAxisAlignment.center,
>           mainAxisAlignment: MainAxisAlignment.center,
>           children: [
>             Text(
>               widget.label,
>               style: TextStyle(
>                 color: Colors.white,
>                 fontSize: 25,
>                 fontWeight: FontWeight.w500,
>               ),
>
>
>

Edit 1: More detail

when I click in category button inside gridView

    onTap: () {
            print(widget.selected);
            setState(
              () {
                widget.selected = !widget.selected;
              },
            );
            widget.onPressCallback(widget.label);

This part of code works randomly (sometimes change category button color and sometimes doesn´t change)
and widget.onPressCallback(widget.label);
calls this method

void handleCategory(String idCategory) {
  if (widget._listCategoriesId.contains(idCategory)) {
    widget._listCategoriesId.remove(idCategory);
    if (widget._listCategoriesId.isEmpty) {
      setState(() {
        widget._isAdded = false;
      });
    }
  } else {
    setState(() {
      widget._isAdded = true;
    });
    widget._listCategoriesId.add(idCategory);
  }
}

this method also works randomly enabling and disabling Start button

      Expanded(
            child: Align(
          alignment: Alignment.bottomCenter,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size.fromHeight(50),
            ),
            onPressed: !widget._isAdded
                ? null
                : () {
                    print("funciono");
                  },
            child: const Text(
              'Empezar',
              style: TextStyle(fontSize: 24),
            ),
          ),
        )),

When this 2 functions change color of category and enable/disable start button
work together, sometimes works fine sometimes nop but if this 2 functions are working alone works fine
I need this 2 functions work fine


问:
Cloudwatch rule not being triggered as event pattern is deployed in lexicographic order usung terraform
I'm trying to write a config where lambda function is being triggered if there is an instance class change in AWS RDS resource.
This is the custom event pattern:

```<code>{
  "source": [
    "aws.rds"
  ],
  "detail-type": [
    "RDS DB Instance Event"
  ],
  "detail": {
    "EventID": [
      "RDS-EVENT-0014"
    ]
  }
}

</code>```

The following is my terraform config for cloud watch event rule resource:

```<code>resource "aws_cloudwatch_event_rule" "rds_instance_event" {
  name      = "${var.region}-rds-instance-event"
  description = "This event trigger is for RDS instance events"
  event_pattern = <<EOF
{
  "source": [
    "aws.rds"
  ],
  "detail-type": [
    "RDS DB Instance Event"
  ],
  "detail": {
    "EventID": [
      "RDS-EVENT-0014"
    ]
  }
}
EOF
}
</code>```

The problem is that event_patter get's uploaded in lexicographical order and the cloud watch event is not being triggered. When I change the event_pattern manually to the original order, it works.

Does anyone know how to fix this?

I tried rendering it from a data template as following, still didn't work.

```<code>data "template_file" "event_pattern" {
  template = file("${path.module}/manifests/rds-notification-event-rule.json")
}

resource "aws_cloudwatch_event_rule" "rds_instance_event" {
   name     = "${var.region}-rds-instance-event"
   description = "This event trigger is for RDS instance events"

   event_pattern = data.template_file.event_pattern.rendered
 }

</code>```

Body:
I'm trying to write a config where lambda function is being triggered if there is an instance class change in AWS RDS resource.
This is the custom event pattern:

{
  "source": [
    "aws.rds"
  ],
  "detail-type": [
    "RDS DB Instance Event"
  ],
  "detail": {
    "EventID": [
      "RDS-EVENT-0014"
    ]
  }
}

The following is my terraform config for cloud watch event rule resource:

resource "aws_cloudwatch_event_rule" "rds_instance_event" {
  name      = "${var.region}-rds-instance-event"
  description = "This event trigger is for RDS instance events"
  event_pattern = <<EOF
{
  "source": [
    "aws.rds"
  ],
  "detail-type": [
    "RDS DB Instance Event"
  ],
  "detail": {
    "EventID": [
      "RDS-EVENT-0014"
    ]
  }
}
EOF
}

The problem is that event_patter get's uploaded in lexicographical order and the cloud watch event is not being triggered. When I change the event_pattern manually to the original order, it works.

Does anyone know how to fix this?

I tried rendering it from a data template as following, still didn't work.

data "template_file" "event_pattern" {
  template = file("${path.module}/manifests/rds-notification-event-rule.json")
}

resource "aws_cloudwatch_event_rule" "rds_instance_event" {
   name     = "${var.region}-rds-instance-event"
   description = "This event trigger is for RDS instance events"

   event_pattern = data.template_file.event_pattern.rendered
 }


问:
How can I import a JSON file on Next.js on build?
I just want to do a simple thing: import a JSON file and read it within a function to return some specific data of it, but it's been really hard to do.

When on dev env, it works perfectly, but when I try to do the build, the file is not fount. It's like it's not being imported. Since I'm new with Next.JS architecture, I'm not able to find a solution by myself (read a lot of pages with help, but no success).

structure

```<code>- root
  - config
    - labels
      data.json
      index.ts
</code>```

index.ts

```<code>import data from './data.json';

export type HomeLabels = typeof data.in.home;
export function getHomeLabels(language: string): HomeLabels {

    return data[language as keyof typeof data].home;

}
</code>```

data.json

```<code>{
    "in":{
        "home":{
            "contact_button": "Contact",
            "view_all_button": "View all"
        }
    },
    "pt-br":{
        "home":{
            "contact_button": "Contato",
            "view_all_button": "Ver tudo"
        }
    }
}
</code>```

error on build

```<code>TypeError: Cannot read properties of undefined (reading 'home')
    at getHomeLabels (/home/runner/work/boutme/boutme/.next/server/chunks/261.js:42:43)
</code>```

All the solutions that I found out was related to using API or getStaticsProps and using on component. But I really don't want it. I think that it's possible to do what I want (import json and read just on a function), but it's been hard.

Body:
I just want to do a simple thing: import a JSON file and read it within a function to return some specific data of it, but it's been really hard to do.

When on dev env, it works perfectly, but when I try to do the build, the file is not fount. It's like it's not being imported. Since I'm new with Next.JS architecture, I'm not able to find a solution by myself (read a lot of pages with help, but no success).

structure

- root
  - config
    - labels
      data.json
      index.ts

index.ts

import data from './data.json';

export type HomeLabels = typeof data.in.home;
export function getHomeLabels(language: string): HomeLabels {

    return data[language as keyof typeof data].home;

}

data.json

{
    "in":{
        "home":{
            "contact_button": "Contact",
            "view_all_button": "View all"
        }
    },
    "pt-br":{
        "home":{
            "contact_button": "Contato",
            "view_all_button": "Ver tudo"
        }
    }
}

error on build

TypeError: Cannot read properties of undefined (reading 'home')
    at getHomeLabels (/home/runner/work/boutme/boutme/.next/server/chunks/261.js:42:43)

All the solutions that I found out was related to using API or getStaticsProps and using on component. But I really don't want it. I think that it's possible to do what I want (import json and read just on a function), but it's been hard.


问:
JS path doesn't work while page is reload
link to the imageCould u please explain me why the jspath return me null if I past it ?
When I copy the JsPath from "Elements", it works when I past it in the console,
but if I copy the JsPath not from the google "Elements" (F12), it return me null, so I have to copy it again from "Elements"...
I'm lost !

I don't understand, please help me


问:
How to check mem and cpu usage in Node parent process, while child processes have spawned?
How to check mem and cpu usage in Node parent process, while child processes have spawned?

Stuff like process.memoryUsage() seems to combine metrics from parent + child processes.


问:
How to handle firebase promises to upload multiple files in React.js?
I want to upload multiple picture to firebase and get link of the images and then send links to backend to save in mongo DB.
The problem is that I don't know where should I place my backend request so that the request will done after uploading and setting urls.

Here is my codw what I imported from firebase.

```<code>import { ServiceRegistration } from '../../https/index';
import { storage } from '../../firebase';
import { getDownloadURL, ref, uploadBytesResumable } from 'firebase/storage';

const ServiceRegister = () => {
const [coverPicUrl, setCoverPicUrl] = useState(null); // to save single picture url
const [galleriesUrl, setgalleriesUrl] = useState([]);// to save multiple picture url
const [coverPic, setCoverPic] = useState();
const [gallery, setGallery] = useState([]);
const [Error, setError] = useState('');

    function handleMultipleImage(e) {
        for (let i = 0; i < e.target.files.length; i++) {
            const newImage = e.target.files[i];
            setGallery((prevState) => [...prevState, newImage]);
        }
    }

    const uploadCoverPicture = () => {
        const storageRef = ref(storage, `/images/${Date.now()}-${coverPic.name}`);
        const uplaodTask = uploadBytesResumable(storageRef, coverPic);
        uplaodTask.on(
            "state_changed",
            (snapshot) => { },
            (error) => setError(error),
            () => {
                getDownloadURL(uplaodTask.snapshot.ref).then((downloadUrl) => {
                    setCoverPicUrl(downloadUrl);
                })
            }
        )
    }

    function uploadGalleryPictures() {
        gallery.map((file) => {
            const storageRef = ref(storage, `/images/${Date.now()}-${file.name}`);
            const uploadTask = uploadBytesResumable(storageRef, file);
            uploadTask.on(
                "state_changed",
                (snapshot) => { },
                (error) => setError(error),
                () => {
                    getDownloadURL(uploadTask.snapshot.ref).then((downloadURLs) => {
                        for (let i = 0; i < galleriesUrl.length; i++) {
                            const newUrl = downloadURLs;
                            setgalleriesUrl((prevState) => [...prevState, newUrl]);
                        }
                        ServiceRegistration({ coverPicUrl, galleriesUrl }).then(res => {
                            setloading(false);
                        }).catch(err => {
                            setloading(false);
                            console.log(err);
                        })
                    });
                }
            );

        })

    }

    function handleFirebaseUplaoding() {
        uploadCoverPicture();
        uploadGalleryPictures();
    }

    function handleRegistration(e) {
        e.preventDefault();
        setloading(true);
        if (!coverPic) {
            setError('Cover photo is required');
            setloading(false);
        }
        else {
            handleFirebaseUplaoding();
        }
    }

return (
        <>
<AppForm headerText='Register your service with WedBook' handleSubmit={handleRegistration} errorText={Error}>
      <div className='w-full pl-12 mt-4'>
          <label htmlFor="coverpic" className='font-semibold'>Upload a cover photo</label><br />
          <input type="file" id='coverpic' onChange={(e) => { setCoverPic(e.target.files[0]) }} className="border border-gray-400 w-[80%] rounded-lg px-3 py-0.5  text-base outline-none " required />
      </div>
      <div className='w-full pl-12 mt-12'>
           <label htmlFor="gallery" className='font-semibold'>Upload Gallery Pictures (maximum 30 picture)</label><br />
           <input type="file" name='coverPic' onChange={(e) => { handleMultipleImage(e) }} id='gallery' className="border border-gray-400 w-[80%] rounded-lg px-3 py-0.5  text-base outline-none " multiple />
      </div>
      <div className='w-full mt-12 flex justify-evenly items-center'>
         <ButtonOutline btnType='button' text='Go Back' clickEvent={() => { setImageForm(false) }} />
         <ButtonOutline btnType='submit' text='Register' />
      </div>
</AppForm>
    </>
    );
}

</code>```

I want to post request after recieving all urls from firebase . ServiceRegistration is backend request

Body:
I want to upload multiple picture to firebase and get link of the images and then send links to backend to save in mongo DB.
The problem is that I don't know where should I place my backend request so that the request will done after uploading and setting urls.

Here is my codw what I imported from firebase.

import { ServiceRegistration } from '../../https/index';
import { storage } from '../../firebase';
import { getDownloadURL, ref, uploadBytesResumable } from 'firebase/storage';

const ServiceRegister = () => {
const [coverPicUrl, setCoverPicUrl] = useState(null); // to save single picture url
const [galleriesUrl, setgalleriesUrl] = useState([]);// to save multiple picture url
const [coverPic, setCoverPic] = useState();
const [gallery, setGallery] = useState([]);
const [Error, setError] = useState('');

    function handleMultipleImage(e) {
        for (let i = 0; i < e.target.files.length; i++) {
            const newImage = e.target.files[i];
            setGallery((prevState) => [...prevState, newImage]);
        }
    }

    const uploadCoverPicture = () => {
        const storageRef = ref(storage, `/images/${Date.now()}-${coverPic.name}`);
        const uplaodTask = uploadBytesResumable(storageRef, coverPic);
        uplaodTask.on(
            "state_changed",
            (snapshot) => { },
            (error) => setError(error),
            () => {
                getDownloadURL(uplaodTask.snapshot.ref).then((downloadUrl) => {
                    setCoverPicUrl(downloadUrl);
                })
            }
        )
    }

    function uploadGalleryPictures() {
        gallery.map((file) => {
            const storageRef = ref(storage, `/images/${Date.now()}-${file.name}`);
            const uploadTask = uploadBytesResumable(storageRef, file);
            uploadTask.on(
                "state_changed",
                (snapshot) => { },
                (error) => setError(error),
                () => {
                    getDownloadURL(uploadTask.snapshot.ref).then((downloadURLs) => {
                        for (let i = 0; i < galleriesUrl.length; i++) {
                            const newUrl = downloadURLs;
                            setgalleriesUrl((prevState) => [...prevState, newUrl]);
                        }
                        ServiceRegistration({ coverPicUrl, galleriesUrl }).then(res => {
                            setloading(false);
                        }).catch(err => {
                            setloading(false);
                            console.log(err);
                        })
                    });
                }
            );

        })

    }

    function handleFirebaseUplaoding() {
        uploadCoverPicture();
        uploadGalleryPictures();
    }

    function handleRegistration(e) {
        e.preventDefault();
        setloading(true);
        if (!coverPic) {
            setError('Cover photo is required');
            setloading(false);
        }
        else {
            handleFirebaseUplaoding();
        }
    }

return (
        <>
<AppForm headerText='Register your service with WedBook' handleSubmit={handleRegistration} errorText={Error}>

          Upload a cover photo

          <input type="file" id='coverpic' onChange={(e) => { setCoverPic(e.target.files[0]) }} className="border border-gray-400 w-[80%] rounded-lg px-3 py-0.5  text-base outline-none " required />

           Upload Gallery Pictures (maximum 30 picture)

           <input type="file" name='coverPic' onChange={(e) => { handleMultipleImage(e) }} id='gallery' className="border border-gray-400 w-[80%] rounded-lg px-3 py-0.5  text-base outline-none " multiple />

         <ButtonOutline btnType='button' text='Go Back' clickEvent={() => { setImageForm(false) }} />
         <ButtonOutline btnType='submit' text='Register' />

</AppForm>
    </>
    );
}

I want to post request after recieving all urls from firebase . ServiceRegistration is backend request


问:
Torch not compiled with CUDA enabled when using pytorch with cuda on geforce 2070 Super
I’m trying to use pytorch with cuda. I have 2070 Super. I’ve installed cuda toolkit (v 10.2), and I’ve installed pytorch using pytorch docs:

```<code>conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 cudatoolkit=10.2 -c pytorch
</code>```

But when I try to use cuda I get an error

```<code>AssertionError: Torch not compiled with CUDA enabled
</code>```

Also torch version is:

```<code>>>> torch.__version__
'1.12.1'
</code>```

Body:
I’m trying to use pytorch with cuda. I have 2070 Super. I’ve installed cuda toolkit (v 10.2), and I’ve installed pytorch using pytorch docs:

conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 cudatoolkit=10.2 -c pytorch

But when I try to use cuda I get an error

AssertionError: Torch not compiled with CUDA enabled

Also torch version is:

>>> torch.__version__
'1.12.1'


问:
Python How to filter by value in two columns but keep values where year and period is less than value?
I have a dataframe that has a year and period column like so:

```<code>year    period
2022       1
2022       2
2022       3
2022       4
2023       1
2023       2
2023       3
2023       4
2024       1
2024       2
</code>```

I want to filter where the year is less than 2023 and period is less than 1. But, I want to keep all rows where the year and period is less than that like:

```<code>year    period
2022       1
2022       2
2022       3
2022       4
2023       1
</code>```

Right now I am doing:

```<code>   year_sub = data[data.year <= 2023]
   new_file = year_sub[year_sub.period == 1]
</code>```

However, this gives me

```<code>year    period
2022       1
2023       1
2024       1
</code>```

Body:
I have a dataframe that has a year and period column like so:

year    period
2022       1
2022       2
2022       3
2022       4
2023       1
2023       2
2023       3
2023       4
2024       1
2024       2

I want to filter where the year is less than 2023 and period is less than 1. But, I want to keep all rows where the year and period is less than that like:

year    period
2022       1
2022       2
2022       3
2022       4
2023       1

Right now I am doing:

   year_sub = data[data.year <= 2023]
   new_file = year_sub[year_sub.period == 1]

However, this gives me

year    period
2022       1
2023       1
2024       1


问:
How to change desktop wallpaper in Intune using PowerShell?
I'm trying to code a program where it will push the desktop wallpaper that I have saved locally on my computer to apply a desktop wallpaper. I've tried to code and the resulting work! Just want to know if this will work on other laptops as I am using my path which is located on my computer.

```<code>$imgPath="C:\Users\EdricVillanueva\Create IT\Create IT Team Site - Documents\08 Graphics\Create IT Wallpaper.jpg"
$code = @'
using System.Runtime.InteropServices;
namespace Win32{

     public class Wallpaper{
        [DllImport("user32.dll", CharSet=CharSet.Auto)]
         static extern int SystemParametersInfo (int uAction , int uParam , string lpvParam , int fuWinIni) ;

         public static void SetWallpaper(string thePath){
            SystemParametersInfo(20,0,thePath,3);
         }
    }
 }
'@

add-type $code

#Apply the Change to the system
[Win32.Wallpaper]::SetWallpaper($imgPath)
</code>```

Anything I can edit to change $imgPath.

Kindly note that the Create IT is from a onedrive folder.

Basically, other user has already onedrive on their laptop but I want to get the string of their username so that I can use their name instead of "EdricVillanueva"

Body:
I'm trying to code a program where it will push the desktop wallpaper that I have saved locally on my computer to apply a desktop wallpaper. I've tried to code and the resulting work! Just want to know if this will work on other laptops as I am using my path which is located on my computer.

$imgPath="C:\Users\EdricVillanueva\Create IT\Create IT Team Site - Documents\08 Graphics\Create IT Wallpaper.jpg"
$code = @'
using System.Runtime.InteropServices;
namespace Win32{

     public class Wallpaper{
        [DllImport("user32.dll", CharSet=CharSet.Auto)]
         static extern int SystemParametersInfo (int uAction , int uParam , string lpvParam , int fuWinIni) ;

         public static void SetWallpaper(string thePath){
            SystemParametersInfo(20,0,thePath,3);
         }
    }
 }
'@

add-type $code

#Apply the Change to the system
[Win32.Wallpaper]::SetWallpaper($imgPath)

Anything I can edit to change $imgPath.

Kindly note that the Create IT is from a onedrive folder.

Basically, other user has already onedrive on their laptop but I want to get the string of their username so that I can use their name instead of "EdricVillanueva"


问:
Is it possible to implicitly cast a generic type?
I'm working with a function that takes a list of email address records and returns the appropriate one for the use case. This list is passed to the function as an List[Map[String, String]], and the first step of the function is to cast each of the Map[String, String] members to a custom EmailAddress case class. Essentially, the relevant code looks like this:

val emails = List(Map("email_normalized" -> "email@address.com"))

object CaseClass {
  def identifyBestEmail(emails: List[Map[String, String]]): Map[String, String] = {
    val emailsCast = emails.map(emailFromMap)
    bestEmail(emailsCast)
  }

  def emailFromMap(x: Map[String, String]): EmailAddress = {
    EmailAddress(email_normalized = x.get("email_normalized").asInstanceOf[Option[String]])
  }

  def bestEmail(x: List[EmailAddress]) = {
    Map("email_normailzed" -> "the best")
  }

  case class EmailAddress(email_normalized: Option[String])
}

CaseClass.identifyBestEmail(emails)
```
<p>I'm new to Scala and just learned about implicits, and I feel like there has to be a way to simply this to something like:</p>
<pre class="lang-scala prettyprint-override"><code>val emails = List(Map("email_normalized" -> "email@address.com"))

object ImplicitClass {
  def identifyBestEmail(emails: List[EmailAddress]): EmailAddress = {
    Map("email_normailzed" -> "the best")
  }

  implicit class EmailAddress(emailMap: Map[String, String])
}

ImplicitClass.identifyBestEmail(emails)
</code>```

This latter example seems to me like it is much simpler, more flexible and easier to read than the previous one. However I can't figure out if there's a way to actually get it to work. When I try to run the code I get this error message:

```<code>error: type mismatch;
 found   : List[scala.collection.immutable.Map[String,String]]
 required: List[ImplicitClass.EmailAddress]
</code>```

Am I on the right track here? Is there a cleaner way of handling the use case than what's in the first example?

UPDATE 1

This seems to work:

val emails = List(Map("email_normalized" -> "email@address.com"))

object ImplicitList {
  def identifyBestEmail(emails: EmailAddressList): Map[String, String] = {
    Map("email_normailzed" -> "the best")
  }

  implicit class EmailAddressList(emailList: List[Map[String, String]])
}

ImplicitList.identifyBestEmail(emails)
```

So I guess that means implicit conversions do not work on generic classes, you need to operate on the top level class.

Body:
I'm working with a function that takes a list of email address records and returns the appropriate one for the use case. This list is passed to the function as an List[Map[String, String]], and the first step of the function is to cast each of the Map[String, String] members to a custom EmailAddress case class. Essentially, the relevant code looks like this:

val emails = List(Map("email_normalized" -> "email@address.com"))

object CaseClass {
  def identifyBestEmail(emails: List[Map[String, String]]): Map[String, String] = {
    val emailsCast = emails.map(emailFromMap)
    bestEmail(emailsCast)
  }

  def emailFromMap(x: Map[String, String]): EmailAddress = {
    EmailAddress(email_normalized = x.get("email_normalized").asInstanceOf[Option[String]])
  }

  def bestEmail(x: List[EmailAddress]) = {
    Map("email_normailzed" -> "the best")
  }

  case class EmailAddress(email_normalized: Option[String])
}

CaseClass.identifyBestEmail(emails)

I'm new to Scala and just learned about implicits, and I feel like there has to be a way to simply this to something like:

val emails = List(Map("email_normalized" -> "email@address.com"))

object ImplicitClass {
  def identifyBestEmail(emails: List[EmailAddress]): EmailAddress = {
    Map("email_normailzed" -> "the best")
  }

  implicit class EmailAddress(emailMap: Map[String, String])
}

ImplicitClass.identifyBestEmail(emails)

This latter example seems to me like it is much simpler, more flexible and easier to read than the previous one. However I can't figure out if there's a way to actually get it to work. When I try to run the code I get this error message:

error: type mismatch;
 found   : List[scala.collection.immutable.Map[String,String]]
 required: List[ImplicitClass.EmailAddress]

Am I on the right track here? Is there a cleaner way of handling the use case than what's in the first example?

UPDATE 1

This seems to work:

val emails = List(Map("email_normalized" -> "email@address.com"))

object ImplicitList {
  def identifyBestEmail(emails: EmailAddressList): Map[String, String] = {
    Map("email_normailzed" -> "the best")
  }

  implicit class EmailAddressList(emailList: List[Map[String, String]])
}

ImplicitList.identifyBestEmail(emails)

So I guess that means implicit conversions do not work on generic classes, you need to operate on the top level class.


问:
FutureWarning Pandas Error for Split Function
I am cleaning my dataset to prepare it for analysis, and I have several lines of code that look like this:

```<code>referrals[['First Name','Last Name']] = referrals['Victim'].str.split(' ', 1, expand=True)
</code>```

The 'Victims' column holds the full name, and I need to split that column into 'First Name' and 'Last Name'. I am getting a FutureWarning that reads the following:

```<code>FutureWarning: In a future version of pandas all arguments of StringMethods.split except for the argument 'pat' will be keyword-only.
</code>```

Can someone clarify what the new Pandas update will be doing that will nullify the way I'm writing the syntax currently? And what will be the updated ver to write the code so that I can prevent this FutureWarning from occurring? Thanks!

Tried to search up answers on Stack Overflow and couldn't seem to find an elucidating, satisfying answer.

Body:
I am cleaning my dataset to prepare it for analysis, and I have several lines of code that look like this:

referrals[['First Name','Last Name']] = referrals['Victim'].str.split(' ', 1, expand=True)

The 'Victims' column holds the full name, and I need to split that column into 'First Name' and 'Last Name'. I am getting a FutureWarning that reads the following:

FutureWarning: In a future version of pandas all arguments of StringMethods.split except for the argument 'pat' will be keyword-only.

Can someone clarify what the new Pandas update will be doing that will nullify the way I'm writing the syntax currently? And what will be the updated ver to write the code so that I can prevent this FutureWarning from occurring? Thanks!

Tried to search up answers on Stack Overflow and couldn't seem to find an elucidating, satisfying answer.


问:
check for unwanted variables in a switch configuration
i want to write a python script, that compares the variables against what is configured, if the config contains more than the expected variable, the script should put it out.

ntp = ntp server 192.168.1.1 ntp server 192.168.1.3 prefer'

if ntp == 'ntp server 1.1.1.1 ntp server 192.168.1.1 ntp server 192.168.1.3prefer':
print('yes')
else:
print('this is not true')


问:
Flask SQLAlchemy - Foreign key relationship not respected when writing record to table using inherited data model
I'm having trouble figuring out an issue with the foreign key integrity check when using inherited data models with Flask-SQLAlchemy and sqlite3. I have verified that the foreign key relationships have been enabled (PRAGMA foreign_keys = ON;) and foreign key constraint violations are triggered for non-inherited models. But for some reason when using a model that is inherited, I'm able to use non-existent id's to create records.

In the example provided, I'm able to create checking accounts using non-existent Provider Ids. I query sqlite and verify that the record is created with the non-existent id. However I try to write the record directly using a SQL command in SQL browser I get a foreign key violation error as expected.

Any ideas on what I'm missing?

Data models

```<code>class Provider(db.Model):
    """Model for account providers"""

    __tablename__ = "provider"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    routing_number = db.Column(db.String(20), nullable=False)

class ProviderSchema(SQLAlchemyAutoSchema):
    """Model's schema for account provider"""

    class Meta:
        model = Provider
        load_instance = True
</code>```
```<code>class Account(db.Model):
    """Model for account based objects."""

    __abstract__ = True
    @declared_attr
    def user_id(cls):
        return db.Column(db.Integer, db.ForeignKey('user.id'))
    @declared_attr
    def provider_id(cls):
        return db.Column(db.Integer, db.ForeignKey('provider.id'))
    nickname = db.Column(db.String(80), nullable=False)
    holder_name = db.Column(db.String(80), nullable=False)
    number = db.Column(db.String(80), nullable=False)
</code>```
```<code>class Checking(Account):
    """Model for checking account."""

    __tablename__ = "checking"
    id = db.Column(db.Integer, primary_key=True)
    provider_id = db.Column(db.Integer, db.ForeignKey('provider.id'))

class CheckingSchema(SQLAlchemyAutoSchema):
    """Model's Schema for checking account."""

    class Meta:
        model = Checking
        load_instance = True

    provider_id = field_for(Provider, "id", dump_only=False)
</code>```
```<code>class Savings(Account):
    """Model for savings account."""

    __tablename__ = "savings"
    id = db.Column(db.Integer, primary_key=True)
    provider_id = db.Column(db.Integer, db.ForeignKey('provider.id'))

class SavingsSchema(SQLAlchemyAutoSchema):
    """Model's Schema for savings account."""

    class Meta:
        model = Savings
        load_instance = True

    provider_id = field_for(Provider, "id", dump_only=False)
</code>```

Writing record

```<code>user_id = self.get_user_id_for_role(current_user, data)
provider_id = self.get_from_data_with_default("provider_id", data, 0)
nickname = self.get_from_data("nickname", data)
holder_name = self.get_from_data("holder_name", data)
number = self.get_from_data("number", data)

checking_account = Checking(user_id=user_id, provider_id=provider_id,
            nickname=nickname, holder_name=holder_name, number=number)

try:
     db.session.add(checking_account)
     db.session.commit()
except exc.SQLAlchemyError as e:
     msg = str(e)

     if msg != None and "UNIQUE contraint failed" in msg:
          db.session.rollback()
...
</code>```

Body:
I'm having trouble figuring out an issue with the foreign key integrity check when using inherited data models with Flask-SQLAlchemy and sqlite3. I have verified that the foreign key relationships have been enabled (PRAGMA foreign_keys = ON;) and foreign key constraint violations are triggered for non-inherited models. But for some reason when using a model that is inherited, I'm able to use non-existent id's to create records.

In the example provided, I'm able to create checking accounts using non-existent Provider Ids. I query sqlite and verify that the record is created with the non-existent id. However I try to write the record directly using a SQL command in SQL browser I get a foreign key violation error as expected.

Any ideas on what I'm missing?

Data models

class Provider(db.Model):
    """Model for account providers"""

    __tablename__ = "provider"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    routing_number = db.Column(db.String(20), nullable=False)

class ProviderSchema(SQLAlchemyAutoSchema):
    """Model's schema for account provider"""

    class Meta:
        model = Provider
        load_instance = True

class Account(db.Model):
    """Model for account based objects."""

    __abstract__ = True
    @declared_attr
    def user_id(cls):
        return db.Column(db.Integer, db.ForeignKey('user.id'))
    @declared_attr
    def provider_id(cls):
        return db.Column(db.Integer, db.ForeignKey('provider.id'))
    nickname = db.Column(db.String(80), nullable=False)
    holder_name = db.Column(db.String(80), nullable=False)
    number = db.Column(db.String(80), nullable=False)

class Checking(Account):
    """Model for checking account."""

    __tablename__ = "checking"
    id = db.Column(db.Integer, primary_key=True)
    provider_id = db.Column(db.Integer, db.ForeignKey('provider.id'))

class CheckingSchema(SQLAlchemyAutoSchema):
    """Model's Schema for checking account."""

    class Meta:
        model = Checking
        load_instance = True

    provider_id = field_for(Provider, "id", dump_only=False)

class Savings(Account):
    """Model for savings account."""

    __tablename__ = "savings"
    id = db.Column(db.Integer, primary_key=True)
    provider_id = db.Column(db.Integer, db.ForeignKey('provider.id'))

class SavingsSchema(SQLAlchemyAutoSchema):
    """Model's Schema for savings account."""

    class Meta:
        model = Savings
        load_instance = True

    provider_id = field_for(Provider, "id", dump_only=False)

Writing record

user_id = self.get_user_id_for_role(current_user, data)
provider_id = self.get_from_data_with_default("provider_id", data, 0)
nickname = self.get_from_data("nickname", data)
holder_name = self.get_from_data("holder_name", data)
number = self.get_from_data("number", data)

checking_account = Checking(user_id=user_id, provider_id=provider_id,
            nickname=nickname, holder_name=holder_name, number=number)

try:
     db.session.add(checking_account)
     db.session.commit()
except exc.SQLAlchemyError as e:
     msg = str(e)

     if msg != None and "UNIQUE contraint failed" in msg:
          db.session.rollback()
...


问:
Execution flow in shell script
I have below code in my entry point script for my java program. I am doing some post processing logic for istio process which is running along with my java application. This is after my main thread of java application stops running. Does the shell script wait for java process to complete before executing next line or do I need to conditionally check if java process has terminated?</p>
```<code>#!/bin/sh
set -e
set +x

    JVM_OPTS="-XX:+UseG1GC"

    # Application start-up JVM args
    START_CMD="java ${JVM_OPTS} ${JVM_ARGS} -jar ${1}"
    $START_CMD
    # will flow execution pause here till java process completes?

    #post processing logic after main java thread finishes
    x=$(echo $?)
    #Do I need to conditionally check for value of x before executing below line?
    curl -fsI -X POST http://localhost:15000/quitquitquit
    exit $x
</code>```

Title: Execution flow in shell script

Body:
I have below code in my entry point script for my java program. I am doing some post processing logic for istio process which is running along with my java application. This is after my main thread of java application stops running. Does the shell script wait for java process to complete before executing next line or do I need to conditionally check if java process has terminated?

#!/bin/sh
set -e
set +x

    JVM_OPTS="-XX:+UseG1GC"

    # Application start-up JVM args
    START_CMD="java ${JVM_OPTS} ${JVM_ARGS} -jar ${1}"
    $START_CMD
    # will flow execution pause here till java process completes?

    #post processing logic after main java thread finishes
    x=$(echo $?)
    #Do I need to conditionally check for value of x before executing below line?
    curl -fsI -X POST http://localhost:15000/quitquitquit
    exit $x


问:
API in python Error 400 "invalid input parameters" - how to fix
I am programming an API in python to query a server if it has endpoint agents in it. The server and the endpoint belong to Apex central SaaS trend micro.
The error I get is that I'm putting the wrong parameters but I don't think the problem is there.

The code I have for the query is as follows:

```<code>import base64
import jwt
import hashlib
import requests
import time
import json
import urllib.parse

def create_checksum(http_method, raw_url, headers, request_body):
    string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + headers + '|' + request_body
    base64_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8')
    return base64_string

def create_jwt_token(appication_id, api_key, http_method, raw_url, headers, request_body,
                     iat=time.time(), algorithm='HS256', version='V1'):
    payload = {'appid': appication_id,
               'iat': iat,
               'version': version,
               'checksum': create_checksum(http_method, raw_url, headers, request_body)}
    token = jwt.encode(payload, api_key, algorithm=algorithm)
    return token

# Use this region to setup the call info of the Apex Central server (server url, application id, api key)

# server info
use_url_base = 'https://arct3w.manage.trendmicro.com'
use_application_id = '52EB0005-B6DA-4249-9764-62AE3BFCDBB1'
use_api_key = 'B3FE1D91-5D05-490C-B45C-26A9EFF6C363'

productAgentAPIPath = '/WebApp/API/AgentResource/ProductAgents'
canonicalRequestHeaders = ''
useQueryString=''

payload = {

    'computerId':'e34a13a1-1d0f-47bc-96e0-ae4db4288940'

    }
useRequestBody = json.dumps(payload)

jwt_token = create_jwt_token(use_application_id, use_api_key, 'POST',
                              productAgentAPIPath + useQueryString,
                              canonicalRequestHeaders, useRequestBody, iat=time.time())

headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}

#Choose by call type.
r = requests.post(use_url_base + productAgentAPIPath + useQueryString, data=useRequestBody, headers=headers, verify=False)

print(r.status_code)

if 'application/json' in r.headers.get('Content-Type', '') and len(r.content):
    print(json.dumps(r.json(), indent=4))
else:
    print(r.text)

</code>```

I tried to do something similar to an api belonging to Vision One but it didn't work:
https://automation.trendmicro.com/xdr/api-v2#tag/Search/paths/~1v2.0~1xdr~1eiqs~1query~1endpointInfo/post

the original code of the query is :
https://automation.trendmicro.com/apex-central/api#tag/Security-Agents/operation/AgentResource_GetProductAgentsV2

Body:
I am programming an API in python to query a server if it has endpoint agents in it. The server and the endpoint belong to Apex central SaaS trend micro.
The error I get is that I'm putting the wrong parameters but I don't think the problem is there.

The code I have for the query is as follows:

import base64
import jwt
import hashlib
import requests
import time
import json
import urllib.parse

def create_checksum(http_method, raw_url, headers, request_body):
    string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + headers + '|' + request_body
    base64_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8')
    return base64_string

def create_jwt_token(appication_id, api_key, http_method, raw_url, headers, request_body,
                     iat=time.time(), algorithm='HS256', version='V1'):
    payload = {'appid': appication_id,
               'iat': iat,
               'version': version,
               'checksum': create_checksum(http_method, raw_url, headers, request_body)}
    token = jwt.encode(payload, api_key, algorithm=algorithm)
    return token

# Use this region to setup the call info of the Apex Central server (server url, application id, api key)

# server info
use_url_base = 'https://arct3w.manage.trendmicro.com'
use_application_id = '52EB0005-B6DA-4249-9764-62AE3BFCDBB1'
use_api_key = 'B3FE1D91-5D05-490C-B45C-26A9EFF6C363'

productAgentAPIPath = '/WebApp/API/AgentResource/ProductAgents'
canonicalRequestHeaders = ''
useQueryString=''

payload = {

    'computerId':'e34a13a1-1d0f-47bc-96e0-ae4db4288940'

    }
useRequestBody = json.dumps(payload)

jwt_token = create_jwt_token(use_application_id, use_api_key, 'POST',
                              productAgentAPIPath + useQueryString,
                              canonicalRequestHeaders, useRequestBody, iat=time.time())

headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}

#Choose by call type.
r = requests.post(use_url_base + productAgentAPIPath + useQueryString, data=useRequestBody, headers=headers, verify=False)

print(r.status_code)

if 'application/json' in r.headers.get('Content-Type', '') and len(r.content):
    print(json.dumps(r.json(), indent=4))
else:
    print(r.text)

I tried to do something similar to an api belonging to Vision One but it didn't work:
https://automation.trendmicro.com/xdr/api-v2#tag/Search/paths/~1v2.0~1xdr~1eiqs~1query~1endpointInfo/post

the original code of the query is :
https://automation.trendmicro.com/apex-central/api#tag/Security-Agents/operation/AgentResource_GetProductAgentsV2


问:
How to reset button after event fires (using removeEventListener)?
I'm currently working on a simple color generator that produces a random hexademical values (#FFFFFF), and changes the background color based on the hexcolor provided.

The program works well enough, but the button element doesn't seem to trigger the submit() function as its supposed to.

button is the reference for the HTML DOM element that will trigger the change in background color. I used button.addEventListener('click', submit()); to listen to the event trigger. It only works if you refresh the page, but not if you click on the button. Here's a link to the github repo.

```<code>// DOM elements
const button = document.getElementById('submit');
const para = document.getElementById('paragraph');

//Hex color variable
let hexaDecimal = [];
const arrangement = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];

// Function that randomizes a character 0-F, and pushes that to the hexaDemical array
const setColor = () => {

    for (let i = 0; i < 6; i++){
        let randNum = Math.floor(Math.random() * 16);

        hexaDecimal.push(arrangement[randNum]);
    }

  hexaDecimal = hexaDecimal.join("");
  hexaDecimal = '#' + hexaDecimal;

  return hexaDecimal;
}

const submit = () => {
    let newColor = setColor();
    document.body.style.backgroundColor = newColor;
    para.innerText = newColor;
    button.removeEventListener('click', submit());
}

button.addEventListener('click', submit());
</code>```

Body:
I'm currently working on a simple color generator that produces a random hexademical values (#FFFFFF), and changes the background color based on the hexcolor provided.

The program works well enough, but the button element doesn't seem to trigger the submit() function as its supposed to.

button is the reference for the HTML DOM element that will trigger the change in background color. I used button.addEventListener('click', submit()); to listen to the event trigger. It only works if you refresh the page, but not if you click on the button. Here's a link to the github repo.

// DOM elements
const button = document.getElementById('submit');
const para = document.getElementById('paragraph');

//Hex color variable
let hexaDecimal = [];
const arrangement = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];

// Function that randomizes a character 0-F, and pushes that to the hexaDemical array
const setColor = () => {

    for (let i = 0; i < 6; i++){
        let randNum = Math.floor(Math.random() * 16);

        hexaDecimal.push(arrangement[randNum]);
    }

  hexaDecimal = hexaDecimal.join("");
  hexaDecimal = '#' + hexaDecimal;

  return hexaDecimal;
}

const submit = () => {
    let newColor = setColor();
    document.body.style.backgroundColor = newColor;
    para.innerText = newColor;
    button.removeEventListener('click', submit());
}

button.addEventListener('click', submit());


问:
Pushing object to triple nested array in Mongoose
I am trying to figure out how to access and push an object into a triple nested array while using mongoose.

My idea is to divide a blog post into an array of chapters, where each has their own array of pages.  Each page will have a title, image and body.

Story schema (parent document)

```<code>const mongoose  = require('mongoose')
const pageSchema = require('./pageModel')

const storySchema = mongoose.Schema({
    storyTitle: {
        type: String,
        required: [true, 'Title required.']
    },
    storyAuthor: {
        type: String,
        required: [true, 'Author required.']
    },
    storyImage: {
        type: String,
        required: true,
    },
    chapters: [{
        chapterTitle: {
            type: String,
            //required: [true, 'Title required.']
        },
        chapterSummary: {
            type: String,
           // required: [true, 'Summary required.']
        },

        pages: [pageSchema]
    }]
})

module.exports = mongoose.model('Story', storySchema)
</code>```

the Page Schema

```<code>const mongoose  = require('mongoose')

const pageSchema = mongoose.Schema({
    pageTitle: {
        type: String,
        required: [true, 'Title required.']
    },
    pageBody: {
        type: String,

    },
    pageImage: {
        type: String,
    }
})
module.exports = pageSchema;
</code>```

Simple ops

```<code>const mongoose = require('mongoose')
const Story = require('./storyModel')
const Page = require('./pageModel')

const test = new Story({
    storyTitle: 'Test',
    storyAuthor: 'Myself',
    storyImage: 'test',

});

console.log(test);

test.chapters.push({
    chapterTitle: 'chapter 1',
    chapterSummary: 'let us see',

})

const first = {
    pageTitle: 'A page',
    pageImage: 'image',
    pageBody: 'A body'
}
console.log(test)

//test.chapters[0].pages[0].push(page)
test.chapters[0].pages.push(first)
console.log(test)

</code>```

When I log each step, the parent is correctly made, and I am able to append a chapter to the chapters array.  But when I the first object, the change isn't visible.

If I log test.chapters, the pages array shows pages: [ [Object] ]

And if I log test.chapters.pages, I just see 'undefined'.

Any suggestions and critique is appreciated.

Body:
I am trying to figure out how to access and push an object into a triple nested array while using mongoose.

My idea is to divide a blog post into an array of chapters, where each has their own array of pages.  Each page will have a title, image and body.

Story schema (parent document)

const mongoose  = require('mongoose')
const pageSchema = require('./pageModel')

const storySchema = mongoose.Schema({
    storyTitle: {
        type: String,
        required: [true, 'Title required.']
    },
    storyAuthor: {
        type: String,
        required: [true, 'Author required.']
    },
    storyImage: {
        type: String,
        required: true,
    },
    chapters: [{
        chapterTitle: {
            type: String,
            //required: [true, 'Title required.']
        },
        chapterSummary: {
            type: String,
           // required: [true, 'Summary required.']
        },

        pages: [pageSchema]
    }]
})

module.exports = mongoose.model('Story', storySchema)

the Page Schema

const mongoose  = require('mongoose')

const pageSchema = mongoose.Schema({
    pageTitle: {
        type: String,
        required: [true, 'Title required.']
    },
    pageBody: {
        type: String,

    },
    pageImage: {
        type: String,
    }
})
module.exports = pageSchema;

Simple ops

const mongoose = require('mongoose')
const Story = require('./storyModel')
const Page = require('./pageModel')

const test = new Story({
    storyTitle: 'Test',
    storyAuthor: 'Myself',
    storyImage: 'test',

});

console.log(test);

test.chapters.push({
    chapterTitle: 'chapter 1',
    chapterSummary: 'let us see',

})

const first = {
    pageTitle: 'A page',
    pageImage: 'image',
    pageBody: 'A body'
}
console.log(test)

//test.chapters[0].pages[0].push(page)
test.chapters[0].pages.push(first)
console.log(test)

When I log each step, the parent is correctly made, and I am able to append a chapter to the chapters array.  But when I the first object, the change isn't visible.

If I log test.chapters, the pages array shows pages: [ [Object] ]

And if I log test.chapters.pages, I just see 'undefined'.

Any suggestions and critique is appreciated.