问:
Error 503 Service unavailable when using Apache with a Node app
So I'm trying to host a Node app on an Ubuntu server. Its a small "To Do" task app that allows the user to add, edit and remove tasks on a list that are loaded from and saved to a MongoDB collection.

Previously I've hosted this locally on localhost:3000 and it's worked well. The app works like so:

```<code>//1. The user goes to http://localhost:3000/ and receives the default HTML page via:

app.get("/", (req, res) => {
    res.sendFile(__dirname+"/public/index.html")
});

//2. On load the HTML page calls a function from code.js that loads the tasks from MongoDB via:

//JS code
async function loadTodos() {
    let response = await fetch('http://localhost:3000/todos')
    let todos = await response.json()
      console.log(todos)
    showTodos(todos)
}
//On the app side
app.get('/todos', async (request, response) => {
    const todos = await Todo.find({})
    response.json(todos)
})

//3. After that all the edits, additions and removals are done the same way. The JS code uses fetch to a certain route and the app returns the values.
</code>```

Now the problems come in when I need to use the Apache server.

I've enabled Apache proxy modules and set the proxy pass to:

```<code><VirtualHost *:8080>
 ProxyPreserveHost on
 ProxyPass / http://localhost:3000/
 ProxyPassReverse / http://localhost:3000/
</VirtualHost>
</code>```

I've installed Express, Mongoose, Cors and iniated the NPM project.

I've added Listen 8080 to /etc/apache2/ports.confsudo and /etc/apache2/ports.conf

The file structure is like so, where code.js contains all the JavaScript for the HTML page and app.js for the Node-app.

```<code>/var/www/nodejs
--app.js
--package-lock.json
--package.json
--node_modules
--public
---code.js
---index.html
---style
----styles.css
</code>```

The problem is that when I try to go to http://[Server IP]:8080/  I receive the 503 Service unavailable error.

Could the issue be that I've used app.get("/" to access the HTML page and the Proxy pass http://localhost:3000/ doesn't work with it?

I am quite lost.

Edit:

The 503 error seems to be caused by the res.sendFile process

Body:
So I'm trying to host a Node app on an Ubuntu server. Its a small "To Do" task app that allows the user to add, edit and remove tasks on a list that are loaded from and saved to a MongoDB collection.

Previously I've hosted this locally on localhost:3000 and it's worked well. The app works like so:

//1. The user goes to http://localhost:3000/ and receives the default HTML page via:

app.get("/", (req, res) => {
    res.sendFile(__dirname+"/public/index.html")
});

//2. On load the HTML page calls a function from code.js that loads the tasks from MongoDB via:

//JS code
async function loadTodos() {
    let response = await fetch('http://localhost:3000/todos')
    let todos = await response.json()
      console.log(todos)
    showTodos(todos)
}
//On the app side
app.get('/todos', async (request, response) => {
    const todos = await Todo.find({})
    response.json(todos)
})

//3. After that all the edits, additions and removals are done the same way. The JS code uses fetch to a certain route and the app returns the values.

Now the problems come in when I need to use the Apache server.

I've enabled Apache proxy modules and set the proxy pass to:

<VirtualHost *:8080>
 ProxyPreserveHost on
 ProxyPass / http://localhost:3000/
 ProxyPassReverse / http://localhost:3000/
</VirtualHost>

I've installed Express, Mongoose, Cors and iniated the NPM project.

I've added Listen 8080 to /etc/apache2/ports.confsudo and /etc/apache2/ports.conf

The file structure is like so, where code.js contains all the JavaScript for the HTML page and app.js for the Node-app.

/var/www/nodejs
--app.js
--package-lock.json
--package.json
--node_modules
--public
---code.js
---index.html
---style
----styles.css

The problem is that when I try to go to http://[Server IP]:8080/  I receive the 503 Service unavailable error.

Could the issue be that I've used app.get("/" to access the HTML page and the Proxy pass http://localhost:3000/ doesn't work with it?

I am quite lost.

Edit:

The 503 error seems to be caused by the res.sendFile process


来源: stackexchange

问:
Random lock timeout error on ArangoDB update
I got this random timeout error when updating existing document.

```<code>AQL: timeout waiting to lock key Operation timed out: Timeout waiting to lock key; key: 1013 (while executing)
</code>```

ArangoDB version: 3.9

ArangoJS version :8.0.0

ContentLicense: CC BY-SA 4.0

Body:
I got this random timeout error when updating existing document.

AQL: timeout waiting to lock key Operation timed out: Timeout waiting to lock key; key: 1013 (while executing)

ArangoDB version: 3.9

ArangoJS version :8.0.0


问:
Add onClick event on a preview image in DropzoneArea (Material-ui)
I have this DropzoneArea component from Material ui and I'm trying to add an onClick event on the file so that I can open a modal with the full size image from the preview image url.

```<code><DropzoneArea
  acceptedFiles={['image/jpeg', 'image/png', 'image/bmp']}
  clearOnUnmount
  dropzoneClass={classes.imageArea}
  dropzoneText="Imagem"
  filesLimit={1}
  getFileAddedMessage={(fileName) => {
    return `Arquivo ${fileName} anexado.`;
  }}
  getDropRejectMessage={(rejectedFile) => {
    return `Este formato de arquivo ${rejectedFile.type} não é permitido.`;
  }}
  getFileRemovedMessage={(fileName) => {
    return `Arquivo ${fileName} removido.`;
  }}
  id="drop"
  initialFiles={[storageUrl + factura.Ficheiro]}
  maxFileSize={5000000}
  onChange={(files) => handleFileUpload(files)}
  showPreviewsInDropzone={true}
  previewGridProps={{
    container: {
      spacing: 1,
      direction: 'row',
      justify: 'center'
    }
  }}
/>;
</code>```

the result expected

I can't find a way to do it. I've been looking over and over the mui props for this component. Does anyone knows any prop that could help me out on that?

Body:
I have this DropzoneArea component from Material ui and I'm trying to add an onClick event on the file so that I can open a modal with the full size image from the preview image url.

<DropzoneArea
  acceptedFiles={['image/jpeg', 'image/png', 'image/bmp']}
  clearOnUnmount
  dropzoneClass={classes.imageArea}
  dropzoneText="Imagem"
  filesLimit={1}
  getFileAddedMessage={(fileName) => {
    return `Arquivo ${fileName} anexado.`;
  }}
  getDropRejectMessage={(rejectedFile) => {
    return `Este formato de arquivo ${rejectedFile.type} não é permitido.`;
  }}
  getFileRemovedMessage={(fileName) => {
    return `Arquivo ${fileName} removido.`;
  }}
  id="drop"
  initialFiles={[storageUrl + factura.Ficheiro]}
  maxFileSize={5000000}
  onChange={(files) => handleFileUpload(files)}
  showPreviewsInDropzone={true}
  previewGridProps={{
    container: {
      spacing: 1,
      direction: 'row',
      justify: 'center'
    }
  }}
/>;

the result expected

I can't find a way to do it. I've been looking over and over the mui props for this component. Does anyone knows any prop that could help me out on that?


问:
Chromium update (Chrome and Edge 108) broke my Javascript that posts data to a bootstrap modal
With the latest Chrome/Edge update (108) my page now hangs instead of showing the data in the modal. I get a unresponsive error and it never resolves. Sometimes the modal footer shows but never the data. If I downgrade my Chrome version it resolves the issue. Am I doing something wrong here that I can correct?

Modal on the main page:

```<code><div class="modal-content">
  <div class="modal-body" style="column-count: 3; column-width: 100px; margin: auto">
  </div>
  <div class="modal-footer">
    <input type="submit" name="Save" class="btn btn-success" value="Save" />
    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
  </div>
</div>
</code>```

Controller:

```<code>[HttpGet]
public async Task<ActionResult> DocumentTypes(int id)
{
   //Code to populate the model
   return PartialView("_DocumentTypes", model);
}
</code>```

Javascript:

```<code>function documentTypeSelect(id) {
  $.get("@Url.Action("Method", "Controller")/" + id,
    function (data) {
      $('.modal-body').html(data);
    });
    $("#documentTypeModel").modal("show");
}
</code>```

Button that fires the Javascript:

```<code><a class="btn btn-default btn-sm" style="white-space: normal; text-align: left" id="@item.Id" onclick="documentTypeSelect(this.id)">
    @Html.DisplayFor(model => item.DocuType)
</a>
</code>```

Edit:

Rendered Javascript:

```<code>function documentTypeSelect(id) {
  $.get("/Controller/Method/" + id,
    function (data) {
      $('.modal-body').html(data);
    });
    $("#documentTypeModel").modal("show");
}
</code>```

If I comment out the following code in my Javascript the modal shows and there is no unresponsive error, but obviously the data in the modal-body doesn't show.

```<code>$('.modal-body').html(data);
</code>```

PartialView where I am rendering the list I created in the controller:

```<code>@for (var i = 0; i < Model.DocumentTypeList.Count(); i++)
{
  <div class="row row-eq-height">
    <div class="form-group col-md">
      <div class="row row-eq-height border-bottom">
        <div class="col-md-10">
          @Html.DisplayFor(m => m.DocumentTypeList[i].Display, new { @class = "control-label" })
        </div>
        <div class="col-md-2">
          @Html.CheckBoxFor(m => m.DocumentTypeList[i].Status, new { @class = "form-control" })
          @Html.HiddenFor(m => m.DocumentTypeList[i].Display)
          @Html.HiddenFor(m => m.DocumentTypeList[i].Code)
        </div>
      </div>
    </div>
  </div>
}
</code>```

Edit 2:

If I remove this styling then the modal displays without Chrome hanging.

```<code><div class="modal-body" style="column-count: 3; column-width: 100px; margin: auto">
</code>```

Edit 3:

If I only remove margin: auto, then it works as well...like so:

```<code><div class="modal-body" style="column-count: 3; column-width: 100px;">
</code>```

Body:
With the latest Chrome/Edge update (108) my page now hangs instead of showing the data in the modal. I get a unresponsive error and it never resolves. Sometimes the modal footer shows but never the data. If I downgrade my Chrome version it resolves the issue. Am I doing something wrong here that I can correct?

Modal on the main page:

    <input type="submit" name="Save" class="btn btn-success" value="Save" />
    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

Controller:

[HttpGet]
public async Task<ActionResult> DocumentTypes(int id)
{
   //Code to populate the model
   return PartialView("_DocumentTypes", model);
}

Javascript:

function documentTypeSelect(id) {
  $.get("@Url.Action("Method", "Controller")/" + id,
    function (data) {
      $('.modal-body').html(data);
    });
    $("#documentTypeModel").modal("show");
}

Button that fires the Javascript:

    @Html.DisplayFor(model => item.DocuType)

Edit:

Rendered Javascript:

function documentTypeSelect(id) {
  $.get("/Controller/Method/" + id,
    function (data) {
      $('.modal-body').html(data);
    });
    $("#documentTypeModel").modal("show");
}

If I comment out the following code in my Javascript the modal shows and there is no unresponsive error, but obviously the data in the modal-body doesn't show.

$('.modal-body').html(data);

PartialView where I am rendering the list I created in the controller:

@for (var i = 0; i < Model.DocumentTypeList.Count(); i++)
{

          @Html.DisplayFor(m => m.DocumentTypeList[i].Display, new { @class = "control-label" })

          @Html.CheckBoxFor(m => m.DocumentTypeList[i].Status, new { @class = "form-control" })
          @Html.HiddenFor(m => m.DocumentTypeList[i].Display)
          @Html.HiddenFor(m => m.DocumentTypeList[i].Code)

}

Edit 2:

If I remove this styling then the modal displays without Chrome hanging.

Edit 3:

If I only remove margin: auto, then it works as well...like so:


问:
Flutter space icons evenly in DropDownButton uniformally and equidistant
I'm building a Flutter Web App and am hacking the appbar for my navigation. I'm creating a dropdown menu to give some more options, only I want the arrow icons to be uniform and not change the spacing. This is an example of what I want:

And this is what I have:

It's subtle but also annoying me. This is the code I have for each dropdownbutton:

```<code>  return DropdownButtonHideUnderline(
      child: DropdownButton<String>(
        isExpanded: false,
        alignment: Alignment.center,

        iconSize: 15,

        value: dropdownValue,
        icon: const Icon(Icons.arrow_downward),
        // elevation: 16,
        style: TextStyle(
          color: Theme.of(context).colorScheme.primary,
          fontFamily: GoogleFonts.lora().fontFamily,
        ),

        onChanged: (String? value) {
          // This is called when the user selects an item.
          setState(() {
            dropdownValue = value!;
          });
        },
</code>```

I tried wrapping them in a sized box with equal height and width, but that also didn't work, this is the closest I've gotten them.

Body:
I'm building a Flutter Web App and am hacking the appbar for my navigation. I'm creating a dropdown menu to give some more options, only I want the arrow icons to be uniform and not change the spacing. This is an example of what I want:

And this is what I have:

It's subtle but also annoying me. This is the code I have for each dropdownbutton:

  return DropdownButtonHideUnderline(
      child: DropdownButton<String>(
        isExpanded: false,
        alignment: Alignment.center,

        iconSize: 15,

        value: dropdownValue,
        icon: const Icon(Icons.arrow_downward),
        // elevation: 16,
        style: TextStyle(
          color: Theme.of(context).colorScheme.primary,
          fontFamily: GoogleFonts.lora().fontFamily,
        ),

        onChanged: (String? value) {
          // This is called when the user selects an item.
          setState(() {
            dropdownValue = value!;
          });
        },

I tried wrapping them in a sized box with equal height and width, but that also didn't work, this is the closest I've gotten them.


问:
detect if pressed escape key during write input (keyboard) Python
I have problem with Python. I need during entering a value (in input),
closing and exiting the program using the ESC key. (By using keyboard)

```<code>Number_of_marks = input("Enter your number") `during write this`
x = 0
while Number_of_marks > x:
    marks = input("Give your mark") ``during write this``
    x += 1
</code>```

I tried sth as
while keyboard.is_pressed('Esc') == False:
but it doesn't work as I want to.
I thank about sleep but in task I have ,,During entering value". I don't have any idea to resolve it
The best will be if the solution won't have any library

Body:
I have problem with Python. I need during entering a value (in input),
closing and exiting the program using the ESC key. (By using keyboard)

Number_of_marks = input("Enter your number") `during write this`
x = 0
while Number_of_marks > x:
    marks = input("Give your mark") ``during write this``
    x += 1

I tried sth as
while keyboard.is_pressed('Esc') == False:
but it doesn't work as I want to.
I thank about sleep but in task I have ,,During entering value". I don't have any idea to resolve it
The best will be if the solution won't have any library


问:
Is there a way to define or use variable with variables in python?
for example, if I want to define many variables as
ParameterA1
ParameterB1
ParameterC1
ParameterD1
...
ParameterZ2
ParameterA2
ParameterB2
ParameterC2
ParameterD2
...
ParameterZ2
...
...
...
ParameterA12
ParameterB12
ParameterC12
ParameterD12
...
ParameterZ12

Do I have to define them one by one, or I can use some loop here?
Thanks.

```<code>ParameterA1=[]
ParameterB1=[]
ParameterC1=[]
ParameterD1=[]
...
ParameterZ2=[]
ParameterA2=[]
ParameterB2=[]
ParameterC2=[]
ParameterD2=[]
...
ParameterZ2=[]
...
...
...
ParameterA12=[]
ParameterB12=[]
ParameterC12=[]
ParameterD12=[]
...
ParameterZ12=[]
</code>```

Body:
for example, if I want to define many variables as
ParameterA1
ParameterB1
ParameterC1
ParameterD1
...
ParameterZ2
ParameterA2
ParameterB2
ParameterC2
ParameterD2
...
ParameterZ2
...
...
...
ParameterA12
ParameterB12
ParameterC12
ParameterD12
...
ParameterZ12

Do I have to define them one by one, or I can use some loop here?
Thanks.

ParameterA1=[]
ParameterB1=[]
ParameterC1=[]
ParameterD1=[]
...
ParameterZ2=[]
ParameterA2=[]
ParameterB2=[]
ParameterC2=[]
ParameterD2=[]
...
ParameterZ2=[]
...
...
...
ParameterA12=[]
ParameterB12=[]
ParameterC12=[]
ParameterD12=[]
...
ParameterZ12=[]


问:
How to declare View class method definition in an Expo native view module
I created an Expo native module like below. I can declare properties of the view. But I have not figured out how to declare class member method yet, like play/pause method of the player view. I am not sure if it's just impossible in Expo. Many thanks

```<code>    View(VideoPlayerView.self) {

      Prop("speed") { (view: VideoPlayerView, speed: Double) in
        view.setSpeed( speed )
      }
</code>```

I searched the source code of Expo

https://github.com/expo/expo/blob/753557f6db11f4ecd1ab25545f2768b0fd863cf7/ios/versioned/sdk47/ExpoModulesCore/ios/Swift/Views/ViewDefinition.swift

and it seems it only support LifeCycleMethod, not generic method. If so, just want to get a confirmation to avoid waste of time

Body:
I created an Expo native module like below. I can declare properties of the view. But I have not figured out how to declare class member method yet, like play/pause method of the player view. I am not sure if it's just impossible in Expo. Many thanks

    View(VideoPlayerView.self) {

      Prop("speed") { (view: VideoPlayerView, speed: Double) in
        view.setSpeed( speed )
      }

I searched the source code of Expo

https://github.com/expo/expo/blob/753557f6db11f4ecd1ab25545f2768b0fd863cf7/ios/versioned/sdk47/ExpoModulesCore/ios/Swift/Views/ViewDefinition.swift

and it seems it only support LifeCycleMethod, not generic method. If so, just want to get a confirmation to avoid waste of time


问:
FirebaseError: Firebase: Error (auth/invalid-api-key) while building docker image in Github Actions
I am trying to create a CI/CD process using GitHub Actions. The process includes testing, building the docker image and uploading it to Google Cloud Run.

Everything works fine when running the project locally, because locally I have access to the .env file. But this file is not been pushed to github repository.

The issue happens when the firebase is initialized, because all the values are inside the .env file

The error showed in the workflow logs is below:

```<code>#15 1.258 info  - Linting and checking validity of types...
#15 8.148 info  - Creating an optimized production build...
#15 19.76 info  - Compiled successfully
#15 19.76 info  - Collecting page data...
#15 20.33 FirebaseError: Firebase: Error (auth/invalid-api-key).
#15 20.33     at createErrorInternal (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:467:40)
#15 20.33     at _assert (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:471:15)
#15 20.33     at file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:6075:13
#15 20.33     at Component.instanceFactory (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:6092:11)
#15 20.33     at Provider.getOrInitializeService (file:///app/node_modules/@firebase/component/dist/esm/index.esm2017.js:290:39)
#15 20.33     at Provider.initialize (file:///app/node_modules/@firebase/component/dist/esm/index.esm2017.js:234:31)
#15 20.33     at initializeAuth (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:585:27)
#15 20.33     at getAuth (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:6141:18)
#15 20.33     at /app/.next/server/chunks/933.js:121:68 ***
#15 20.33   code: 'auth/invalid-api-key',
#15 20.33   customData: *** appName: '[DEFAULT]' ***
#15 20.33 ***
</code>```

I inserted the environment variable in the files:

GitHub: Settings -> Security -> Secrets -> Actions

Cloud Run: Environment variables

next.config

const nextConfig = {
reactStrictMode: true,
swcMinify: true,
output: 'standalone',
env: {
NEXT_PUBLIC_FIREBASE_API_KEY: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
NEXT_PUBLIC_FIREBASE_PROJECT_ID: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
}
}

module.exports = nextConfig

Below is the workflow. I placed the environment variables for the building process and the push to cloud run process.

```<code>name: CI and CD

on:
  workflow_dispatch:
  push:
    branches: [main, develop]

env:
  REGISTRY: gcr.io
  IMAGE_NAME: ${{ secrets.GCP_PROJECT_NAME }}/${{ secrets.CLOUD_RUN_SERVICE }}
  REGION: us-central1

jobs:
  test-code:
    runs-on: ubuntu-20.04

    steps:
    - uses: actions/checkout@v3
    - name: Use Node.js 16.x
      uses: actions/setup-node@v3
      with:
        node-version: 16.x
    - run: npm ci
    - run: npm run test

  build-image:
    needs: test-code
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-20.04
    outputs:
      tags: ${{ steps.meta.outputs.tags }}
    concurrency: build-image-process
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      # Workaround: https://github.com/docker/build-push-action/issues/461
      - name: Setup Docker buildx
        uses: docker/setup-buildx-action@79abd3f86f79a9d68a23c75a09a9a85889262adf

      # Login against a Docker registry except on PR
      # https://github.com/docker/login-action
      - name: Log into registry ${{ env.REGISTRY }}
        if: github.event_name != 'pull_request'
        uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c
        with:
          registry: ${{ env.REGISTRY }}
          username: _json_key
          password: ${{ secrets.GCP_SERVICE_ACCOUNT }}

      # Extract metadata (tags, labels) for Docker
      # https://github.com/docker/metadata-action
      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      # Build and push Docker image with Buildx (don't push on PR)
      # https://github.com/docker/build-push-action
      - name: Build and push Docker image
        id: build-and-push
        uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a
        if: ${{ github.event_name != 'pull_request' }}
        with:
          context: .
          file: ./Dockerfile.prod
          secrets: |
            "NEXT_PUBLIC_FIREBASE_API_KEY=${{ secrets.NEXT_PUBLIC_FIREBASE_API_KEY }}"
            "NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=${{ secrets.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN }}"
            "NEXT_PUBLIC_FIREBASE_PROJECT_ID=${{ secrets.NEXT_PUBLIC_FIREBASE_PROJECT_ID }}"
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Outputs tags
        run: echo "${{ steps.meta.outputs.tags }}"

  deploy-image:
    needs: build-image
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-20.04
    steps:

      - name: Checkout repository
        uses: actions/checkout@v3

      - id: 'auth'
        uses: 'google-github-actions/auth@v0'
        with:
          credentials_json: '${{ secrets.GCP_SERVICE_ACCOUNT }}'

      - name: Build Image Outputs Tags
        run: echo "${{ needs.build-image.outputs.tags }}"

      - name: 'Deploy to Cloud Run'
        uses: 'google-github-actions/deploy-cloudrun@v0'
        with:
          service: ${{ secrets.CLOUD_RUN_SERVICE }}
          image: "${{ needs.build-image.outputs.tags }}"
          region: ${{ env.REGION }}
          env_vars:
            NEXT_PUBLIC_FIREBASE_API_KEY=${{ secrets.NEXT_PUBLIC_FIREBASE_API_KEY }}
            NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=${{ secrets.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN }}
            NEXT_PUBLIC_FIREBASE_PROJECT_ID=${{ secrets.NEXT_PUBLIC_FIREBASE_PROJECT_ID }}
</code>```

I appreciate any help to make the whole process to work smoothly.

Body:
I am trying to create a CI/CD process using GitHub Actions. The process includes testing, building the docker image and uploading it to Google Cloud Run.

Everything works fine when running the project locally, because locally I have access to the .env file. But this file is not been pushed to github repository.

The issue happens when the firebase is initialized, because all the values are inside the .env file

The error showed in the workflow logs is below:

#15 1.258 info  - Linting and checking validity of types...
#15 8.148 info  - Creating an optimized production build...
#15 19.76 info  - Compiled successfully
#15 19.76 info  - Collecting page data...
#15 20.33 FirebaseError: Firebase: Error (auth/invalid-api-key).
#15 20.33     at createErrorInternal (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:467:40)
#15 20.33     at _assert (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:471:15)
#15 20.33     at file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:6075:13
#15 20.33     at Component.instanceFactory (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:6092:11)
#15 20.33     at Provider.getOrInitializeService (file:///app/node_modules/@firebase/component/dist/esm/index.esm2017.js:290:39)
#15 20.33     at Provider.initialize (file:///app/node_modules/@firebase/component/dist/esm/index.esm2017.js:234:31)
#15 20.33     at initializeAuth (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:585:27)
#15 20.33     at getAuth (file:///app/node_modules/@firebase/auth/dist/node-esm/index-3246d34e.js:6141:18)
#15 20.33     at /app/.next/server/chunks/933.js:121:68 ***
#15 20.33   code: 'auth/invalid-api-key',
#15 20.33   customData: *** appName: '[DEFAULT]' ***
#15 20.33 ***

I inserted the environment variable in the files:

GitHub: Settings -> Security -> Secrets -> Actions

Cloud Run: Environment variables

next.config

const nextConfig = {
reactStrictMode: true,
swcMinify: true,
output: 'standalone',
env: {
NEXT_PUBLIC_FIREBASE_API_KEY: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
NEXT_PUBLIC_FIREBASE_PROJECT_ID: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
}
}

module.exports = nextConfig

Below is the workflow. I placed the environment variables for the building process and the push to cloud run process.

name: CI and CD

on:
  workflow_dispatch:
  push:
    branches: [main, develop]

env:
  REGISTRY: gcr.io
  IMAGE_NAME: ${{ secrets.GCP_PROJECT_NAME }}/${{ secrets.CLOUD_RUN_SERVICE }}
  REGION: us-central1

jobs:
  test-code:
    runs-on: ubuntu-20.04

    steps:
    - uses: actions/checkout@v3
    - name: Use Node.js 16.x
      uses: actions/setup-node@v3
      with:
        node-version: 16.x
    - run: npm ci
    - run: npm run test

  build-image:
    needs: test-code
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-20.04
    outputs:
      tags: ${{ steps.meta.outputs.tags }}
    concurrency: build-image-process
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      # Workaround: https://github.com/docker/build-push-action/issues/461
      - name: Setup Docker buildx
        uses: docker/setup-buildx-action@79abd3f86f79a9d68a23c75a09a9a85889262adf

      # Login against a Docker registry except on PR
      # https://github.com/docker/login-action
      - name: Log into registry ${{ env.REGISTRY }}
        if: github.event_name != 'pull_request'
        uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c
        with:
          registry: ${{ env.REGISTRY }}
          username: _json_key
          password: ${{ secrets.GCP_SERVICE_ACCOUNT }}

      # Extract metadata (tags, labels) for Docker
      # https://github.com/docker/metadata-action
      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      # Build and push Docker image with Buildx (don't push on PR)
      # https://github.com/docker/build-push-action
      - name: Build and push Docker image
        id: build-and-push
        uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a
        if: ${{ github.event_name != 'pull_request' }}
        with:
          context: .
          file: ./Dockerfile.prod
          secrets: |
            "NEXT_PUBLIC_FIREBASE_API_KEY=${{ secrets.NEXT_PUBLIC_FIREBASE_API_KEY }}"
            "NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=${{ secrets.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN }}"
            "NEXT_PUBLIC_FIREBASE_PROJECT_ID=${{ secrets.NEXT_PUBLIC_FIREBASE_PROJECT_ID }}"
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Outputs tags
        run: echo "${{ steps.meta.outputs.tags }}"

  deploy-image:
    needs: build-image
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-20.04
    steps:

      - name: Checkout repository
        uses: actions/checkout@v3

      - id: 'auth'
        uses: 'google-github-actions/auth@v0'
        with:
          credentials_json: '${{ secrets.GCP_SERVICE_ACCOUNT }}'

      - name: Build Image Outputs Tags
        run: echo "${{ needs.build-image.outputs.tags }}"

      - name: 'Deploy to Cloud Run'
        uses: 'google-github-actions/deploy-cloudrun@v0'
        with:
          service: ${{ secrets.CLOUD_RUN_SERVICE }}
          image: "${{ needs.build-image.outputs.tags }}"
          region: ${{ env.REGION }}
          env_vars:
            NEXT_PUBLIC_FIREBASE_API_KEY=${{ secrets.NEXT_PUBLIC_FIREBASE_API_KEY }}
            NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=${{ secrets.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN }}
            NEXT_PUBLIC_FIREBASE_PROJECT_ID=${{ secrets.NEXT_PUBLIC_FIREBASE_PROJECT_ID }}

I appreciate any help to make the whole process to work smoothly.


问:
How to call function after permission is given in flutter with permission handler
I'm asking for storage permission on android using permission manager. In case permission is given, just after the user accepted, I want to call a function to store some data but is not working.
I DONT HAVE PROBLEMS WITH THE PERMISSION ITSELF, just with the function that i'm calling right after permission is given.
My code is the folowing:

```<code>  void exportFile() async {
    var status = await Permission.storage.status;
    if (await !status.isGranted) {
      await Permission.storage.request();
      if (await status.isGranted) {
        writeFile(); /// this is not working!!
      }else{
        print("access not granted") /// this works fine
      }
    }
  }
</code>```

If the user accepts, permision is granted but the function writeFile is not called right after the permission is given and that is what I want to achieve. I don't see what i'm missing here. I appreciate any idea or suggerstion.

Body:
I'm asking for storage permission on android using permission manager. In case permission is given, just after the user accepted, I want to call a function to store some data but is not working.
I DONT HAVE PROBLEMS WITH THE PERMISSION ITSELF, just with the function that i'm calling right after permission is given.
My code is the folowing:

  void exportFile() async {
    var status = await Permission.storage.status;
    if (await !status.isGranted) {
      await Permission.storage.request();
      if (await status.isGranted) {
        writeFile(); /// this is not working!!
      }else{
        print("access not granted") /// this works fine
      }
    }
  }

If the user accepts, permision is granted but the function writeFile is not called right after the permission is given and that is what I want to achieve. I don't see what i'm missing here. I appreciate any idea or suggerstion.


问:
Neutrino : Npm start failed to launch the project
What version of Neutrino are you using?

9 . 5 . 0

1 ) Are you trying to use any presets? If so, which ones, and what versions?

React - Jest - Airbnb

2 ) Are you using the Yarn client or the npm client? What version?

NPM 8 . 19 .2

3 ) What version of Node.js are you using?

18 . 12 . 1

4 ) What operating system are you using?

Linux UBUNTU 22.04

5 ) What did you do?

Run this command :

npx @neutrinojs/create-project <directory-name>

Next command :

npm start

6 ) What did you expect to happen?

Seeing the first or the index page on the browser.

What actually happened, contrary to your expectations?

```<code>Internal Error:
 react-app@1.0.0 start
> webpack-dev-server --mode development --open

ℹ ｢wds｣: Project is running at http://localhost:5000/
ℹ ｢wds｣: webpack output is served from /
ℹ ｢wds｣: Content not from webpack is served from /home/alaeddine/Apps/react-app
ℹ ｢wds｣: 404s will fallback to /index.html
node:internal/crypto/hash:71
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/home/alaeddine/Apps/react-app/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:417:16)
    at handleParseError (/home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:471:10)
    at /home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:503:5
    at /home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:358:12
    at /home/alaeddine/Apps/react-app/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/home/alaeddine/Apps/react-app/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at Array.<anonymous> (/home/alaeddine/Apps/react-app/node_modules/loader-runner/lib/LoaderRunner.js:205:4) {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.12.1
</code>```

Browser :

Body:
What version of Neutrino are you using?

9 . 5 . 0

1 ) Are you trying to use any presets? If so, which ones, and what versions?

React - Jest - Airbnb

2 ) Are you using the Yarn client or the npm client? What version?

NPM 8 . 19 .2

3 ) What version of Node.js are you using?

18 . 12 . 1

4 ) What operating system are you using?

Linux UBUNTU 22.04

5 ) What did you do?

Run this command :

npx @neutrinojs/create-project <directory-name>

Next command :

npm start

6 ) What did you expect to happen?

Seeing the first or the index page on the browser.

What actually happened, contrary to your expectations?

Internal Error:
 react-app@1.0.0 start
> webpack-dev-server --mode development --open

ℹ ｢wds｣: Project is running at http://localhost:5000/
ℹ ｢wds｣: webpack output is served from /
ℹ ｢wds｣: Content not from webpack is served from /home/alaeddine/Apps/react-app
ℹ ｢wds｣: 404s will fallback to /index.html
node:internal/crypto/hash:71
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/home/alaeddine/Apps/react-app/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:417:16)
    at handleParseError (/home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:471:10)
    at /home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:503:5
    at /home/alaeddine/Apps/react-app/node_modules/webpack/lib/NormalModule.js:358:12
    at /home/alaeddine/Apps/react-app/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/home/alaeddine/Apps/react-app/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at Array.<anonymous> (/home/alaeddine/Apps/react-app/node_modules/loader-runner/lib/LoaderRunner.js:205:4) {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.12.1

Browser :


问:
Get value out of a tailing closure to global variable in Swift
I'm still new to Swift so I feel this question could be very simple, I'm using HKSampleQuery and inside the tailing closure I get a Date value that I want to use outside, the value inside is printed fine but I cant return the value as the HKSampleQuery is declared void function, but I dont know why i cant assign to global variable like value is destroyed after that closure

```<code>let sleepQuery = HKSampleQuery(
        sampleType: HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!,
        predicate: predicate,
        limit: 0,
        sortDescriptors: [sortDescriptor])
    {
        (query, results, error) -> Void in
        if error != nil
        {
            return
        }
        myGlobalVariable=CertainDate
        //here value in global variable is correct
    }
print(myGlobalVariable)
//here value in global variable is wrong like it was never assigned, same is seen in
//global scope
</code>```

I tried changing the return type of the function but I get the environment is void and is not expecting other type to be returned, also tried returning from inside the closure but I got error saying a value was escaping a closude, also tried assigning to a global variabl and didnt work. Tried also making a local variable in the funciton where this query is made and assigning the value to that and later returning it to main code but didnt work like the value is not prevalent out of the closure

Making the return type different is not allowed and so returning the value will not work, same for assigning it to global variable

```<code>    let sleepQuery = HKSampleQuery(
            sampleType: HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!,
            predicate: predicate,
            limit: 0,
            sortDescriptors: [sortDescriptor]) ->Date

</code>```

Body:
I'm still new to Swift so I feel this question could be very simple, I'm using HKSampleQuery and inside the tailing closure I get a Date value that I want to use outside, the value inside is printed fine but I cant return the value as the HKSampleQuery is declared void function, but I dont know why i cant assign to global variable like value is destroyed after that closure

let sleepQuery = HKSampleQuery(
        sampleType: HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!,
        predicate: predicate,
        limit: 0,
        sortDescriptors: [sortDescriptor])
    {
        (query, results, error) -> Void in
        if error != nil
        {
            return
        }
        myGlobalVariable=CertainDate
        //here value in global variable is correct
    }
print(myGlobalVariable)
//here value in global variable is wrong like it was never assigned, same is seen in
//global scope

I tried changing the return type of the function but I get the environment is void and is not expecting other type to be returned, also tried returning from inside the closure but I got error saying a value was escaping a closude, also tried assigning to a global variabl and didnt work. Tried also making a local variable in the funciton where this query is made and assigning the value to that and later returning it to main code but didnt work like the value is not prevalent out of the closure

Making the return type different is not allowed and so returning the value will not work, same for assigning it to global variable

    let sleepQuery = HKSampleQuery(
            sampleType: HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!,
            predicate: predicate,
            limit: 0,
            sortDescriptors: [sortDescriptor]) ->Date


问:
Using DefaultAzureCredential with Ubuntu + Rider
I am attempting to run a .NET 6.0 project locally on my Ubuntu machine using rider. The project using the DefaultAzureCredential class but when I trying running it gives the following error

"DefaultAzureCredential failed to retrieve a token from the included
credentials. See the troubleshooting guide for more information.
https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot\n-
EnvironmentCredential authentication unavailable. Environment
variables are not fully configured. See the troubleshooting guide for
more information.
https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot\n-
ManagedIdentityCredential authentication unavailable. Multiple
attempts failed to obtain a token from the managed identity
endpoint.\n- Operating system Linux 5.19.0-26-generic #27-Ubuntu SMP
PREEMPT_DYNAMIC Wed Nov 23 20:44:15 UTC 2022 isn't supported.\n-
Stored credentials not found. Need to authenticate user in VSCode
Azure Account. See the troubleshooting guide for more information.
https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot\n-
Please run 'az login' to set up account\n- PowerShell is not
installed."

I tried installing the Azure Cli and using az login which logs me in successfully but that does not resolve the error. I also tried installing the Azure Toolkit in rider and signing in through that with a 'device code'. Again that works successfully but when running the application I still getting the same issue.

This same project work fine using rider or visual studio in Windows, so it seems to be something about this class being unable to consume credentials on my Linux machine that is not a problem when using a Windows.


问:
How to make Dynamic dropdown list depended on sql query in moodle?
please help me to achieve this code
I wanna to make a dropdown list depended on the selection element using jQuery and JavaScript.
here the code :

form.php code:

require_once("$CFG->libdir/formslib.php");

$PAGE - > requires - > jquery();
$PAGE - > requires - > js(new moodle_url($CFG - > wwwroot.
  '/local/regform/classes/forms/validation.php'));
class registration_form extends moodleform {
  //Add elements to form
  public function definition() {
    global $CFG;
    global $DB;
    global $PAGE;
    $mform = $this - > _form; // Don't forget the underscore!

    //Branche info
    $branche = $DB - > get_records_sql('select branche.id,branche.idnumber,branche.name as name from {course_categories} as branche where branche.parent=0');
    $brancheArray = array();
    $brancheArray[0] = "اختر الفرع";

    foreach($branche as $row) {
      $key = $row - > id;
      $value = $row - > name;
      $brancheArray[$key] = $value;
    }

    $attributes = array('onchange' => 'javascript:branchelist()');
    $mform - > addElement('select', 'branche', 'branche / الفرع', $brancheArray, $attributes);

    //year info
    $yearArray = array("select year");
    $mform - > addElement('select', 'year', 'year / السنة', $yearArray);
```
<p><strong>javascript/jQuery code on validation.php:</strong></p>
<pre class="lang-html prettyprint-override"><code><script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.13.1/datatables.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

<script>
  function branchelist(){
    const branche_id = window.$("#id_branche").val();
    alert(branche_id);
    window.$("#id_year").load("getter.php?brancheid=" + branche_id);
  }
</script>
```php
**This is the code that will be load on the target element (#year) in file getter.php:**
```php
<?php
require_once (__DIR__ .'/../../config.php');
global $DB;

// Get the parameter
$brancheid = optional_param('brancheid',  0,  PARAM_INT);

if($brancheid) {
    // Do your query
    $query = 'SELECT * FROM {course_categories} WHERE parent = ' . $brancheid;
    $year_array = $DB->get_records_sql($query, null,  $limitfrom=0,  $limitnum=0);

    // echo your results, loop the array of objects and echo each one
    echo "<option value='0'>All Students</option>";

    foreach ($year_array as $year) {
        echo "<option value=".$year->id.">" . $year->name . "</option>";
    }
}
</code>```

So I tested the alert function and it works fine but there no data changed on the target element  (#year).

any help,

thanks in advance.

I tried to load the content of getter.php by send the parameter brancheid but nothing happend.

function branchelist(){
    const branche_id = window.$("#id_branche").val();
    alert(branche_id);
    window.$("#id_year").load("getter.php?brancheid=" + branche_id);
}
```

Body:
please help me to achieve this code
I wanna to make a dropdown list depended on the selection element using jQuery and JavaScript.
here the code :

form.php code:

require_once("$CFG->libdir/formslib.php");

$PAGE - > requires - > jquery();
$PAGE - > requires - > js(new moodle_url($CFG - > wwwroot.
  '/local/regform/classes/forms/validation.php'));
class registration_form extends moodleform {
  //Add elements to form
  public function definition() {
    global $CFG;
    global $DB;
    global $PAGE;
    $mform = $this - > _form; // Don't forget the underscore!

    //Branche info
    $branche = $DB - > get_records_sql('select branche.id,branche.idnumber,branche.name as name from {course_categories} as branche where branche.parent=0');
    $brancheArray = array();
    $brancheArray[0] = "اختر الفرع";

    foreach($branche as $row) {
      $key = $row - > id;
      $value = $row - > name;
      $brancheArray[$key] = $value;
    }

    $attributes = array('onchange' => 'javascript:branchelist()');
    $mform - > addElement('select', 'branche', 'branche / الفرع', $brancheArray, $attributes);

    //year info
    $yearArray = array("select year");
    $mform - > addElement('select', 'year', 'year / السنة', $yearArray);

javascript/jQuery code on validation.php:

```php
**This is the code that will be load on the target element (#year) in file getter.php:**
```php
<?php
require_once (__DIR__ .'/../../config.php');
global $DB;

// Get the parameter
$brancheid = optional_param('brancheid',  0,  PARAM_INT);

if($brancheid) {
    // Do your query
    $query = 'SELECT * FROM {course_categories} WHERE parent = ' . $brancheid;
    $year_array = $DB->get_records_sql($query, null,  $limitfrom=0,  $limitnum=0);

    // echo your results, loop the array of objects and echo each one
    echo "<option value='0'>All Students</option>";

    foreach ($year_array as $year) {
        echo "<option value=".$year->id.">" . $year->name . "</option>";
    }
}

So I tested the alert function and it works fine but there no data changed on the target element  (#year).

any help,

thanks in advance.

I tried to load the content of getter.php by send the parameter brancheid but nothing happend.

function branchelist(){
    const branche_id = window.$("#id_branche").val();
    alert(branche_id);
    window.$("#id_year").load("getter.php?brancheid=" + branche_id);
}


问:
IJSInProcessRuntime Blazor Wasm to MAUI
I have a Blazor Wasm application I would like to port to Blazor MAUI. In many of the pages we are using IJSInProcessRuntime because we found its faster to pass large chunks of data to javascript which we are using in order to render grids in third party components.

But now, as far as I understand IJSInProcessRuntime is not available in MAUI and not even planned to be.

What is reasonable way forward? Can I register the service somehow to fallback on other JSRuntime if its not available?

I am registering the service like this

```<code>builder.Services.AddSingleton(serviceProvider => (IJSInProcessRuntime)serviceProvider.GetRequiredService<IJSRuntime>());
</code>```

then we inject it on many pages like this

```<code>@inject IJSInProcessRuntime JSInProcessRuntime
</code>```

Upon page load this error shows up

```<code>System.InvalidCastException: 'Unable to cast object of type 'Microsoft.AspNetCore.Components.WebView.Services.WebViewJSRuntime' to type 'Microsoft.JSInterop.IJSInProcessRuntime'.'
</code>```

Title: IJSInProcessRuntime Blazor Wasm to MAUI

Body:
I have a Blazor Wasm application I would like to port to Blazor MAUI. In many of the pages we are using IJSInProcessRuntime because we found its faster to pass large chunks of data to javascript which we are using in order to render grids in third party components.

But now, as far as I understand IJSInProcessRuntime is not available in MAUI and not even planned to be.

What is reasonable way forward? Can I register the service somehow to fallback on other JSRuntime if its not available?

I am registering the service like this

builder.Services.AddSingleton(serviceProvider => (IJSInProcessRuntime)serviceProvider.GetRequiredService<IJSRuntime>());

then we inject it on many pages like this

@inject IJSInProcessRuntime JSInProcessRuntime

Upon page load this error shows up

System.InvalidCastException: 'Unable to cast object of type 'Microsoft.AspNetCore.Components.WebView.Services.WebViewJSRuntime' to type 'Microsoft.JSInterop.IJSInProcessRuntime'.'


问:
Get Deleted JtextField Text
I've implemented a keylistener:

```<code>    txtAddress.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent e) {
            System.out.println("keyPressed " + e.getKeyCode() + " delete " + KeyEvent.VK_DELETE + " backspace " + KeyEvent.VK_BACK_SPACE);
            if (e.getKeyCode() == KeyEvent.VK_DELETE || e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {

                StringSelection theValue = new StringSelection(txtAddress.getText());
                deleteSubscriber(theValue);

            }
        }
    });
</code>```

I need to get the deleted text for processing.  theValue is the current text of the field not the selected text that is to be deleted.

ContentLicense: CC BY-SA 3.0

Title: Get Deleted JtextField Text

Body:
I've implemented a keylistener:

    txtAddress.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent e) {
            System.out.println("keyPressed " + e.getKeyCode() + " delete " + KeyEvent.VK_DELETE + " backspace " + KeyEvent.VK_BACK_SPACE);
            if (e.getKeyCode() == KeyEvent.VK_DELETE || e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {

                StringSelection theValue = new StringSelection(txtAddress.getText());
                deleteSubscriber(theValue);

            }
        }
    });

I need to get the deleted text for processing.  theValue is the current text of the field not the selected text that is to be deleted.


问:
How do I display on the 8-segment display when I presses a certain number on the keyboard lets say its in the 12th place
I need to show an E on the 8-segment display, I have the E ready but I can't get it to show when someone hits certain numbers on the keypad.

THIS IS FOR ARMSIM

swi 0x203

cmp r3, #2

BEQ fwd

cmp r0, #7

BEQ fwd

cmp r0, #11

BEQ fwd

cmp r0, #12

BEQ fwd

cmp r0, #14

BEQ fwd

cmp r0, #15

BEQ fwd

B Done

fwd:

mov r0, #E

swi 0x200

Done:

;second attempt

cmp r0, #0x04

moveq r1,#0x04

BEQ fwd

cmp r0, #0x08

moveq r1,#0x08

BEQ fwd

cmp r0, #0x12

moveq r1,#0x12

BEQ fwd

cmp r0, #0x13

moveq r1,#0x13

BEQ fwd

cmp r0, #0x15

moveq r1,#0x15

BEQ fwd

cmp r0, #0x16

moveq r1,#0x16

BEQ fwd

B Done

fwd:

mov r0, #E

swi 0x200

Done:

;I tried 2 ways but none of them work!


问:
Blazor Server - Refresh User Roles without Logging Out?
Say you're using the built in AspNetCore Identity implementation.

To access some data a User must have the "CanFetchData" role. If they don't, a "Get Access" button is displayed which upon being clicked gives the User the Role and now they can see the data. Without Loggin Out. That's all I'm trying to do.

So onclick we:

```<code>var authState = await authenticationStateTask;
var currUser = await UserManager.GetUserAsync(authState.User);
await UserManager.AddToRoleAsync(currUser, "CanFetchData");
</code>```

And now the Role is in the db. But the only way to update the view is to fully logout.

I've tried using StateHasChanged(); and SignInManager.RefreshSignInAsync(currUser) and a number of other approaches.

I realized that if I add the Claim directly it will update properly:

```<code>var newIdentity = new ClaimsIdentity();
newIdentity.AddClaim(new Claim(ClaimTypes.Role, "CanFetchData"));
authState.User.AddIdentity(newIdentity);
</code>```

But is there no built in function to just refresh from the db?

Body:
Say you're using the built in AspNetCore Identity implementation.

To access some data a User must have the "CanFetchData" role. If they don't, a "Get Access" button is displayed which upon being clicked gives the User the Role and now they can see the data. Without Loggin Out. That's all I'm trying to do.

So onclick we:

var authState = await authenticationStateTask;
var currUser = await UserManager.GetUserAsync(authState.User);
await UserManager.AddToRoleAsync(currUser, "CanFetchData");

And now the Role is in the db. But the only way to update the view is to fully logout.

I've tried using StateHasChanged(); and SignInManager.RefreshSignInAsync(currUser) and a number of other approaches.

I realized that if I add the Claim directly it will update properly:

var newIdentity = new ClaimsIdentity();
newIdentity.AddClaim(new Claim(ClaimTypes.Role, "CanFetchData"));
authState.User.AddIdentity(newIdentity);

But is there no built in function to just refresh from the db?


问:
Mockito test to throw RuntimeException on 3rd call to a void method
UPDATED QUESTION TO CLARIFY

I have a class with a void method.  This method will call a service which will lock user after X failed attempts to unlock a door.

Here are my classes:

@Stateless(name = "DoorServiceEjb")
public class DoorServiceEjb {
    private static final int EXPIRY_PERIOD = 1;
    private static final int MAX_ATTEMPTS = 3;

    private LoadingCache<String, Integer> attemptsCache;

    public DoorServiceEjb() {
        super();
        attemptsCache = CacheBuilder
            .newBuilder()
            .expireAfterWrite(EXPIRY_PERIOD, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Integer>() {
                       @Override
                       public Integer load(String key) throws Exception {
                           return 0;
                       }
                   }
            );
    }

    public boolean isLockedOut(String key) {
        try {
            boolean returnValue = attemptsCache.get(key) >= MAX_ATTEMPTS;
            return  returnValue;
        }catch (ExecutionException e) {
            return false;
        }
    }
}
```
<pre class="lang-java prettyprint-override"><code>public class Door {

    @EJB(beanName = "DoorServiceEjb")
    private DoorServiceEjb doorServiceEjb;

    public void unlock(String user) {
        if (doorServiceEjb.isLockedOut(user)) {
            throw new RuntimeException("Locked");
        }

        // Do something else
    }
}
</code>```

I am expecting that unlock() method to throw RuntimeException if user attempts to call it with invalid username 3 or more times.

MY QUESTIONABLE SOLUTION

Here is my solution to test but I am not sure if this is correct.  I was always under impression that asserts and verifications are called always against @InjectMock objects (called subject under test) whereas @Mock objects are just used to mock internal dependencies inside @InjectMock object (basically, they are used to help test setup and run).
My solution, on the contrary, does not use @InjectMock at all and does verify and assert against @Mock object.

And finally, it still fails because last assert fails.

@ExtendWith(MockitoExtension.class)
public class DoorTest {

    @Mock
    private Door door;

    @Test
    public void test_3FailedUnlockAttempts_ShouldLock() {

        Mockito.doNothing().doNothing().doThrow(RuntimeException.class).when(door).unlock(anyString());

        door.unlock(anyString());
        door.unlock(anyString());

        RuntimeException exception = assertThrows(RuntimeException.class, () -> {
            door.unlock(anyString()); // should throw RuntimeException
        });

        Mockito.verify(door, times(3)).unlock(anyString());

   //this fails, the exception message is null rather than "Unlocked"
  Assertions.assertTrue(exception.getMessage().contains("Locked"));
    }
}
```

Body:
UPDATED QUESTION TO CLARIFY

I have a class with a void method.  This method will call a service which will lock user after X failed attempts to unlock a door.

Here are my classes:

@Stateless(name = "DoorServiceEjb")
public class DoorServiceEjb {
    private static final int EXPIRY_PERIOD = 1;
    private static final int MAX_ATTEMPTS = 3;

    private LoadingCache<String, Integer> attemptsCache;

    public DoorServiceEjb() {
        super();
        attemptsCache = CacheBuilder
            .newBuilder()
            .expireAfterWrite(EXPIRY_PERIOD, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Integer>() {
                       @Override
                       public Integer load(String key) throws Exception {
                           return 0;
                       }
                   }
            );
    }

    public boolean isLockedOut(String key) {
        try {
            boolean returnValue = attemptsCache.get(key) >= MAX_ATTEMPTS;
            return  returnValue;
        }catch (ExecutionException e) {
            return false;
        }
    }
}

public class Door {

    @EJB(beanName = "DoorServiceEjb")
    private DoorServiceEjb doorServiceEjb;

    public void unlock(String user) {
        if (doorServiceEjb.isLockedOut(user)) {
            throw new RuntimeException("Locked");
        }

        // Do something else
    }
}

I am expecting that unlock() method to throw RuntimeException if user attempts to call it with invalid username 3 or more times.

MY QUESTIONABLE SOLUTION

Here is my solution to test but I am not sure if this is correct.  I was always under impression that asserts and verifications are called always against @InjectMock objects (called subject under test) whereas @Mock objects are just used to mock internal dependencies inside @InjectMock object (basically, they are used to help test setup and run).
My solution, on the contrary, does not use @InjectMock at all and does verify and assert against @Mock object.

And finally, it still fails because last assert fails.

@ExtendWith(MockitoExtension.class)
public class DoorTest {

    @Mock
    private Door door;

    @Test
    public void test_3FailedUnlockAttempts_ShouldLock() {

        Mockito.doNothing().doNothing().doThrow(RuntimeException.class).when(door).unlock(anyString());

        door.unlock(anyString());
        door.unlock(anyString());

        RuntimeException exception = assertThrows(RuntimeException.class, () -> {
            door.unlock(anyString()); // should throw RuntimeException
        });

        Mockito.verify(door, times(3)).unlock(anyString());

   //this fails, the exception message is null rather than "Unlocked"
  Assertions.assertTrue(exception.getMessage().contains("Locked"));
    }
}


问:
Is there any way to use different scheduler for distinct parameter groups in pytorch?
Consider that we have the following Pytorch classes:

```<code>class NN1(nn.Module):

 # Any parameters

class NN2(nn.Module):

 # Any parameters

</code>```

Now, we want to train them but with different learning rates. Therefore, we define:

```<code>module1 = NN1()
module2 = NN2()

criterion = nn.MSELoss() # Mean Square Error Loss
optimizer = torch.optim.Adam([
                {'params': module1.parameters(), 'lr':0.2},
                {'params': module2.parameters(), 'lr': 0.1}
            ])
</code>```

Finally, we want different adaptive learning rates for each group of parameters, but I couldn't find any solutions.

For example, I want exponential adaptive learning rate with gamma = 0.8 and gamma = 0.9 for the module1 and module2, respectively. If one uses the following, it will decay both learning rates with the same gamma=0.9.

```<code>scheduler = ExponentialLR(optimizer, gamma=0.9, verbose = True)
</code>```

I found this question on GitHub https://github.com/Lightning-AI/lightning/issues/4983, but it uses a different type of Pytorch scheduler.

Thanks in advance!

Body:
Consider that we have the following Pytorch classes:

class NN1(nn.Module):

 # Any parameters

class NN2(nn.Module):

 # Any parameters

Now, we want to train them but with different learning rates. Therefore, we define:

module1 = NN1()
module2 = NN2()

criterion = nn.MSELoss() # Mean Square Error Loss
optimizer = torch.optim.Adam([
                {'params': module1.parameters(), 'lr':0.2},
                {'params': module2.parameters(), 'lr': 0.1}
            ])

Finally, we want different adaptive learning rates for each group of parameters, but I couldn't find any solutions.

For example, I want exponential adaptive learning rate with gamma = 0.8 and gamma = 0.9 for the module1 and module2, respectively. If one uses the following, it will decay both learning rates with the same gamma=0.9.

scheduler = ExponentialLR(optimizer, gamma=0.9, verbose = True)

I found this question on GitHub https://github.com/Lightning-AI/lightning/issues/4983, but it uses a different type of Pytorch scheduler.

Thanks in advance!


问:
Connect-ExchangeOnline failing with error: Cannot retrieve the dynamic parameters for the cmdlet. Unable to find type
Got a mystery on my hands. This works locally on my IIS. But not on the on-prem server.

Downloaded ExchangeOnlineManagement v3.0.0 to my desktop and then copied the file over to C:\Program Files\WindowsPowerShell\Modules on the server. (Firewall said no to the PowerShell installation)

Installed on my local machine via PowerShell install command: Install-Module -Name ExchangeOnlineManagement

Online logs are showing this error: Cannot retrieve the dynamic parameters for the cmdlet. Unable to find type [Microsoft.Online.CSE.RestApiPowerShellModule.Instrumentation.LogLevel]

PowerShell ExchangeOnlineManagement v3.0.0 Source here https://www.powershellgallery.com/packages/ExchangeOnlineManagement/3.0.0/Content/netFramework%5CExchangeOnlineManagement.psm1 shows the type is indeed referenced in the dynamic dynamic parameters of several cmdlets.

Code:

```<code>            var exchange = new ExchangeHelper();

        using (var runspace = RunspaceFactory.CreateRunspace())
        {
            runspace.Open();

            using (var psInstance = PowerShell.Create())
            {
                try
                {
                    psInstance.Runspace = runspace;
                    exchange.AuthenticateInstance(psInstance, EnumExchangeUser.Web);
</code>```

...

```<code>        public PowerShell AuthenticateInstance(PowerShell psInstance, EnumExchangeUser enumExchangeUser)
    {
        var thumbprint = ConfigurationHelper.AuthThumbprint;

        psInstance.Commands.Clear();
        psInstance.AddCommand("Set-ExecutionPolicy")
         .AddParameter("Scope", "Process")
         .AddParameter("ExecutionPolicy", "Unrestricted")
         .AddParameter("Confirm", false)
         .AddParameter("Force", true)
         .Invoke();

        psInstance.Commands.Clear();
         psInstance.AddCommand("Connect-ExchangeOnline")
         .AddParameter("CertificateThumbPrint", thumbprint)
         .AddParameter("AppID", "appID Guid goes here")
         .AddParameter("Organization", "myorg.onmicrosoft.com")
         .Invoke();
        return psInstance;
    }
</code>```

Any idea why this is failing when calling "Connect-ExchangeOnline" and what I need to do?

Pulling out my hair here

Body:
Got a mystery on my hands. This works locally on my IIS. But not on the on-prem server.

Downloaded ExchangeOnlineManagement v3.0.0 to my desktop and then copied the file over to C:\Program Files\WindowsPowerShell\Modules on the server. (Firewall said no to the PowerShell installation)

Installed on my local machine via PowerShell install command: Install-Module -Name ExchangeOnlineManagement

Online logs are showing this error: Cannot retrieve the dynamic parameters for the cmdlet. Unable to find type [Microsoft.Online.CSE.RestApiPowerShellModule.Instrumentation.LogLevel]

PowerShell ExchangeOnlineManagement v3.0.0 Source here https://www.powershellgallery.com/packages/ExchangeOnlineManagement/3.0.0/Content/netFramework%5CExchangeOnlineManagement.psm1 shows the type is indeed referenced in the dynamic dynamic parameters of several cmdlets.

Code:

            var exchange = new ExchangeHelper();

        using (var runspace = RunspaceFactory.CreateRunspace())
        {
            runspace.Open();

            using (var psInstance = PowerShell.Create())
            {
                try
                {
                    psInstance.Runspace = runspace;
                    exchange.AuthenticateInstance(psInstance, EnumExchangeUser.Web);

...

        public PowerShell AuthenticateInstance(PowerShell psInstance, EnumExchangeUser enumExchangeUser)
    {
        var thumbprint = ConfigurationHelper.AuthThumbprint;

        psInstance.Commands.Clear();
        psInstance.AddCommand("Set-ExecutionPolicy")
         .AddParameter("Scope", "Process")
         .AddParameter("ExecutionPolicy", "Unrestricted")
         .AddParameter("Confirm", false)
         .AddParameter("Force", true)
         .Invoke();

        psInstance.Commands.Clear();
         psInstance.AddCommand("Connect-ExchangeOnline")
         .AddParameter("CertificateThumbPrint", thumbprint)
         .AddParameter("AppID", "appID Guid goes here")
         .AddParameter("Organization", "myorg.onmicrosoft.com")
         .Invoke();
        return psInstance;
    }

Any idea why this is failing when calling "Connect-ExchangeOnline" and what I need to do?

Pulling out my hair here


问:
JSON changelog file connecting to a bootstrap card element
I'm currently making a change log for a website and was wondering how to connect the changelog.JSON file to my HTML file and subsequently extract it to turn it into the change log you see.

Its a bootstrap .card element...

The JSON file is called changelog.json

```<code>[
  {
    "version": "1.2",
    "date": "8 Dec 2022",
    "greennote": [
        "All note files added!",
        "Math homeworks offically available (permisson granted)"
    ],
    "purplenote": [
      "Wbebsite ui updated"
    ]
  },

  {
    "version": "1.0",
    "date": "2 Dec 2022",
    "greennote": [
        "Math Notes Version 1.1 file added",
        "Math homeworks offically available (permisson granted)"
    ],
    "purplenote": [
      "Wbebsite created"
    ]
}]

</code>```

I have tried a few things however im quite the beginner. If you could put me on the right track. Additionally with the greennote there are two elements how do you read this and provide a new check element for each as shown in the screenshot?

Body:
I'm currently making a change log for a website and was wondering how to connect the changelog.JSON file to my HTML file and subsequently extract it to turn it into the change log you see.

Its a bootstrap .card element...

The JSON file is called changelog.json

[
  {
    "version": "1.2",
    "date": "8 Dec 2022",
    "greennote": [
        "All note files added!",
        "Math homeworks offically available (permisson granted)"
    ],
    "purplenote": [
      "Wbebsite ui updated"
    ]
  },

  {
    "version": "1.0",
    "date": "2 Dec 2022",
    "greennote": [
        "Math Notes Version 1.1 file added",
        "Math homeworks offically available (permisson granted)"
    ],
    "purplenote": [
      "Wbebsite created"
    ]
}]

I have tried a few things however im quite the beginner. If you could put me on the right track. Additionally with the greennote there are two elements how do you read this and provide a new check element for each as shown in the screenshot?


问:
Is it possible to disable the same-origin policy in Chrome on Android for strictly development purposes?
CORS is configured correctly on the various web services that are part of my application.

I would like to reach one part of the application, the website, hosted on another development machine on my LAN.

I would like my test device to visit this website, which will have a non-localhost URL, and to also allow it to connect to other production web services, which have well defined and working CORS policies.

For testing purposes, I would like to ignore CORS.

Is there a way to do this on a Pixel 6a?

On a PC or macOS device, I start Chromium with --disable-web-security --user-dir=/path. This is adequate for testing. I am seeking something similar.


问:
Dynamically change chart properties with slider in altair?
I'm trying to make a histogram in Altair with a slider that dynamically sets the maxbins parameter in alt.Bin(). The idea is to show how bin choice can affect a histogram.

A working example of the histogram without dynamic bins is:

```<code>import pandas as pd
import numpy as np
import altair as alt

weather = pd.read_csv('https://raw.githubusercontent.com/altair-viz/vega_datasets/master/vega_datasets/_data/seattle-weather.csv')

alt.Chart(weather).mark_bar().encode(
    alt.X("wind:Q",
          bin=alt.Bin(maxbins=50)),
    y='count()',
)
</code>```

What I would like to do is something along these lines (this code produces an error saying 'maxbins.maxbins' is not of type 'number'):

```<code>import pandas as pd
import numpy as np
import altair as alt

weather = pd.read_csv('https://raw.githubusercontent.com/altair-viz/vega_datasets/master/vega_datasets/_data/seattle-weather.csv')

slider = alt.binding_range(min=0,
                           max=len(np.unique(weather.wind)),
                           step=1)

selector = alt.selection_single(name='maxbins',
                                fields=['wind'],
                                bind=slider,
                                init={'wind': len(np.unique(weather.wind))/5})

alt.Chart(weather).mark_bar().encode(
    alt.X("wind:Q",
          bin=alt.Bin(maxbins=selector.maxbins)),
    y='count()',
).add_selection(
    selector
)
</code>```

I think that, more generally, my question is whether chart properties (rather than selections of data) can be set by a slider in Altair.

Body:
I'm trying to make a histogram in Altair with a slider that dynamically sets the maxbins parameter in alt.Bin(). The idea is to show how bin choice can affect a histogram.

A working example of the histogram without dynamic bins is:

import pandas as pd
import numpy as np
import altair as alt

weather = pd.read_csv('https://raw.githubusercontent.com/altair-viz/vega_datasets/master/vega_datasets/_data/seattle-weather.csv')

alt.Chart(weather).mark_bar().encode(
    alt.X("wind:Q",
          bin=alt.Bin(maxbins=50)),
    y='count()',
)

What I would like to do is something along these lines (this code produces an error saying 'maxbins.maxbins' is not of type 'number'):

import pandas as pd
import numpy as np
import altair as alt

weather = pd.read_csv('https://raw.githubusercontent.com/altair-viz/vega_datasets/master/vega_datasets/_data/seattle-weather.csv')

slider = alt.binding_range(min=0,
                           max=len(np.unique(weather.wind)),
                           step=1)

selector = alt.selection_single(name='maxbins',
                                fields=['wind'],
                                bind=slider,
                                init={'wind': len(np.unique(weather.wind))/5})

alt.Chart(weather).mark_bar().encode(
    alt.X("wind:Q",
          bin=alt.Bin(maxbins=selector.maxbins)),
    y='count()',
).add_selection(
    selector
)

I think that, more generally, my question is whether chart properties (rather than selections of data) can be set by a slider in Altair.


问:
How can we create Custom keyboard app & Keyboard Themes with flutter? - Android & IOS
How can we create Custom keyboard app & Keyboard Themes with flutter for Android & IOS? (English Language Keyboard). Is there any package or Source code I can use to build this custom keyboard app? Highly appreciate your support explanation with source code or package.

Appreciate if you can explain with either Source code or package use to build this.


问:
Edge Browser: Link From PDF Not Opening a New PDF File
I installed an adobe acrobat extension in Edge browser. My link is relative path. I set up all these options with this extension:

In my PDF file, the embed link is a button.
After the click, it did not open a PDF file in Edge, but works fine in Chrome and Opera. What do I do to make it work in Edge?

(UPDATE)

This is how Opera and Google Chrome show my URL after I click a button in the PDF, which opens a PDF file.

//example.azurewebsites.net/CANGC/Process/off-site-facility-management/6_1-Chemistry/Step-Descriptions/6-1-1/6-1-1-1.pdf

This is how Edge shows the URL after the click, which cannot locate the file.

//example.azurewebsites.net/CANGC/Process/off-site-facility-management/6_1-Chemistry/Flow-Chart/6.1%20Ultrasonic%20Chemistry%20Management/2.%20Process%20Design/2b.%20Step%20Descriptions/1%20-%20Chemical%20Inventory/6-1-1-1.pdf

Edge rewrote the URL longer, forcing the path wrong.

What's funny is that I put the same URL into the Edge Browser, which opens that PDF file. The extensions do not solve my problem. Is there another solution out there?


问:
Abandoned Mutex Exception on a Multithread TCP Server
I am creating a multithread server and I am using mutex to control the sending data, the problem is when a client disconnect all the others clients also disconnect.

This is the server code

```<code>using Newtonsoft.Json;
using Pastel;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DeepestSwordServer
{
    public class Program
    {
        public static TcpListener server;
        public static TcpClient client = new TcpClient();
        public static Thread t;
        public static Mutex mutex = new Mutex(false, "poligamerMod");
        public static List<Connection> list = new List<Connection>();
        public static Connection con;

        static void Main(string[] args)
        {
            string ConfigPath = Path.Combine(Environment.CurrentDirectory, "config.json");

            if (File.Exists(ConfigPath))
            {
                Console.WriteLine("Starting Server...".Pastel(Color.FromArgb(165, 229, 250)));

                try
                {
                    string json = File.ReadAllText(ConfigPath);

                    Config config = JsonConvert.DeserializeObject<Config>(json);

                    Start(config.Ip, config.Port);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed To Start Server Error: {e.Message}".Pastel(Color.FromArgb(255, 0, 0)));
                }
            }
            else
            {
                Console.WriteLine("Creating Config File...".Pastel(Color.FromArgb(165, 229, 250)));

                Config config = new Config();
                config.Ip = "0.0.0.0";
                config.Port = 3878;

                string json = JsonConvert.SerializeObject(config);

                File.Create(ConfigPath).Dispose();
                File.WriteAllText(ConfigPath, json);

                Console.WriteLine("File Created!".Pastel(Color.FromArgb(58, 255, 0)));

                Console.WriteLine("Please see the config.json where is the ip, port and password if needed of the server, you need to restart the server!".Pastel(Color.FromArgb(165, 229, 250)));
                Console.ReadLine();
            }
        }

        public static void Start(string ip, int port)
        {
            Console.WriteLine("Server Ready!".Pastel(Color.FromArgb(58, 255, 0)));
            server = new TcpListener(IPAddress.Parse(ip), port);
            server.Start();

            while (true)
            {
                client = server.AcceptTcpClient();

                con = new Connection();
                con.stream = client.GetStream();
                con.streamr = new StreamReader(con.stream);
                con.streamw = new StreamWriter(con.stream);

                con.username = con.streamr.ReadLine();
                con.id = con.streamr.ReadLine();

                Event @event = new Event();

                @event.EventType = EventType.Join;
                @event.Username = con.username;
                @event.Id = con.id;

                string join = JsonConvert.SerializeObject(@event);

                foreach (Connection c in list)
                {
                    c.streamw.WriteLine(join);

                    @event = new Event();

                    @event.EventType = EventType.Join;
                    @event.Username = c.username;
                    @event.Id = c.id;

                    string newJoin = JsonConvert.SerializeObject(@event);

                    con.streamw.WriteLine(newJoin);
                }

                list.Add(con);

                @event = new Event();
                @event.EventType = EventType.List;

                foreach (Connection c in list.ToList())
                {
                    @event.List.Add(c.username, c.id);
                }

                string playerList = JsonConvert.SerializeObject(@event);

                con.streamw.WriteLine(playerList);

                Console.WriteLine($"{con.username} with id {con.id} has connected!".Pastel(Color.FromArgb(58, 255, 0)));

                t = new Thread(HearConnection);
                t.Start();
            }
        }

        public static void HearConnection()
        {
            Connection hcon = con;

            do
            {
                try
                {
                    foreach (Connection c in list.ToList())
                    {
                        mutex.WaitOne();
                        c.streamw.WriteLine(hcon.streamr.ReadLine());
                        mutex.ReleaseMutex();
                    }
                }
                catch (Exception e)
                {
                    list.Remove(hcon);

                    Event @event = new Event();
                    @event.EventType = EventType.Leave;
                    @event.Username = con.username;
                    @event.Id = con.id;

                    string leave = JsonConvert.SerializeObject(@event);

                    foreach (Connection c in list)
                    {
                        c.streamw.WriteLine(leave);
                    }

                    Console.WriteLine($"{hcon.username} with id {hcon.id} has disconnected!".Pastel(Color.FromArgb(255, 0, 0)));

                    Console.WriteLine(e.ToString());
                    break;
                }
            } while (true);
        }

        public struct Connection
        {
            public NetworkStream stream;
            public StreamWriter streamw;
            public StreamReader streamr;
            public string username;
            public string id;
        }
    }
}

</code>```

Here is the important parts of the client code

```<code>public void Connect()
{
    MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Button>().enabled = false;
    MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Connecting...";

    try
    {
        client.Connect(IPAddress.Parse(Ip.GetComponent<InputField>().text), Convert.ToInt32(Port.GetComponent<InputField>().text));

        if (client.Connected)
        {
            t = new Thread(Listen);

            stream = client.GetStream();
            streamw = new StreamWriter(stream);
            streamr = new StreamReader(stream);

            streamw.AutoFlush = true;

            streamw.WriteLine(Username);
            streamw.WriteLine(Id);

            t.IsBackground = true;

            t.Start();

            StartCoroutine(Yes());
        }
        else
        {
            MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Cant Connect To Server!";
            MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Image>().color = Color.red;
            StartCoroutine(No());
        }
    }
    catch (Exception e)
    {
        Logger.LogInfo(e.Message);
        MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Cant Connect To Server!";
        MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Image>().color = Color.red;
        StartCoroutine(No());
    }
}

public void Listen()
{
    while (client.Connected)
    {
        try
        {
            string message = streamr.ReadLine();

            DoEvent(message);

            Logger.LogInfo(message);
        }
        catch(Exception e)
        {
            if (!client.Connected)
            {
                LostConnection = true;
            }
            else
            {
                Logger.LogError(e.ToString());
            }
        }
    }
}
</code>```

What I want is that the others clients dont disconnect if one client disconnect.

Body:
I am creating a multithread server and I am using mutex to control the sending data, the problem is when a client disconnect all the others clients also disconnect.

This is the server code

using Newtonsoft.Json;
using Pastel;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DeepestSwordServer
{
    public class Program
    {
        public static TcpListener server;
        public static TcpClient client = new TcpClient();
        public static Thread t;
        public static Mutex mutex = new Mutex(false, "poligamerMod");
        public static List<Connection> list = new List<Connection>();
        public static Connection con;

        static void Main(string[] args)
        {
            string ConfigPath = Path.Combine(Environment.CurrentDirectory, "config.json");

            if (File.Exists(ConfigPath))
            {
                Console.WriteLine("Starting Server...".Pastel(Color.FromArgb(165, 229, 250)));

                try
                {
                    string json = File.ReadAllText(ConfigPath);

                    Config config = JsonConvert.DeserializeObject<Config>(json);

                    Start(config.Ip, config.Port);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed To Start Server Error: {e.Message}".Pastel(Color.FromArgb(255, 0, 0)));
                }
            }
            else
            {
                Console.WriteLine("Creating Config File...".Pastel(Color.FromArgb(165, 229, 250)));

                Config config = new Config();
                config.Ip = "0.0.0.0";
                config.Port = 3878;

                string json = JsonConvert.SerializeObject(config);

                File.Create(ConfigPath).Dispose();
                File.WriteAllText(ConfigPath, json);

                Console.WriteLine("File Created!".Pastel(Color.FromArgb(58, 255, 0)));

                Console.WriteLine("Please see the config.json where is the ip, port and password if needed of the server, you need to restart the server!".Pastel(Color.FromArgb(165, 229, 250)));
                Console.ReadLine();
            }
        }

        public static void Start(string ip, int port)
        {
            Console.WriteLine("Server Ready!".Pastel(Color.FromArgb(58, 255, 0)));
            server = new TcpListener(IPAddress.Parse(ip), port);
            server.Start();

            while (true)
            {
                client = server.AcceptTcpClient();

                con = new Connection();
                con.stream = client.GetStream();
                con.streamr = new StreamReader(con.stream);
                con.streamw = new StreamWriter(con.stream);

                con.username = con.streamr.ReadLine();
                con.id = con.streamr.ReadLine();

                Event @event = new Event();

                @event.EventType = EventType.Join;
                @event.Username = con.username;
                @event.Id = con.id;

                string join = JsonConvert.SerializeObject(@event);

                foreach (Connection c in list)
                {
                    c.streamw.WriteLine(join);

                    @event = new Event();

                    @event.EventType = EventType.Join;
                    @event.Username = c.username;
                    @event.Id = c.id;

                    string newJoin = JsonConvert.SerializeObject(@event);

                    con.streamw.WriteLine(newJoin);
                }

                list.Add(con);

                @event = new Event();
                @event.EventType = EventType.List;

                foreach (Connection c in list.ToList())
                {
                    @event.List.Add(c.username, c.id);
                }

                string playerList = JsonConvert.SerializeObject(@event);

                con.streamw.WriteLine(playerList);

                Console.WriteLine($"{con.username} with id {con.id} has connected!".Pastel(Color.FromArgb(58, 255, 0)));

                t = new Thread(HearConnection);
                t.Start();
            }
        }

        public static void HearConnection()
        {
            Connection hcon = con;

            do
            {
                try
                {
                    foreach (Connection c in list.ToList())
                    {
                        mutex.WaitOne();
                        c.streamw.WriteLine(hcon.streamr.ReadLine());
                        mutex.ReleaseMutex();
                    }
                }
                catch (Exception e)
                {
                    list.Remove(hcon);

                    Event @event = new Event();
                    @event.EventType = EventType.Leave;
                    @event.Username = con.username;
                    @event.Id = con.id;

                    string leave = JsonConvert.SerializeObject(@event);

                    foreach (Connection c in list)
                    {
                        c.streamw.WriteLine(leave);
                    }

                    Console.WriteLine($"{hcon.username} with id {hcon.id} has disconnected!".Pastel(Color.FromArgb(255, 0, 0)));

                    Console.WriteLine(e.ToString());
                    break;
                }
            } while (true);
        }

        public struct Connection
        {
            public NetworkStream stream;
            public StreamWriter streamw;
            public StreamReader streamr;
            public string username;
            public string id;
        }
    }
}

Here is the important parts of the client code

public void Connect()
{
    MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Button>().enabled = false;
    MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Connecting...";

    try
    {
        client.Connect(IPAddress.Parse(Ip.GetComponent<InputField>().text), Convert.ToInt32(Port.GetComponent<InputField>().text));

        if (client.Connected)
        {
            t = new Thread(Listen);

            stream = client.GetStream();
            streamw = new StreamWriter(stream);
            streamr = new StreamReader(stream);

            streamw.AutoFlush = true;

            streamw.WriteLine(Username);
            streamw.WriteLine(Id);

            t.IsBackground = true;

            t.Start();

            StartCoroutine(Yes());
        }
        else
        {
            MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Cant Connect To Server!";
            MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Image>().color = Color.red;
            StartCoroutine(No());
        }
    }
    catch (Exception e)
    {
        Logger.LogInfo(e.Message);
        MultiPlayerSubMenu.transform.GetChild(2).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Cant Connect To Server!";
        MultiPlayerSubMenu.transform.GetChild(2).gameObject.GetComponent<Image>().color = Color.red;
        StartCoroutine(No());
    }
}

public void Listen()
{
    while (client.Connected)
    {
        try
        {
            string message = streamr.ReadLine();

            DoEvent(message);

            Logger.LogInfo(message);
        }
        catch(Exception e)
        {
            if (!client.Connected)
            {
                LostConnection = true;
            }
            else
            {
                Logger.LogError(e.ToString());
            }
        }
    }
}

What I want is that the others clients dont disconnect if one client disconnect.


问:
Will Microservices Architecture Speed Up Spring Boot Startup Time?
I have a Spring Boot application with Gradle that currently is taking a lot of time.
Now, is taking about 10 minutes plus just to startup.
The source code indeed is growing rapidly, 6 Months ago, it only taking 3 minutes plus to startup.

Possible Causes

Here are facts that I think are causing the slowness:

Usage of Hibernate: current source code uses a lot of sql queries.
In fact, I cant use hibernate.show_sql since it will make the startup time longer
with never ending logs keep showing up.

There are 160+ entities with each entity is for a table.

There are 20+ schedulers.

There are 60+ dependencies used

Thought on Microservice

I just learnt the concept of Microsevice where
it breaks down an application to smaller pieces.
So, with that, would it possibly speed up the startup time?

I have tried to comment Schedulers during
startup time in my local, but still takes 10 mins plus

I have used spring.main.lazy-initalization = true
but still takes 9 mins plus

I used
org.gradle.paralel = true, still takes 10 mins plus


问:
Voice Recording is muted after calling record Android
I'm voice recorder developer.

my problem is voice recording is muted after calling with record, not just calling

it is ok that the recording is muted while calling because after calling the app get back MediaRecorder.AudioSource.MIC and is available for recording

but calling with calling record, the app records mute at all

this problem occurs AudioRecord and MediaRecorder both.

is there any way to get MIC again so record after calling?

please help me and save my time.


问:
How to do I code for ANOVA repeated measures testing using numpy pandas statsmodels?
I want to know how to conduct ANOVA repeated measures testing using the numpy pandas statsmodels library. My dataset contains information about depression scores pre-treatment, post-treatment, and follow-up after 6 months:

Dataset screenshot

Here are my null and research hypotheses:

H0 = Depression scores remain the same or have decreased after treatment over time.

H1 = Depression scores have increased after treatment over time.

I tried using the AnovaRM function, but it is giving me an error. I am not sure what I am doing wrong.

What I tried

Here is the error I am getting:

Error

I am a beginner at coding so I am quite confused! Thank you in advance for all your help!