问:
Android background sound not played on all devices
I'm developing an android app that is mostly run in the background and uses Firebase Realtime Database for data syncing.

I want the app to play a 10 second sound when new data is received from Firebase and I've successfully managed to implement this, however, my solution doesn't work on all devices.

Here's my code:

```<code>class MyViewModel constructor(

) : ViewModel() {
   private var mediaPlayer: MediaPlayer? = null

   fun initRtdListener(context: Context) {
      val ref = Firebase.database.getReference("my-path")
      mediaPlayer = MediaPlayer.create(context, R.raw.my_short_audio)

      ref.addValueEventListener(object : ValueEventListener {
          override fun onDataChange(dataSnapshot: DataSnapshot) {
            mediaPlayer?.start()
          }

          override fun onCancelled(error: DatabaseError) {}
      })
   }
}
</code>```

This solution works perfectly on most devices even when the app is running in the background, however, on some devices (like Realme X) the sound is played only when the app is in foreground. What could be the problem? Is it because I play the sound not in the context of a service? If yes, do I really need a service considering that my sounds are short?

P.S. I have two background services which are working without any issues on all devices

Body:
I'm developing an android app that is mostly run in the background and uses Firebase Realtime Database for data syncing.

I want the app to play a 10 second sound when new data is received from Firebase and I've successfully managed to implement this, however, my solution doesn't work on all devices.

Here's my code:

class MyViewModel constructor(

) : ViewModel() {
   private var mediaPlayer: MediaPlayer? = null

   fun initRtdListener(context: Context) {
      val ref = Firebase.database.getReference("my-path")
      mediaPlayer = MediaPlayer.create(context, R.raw.my_short_audio)

      ref.addValueEventListener(object : ValueEventListener {
          override fun onDataChange(dataSnapshot: DataSnapshot) {
            mediaPlayer?.start()
          }

          override fun onCancelled(error: DatabaseError) {}
      })
   }
}

This solution works perfectly on most devices even when the app is running in the background, however, on some devices (like Realme X) the sound is played only when the app is in foreground. What could be the problem? Is it because I play the sound not in the context of a service? If yes, do I really need a service considering that my sounds are short?

P.S. I have two background services which are working without any issues on all devices


来源: stackexchange

问:
convert vue ast back to template
I'm using vue-template-compiler to transform a text in the vue template to an expression

I have this vueJs file

```<code><template>
    <p>hi</p>
</template>
</code>```

I'm trying to change the text with expression like this

```<code><p>{{fun('hi')}}</p>
</code>```

my code

  const compiled = compiler.compile(
    data,
    {
      modules: [
        {
          transformNode(data) {
            const children = data.children.map((child) => {
              if (child.type === 3 && child.text.trim()) {
                return ({
                    type: 2,
                    expression: "_s(fun('hi'))",
                    tokens: [
                        {
                            '@binding': "fun('hi')"
                        }
                    ],
                    text: "{{fun('hi)}}"
                })
              }
              return child;
            });

            return { ...data, children };
          },
        },
      ],
    },
    {
      whitespace: "condense",
    }
  );
```
<p>it maps over the texts and replace it with the expression.
and it returns the final <code>ast</code>.<br />
but I need to convert it back to string</p>
<p>like that:</p>
```
{{fun('hi')}}

```

I need to convert the final ast back to the template

ContentLicense: CC BY-SA 4.0

Title: convert vue ast back to template

Body:
I'm using vue-template-compiler to transform a text in the vue template to an expression

I have this vueJs file

<template>

hi

</template>

I'm trying to change the text with expression like this

{{fun('hi')}}

my code

  const compiled = compiler.compile(
    data,
    {
      modules: [
        {
          transformNode(data) {
            const children = data.children.map((child) => {
              if (child.type === 3 && child.text.trim()) {
                return ({
                    type: 2,
                    expression: "_s(fun('hi'))",
                    tokens: [
                        {
                            '@binding': "fun('hi')"
                        }
                    ],
                    text: "{{fun('hi)}}"
                })
              }
              return child;
            });

            return { ...data, children };
          },
        },
      ],
    },
    {
      whitespace: "condense",
    }
  );

it maps over the texts and replace it with the expression.
and it returns the final ast.

but I need to convert it back to string

like that:

{{fun('hi')}}

I need to convert the final ast back to the template


问:
partial update in django rest viewset(not modelviewset)
i am beginner in django and i was trying to learn work with djangorest viewset(not modelviewset)
and i cant find any resource to undrestand it.
i want to learn how to write a partial_update  with viewset.

here is what i have tried:

models.py :

```<code>class UserIdentDocs(models.Model):
    owner = models.ForeignKey(User,on_delete=models.CASCADE, related_name = "user_ident_Docs")
    code = models.PositiveBigIntegerField(null=True)
    img = models.ImageField(null=True)
    video = models.FileField(null=True)
    is_complete = models.BooleanField(default=False)
</code>```

serializers.py:

```<code>class AdminUserIdentSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserIdentDocs
        fields = [
            "owner",
            "code",
            "img",
            "video",
            "is_complete",
        ]
</code>```

views.py:

```<code>from rest_framework.parsers import MultiPartParser, FormParser

class UserDocAdminViewSet(viewsets.ViewSet):
    """User docs admin view set"""

    permission_classes = [AllowAny]
    parser_classes = (MultiPartParser, FormParser)
    serializer_class = AdminUserIdentSerializer
    queryset = UserIdentDocs.objects.filter(is_complete=False)

    def list(self, request):
        serializer = self.serializer_class(self.queryset, many=True)
        return Response(serializer.data)

    def retrive(self, request, pk=None):
        doc_object = get_object_or_404(self.queryset, pk=pk)
        serializer = self.serializer_class(doc_object)
        return Response(serializer.data)

    def create(self, request ):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)

    def partial_update(self, request, pk=None):
        doc_object = get_object_or_404(self.queryset, pk=pk)
        serializer = self.serializer_class(doc_object,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"detail":"item updated succesfuly"}, status=status.HTTP_205_RESET_CONTENT)
</code>```

urls.py:

```<code>urlpatterns = [
    ...
    # admin viewset for docs
        # list of accounts with is_complete=False
    path("admin/userdocs/", UserDocAdminViewSet.as_view({"get":"list", "post":"create"}), name="user-docs-list"),
    path("admin/userdocs/<int:pk>", UserDocAdminViewSet.as_view({"get":"retrive","patch":"partial_update"}), name="user-docs-detail"),

]
</code>```

i can create user in browsable api but when i want to use partial update i can't even see the fields in browsable api and i only  see this :
media type: multipart/form-data
content:this is what i see

Body:
i am beginner in django and i was trying to learn work with djangorest viewset(not modelviewset)
and i cant find any resource to undrestand it.
i want to learn how to write a partial_update  with viewset.

here is what i have tried:

models.py :

class UserIdentDocs(models.Model):
    owner = models.ForeignKey(User,on_delete=models.CASCADE, related_name = "user_ident_Docs")
    code = models.PositiveBigIntegerField(null=True)
    img = models.ImageField(null=True)
    video = models.FileField(null=True)
    is_complete = models.BooleanField(default=False)

serializers.py:

class AdminUserIdentSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserIdentDocs
        fields = [
            "owner",
            "code",
            "img",
            "video",
            "is_complete",
        ]

views.py:

from rest_framework.parsers import MultiPartParser, FormParser

class UserDocAdminViewSet(viewsets.ViewSet):
    """User docs admin view set"""

    permission_classes = [AllowAny]
    parser_classes = (MultiPartParser, FormParser)
    serializer_class = AdminUserIdentSerializer
    queryset = UserIdentDocs.objects.filter(is_complete=False)

    def list(self, request):
        serializer = self.serializer_class(self.queryset, many=True)
        return Response(serializer.data)

    def retrive(self, request, pk=None):
        doc_object = get_object_or_404(self.queryset, pk=pk)
        serializer = self.serializer_class(doc_object)
        return Response(serializer.data)

    def create(self, request ):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)

    def partial_update(self, request, pk=None):
        doc_object = get_object_or_404(self.queryset, pk=pk)
        serializer = self.serializer_class(doc_object,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"detail":"item updated succesfuly"}, status=status.HTTP_205_RESET_CONTENT)

urls.py:

urlpatterns = [
    ...
    # admin viewset for docs
        # list of accounts with is_complete=False
    path("admin/userdocs/", UserDocAdminViewSet.as_view({"get":"list", "post":"create"}), name="user-docs-list"),
    path("admin/userdocs/<int:pk>", UserDocAdminViewSet.as_view({"get":"retrive","patch":"partial_update"}), name="user-docs-detail"),

]

i can create user in browsable api but when i want to use partial update i can't even see the fields in browsable api and i only  see this :
media type: multipart/form-data
content:this is what i see


问:
Fix for Reference lines and fill between being shown outside of the Seaborn plot
Writing the follow code:

```<code>sns.jointplot(x="horsepower", y="mpg", data=df, kind='scatter', color="black", height=14, hue="origin");

LSL = 20
USL = 30

plt.axhline(y=LSL, color="b", linestyle="--")
plt.axhline(y=USL, color="b", linestyle="--")

# Fill the area between the LSL and USL reference lines with green color
plt.fill_between([df["horsepower"].min(), df["horsepower"].max()], LSL, USL, color="g", alpha=0.1)

plt.show()
</code>```

I get the output as:
plot

The reference lines and green fill are getting placed to the right of the plot.

I tried changing the x range to hardcoded values [0,250] for example and it didn't work.

Body:
Writing the follow code:

sns.jointplot(x="horsepower", y="mpg", data=df, kind='scatter', color="black", height=14, hue="origin");

LSL = 20
USL = 30

plt.axhline(y=LSL, color="b", linestyle="--")
plt.axhline(y=USL, color="b", linestyle="--")

# Fill the area between the LSL and USL reference lines with green color
plt.fill_between([df["horsepower"].min(), df["horsepower"].max()], LSL, USL, color="g", alpha=0.1)

plt.show()

I get the output as:
plot

The reference lines and green fill are getting placed to the right of the plot.

I tried changing the x range to hardcoded values [0,250] for example and it didn't work.


问:
How to keep header at top of visual viewport after layout/visual viewport changes in Chrome mobile web?
I know there have been multiple SO questions about this, but none of them seem to work anymore since the browser teams have made changes since those questions were asked. I'm trying to find the most up-to-date solution to this problem.

Objective

My desire is to have a fixed header stay stationary at the top for an app-like experience when using a mobile web browser, specifically when the user has focus on an input field and the virtual keyboard is showing.

Background context

Recently, the Chrome mobile team changed how they resize their layout and visual viewports for mobile web to be in alignment with Chrome on iOS and mobile Safari on iOS.

This GIF from an article by David Fedor very succinctly demonstrates the current status of most (but not all) mobile browser with regards to the visual viewport being "moved up" when the On-Screen Keyboard (OSK, aka Virtual Keyboard) is shown when a field is focused.

The biggest issue I'm facing is that I cannot get a header element to stay visually present at the top when the OSK is shown. This is a big deal when your top appbar has primary actions for a form like "Save". It makes the UX confusing, which leads to customers leaving in frustration, so this is isn't something trivial in my opinion.

I've tried the VisualViewport API that Chrome team recommended, referencing the env(keyboard-inset-height) and that just doesn't seem to work, which makes me think I'm doing something weird with my layout such that the ENV isn't being set properly.

My code

Nothing too crazy, using CSS grid to control layout.

HTML

```<code><html>
<body>
  <div id="container">
    <header id="header">header</header>
    <main id="main">
      main
      <input type="text" />
    </main>
    <footer id="footer">footer</footer>
  </div>
</body>
</html>
</code>```

CSS style

```<code>body {
  margin: 0;
}

#container {
  height: 100dvh;
  display: grid;
  grid-template:
    "header" 50px
    "main" 1fr
    "footer" 50px
    "keyboard" env(keyboard-inset-height, 0px); // does not seem to work?
}

#header {
  grid-area: header;
}

#main {
  grid-area: main;
  overflow-y: scroll;
}

#footer {
  grid-area: footer;
}
</code>```

What I get is the following 2 screenshots, the full-page one being the layout as I want it, and the 2nd one being when you focus the cursor into an input near the bottom and it "pushes" the entire visual viewport up such that the header is offscreen.

fullscreen
input focused

Is there any way currently to ensure that the header stays at the top of the visual viewport always? I cannot find a working solution to this at the moment after the recent Chrome updates.

Body:
I know there have been multiple SO questions about this, but none of them seem to work anymore since the browser teams have made changes since those questions were asked. I'm trying to find the most up-to-date solution to this problem.

Objective

My desire is to have a fixed header stay stationary at the top for an app-like experience when using a mobile web browser, specifically when the user has focus on an input field and the virtual keyboard is showing.

Background context

Recently, the Chrome mobile team changed how they resize their layout and visual viewports for mobile web to be in alignment with Chrome on iOS and mobile Safari on iOS.

This GIF from an article by David Fedor very succinctly demonstrates the current status of most (but not all) mobile browser with regards to the visual viewport being "moved up" when the On-Screen Keyboard (OSK, aka Virtual Keyboard) is shown when a field is focused.

The biggest issue I'm facing is that I cannot get a header element to stay visually present at the top when the OSK is shown. This is a big deal when your top appbar has primary actions for a form like "Save". It makes the UX confusing, which leads to customers leaving in frustration, so this is isn't something trivial in my opinion.

I've tried the VisualViewport API that Chrome team recommended, referencing the env(keyboard-inset-height) and that just doesn't seem to work, which makes me think I'm doing something weird with my layout such that the ENV isn't being set properly.

My code

Nothing too crazy, using CSS grid to control layout.

HTML

    header

      main
      <input type="text" />

    footer

CSS style

body {
  margin: 0;
}

#container {
  height: 100dvh;
  display: grid;
  grid-template:
    "header" 50px
    "main" 1fr
    "footer" 50px
    "keyboard" env(keyboard-inset-height, 0px); // does not seem to work?
}

#header {
  grid-area: header;
}

#main {
  grid-area: main;
  overflow-y: scroll;
}

#footer {
  grid-area: footer;
}

What I get is the following 2 screenshots, the full-page one being the layout as I want it, and the 2nd one being when you focus the cursor into an input near the bottom and it "pushes" the entire visual viewport up such that the header is offscreen.

fullscreen
input focused

Is there any way currently to ensure that the header stays at the top of the visual viewport always? I cannot find a working solution to this at the moment after the recent Chrome updates.


问:
How set 2 hours interval on AmChart 4 Stacked Area Chart?
I have got a Stacked AreaChart and require to display 2 hours intervals between dates on DateAxis bar.

Now my charts showing interval in DateAxis (12.27 00:00, 12.27 12:00, 12.28 00:00, 12.28 12:00 12.29 00:00, ..) my chart. I want it to show on the cursor hover tooltip every 2 hours (12.27 10:00, 12.27 12:00, 12.27 14:00, 12.27, 16:00, ....) like here. The adding dateAxis.baseInterval didn't help.
How can I achieve this in Amcharts?

```<code>The code example goes here:

      //create chart
      let chart = am4core.create("chartdiv", am4charts.XYChart);

      //dateAxis
      let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
      dateAxis.renderer.grid.template.visible = false;
      dateAxis.dateFormats.setKey("day", "MM/dd");
      dateAxis.periodChangeDateFormats.setKey("day", "MM/dd");
      dateAxis.renderer.minGridDistance = 60;
      dateAxis.startLocation = 0.5;
      dateAxis.endLocation = 0.5;
      dateAxis.baseInterval = {
        timeUnit: "hour",
        count: 2
      };

      //valueAxis
      let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
      valueAxis.renderer.grid.template.visible = false;
      valueAxis.tooltip.disabled = true;

      //axis tooltip
      let axisTooltip = dateAxis.tooltip;
      axisTooltip.background.fill = am4core.color("darkgrey");
      axisTooltip.background.strokeWidth = 0;
      axisTooltip.fontSize = 11;
      axisTooltip.width = 30;
      axisTooltip.dy = 5;

      //series
      for (let i = 0; i < this.categories.length; i++) {
        let series = chart.series.push(new am4charts.LineSeries());
        series.dataFields.dateX = "timestamp";
        series.dataFields.valueY = this.categories[i].key;
        series.fill = am4core.color(this.setColorByCategory(this.categories[i].key));
        series.fillOpacity = 1;
        series.strokeWidth = 0;
        series.stacked = true;

        // tooltip
        series.tooltip.getFillFromObject = false;
        series.tooltip.background.fill = am4core.color("#fff");
        series.tooltip.background.opacity = 0.85;
        series.tooltip.pointerOrientation = "horizontal";
        const totalHTML = `
            <table class ='tooltip-table'>
              <tr>
                <td>
                  <div style="background:black;"></div>
                  <span>Total:</span>
                  <span class="float-right"> {total}</span>
                </td>
              </tr>\

            </table>
            `;
        let categoriesHTML = '';
        for (let k = 0; k < this.categories.length; k++) {
          let key = this.categories[k].key;
          categoriesHTML += `
            <table class ='tooltip-table'>
              <tr>
                <td>
                  <div style="background: ${this.setColorByCategory(key) || this.availableColors[i]};"></div>
                  <span">${key}:</span>
                  <span class="float-right">{${key}}</span>
                </td>
              </tr>
            </table>
          `;
        }
        series.tooltipHTML = categoriesHTML + totalHTML;
      }

      //cursor
      chart.cursor = new am4charts.XYCursor();
      chart.cursor.lineY.disabled = true;
      chart.cursor.maxTooltipDistance = -1;
      chart.cursor.fullWidthLineX = true;
      this.chart = chart;
</code>```

Body:
I have got a Stacked AreaChart and require to display 2 hours intervals between dates on DateAxis bar.

Now my charts showing interval in DateAxis (12.27 00:00, 12.27 12:00, 12.28 00:00, 12.28 12:00 12.29 00:00, ..) my chart. I want it to show on the cursor hover tooltip every 2 hours (12.27 10:00, 12.27 12:00, 12.27 14:00, 12.27, 16:00, ....) like here. The adding dateAxis.baseInterval didn't help.
How can I achieve this in Amcharts?

The code example goes here:

      //create chart
      let chart = am4core.create("chartdiv", am4charts.XYChart);

      //dateAxis
      let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
      dateAxis.renderer.grid.template.visible = false;
      dateAxis.dateFormats.setKey("day", "MM/dd");
      dateAxis.periodChangeDateFormats.setKey("day", "MM/dd");
      dateAxis.renderer.minGridDistance = 60;
      dateAxis.startLocation = 0.5;
      dateAxis.endLocation = 0.5;
      dateAxis.baseInterval = {
        timeUnit: "hour",
        count: 2
      };

      //valueAxis
      let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
      valueAxis.renderer.grid.template.visible = false;
      valueAxis.tooltip.disabled = true;

      //axis tooltip
      let axisTooltip = dateAxis.tooltip;
      axisTooltip.background.fill = am4core.color("darkgrey");
      axisTooltip.background.strokeWidth = 0;
      axisTooltip.fontSize = 11;
      axisTooltip.width = 30;
      axisTooltip.dy = 5;

      //series
      for (let i = 0; i < this.categories.length; i++) {
        let series = chart.series.push(new am4charts.LineSeries());
        series.dataFields.dateX = "timestamp";
        series.dataFields.valueY = this.categories[i].key;
        series.fill = am4core.color(this.setColorByCategory(this.categories[i].key));
        series.fillOpacity = 1;
        series.strokeWidth = 0;
        series.stacked = true;

        // tooltip
        series.tooltip.getFillFromObject = false;
        series.tooltip.background.fill = am4core.color("#fff");
        series.tooltip.background.opacity = 0.85;
        series.tooltip.pointerOrientation = "horizontal";
        const totalHTML = `

                  Total:
                   {total}

\

            `;
        let categoriesHTML = '';
        for (let k = 0; k < this.categories.length; k++) {
          let key = this.categories[k].key;
          categoriesHTML += `

                  ${key}:
                  {${key}}

          `;
        }
        series.tooltipHTML = categoriesHTML + totalHTML;
      }

      //cursor
      chart.cursor = new am4charts.XYCursor();
      chart.cursor.lineY.disabled = true;
      chart.cursor.maxTooltipDistance = -1;
      chart.cursor.fullWidthLineX = true;
      this.chart = chart;


问:
How to fix error "Unable to upload artifact streamlitfunction:python3.8-v1 referenced by ImageUri parameter of StreamlitFunction resource
i am trying to deploy this lambda function into aws ecr registry using docker but im running into this problem. How do i fix it?

Note:A similar function worked for me a few days back with same settings and now when i try the same thing on that..this error persists (w)

```<code>sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Found
        Reading default arguments  :  Success

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [streamlit-openaiapp]:
        AWS Region [us-east-1]:
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [Y/n]: y
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: y
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [Y/n]: y
        StreamlitFunction may not have authorization defined, Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: y
        SAM configuration file [samconfig.toml]:
        SAM configuration environment [default]:

        Looking for resources needed for deployment:
         Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-18mtvtv9a39lx
         A different default S3 bucket can be set in samconfig.toml
         Image repositories: Found (1 of 1) #Different image repositories can be set in samconfig.toml
         StreamlitFunction: 377804275255.dkr.ecr.us-east-1.amazonaws.com/openaiqamodeld50b3bc0/helloworldfunction19d43fc4repo

        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

Error: Unable to upload artifact streamlitfunction:python3.8-v1 referenced by ImageUri parameter of StreamlitFunction resource.
500 Server Error: Internal Server Error ("Get "https://377804275255.dkr.ecr.us-east-1.amazonaws.com/v2/": net/http: TLS handshake timeout")
</code>```

Body:
i am trying to deploy this lambda function into aws ecr registry using docker but im running into this problem. How do i fix it?

Note:A similar function worked for me a few days back with same settings and now when i try the same thing on that..this error persists (w)

sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Found
        Reading default arguments  :  Success

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [streamlit-openaiapp]:
        AWS Region [us-east-1]:
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [Y/n]: y
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: y
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [Y/n]: y
        StreamlitFunction may not have authorization defined, Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: y
        SAM configuration file [samconfig.toml]:
        SAM configuration environment [default]:

        Looking for resources needed for deployment:
         Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-18mtvtv9a39lx
         A different default S3 bucket can be set in samconfig.toml
         Image repositories: Found (1 of 1) #Different image repositories can be set in samconfig.toml
         StreamlitFunction: 377804275255.dkr.ecr.us-east-1.amazonaws.com/openaiqamodeld50b3bc0/helloworldfunction19d43fc4repo

        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

Error: Unable to upload artifact streamlitfunction:python3.8-v1 referenced by ImageUri parameter of StreamlitFunction resource.
500 Server Error: Internal Server Error ("Get "https://377804275255.dkr.ecr.us-east-1.amazonaws.com/v2/": net/http: TLS handshake timeout")


问:
Internal Server Error: readlink /var/lib/docker/overlay2/l/<id>: no such file or directory
After installing Yacht on docker compose with this docker-compose.yml

```<code>---

version: "3"
services:
  yacht:
    container_name: yacht
    restart: unless-stopped
    ports:
      - 8000:8000
    volumes:
      - yacht:/config
      - /var/run/docker.sock:/var/run/docker.sock
    image: selfhostedpro/yacht

volumes:
  yacht:
</code>```

yacht starts normally with docker-compose up -d but the dashboard doesn't load anything, on every page i get this popup error:
popup error

I tried the following things:

Restarting Yacht

Manually creating the directory but gave an error "invalid argument"

rebooting the PC

Do somebody know how to fix?

Body:
After installing Yacht on docker compose with this docker-compose.yml

---

version: "3"
services:
  yacht:
    container_name: yacht
    restart: unless-stopped
    ports:
      - 8000:8000
    volumes:
      - yacht:/config
      - /var/run/docker.sock:/var/run/docker.sock
    image: selfhostedpro/yacht

volumes:
  yacht:

yacht starts normally with docker-compose up -d but the dashboard doesn't load anything, on every page i get this popup error:
popup error

I tried the following things:

Restarting Yacht

Manually creating the directory but gave an error "invalid argument"

rebooting the PC

Do somebody know how to fix?


问:
How to upload video from iPhone to iis media services
Has anyone idea about IIS Media services. I want to stream video recorded from iPhone. Has anyone know how to upload video to IIS Media services? I found this url but in this they are using expression encoder 4

http://learn.iis.net/page.aspx/854/apple-http-live-streaming-with-iis-media-services

Please help me i am working on Video streaming application in which i have to upload continuous video to server.

Thanks in advance.

ContentLicense: CC BY-SA 3.0


问:
Querying a dynamic JSON KeyValue Store and pivoting it in Microsoft SQL Server
I have a query in Microsoft SQL Server querying a JSON Column

```<code>SELECT [KEY], [Value]
FROM openjson((SELECT TOP 1 KeyValueIntegers from
[MatrixAnalyzer].[CountsMatrixInitial] Where MatrixId = 16), '$') AS L1

//returns
KEY          VALUE

WT1          [1,2,3,4,5]
LDI_FC       [5,4,3,2,1]

</code>```

both the names of the keys and the number of the keys are unknown. I am trying to pivot this so that I get a matrix that looks like.

```<code>WT1       LDI_FC
1         5
2         4
3         3
4         2
5         1
</code>```

What is the most efficient way to pivot this table. If I knew the names of the key's before hand it wouldn't be so bad but they are always different. How would I go about doing a dynamic pivot.

Body:
I have a query in Microsoft SQL Server querying a JSON Column

SELECT [KEY], [Value]
FROM openjson((SELECT TOP 1 KeyValueIntegers from
[MatrixAnalyzer].[CountsMatrixInitial] Where MatrixId = 16), '$') AS L1

//returns
KEY          VALUE

WT1          [1,2,3,4,5]
LDI_FC       [5,4,3,2,1]

both the names of the keys and the number of the keys are unknown. I am trying to pivot this so that I get a matrix that looks like.

WT1       LDI_FC
1         5
2         4
3         3
4         2
5         1

What is the most efficient way to pivot this table. If I knew the names of the key's before hand it wouldn't be so bad but they are always different. How would I go about doing a dynamic pivot.


问:
Can MappingScore() be used to get an absolute measure of scRNAseq dataset similarity to the reference dataset?
I have been using Seurat v4 Reference Mapping align some query scRNAseq datasets that come from IPSC-derived cells that were subject to several directed cortical differentiation protocols at multiple timepoints. The reference dataset I made by merging several individual fetal cortical sample datasets that I had annotated based on their unsupervised cluster DEGs (following this vignette using the default parameters).

I am interested in seeing which protocol produces cells most similar to the cells found in the fetal datasets as well as which fetal timepoints the query datasets tend to map to. I understand that the MappingScore() function can show me query cells that aren't well represented in the reference dataset, so I figured that these scores could tell me which datasets are most similar to the reference dataset. However, in comparing the violin plots of the mapping scores for a query dataset from one of the differentiation protocols to a query dataset that contains just pluripotent cells it looks like there are cells with high mapping scores found in both cases (see attached images) even though really only the differentiated cells should have cells closely resembling the fetal cortical tissue cells. I attached the code as a .txt file.

My question is whether or not the mapping score can be used as an absolute measurement of query to reference dataset similarity or if it is always just a relative measure where the high and low thresholds are set by the query dataset. If the latter, what alternative functions might I use here to get information about absolute similarity?

Thanks.

Attachments:
Pluripotent Cell Mapping Score
Differentiated Cell Mapping Score
Code Used For Mapping


问:
Npgsql - FULL OUTER JOIN on two unrelated tables
I have two tables, point_transactions which shows how users got and spent their in-app points, and wallet_transactions which shows how users got and spent their wallet money (real money). These two tables do not have direct relation with each other. They both have a created_on column which shows when they were created. I need to create a table that shows history of a user's transactions (both point and wallet). This table is sorted based on the creation time of the transaction and has paging, which means it's better to get paged result from database rather than loading all data into memory.

The following query gives me what I want:

select *,
    case
        when pt.id is null then wt.created_on
        else pt.created_on
    end as tx_created_on
from point_transactions as pt
full outer join wallet_transactions as wt on false
order by tx_created_on desc
```

Is there any way I can get this with EF Core?

Body:
I have two tables, point_transactions which shows how users got and spent their in-app points, and wallet_transactions which shows how users got and spent their wallet money (real money). These two tables do not have direct relation with each other. They both have a created_on column which shows when they were created. I need to create a table that shows history of a user's transactions (both point and wallet). This table is sorted based on the creation time of the transaction and has paging, which means it's better to get paged result from database rather than loading all data into memory.

The following query gives me what I want:

select *,
    case
        when pt.id is null then wt.created_on
        else pt.created_on
    end as tx_created_on
from point_transactions as pt
full outer join wallet_transactions as wt on false
order by tx_created_on desc

Is there any way I can get this with EF Core?


问:
How to start unique windows for running paralell instances of a program in Powershell, with input file?
I want to write a powershell script that opens unique instances of the same program, with input arguments to it. But my problem is when I use the example code below - the xml-file is opened in the same program window. Not in unique windows.

So, first example. When I execute the following code I get four instances of the program opened.

```<code>start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"
Start-Sleep -Seconds 10

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"
Start-Sleep -Seconds 10

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"
Start-Sleep -Seconds 10

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"
</code>```

All good so far.

I can also open the program with xml-file input and by that starting a script. This is done with this code:

```<code>start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A003\open.xml"
</code>```

Still all is fine.

But when I run the following code, with the attempt to open four separate windows/instances and running the four different scripts in parallel - they are opened in the same window instead of four different windows.

```<code>$proc1 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A003\open.xml" -PassThru
Start-Sleep -Seconds 10

$proc2 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A005\open.xml" -PassThru
Start-Sleep -Seconds 10

$proc3 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A031\open.xml" -PassThru
Start-Sleep -Seconds 10

$proc4 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18B029\open.xml" -PassThru
Start-Sleep -Seconds 10
</code>```

Any idea of how I can solve this?

Body:
I want to write a powershell script that opens unique instances of the same program, with input arguments to it. But my problem is when I use the example code below - the xml-file is opened in the same program window. Not in unique windows.

So, first example. When I execute the following code I get four instances of the program opened.

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"
Start-Sleep -Seconds 10

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"
Start-Sleep -Seconds 10

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"
Start-Sleep -Seconds 10

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe"

All good so far.

I can also open the program with xml-file input and by that starting a script. This is done with this code:

start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A003\open.xml"

Still all is fine.

But when I run the following code, with the attempt to open four separate windows/instances and running the four different scripts in parallel - they are opened in the same window instead of four different windows.

$proc1 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A003\open.xml" -PassThru
Start-Sleep -Seconds 10

$proc2 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A005\open.xml" -PassThru
Start-Sleep -Seconds 10

$proc3 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18A031\open.xml" -PassThru
Start-Sleep -Seconds 10

$proc4 = start-process "C:\Program Files\OCAD\OCAD 2018 Mapping Solution\OCAD 2018 Mapping Solution_64bit.exe" "D:\laserkartor\18B029\open.xml" -PassThru
Start-Sleep -Seconds 10

Any idea of how I can solve this?


问:
Is it possible to load microsoft forms dropdown list from excel or text file
Is it possible to load microsoft forms dropdown list from excel or text file

Is it possible to load microsoft forms dropdown list from excel or text file.
As the form options will keep changing frequently like daily, so if options can be loaded from a file or excel or onedrive file
can use script to update the file which can help with updationg fields of dropdown manually.
Any idea or workaround let me know. Thanks for your inputs.

Exploring the same in sharepoint forms as well.


问:
File format Error after Download - Jekyll blog
I would like users to download a zip file and I have the following code.

```<code><a href="directory/fileName.zip" download>DOWNLOAD</a>
</code>```

However, when I test it out, the file downloads instantly and when I try to open it, I get the unsupported format error. On localhost, it downloads instantly but the zip file successfully opens.

I am on MacOS and have git lfs installed if that is important. Any help would be greatly appreciated. Thank you.

I tried renaming the file so that there are no spaces in its name, tried to separately compress the directory to be zipped.

Body:
I would like users to download a zip file and I have the following code.

DOWNLOAD

However, when I test it out, the file downloads instantly and when I try to open it, I get the unsupported format error. On localhost, it downloads instantly but the zip file successfully opens.

I am on MacOS and have git lfs installed if that is important. Any help would be greatly appreciated. Thank you.

I tried renaming the file so that there are no spaces in its name, tried to separately compress the directory to be zipped.


问:
Why is browser using cached response headers if they are not present in the actual response?
I realized that a response header would be present in the Network tab of the Chrome console even if that header wasn't set in express. I found this answer suggesting disallowing caching. What confuses me is why the cached response is still used even if a request is made to the server.

request from react

```<code>const baseURL = 'http://localhost:3001'
const axiosClient = axios.create({
  baseURL,
  withCredentials: true,
})

let accessToken

axiosClient.interceptors.response.use((response) => {
  const { data, headers } = response
  //store access token in memory
  accessToken = headers['x-access-token']
  console.log(accessToken)
  // if (accessToken) axiosClient.defaults.headers['X-Access-Token'] = accessToken
  return data
})

async me() {
    return await axiosClient.get('/auth/me')
  }
</code>```

request reaches route

```<code>router.get('/me', (req, res) => {
  // res.set('X-Access-Token', 'test 4')
  res.send('me')
})
</code>```

vscode debug console

```<code>res.getHeaders()
{x-powered-by: 'Express', access-control-allow-origin: 'http://localhost:3000', vary: 'Origin', access-control-allow-credentials: 'true', access-control-expose-headers: 'X-Access-Token'}
req.headers
{host: 'localhost:3001', connection: 'keep-alive', sec-ch-ua: '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"', accept: 'application/json, text/plain, */*', sec-ch-ua-mobile: '?0', …}
</code>```

old token still appears in chrome

Since Chrome made a request to the server instead of just using the cached response (First, since there is no need to deliver the request to the origin server, then the closer the client and cache are, the faster the response will be), why isn't Chrome using the received response where the token header isn't present?

Body:
I realized that a response header would be present in the Network tab of the Chrome console even if that header wasn't set in express. I found this answer suggesting disallowing caching. What confuses me is why the cached response is still used even if a request is made to the server.

request from react

const baseURL = 'http://localhost:3001'
const axiosClient = axios.create({
  baseURL,
  withCredentials: true,
})

let accessToken

axiosClient.interceptors.response.use((response) => {
  const { data, headers } = response
  //store access token in memory
  accessToken = headers['x-access-token']
  console.log(accessToken)
  // if (accessToken) axiosClient.defaults.headers['X-Access-Token'] = accessToken
  return data
})

async me() {
    return await axiosClient.get('/auth/me')
  }

request reaches route

router.get('/me', (req, res) => {
  // res.set('X-Access-Token', 'test 4')
  res.send('me')
})

vscode debug console

res.getHeaders()
{x-powered-by: 'Express', access-control-allow-origin: 'http://localhost:3000', vary: 'Origin', access-control-allow-credentials: 'true', access-control-expose-headers: 'X-Access-Token'}
req.headers
{host: 'localhost:3001', connection: 'keep-alive', sec-ch-ua: '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"', accept: 'application/json, text/plain, */*', sec-ch-ua-mobile: '?0', …}

old token still appears in chrome

Since Chrome made a request to the server instead of just using the cached response (First, since there is no need to deliver the request to the origin server, then the closer the client and cache are, the faster the response will be), why isn't Chrome using the received response where the token header isn't present?


问:
Github Packages authentication failure from GitHub Action
I am receiving an authentication error (401) when trying to restore a package from my other GitHub repository package source.

My project called Identity (in it's own repo) consumes my project (in a separate repo) called Core. Local build and reference in Visual Studio works fine. However my Build/Test action in the Identity repo fails to authenticate (see screenshot).

I have granted permissions to the Identity repo from the Core repo (see screenshot).

I have added specific repo location to the related Identity .csproj (see screenshot).

I think I am missing maybe something in the Action environment of the Identity project...but cannot identify what.


问:
php Header('location') is not redirecting
I am having some problems with redirecting to another page in Php.

I am using :

```<code>header("Location: mypage.html");
</code>```

But instead of redirecting to this page it is just printing the html file of the 'mypage.html' into the console. With console being the debug console in the Google Chrome inspect view aka (ctrl + shift + i).

This is the relevant part of the code for this error:

```<code><?php

    ob_clean(); // did not work...

    function isValid(){
        if(
            $_POST["name"] != "" &&
            $_POST["tel"] != "" &&
            $_POST["email"] != "" &&
            $_POST["msg"] != "" &&
            $_POST["reg"] != ""
        ) {
            return true;
        }
        return false;
    }

    if (isValid()){
        $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'; // URL to the reCAPTCHA server
        $recaptcha_secret = 'XXXXXXsecretkeyXXXXX'; // Secret key
        $recaptcha_response = $_POST['recaptchaResponse']; // Response from reCAPTCHA server, added to the form during processing
        $recaptcha = file_get_contents($recaptcha_url.'?secret='.$recaptcha_secret.'&response='.$recaptcha_response); // Send request to the server
        $recaptcha = json_decode($recaptcha); // Decode the JSON response

        if($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == "submit"){
            // echo "Score : ".$recaptcha->score;
            // Send the email

            $Name = $_POST["name"];
            $Tel = $_POST["tel"];
            $MailFrom = $_POST["email"];
            $Message = UTF8_decode($_POST["msg"]);
            $Reg = $_POST["reg"];

            $MailTo  = "mail@mail.com";
            $Subject = "".$Name." | Mail@mail.com";

            $Headers = array(
                'From'         => $MailTo,
                'Reply-To'     => $MailTo,
                'MIME-Version' => '1.0',
                'Content-type' => 'text/html',
                'charset'      => 'UTF-8',
                'X-Mailer'     => 'PHP/' . phpversion()
            );

            $Msg = 'Namn: ' . $Name . '<br />Telefonnummer: ' . $Tel . '<br />E-mail: ' . $MailFrom . '<br />Regnummer: ' . $Reg . '<br /><br />Meddelande: ' . wordwrap($Message, 50);

            $test = mail($MailTo, $Subject, $Msg, $Headers);

            if ($test === true) {
                ob_clean(); // this did not work here either...
                header("Location: redirect.html"); // this is where the error is!
            } else {
                echo "Meddelandet kunde inte skickas, vänligen kontakta oss på följande mail. (mail@mail.com)";
            }

        } else {
            // reCAPTCHA failed, dont send mail
            echo "Vi tror att du är en robot, är du inte en robot så vänligen kontakta oss på följande mail. (mail@mail.com)";
        }
    }
?>
</code>```

To fix this problem I have tried to remove all of the echos in the php file since I thought that it might not work with echos. But no success.

I have also tried to use a function called ob_clean() to prevent it from writing in the console but no luck there either.

Any ideas would be greatly appreciated.

Body:
I am having some problems with redirecting to another page in Php.

I am using :

header("Location: mypage.html");

But instead of redirecting to this page it is just printing the html file of the 'mypage.html' into the console. With console being the debug console in the Google Chrome inspect view aka (ctrl + shift + i).

This is the relevant part of the code for this error:

<?php

    ob_clean(); // did not work...

    function isValid(){
        if(
            $_POST["name"] != "" &&
            $_POST["tel"] != "" &&
            $_POST["email"] != "" &&
            $_POST["msg"] != "" &&
            $_POST["reg"] != ""
        ) {
            return true;
        }
        return false;
    }

    if (isValid()){
        $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'; // URL to the reCAPTCHA server
        $recaptcha_secret = 'XXXXXXsecretkeyXXXXX'; // Secret key
        $recaptcha_response = $_POST['recaptchaResponse']; // Response from reCAPTCHA server, added to the form during processing
        $recaptcha = file_get_contents($recaptcha_url.'?secret='.$recaptcha_secret.'&response='.$recaptcha_response); // Send request to the server
        $recaptcha = json_decode($recaptcha); // Decode the JSON response

        if($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == "submit"){
            // echo "Score : ".$recaptcha->score;
            // Send the email

            $Name = $_POST["name"];
            $Tel = $_POST["tel"];
            $MailFrom = $_POST["email"];
            $Message = UTF8_decode($_POST["msg"]);
            $Reg = $_POST["reg"];

            $MailTo  = "mail@mail.com";
            $Subject = "".$Name." | Mail@mail.com";

            $Headers = array(
                'From'         => $MailTo,
                'Reply-To'     => $MailTo,
                'MIME-Version' => '1.0',
                'Content-type' => 'text/html',
                'charset'      => 'UTF-8',
                'X-Mailer'     => 'PHP/' . phpversion()
            );

            $Msg = 'Namn: ' . $Name . '
Telefonnummer: ' . $Tel . '
E-mail: ' . $MailFrom . '
Regnummer: ' . $Reg . '

Meddelande: ' . wordwrap($Message, 50);

            $test = mail($MailTo, $Subject, $Msg, $Headers);

            if ($test === true) {
                ob_clean(); // this did not work here either...
                header("Location: redirect.html"); // this is where the error is!
            } else {
                echo "Meddelandet kunde inte skickas, vänligen kontakta oss på följande mail. (mail@mail.com)";
            }

        } else {
            // reCAPTCHA failed, dont send mail
            echo "Vi tror att du är en robot, är du inte en robot så vänligen kontakta oss på följande mail. (mail@mail.com)";
        }
    }
?>

To fix this problem I have tried to remove all of the echos in the php file since I thought that it might not work with echos. But no success.

I have also tried to use a function called ob_clean() to prevent it from writing in the console but no luck there either.

Any ideas would be greatly appreciated.


问:
Can not make cache safe url
I am working with Sharepoint 2007 and VS 2008. I created a web part with user control which refrences some external files (js,css and images). I deployed both the web part and the external files (files in 12 hive folder structure). When i try to use to web part I get the following error.

Cannot make a cache safe URL for
  "/DatePicker/JS/JsDatePick.min.1.3.js", file not found. Please verify
  that the file exists under the layouts directory.

Though the js file exists in layout folder.

Please help. Thanks.

Title: Can not make cache safe url


问:
Link two federated auth providers to single email account?
In firebase, I'm using their authentication and I have a need to allow users to link multiple federated auth providers to their same firebase account. This seems to work well when the user has a email/password provider, and then I want to add either Google or Microsoft provider to their account.

However, I have use case where user is using Google for Authentication and now they want to add the Microsoft Provider.  Instructions are here: https://firebase.google.com/docs/auth/web/account-linking#web-version-8_1  and it seems to indicate any other providers can be added to same account.

My snippet of code to link them to Microsoft as an example is:

```<code>const LinkNewProvider = async () => {
  const provider = new firebase.auth.OAuthProvider('microsoft.com');
  try{
    const result = firebase.auth().currentUser.linkWithPopup(provider);
    var credential = result.credential;
    var user = result.user;
    console.log(credential);
  } catch(error) {
    console.log(error)
  }
}
</code>```

When I try this, however, I get the error back "FirebaseError: Firebase: The email address is already in use by another account. (auth/email-already-in-use)."

What am I missing? Is it possible to link multiple federated providers to single account?

Body:
In firebase, I'm using their authentication and I have a need to allow users to link multiple federated auth providers to their same firebase account. This seems to work well when the user has a email/password provider, and then I want to add either Google or Microsoft provider to their account.

However, I have use case where user is using Google for Authentication and now they want to add the Microsoft Provider.  Instructions are here: https://firebase.google.com/docs/auth/web/account-linking#web-version-8_1  and it seems to indicate any other providers can be added to same account.

My snippet of code to link them to Microsoft as an example is:

const LinkNewProvider = async () => {
  const provider = new firebase.auth.OAuthProvider('microsoft.com');
  try{
    const result = firebase.auth().currentUser.linkWithPopup(provider);
    var credential = result.credential;
    var user = result.user;
    console.log(credential);
  } catch(error) {
    console.log(error)
  }
}

When I try this, however, I get the error back "FirebaseError: Firebase: The email address is already in use by another account. (auth/email-already-in-use)."

What am I missing? Is it possible to link multiple federated providers to single account?


问:
xwiki docker container: ERROR DefaultExtensionLicenseManager - Failed to load license file at
I'm running the xwiki docker container with docker swarm and the xwiki container keeps randomly crashing. This is the docker-compose configuration:

```<code>  xwiki:
    image: xwiki:lts-mysql
    environment:
      DB_DATABASE: ${XWIKI_DB}
      DB_USER: ${XWIKI_USER}
      DB_PASSWORD: ${XWIKI_PASS}
      DB_HOST: mysql
    volumes:
      - ./xwiki:/usr/local/xwiki
    networks:
      - web
      - mysql-net
    deploy:
      resources:
        limits:
          cpus: '1.00'
          memory: 1024m
</code>```

The following stacktrace keep popping up, does anyone know what is going on here?:

```<code>java.lang.NullPointerException: null
  at org.xwiki.extension.internal.DefaultExtensionLicenseManager.initialize(DefaultExtensionLicenseManager.java:94)
  at org.xwiki.component.embed.InitializableLifecycleHandler.handle(InitializableLifecycleHandler.java:39)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:365)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getDependencyInstance(EmbeddableComponentManager.java:406)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:355)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:189)
  at org.xwiki.extension.repository.internal.local.LocalExtensionStorage.<init>(LocalExtensionStorage.java:91)
  at org.xwiki.extension.repository.internal.local.DefaultLocalExtensionRepository.initialize(DefaultLocalExtensionRepository.java:100)
  at org.xwiki.component.embed.InitializableLifecycleHandler.handle(InitializableLifecycleHandler.java:39)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:365)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getDependencyInstance(EmbeddableComponentManager.java:406)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:355)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getDependencyInstance(EmbeddableComponentManager.java:406)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:355)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:189)
  at org.xwiki.container.servlet.XWikiServletContextListener.contextInitialized(XWikiServletContextListener.java:116)
  at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4764)
  at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5222)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
  at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:698)
  at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:696)
  at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1184)
  at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1932)
  at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
  at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
  at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
  at java.base/java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
  at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1094)
  at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:476)
  at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1617)
  at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:318)
  at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
  at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:423)
  at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:366)
  at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
  at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1383)
  at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
  at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
  at java.base/java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
  at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916)
  at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:265)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.StandardService.startInternal(StandardService.java:430)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.startup.Catalina.start(Catalina.java:772)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.base/java.lang.reflect.Method.invoke(Unknown Source)
  at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:347)
  at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:478)
2023-01-02 20:28:14,183 [main] ERROR DefaultExtensionLicenseManager - Failed to load license file at [null]
java.lang.NullPointerException: null
  at org.xwiki.extension.internal.DefaultExtensionLicenseManager.initialize(DefaultExtensionLicenseManager.java:94)
  at org.xwiki.component.embed.InitializableLifecycleHandler.handle(InitializableLifecycleHandler.java:39)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:365)
  at org.xwiki.component.embed.Embeddable
</code>```

It always crashes at some point with this error message but also works until this error message appears.

Body:
I'm running the xwiki docker container with docker swarm and the xwiki container keeps randomly crashing. This is the docker-compose configuration:

  xwiki:
    image: xwiki:lts-mysql
    environment:
      DB_DATABASE: ${XWIKI_DB}
      DB_USER: ${XWIKI_USER}
      DB_PASSWORD: ${XWIKI_PASS}
      DB_HOST: mysql
    volumes:
      - ./xwiki:/usr/local/xwiki
    networks:
      - web
      - mysql-net
    deploy:
      resources:
        limits:
          cpus: '1.00'
          memory: 1024m

The following stacktrace keep popping up, does anyone know what is going on here?:

java.lang.NullPointerException: null
  at org.xwiki.extension.internal.DefaultExtensionLicenseManager.initialize(DefaultExtensionLicenseManager.java:94)
  at org.xwiki.component.embed.InitializableLifecycleHandler.handle(InitializableLifecycleHandler.java:39)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:365)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getDependencyInstance(EmbeddableComponentManager.java:406)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:355)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:189)
  at org.xwiki.extension.repository.internal.local.LocalExtensionStorage.<init>(LocalExtensionStorage.java:91)
  at org.xwiki.extension.repository.internal.local.DefaultLocalExtensionRepository.initialize(DefaultLocalExtensionRepository.java:100)
  at org.xwiki.component.embed.InitializableLifecycleHandler.handle(InitializableLifecycleHandler.java:39)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:365)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getDependencyInstance(EmbeddableComponentManager.java:406)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:355)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getDependencyInstance(EmbeddableComponentManager.java:406)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:355)
  at org.xwiki.component.embed.EmbeddableComponentManager.getComponentInstance(EmbeddableComponentManager.java:451)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:201)
  at org.xwiki.component.embed.EmbeddableComponentManager.getInstance(EmbeddableComponentManager.java:189)
  at org.xwiki.container.servlet.XWikiServletContextListener.contextInitialized(XWikiServletContextListener.java:116)
  at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4764)
  at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5222)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
  at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:698)
  at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:696)
  at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1184)
  at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1932)
  at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
  at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
  at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
  at java.base/java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
  at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1094)
  at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:476)
  at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1617)
  at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:318)
  at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
  at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:423)
  at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:366)
  at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
  at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1393)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1383)
  at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
  at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
  at java.base/java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
  at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916)
  at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:265)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.StandardService.startInternal(StandardService.java:430)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
  at org.apache.catalina.startup.Catalina.start(Catalina.java:772)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.base/java.lang.reflect.Method.invoke(Unknown Source)
  at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:347)
  at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:478)
2023-01-02 20:28:14,183 [main] ERROR DefaultExtensionLicenseManager - Failed to load license file at [null]
java.lang.NullPointerException: null
  at org.xwiki.extension.internal.DefaultExtensionLicenseManager.initialize(DefaultExtensionLicenseManager.java:94)
  at org.xwiki.component.embed.InitializableLifecycleHandler.handle(InitializableLifecycleHandler.java:39)
  at org.xwiki.component.embed.EmbeddableComponentManager.createInstance(EmbeddableComponentManager.java:365)
  at org.xwiki.component.embed.Embeddable

It always crashes at some point with this error message but also works until this error message appears.


问:
Return an item in a list that has the highest similarity with a compared value (using SpaCy)
I have an assignment where I am building a function that will take in a movie description and will compare it to a list containing 10 other movie descriptions. Using spacy, I have gotten as far as being able to print the 10 values of similarity, as seen below:

in the function, 'x' will represent the variable for the movie description.

```<code>def movie_reccomendation(x):
    with open("movies.txt", "r", encoding='utf-8') as file_read:
        lines = file_read.readlines()
        movie_list = []
        for sub in lines:
            movie_list.append(sub.replace("\n", ""))

    for token in x:
        token = nlp(token)
        for token_ in movie_list:
            token_ = nlp(token_)
            movie_similarity = token.similarity(token_)
            print(movie_similarity) # Prints the 10 similarity values
</code>```

I then figure I should be able to use max() on movie similarity, take that value and call the corresponding place in the list of 10 movies and display the recommendation, but the first issue I ran into with using max was a TypeError indicating 'float' object is not iterable. I am lost from where I need to go here...

Body:
I have an assignment where I am building a function that will take in a movie description and will compare it to a list containing 10 other movie descriptions. Using spacy, I have gotten as far as being able to print the 10 values of similarity, as seen below:

in the function, 'x' will represent the variable for the movie description.

def movie_reccomendation(x):
    with open("movies.txt", "r", encoding='utf-8') as file_read:
        lines = file_read.readlines()
        movie_list = []
        for sub in lines:
            movie_list.append(sub.replace("\n", ""))

    for token in x:
        token = nlp(token)
        for token_ in movie_list:
            token_ = nlp(token_)
            movie_similarity = token.similarity(token_)
            print(movie_similarity) # Prints the 10 similarity values

I then figure I should be able to use max() on movie similarity, take that value and call the corresponding place in the list of 10 movies and display the recommendation, but the first issue I ran into with using max was a TypeError indicating 'float' object is not iterable. I am lost from where I need to go here...


问:
how to transform mulivariable function using numpy library so it computes faster
I am studying economics and in order to learn Python I chose to make an economic model in it. I solved the model numerically, computed it in to python. Unfortunately the computation takes way too much time. Can you give me some tips how to improve it?

At first, I transformed dictionary set of data into numpy array, but it did not improve the process much. Normally, the higher value of j appear, more time it takes to count next value. What would u recommend?

Here are the most important parts of the code (without numbers)

def c(j,e):
    if j == 1 :
        return ((1+t_l)*(1-t_)*(ind_w(j,e)+suma_ind_w(j,e))+suma_p(j)+miu+suma_miu(j))/((1+t_c)*(((1+phi)*(1+suma_beta(j)))+suma_beta_r(j)))
    elif j < k and j!=1 :
        return ((1+t_l)*(1-t_)*(ind_w(j,e)+suma_ind_w(j,e))+suma_p(j)+miu+suma_miu(j)+(1+r)*a(j-1, e))/((1+t_c)*(((1+phi)*(1+suma_beta(j)))+suma_beta_r(j)))
    elif j>=k and j!=J:
        return (p()+suma_p(j)+(1+r)*a(j-1,e))/((1+t_c)*(1+suma_beta_r(j)))
    elif j==J:
        return (p()+(1+r)*a(J-1,e))/(1+t_c)
    else:
        return "mistake"

def a(j,e):
    if j==1:
        return float((1-t_l)*(1-t_)*ind_w(j,e)+miu-(1+t_c)*(1+phi)*c(1,e))
    elif j<k and j>1:
        return float((1-t_l)*(1-t_)*ind_w(j,e)+miu-(1+t_c)*(1+phi)*c(j,e)+(1+r)*a(j-1,e))
    elif j>=k and j!=J:
        return float(p()-(1+t_c)*(1+phi)*c(j,e)+(1+r)*a(j-1,e))
    elif j==J:
        return 0

while (iter<10):

    r = alph*(Kold**(alph-1))-delta
    #print("r,", r)
    w = (1-alph)*Kold**alph
    print("w,", w)
    Knew=0
    Knew_numerator=0
    knew_denominator=0
    for j in range(1,J+1):
        for e in range(1,10):

            p()

            c(j,e)

            a(j,e)
            Knew_numerator+=(N(j,e)*a(j,e))

    for j in range (1,k):
        for e in range(1,10):
         knew_denominator+= (ind_w(j,e)/w)*l(j,e)*N(j,e)

    Knew+=Knew_numerator/knew_denominator
```

Over all, I need to count sum of N(j,e)*a(j,e) for j in range 1-60 and e in range 1-9.

I tried to transform it into numpy arrays but without success. I was able to make array which stores c function regarding j and e values, but it did not improve computing time.

Body:
I am studying economics and in order to learn Python I chose to make an economic model in it. I solved the model numerically, computed it in to python. Unfortunately the computation takes way too much time. Can you give me some tips how to improve it?

At first, I transformed dictionary set of data into numpy array, but it did not improve the process much. Normally, the higher value of j appear, more time it takes to count next value. What would u recommend?

Here are the most important parts of the code (without numbers)

def c(j,e):
    if j == 1 :
        return ((1+t_l)*(1-t_)*(ind_w(j,e)+suma_ind_w(j,e))+suma_p(j)+miu+suma_miu(j))/((1+t_c)*(((1+phi)*(1+suma_beta(j)))+suma_beta_r(j)))
    elif j < k and j!=1 :
        return ((1+t_l)*(1-t_)*(ind_w(j,e)+suma_ind_w(j,e))+suma_p(j)+miu+suma_miu(j)+(1+r)*a(j-1, e))/((1+t_c)*(((1+phi)*(1+suma_beta(j)))+suma_beta_r(j)))
    elif j>=k and j!=J:
        return (p()+suma_p(j)+(1+r)*a(j-1,e))/((1+t_c)*(1+suma_beta_r(j)))
    elif j==J:
        return (p()+(1+r)*a(J-1,e))/(1+t_c)
    else:
        return "mistake"

def a(j,e):
    if j==1:
        return float((1-t_l)*(1-t_)*ind_w(j,e)+miu-(1+t_c)*(1+phi)*c(1,e))
    elif j<k and j>1:
        return float((1-t_l)*(1-t_)*ind_w(j,e)+miu-(1+t_c)*(1+phi)*c(j,e)+(1+r)*a(j-1,e))
    elif j>=k and j!=J:
        return float(p()-(1+t_c)*(1+phi)*c(j,e)+(1+r)*a(j-1,e))
    elif j==J:
        return 0

while (iter<10):

    r = alph*(Kold**(alph-1))-delta
    #print("r,", r)
    w = (1-alph)*Kold**alph
    print("w,", w)
    Knew=0
    Knew_numerator=0
    knew_denominator=0
    for j in range(1,J+1):
        for e in range(1,10):

            p()

            c(j,e)

            a(j,e)
            Knew_numerator+=(N(j,e)*a(j,e))

    for j in range (1,k):
        for e in range(1,10):
         knew_denominator+= (ind_w(j,e)/w)*l(j,e)*N(j,e)

    Knew+=Knew_numerator/knew_denominator

Over all, I need to count sum of N(j,e)*a(j,e) for j in range 1-60 and e in range 1-9.

I tried to transform it into numpy arrays but without success. I was able to make array which stores c function regarding j and e values, but it did not improve computing time.


问:
x many for loops - how to do that?
Basically I have a problem, which requires me to do x many for loops (for each number in a loop, x is different).

Maybe there's another way of doing this task, which I haven't figured out.

Here's what I need to do. I have these functions:

```<code>connections = {}

def arrow(x, y):
    if x not in connections.keys():
        connections[x] = [y]
    else:
        connections[x].append(y)

def draw(x):
    if 2 * x <= n:
        arrow(x, 2 * x)
        draw(2 * x)

    if (2 * x) + 1 <= n:
        arrow(x, (2 * x) + 1)
        draw((2 * x) + 1)
</code>```

For each key in connections I draw a line (arrow) to both values.

Task: I have a list of 1000 pairs [x, y] where y > x. And I need to figure out whether I can get from x to y only going downwards (with the flow of the arrow) using one or more arrows.

My approach was to iterate through every possible combination for example: connections[1] = [2, 3] so I "choose" 2 then 4 and so on. if the current position (number) is too big I try another combination for example 2 then 5 or 3 then 6. The problem is I don't know how many for loops I need to use for different [x, y] pairs. How do I do that?

Title: x many for loops - how to do that?

Body:
Basically I have a problem, which requires me to do x many for loops (for each number in a loop, x is different).

Maybe there's another way of doing this task, which I haven't figured out.

Here's what I need to do. I have these functions:

connections = {}

def arrow(x, y):
    if x not in connections.keys():
        connections[x] = [y]
    else:
        connections[x].append(y)

def draw(x):
    if 2 * x <= n:
        arrow(x, 2 * x)
        draw(2 * x)

    if (2 * x) + 1 <= n:
        arrow(x, (2 * x) + 1)
        draw((2 * x) + 1)

For each key in connections I draw a line (arrow) to both values.

Task: I have a list of 1000 pairs [x, y] where y > x. And I need to figure out whether I can get from x to y only going downwards (with the flow of the arrow) using one or more arrows.

My approach was to iterate through every possible combination for example: connections[1] = [2, 3] so I "choose" 2 then 4 and so on. if the current position (number) is too big I try another combination for example 2 then 5 or 3 then 6. The problem is I don't know how many for loops I need to use for different [x, y] pairs. How do I do that?


问:
Direct convert "mkv" to "wav" using python
How can I directly convert an "mkv" file to a "wav" file? It means that my goal is to extract the audio of a movie file using python. What is the process of this?

Can anybody help me with how I can do it?

My Python version is 3.10.8 and I guess it is possible with ffmpeg or moviepy. I have tried converting "mkv" to "mp4" and then extracting the audio as "wav", but I want to know is there any direct way to do this task?


问:
How do you create a clickable object in Java Swing?

how do you create a JButton with a particular shape? here I want the shape of a pen, ie I want it to be clickable only on the surface of the pen.
Thanks!


问:
Stepper next steps are not start from top - flutter
When I finish the first step and click the continue button, It opens the next step properly but, It does not start from the top. It starts from the bottom. The user has to scroll up to read.

This screenshot shows what happened clearly,

1st Screenshot - completed step 01 and press continue

2nd Screenshot - It shows the bottom of step 02.

My code here:

Stepper: int currentStep = 0;

```<code>Stepper(
            type: StepperType.horizontal,
            steps: getSteps(),
            currentStep: currentStep,
            onStepContinue: () {
              final isLastStep = currentStep == getSteps().length - 1;
              if (isLastStep) {
                print("completed");
              } else {
                setState(() {
                  currentStep += 1;
                });
              }
            },
            onStepCancel: () {
              setState(() {
                currentStep -= 1;
              });
            },
),
</code>```

getSteps:

```<code>List<Step> getSteps() => [
Step(
 isActive: currentStep >= 0, title: Text("step1"), content: Form1()),
Step(
 isActive: currentStep >= 1, title: Text("step2"), content: Form2()),
];
</code>```

Form1 and Form2 just return a lorem text.

Body:
When I finish the first step and click the continue button, It opens the next step properly but, It does not start from the top. It starts from the bottom. The user has to scroll up to read.

This screenshot shows what happened clearly,

1st Screenshot - completed step 01 and press continue

2nd Screenshot - It shows the bottom of step 02.

My code here:

Stepper: int currentStep = 0;

Stepper(
            type: StepperType.horizontal,
            steps: getSteps(),
            currentStep: currentStep,
            onStepContinue: () {
              final isLastStep = currentStep == getSteps().length - 1;
              if (isLastStep) {
                print("completed");
              } else {
                setState(() {
                  currentStep += 1;
                });
              }
            },
            onStepCancel: () {
              setState(() {
                currentStep -= 1;
              });
            },
),

getSteps:

List<Step> getSteps() => [
Step(
 isActive: currentStep >= 0, title: Text("step1"), content: Form1()),
Step(
 isActive: currentStep >= 1, title: Text("step2"), content: Form2()),
];

Form1 and Form2 just return a lorem text.


问:
How can I store data collected on a certain website into the local storage of another tab using a browserextension and typescript/javasccript?
I have been developing a browserextension to extract data of online shoppingcarts and then transfer that data to another site. In order to do that my boss wants me to store the data I extracted on the shop site, lets call it x, his website, lets call it y. How can I now send that data from x to y using a chrome/firefox extension.

I have tryed using chrome.storage, but it isn't working. I have the storage permission in the manifest and I am not getting any errors or anything else. Simply nothing is happening. I have also tryed using a callback to verify if it worked, but still nothing happens. Do I maybe have to use it in the background script in order for it to work? Or are there any other ways to access the local storage of other browser tabs? Thank you in advance.


问:
I get error on navigation from 2 different nested routes
Whenever I try to navigate from 2 different nested routes I get this error

Error

I am trying to logout from a portal
routing from (patient/dashboard) to (auth/login)
using the header component (shared module)

this is app-routing.module.ts
app-routing.module

patient.html

```<code><nz-layout>
  <app-header></app-header>
  <nz-content>
    <router-outlet></router-outlet>
  </nz-content>
  <app-footer></app-footer>
</nz-layout>
</code>```

header.html

```<code> <button mat-menu-item (click)="onLogout()">
     <mat-icon>logout</mat-icon>
     <span>Logout</span>
  </button>
</code>```

header.ts

```<code>  onLogout() {
    this.router.navigate(['/auth/login']);
  }
</code>```

Body:
Whenever I try to navigate from 2 different nested routes I get this error

Error

I am trying to logout from a portal
routing from (patient/dashboard) to (auth/login)
using the header component (shared module)

this is app-routing.module.ts
app-routing.module

patient.html

<nz-layout>
  <app-header></app-header>
  <nz-content>
    <router-outlet></router-outlet>
  </nz-content>
  <app-footer></app-footer>
</nz-layout>

header.html

 <button mat-menu-item (click)="onLogout()">
     <mat-icon>logout</mat-icon>
     Logout
  </button>

header.ts

  onLogout() {
    this.router.navigate(['/auth/login']);
  }


问:
UMAP plot string labels next to dots
```<code>mapper = umap.UMAP(n_neighbors=5, metric='hamming').fit(data.drop('pid',axis=1))
umap.plot.points(mapper,labels=np.array(clusters['leaves_color_list']))
</code>```

The result looks like this:

Instead of/In addition to colored dots, I'd like to plot the 'pid' labels (string). I need to see which dots correspond to which data.

Title: UMAP plot string labels next to dots

Body:
mapper = umap.UMAP(n_neighbors=5, metric='hamming').fit(data.drop('pid',axis=1))
umap.plot.points(mapper,labels=np.array(clusters['leaves_color_list']))

The result looks like this:

Instead of/In addition to colored dots, I'd like to plot the 'pid' labels (string). I need to see which dots correspond to which data.


问:
Trouble with the password hashing and salting
I'm trying to implement a login system for my web application, but I'm having trouble with the password hashing and salting. My current code is generating different hash values for the same password, and I'm not sure what I'm doing wrong. Can anyone help me troubleshoot this issue? Here is the relevant code:

```<code>
import hashlib
import random

def hash_password(password):
    salt = random.randint(0, 1000000)
    hashed_password = hashlib.sha256((password + str(salt)).encode()).hexdigest()
    return (hashed_password, salt)

password = 'password123'
hashed_password, salt = hash_password(password)
print(hashed_password)

</code>```

Any help would be greatly appreciated!

Body:
I'm trying to implement a login system for my web application, but I'm having trouble with the password hashing and salting. My current code is generating different hash values for the same password, and I'm not sure what I'm doing wrong. Can anyone help me troubleshoot this issue? Here is the relevant code:

import hashlib
import random

def hash_password(password):
    salt = random.randint(0, 1000000)
    hashed_password = hashlib.sha256((password + str(salt)).encode()).hexdigest()
    return (hashed_password, salt)

password = 'password123'
hashed_password, salt = hash_password(password)
print(hashed_password)

Any help would be greatly appreciated!


问:
How can I "print" text in Javascript while pausing the script
I want to "print" / "echo" text in javascript while pausing the script between.
Currently my script works but it prints all at the same time .

Sorry I am not familiar with Javascript

```<code><script>
function wait(ms)
{
    var d = new Date();
    var d2 = null;
    do { d2 = new Date(); }
    while(d2-d < ms);
}
wait(1000);
document.write('hello');
wait(1000);
document.write(' how are you?');
</script>
</code>```


问:
Javascript: How to solve sending message from background to HTML script.js file?
I am having some trouble with my small project. Currently I listen for firebase updates in my background.js file. And when an update is detected I send a message to my HTML script file to add a new html element to the popup. So far this works, just fine, with one exception.

How the DB works is when the user click on a tab, the URL is stored in the DB with a user typed message as its child. What i am then actually listeing for is if a new child has been added.
Background.js file

```<code>function checkLivechat() {
  try {
    firebase
      .database()
      .ref(`livechat/${encodeUrlToBase64(lastUrl)}/messages`)
      .on("child_added", function (snapshot) {
        console.log("retrieve  messages now");
        try {
          var html = "";
          html += "<li>";
          html += snapshot.val().time + " ~ " + snapshot.val().message;
          html += "</li>";

          chrome.runtime.sendMessage({ message: "retrieveChat", data: html });
        } catch (e) {
          console.log(e);
        }
      });
  } catch (e) {
    console.log(e);
  }
}
</code>```

HTML script:

```<code>chrome.runtime.onMessage.addListener(function (request, sender) {
  if (request.message === "retrieveChat") {
    try {
      document.getElementById("messages").innerHTML += request.data;
    } catch (e) {
      console.log(e);
    }

    // sendResponse({ farewell: "Hello, Background!" });
  }
});
</code>```

Now the problem is, when i reload the extension (not the page) and navigate to a tab, which URL is already stored in the database, i get this annoying error:

Uncaught (in promise) Error: Could not establish connection. Receiving
end does not exist.

I think the problem is that the background file is executed before the HTML script, and when it tries to send a message to the HTML script it fails, because is hasn’t loaded yet.

Not sure if this is relatefd to this issue, but i also get this warning:

Event handler of 'message' event must be added on the initial
evaluation of worker script.

Not sure if this is the actual reason. Any ideas on how to solve this?

Body:
I am having some trouble with my small project. Currently I listen for firebase updates in my background.js file. And when an update is detected I send a message to my HTML script file to add a new html element to the popup. So far this works, just fine, with one exception.

How the DB works is when the user click on a tab, the URL is stored in the DB with a user typed message as its child. What i am then actually listeing for is if a new child has been added.
Background.js file

function checkLivechat() {
  try {
    firebase
      .database()
      .ref(`livechat/${encodeUrlToBase64(lastUrl)}/messages`)
      .on("child_added", function (snapshot) {
        console.log("retrieve  messages now");
        try {
          var html = "";
          html += "
";
          html += snapshot.val().time + " ~ " + snapshot.val().message;
          html += "
";

          chrome.runtime.sendMessage({ message: "retrieveChat", data: html });
        } catch (e) {
          console.log(e);
        }
      });
  } catch (e) {
    console.log(e);
  }
}

HTML script:

chrome.runtime.onMessage.addListener(function (request, sender) {
  if (request.message === "retrieveChat") {
    try {
      document.getElementById("messages").innerHTML += request.data;
    } catch (e) {
      console.log(e);
    }

    // sendResponse({ farewell: "Hello, Background!" });
  }
});

Now the problem is, when i reload the extension (not the page) and navigate to a tab, which URL is already stored in the database, i get this annoying error:

Uncaught (in promise) Error: Could not establish connection. Receiving
end does not exist.

I think the problem is that the background file is executed before the HTML script, and when it tries to send a message to the HTML script it fails, because is hasn’t loaded yet.

Not sure if this is relatefd to this issue, but i also get this warning:

Event handler of 'message' event must be added on the initial
evaluation of worker script.

Not sure if this is the actual reason. Any ideas on how to solve this?


问:
Adding Hint to @OneToXXX and @ManyToXXX
Is there a way to add a default @NamedEntityGraph to a @OneToXXX or @ManyToXXX relation?

I have the following entities:

```<code>@Entity
@NamedEntityGraph(name = "bar.baz", attributeNodes = {@NamedAttributeNode("baz")})
public class Bar {
    @Id
    @GeneratedValue
    private Long id;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "baz_id", referencedColumnName = "id")
    private Baz baz;

    public Baz getBaz() {
        return baz;
    }

    public void setBaz(Baz baz) {
        this.baz = baz;
    }
}

@Entity
public class Baz {

    @Id
    @GeneratedValue
    private Long id;

    private String baz = UUID.randomUUID().toString();

    public Long getId() {
        return id;
    }

    public String getBaz() {
        return baz;
    }
}

@Entity
public class Foo {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "foo_id")
    private List<Bar> bars = new ArrayList<>();

    public List<Bar> getBars() {
        return bars;
    }
}
</code>```

I'm accessing them in the following manner.

```<code>@Service
public static class MyService {
    @Autowired
    private EntityManager entityManager;

    @Transactional
    public void persist() {
        Foo foo = new Foo();
        for (int i = 0; i < 20; i++) {
            Bar bar = new Bar();
            bar.setBaz(new Baz());
            foo.getBars().add(bar);
        }
        entityManager.persist(foo);
    }

    @Transactional
    public void load() {
        entityManager.createQuery("from Bar", Bar.class)
                .setHint("javax.persistence.fetchgraph", entityManager.getEntityGraph("bar.baz"))
                .getResultList();
        String bazs = entityManager.createQuery("from Foo", Foo.class).getResultStream()
                .flatMap(foo -> foo.getBars().stream())
                .map(Bar::getBaz)
                .map(Baz::getBaz)
                .collect(Collectors.joining(", "));
        LOG.info(bazs);
    }
}
</code>```

Is there a way to make the fetching to happen implicitly without me having to call it? In the real  world there are many other Entities accessing Baz, but I only want it to be explicitly fetched when it's accessed via the Foo.bar relation (it has certain prior knowledge, like Foo being of some particular type which always needs the Baz-Entity).

Title: Adding Hint to @OneToXXX and @ManyToXXX

Body:
Is there a way to add a default @NamedEntityGraph to a @OneToXXX or @ManyToXXX relation?

I have the following entities:

@Entity
@NamedEntityGraph(name = "bar.baz", attributeNodes = {@NamedAttributeNode("baz")})
public class Bar {
    @Id
    @GeneratedValue
    private Long id;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "baz_id", referencedColumnName = "id")
    private Baz baz;

    public Baz getBaz() {
        return baz;
    }

    public void setBaz(Baz baz) {
        this.baz = baz;
    }
}

@Entity
public class Baz {

    @Id
    @GeneratedValue
    private Long id;

    private String baz = UUID.randomUUID().toString();

    public Long getId() {
        return id;
    }

    public String getBaz() {
        return baz;
    }
}

@Entity
public class Foo {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "foo_id")
    private List<Bar> bars = new ArrayList<>();

    public List<Bar> getBars() {
        return bars;
    }
}

I'm accessing them in the following manner.

@Service
public static class MyService {
    @Autowired
    private EntityManager entityManager;

    @Transactional
    public void persist() {
        Foo foo = new Foo();
        for (int i = 0; i < 20; i++) {
            Bar bar = new Bar();
            bar.setBaz(new Baz());
            foo.getBars().add(bar);
        }
        entityManager.persist(foo);
    }

    @Transactional
    public void load() {
        entityManager.createQuery("from Bar", Bar.class)
                .setHint("javax.persistence.fetchgraph", entityManager.getEntityGraph("bar.baz"))
                .getResultList();
        String bazs = entityManager.createQuery("from Foo", Foo.class).getResultStream()
                .flatMap(foo -> foo.getBars().stream())
                .map(Bar::getBaz)
                .map(Baz::getBaz)
                .collect(Collectors.joining(", "));
        LOG.info(bazs);
    }
}

Is there a way to make the fetching to happen implicitly without me having to call it? In the real  world there are many other Entities accessing Baz, but I only want it to be explicitly fetched when it's accessed via the Foo.bar relation (it has certain prior knowledge, like Foo being of some particular type which always needs the Baz-Entity).


问:
configure my TURN server for client whose firewall blocks UDP traffic
I have a client who sits behind a firewall that blocks UDP traffic and only allows  port 443 for tcp. I need to configure my turn server so that it can bypass the firewall and a connection between server and client can be established. I tried setting up coturn server but it fails to overcome the issue. I think there is some issue with the turn server configuration that I'm using. Need help for this issue.
Turn server configuration that I'm using =>

listening-port=80

tls-listening-port=443

user=user:pass

listening-ip=<private_ip_ec2>

relay-ip=<private_ip_ec2>

external-ip=<public_ip_ec2>/<private_ip_ec2>

#enable verbose logging

verbose

realm=domain.com

server-name=a.domain.com

fingerprint

lt-cred-mech

#use real-valid certificate/privatekey files

cert=/etc/ssl/certificate.pem

pkey=/etc/ssl/private.key

log-file=/var/log/turnserver/turn.log

no-stdout-log
`

Need help in configuring turn server for the above issue.