问:
Baseline Profiles fail at profile generation with Shell.isSessionRooted
I am trying to integrate the newly introduced baseline profiles into our app. I am using the following simple snippet to generate a baseline profile.

@RunWith(AndroidJUnit4::class)
class BaseProfileGenerator {

    @get:Rule
    val baselineProfile = BaselineProfileRule()

    @Test
    fun appStartup() {
        baselineProfile.collectBaselineProfile(packageName = InstrumentationRegistry.getInstrumentation().context.packageName) {
        pressHome()
        startActivityAndWait()
     }
   }
}
```
<p>However, on running the test on a gradle managed device/emulator, I am getting the following exception:</p>
<pre class="lang-java prettyprint-override"><code>java.lang.ExceptionInInitializerError
    at androidx.benchmark.Shell.isSessionRooted(Shell.kt:165)
    at androidx.benchmark.macro.BaselineProfilesKt$collectBaselineProfile$killProcessBlock$1.invoke(BaselineProfiles.kt:64)
    at androidx.benchmark.macro.BaselineProfilesKt$collectBaselineProfile$killProcessBlock$1.invoke(BaselineProfiles.kt:60)
    at androidx.benchmark.macro.BaselineProfilesKt.collectBaselineProfile(BaselineProfiles.kt:69)
    at androidx.benchmark.macro.junit4.BaselineProfileRule.collectBaselineProfile(BaselineProfileRule.kt:94)
    at androidx.benchmark.macro.junit4.BaselineProfileRule.collectBaselineProfile$default(BaselineProfileRule.kt:88)
    at com.package.name.baselineprofile.BaseProfileGenerator.appStartup(BaseProfileGenerator.kt:28)
    ... 36 trimmed
Caused by: java.io.IOException: Operation not permitted
    at java.io.UnixFileSystem.createFileExclusively0(Native Method)
    at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
    at java.io.File.createTempFile(File.java:2007)
    at androidx.benchmark.ShellImpl.createShellScript(Shell.kt:507)
    at androidx.benchmark.ShellImpl.<clinit>(Shell.kt:471)
    ... 44 more
</code>```

According the the docs, it was stated that we need a userdebug/rooted device in order to generate the profile and I was under the impression gradle managed devices with aosp system image will satisfy that need.

For reference, here's the device in my build.gradle.kts:

managedDevices {
    devices {
        add(
            ManagedVirtualDevice("pixel2Api31").apply {
                device = "Pixel 2"
                apiLevel = 31
                systemImageSource = "aosp"
            }
        )
    }
}
```

Android Gradle Plugin = v7.3.1 macroBenchmarVersion = v1.2.0-alpha07 profileInstallerVersion = 1.3.0-alpha01

Any idea what might be happening here? I searched around but couldn't find anything relevant.

I tried updating the dependencies to the latest alpha versions since apparently according to the release notes, baseline profiles no longer need rooted devices but even then its failing with the same exception.

Body:
I am trying to integrate the newly introduced baseline profiles into our app. I am using the following simple snippet to generate a baseline profile.

@RunWith(AndroidJUnit4::class)
class BaseProfileGenerator {

    @get:Rule
    val baselineProfile = BaselineProfileRule()

    @Test
    fun appStartup() {
        baselineProfile.collectBaselineProfile(packageName = InstrumentationRegistry.getInstrumentation().context.packageName) {
        pressHome()
        startActivityAndWait()
     }
   }
}

However, on running the test on a gradle managed device/emulator, I am getting the following exception:

java.lang.ExceptionInInitializerError
    at androidx.benchmark.Shell.isSessionRooted(Shell.kt:165)
    at androidx.benchmark.macro.BaselineProfilesKt$collectBaselineProfile$killProcessBlock$1.invoke(BaselineProfiles.kt:64)
    at androidx.benchmark.macro.BaselineProfilesKt$collectBaselineProfile$killProcessBlock$1.invoke(BaselineProfiles.kt:60)
    at androidx.benchmark.macro.BaselineProfilesKt.collectBaselineProfile(BaselineProfiles.kt:69)
    at androidx.benchmark.macro.junit4.BaselineProfileRule.collectBaselineProfile(BaselineProfileRule.kt:94)
    at androidx.benchmark.macro.junit4.BaselineProfileRule.collectBaselineProfile$default(BaselineProfileRule.kt:88)
    at com.package.name.baselineprofile.BaseProfileGenerator.appStartup(BaseProfileGenerator.kt:28)
    ... 36 trimmed
Caused by: java.io.IOException: Operation not permitted
    at java.io.UnixFileSystem.createFileExclusively0(Native Method)
    at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
    at java.io.File.createTempFile(File.java:2007)
    at androidx.benchmark.ShellImpl.createShellScript(Shell.kt:507)
    at androidx.benchmark.ShellImpl.<clinit>(Shell.kt:471)
    ... 44 more

According the the docs, it was stated that we need a userdebug/rooted device in order to generate the profile and I was under the impression gradle managed devices with aosp system image will satisfy that need.

For reference, here's the device in my build.gradle.kts:

managedDevices {
    devices {
        add(
            ManagedVirtualDevice("pixel2Api31").apply {
                device = "Pixel 2"
                apiLevel = 31
                systemImageSource = "aosp"
            }
        )
    }
}

Android Gradle Plugin = v7.3.1 macroBenchmarVersion = v1.2.0-alpha07 profileInstallerVersion = 1.3.0-alpha01

Any idea what might be happening here? I searched around but couldn't find anything relevant.

I tried updating the dependencies to the latest alpha versions since apparently according to the release notes, baseline profiles no longer need rooted devices but even then its failing with the same exception.


来源: stackexchange

问:
Python - using And/OR for condition
I have a script where I'm asking it to look for a phrase which is along the lines of:

```<code>if "1" in response and "2" in response and "(" + age + ")" in response:
</code>```

but I need it to do something like this:

```<code>if "1" in response and "2" in response and ( ("(" + age + ")") or ("[" + age + "]")  in response:
</code>```

to account for the symbol being either ( or [ around age - it then passes the verification and moves to the next step. Right now I'm missing anything with a [ bracket.

I tried it a long these lines but couldn't figure these expressions out.

ContentLicense: CC BY-SA 4.0

Title: Python - using And/OR for condition

Body:
I have a script where I'm asking it to look for a phrase which is along the lines of:

if "1" in response and "2" in response and "(" + age + ")" in response:

but I need it to do something like this:

if "1" in response and "2" in response and ( ("(" + age + ")") or ("[" + age + "]")  in response:

to account for the symbol being either ( or [ around age - it then passes the verification and moves to the next step. Right now I'm missing anything with a [ bracket.

I tried it a long these lines but couldn't figure these expressions out.


问:
Safe a in excel created word doc at a different path
I have a problem saving a Word document created by VBA to another location.
I wrote a code in the module of the Excel file and its working fine, but now I want to switch the save of the macro in my personal module. Neither does the data get filled in nor does the Word doc get saved at the right place.

This is my Code (with Explanation in German :D ):

```<code>Sub ExportToWordEngineering()

'Biblothek aktivieren

Dim wordapp As New Word.Application
Dim doc As Word.Document
Dim Zeile As Long

Zeile = ActiveCell.Row

'Word sichtbar machen
wordapp.Visible = True

'Word-Datei öffnen
Set doc = wordapp.Documents.Open("J:\I\Vollmachten\Template_Engineering_Muster.docx")

'word-Datei mit Excel-Daten befüllen
doc.Bookmarks("first_name").Range.Text = Tabelle1.Cells(Zeile, 2).Value
doc.Bookmarks("last_name").Range.Text = Tabelle1.Cells(Zeile, 1).Value

'Word-Datei abspeichern
doc.SaveAs2 ThisWorkbook.Path & "\Engineering_" & Tabelle1.Cells(Zeile, 2).Value & "_" & Tabelle1.Cells(Zeile, 1).Value & "_" & Tabelle1.Cells(Zeile, 9).Value & ".docx"

'Word-Datei schliesßen
doc.Close SaveChanges:=False

'Word-Datei schließen
wordapp.Quit

End Sub
</code>```

Body:
I have a problem saving a Word document created by VBA to another location.
I wrote a code in the module of the Excel file and its working fine, but now I want to switch the save of the macro in my personal module. Neither does the data get filled in nor does the Word doc get saved at the right place.

This is my Code (with Explanation in German :D ):

Sub ExportToWordEngineering()

'Biblothek aktivieren

Dim wordapp As New Word.Application
Dim doc As Word.Document
Dim Zeile As Long

Zeile = ActiveCell.Row

'Word sichtbar machen
wordapp.Visible = True

'Word-Datei öffnen
Set doc = wordapp.Documents.Open("J:\I\Vollmachten\Template_Engineering_Muster.docx")

'word-Datei mit Excel-Daten befüllen
doc.Bookmarks("first_name").Range.Text = Tabelle1.Cells(Zeile, 2).Value
doc.Bookmarks("last_name").Range.Text = Tabelle1.Cells(Zeile, 1).Value

'Word-Datei abspeichern
doc.SaveAs2 ThisWorkbook.Path & "\Engineering_" & Tabelle1.Cells(Zeile, 2).Value & "_" & Tabelle1.Cells(Zeile, 1).Value & "_" & Tabelle1.Cells(Zeile, 9).Value & ".docx"

'Word-Datei schliesßen
doc.Close SaveChanges:=False

'Word-Datei schließen
wordapp.Quit

End Sub


问:
Write access for non root users on file store using Kubernetes in GCP
How to setup Kubernetes so that non root user can write inside the file store in GCP.

I tried below configuration in yaml file but still non root user is not able to write.

```<code>securityContext:
    runAsUser: 1000
    runAsGroup: 1000
    fsGroup: 1000
</code>```

Body:
How to setup Kubernetes so that non root user can write inside the file store in GCP.

I tried below configuration in yaml file but still non root user is not able to write.

securityContext:
    runAsUser: 1000
    runAsGroup: 1000
    fsGroup: 1000


问:
Does calling setInterval outside of a vue component cause the object to become non-reactive?
I'm currently working on a web game in Vue where I want to be calling my update function every 0.02 seconds. I have a Game class in typescript with the following methods:

```<code>start() {
    this.gameLoop = setInterval(() => {this.update()}, 0.02)
}

update() {
    this.resource += 1
}
</code>```

However, whenever I try to reference the resource field of the Game class in a Vue component, it doesn't update reactively. Here's the script:

```<code>export default defineComponent({
    data() {
        return {
            resource: App.game.resource,
        }
    },
})
</code>```

The template:

```<code><template>
    <p>{{ resource }}</p>
</template>
</code>```

And the static App class that allows App.game to be referenced from anywhere:

```<code>export class App {
    static game: Game = new Game() as Game

    static start(): void {
        this.game = reactive(new Game())
        this.game.start()
    }
}
</code>```

And main.ts which starts the whole thing:

```<code>declare global {
    interface Window {
        App: App,
    }
}

window.onload = function () {
    App.start()
    window.App = App
    createApp(VueApp).mount('#app')
}
</code>```

I've verified that the value is actually changing in the console, but the rerender doesn't occur. I'm imagining this has something to do with the fact that this setInterval might be changing things through the window, which isn't known about by Vue, but how would I reference this more properly?

Body:
I'm currently working on a web game in Vue where I want to be calling my update function every 0.02 seconds. I have a Game class in typescript with the following methods:

start() {
    this.gameLoop = setInterval(() => {this.update()}, 0.02)
}

update() {
    this.resource += 1
}

However, whenever I try to reference the resource field of the Game class in a Vue component, it doesn't update reactively. Here's the script:

export default defineComponent({
    data() {
        return {
            resource: App.game.resource,
        }
    },
})

The template:

<template>

{{ resource }}

</template>

And the static App class that allows App.game to be referenced from anywhere:

export class App {
    static game: Game = new Game() as Game

    static start(): void {
        this.game = reactive(new Game())
        this.game.start()
    }
}

And main.ts which starts the whole thing:

declare global {
    interface Window {
        App: App,
    }
}

window.onload = function () {
    App.start()
    window.App = App
    createApp(VueApp).mount('#app')
}

I've verified that the value is actually changing in the console, but the rerender doesn't occur. I'm imagining this has something to do with the fact that this setInterval might be changing things through the window, which isn't known about by Vue, but how would I reference this more properly?


问:
triggering a cli command via a restful api
I have a cli command, that is supposed to create a schema and run migration migrations on a database for an application. Due to new requirements, I'm having to run migrations via an api, and this api happens to be the same api for the application. I'd like to know if it is a good pattern, or practise to invoke cli commands via a RESTful Api in such a way? What should my concerns be regarding the api and application at hand?</p>


问:
The v-model does not seems to be updating
I'm fairly new to vue so I'm sure this is just a dumb mistake on my part...

I am using vue 3 with vue-class-component and typescript.

I have a component that is essentially a wrapper for a <textarea>. It will eventually be a lightweight code editing component but for now, I'm just adding a "copy" button to it. Here is the relevant code:

ToolTextArea.vue

<template>

    {{ label }}

        <button @click="copy" class="copy-button">copy</button>

        <textarea
          autocapitalize="false"
          autocomplete="false"
          spellcheck="false"
          :class="cssClasses"
          :id="id"
          data-gramm="false"
          data-gramm_editor="false"
          data-enable-grammarly="false"
          :value="value"
          @input="handleChange"
          @keydown="handleKeydownEvent"
        ></textarea>

</template>
```
<p><em>ToolTextarea.ts</em></p>
<pre class="lang-js prettyprint-override"><code>import { Options, Vue, prop } from "vue-class-component";

...

class Props {
  label = prop<string>({ type: String, required: true });
  id = prop<string>({ type: String, required: true });
  value = prop<string>({ type: String, required: false, default: "" });
  textareaCssClass = prop<string>({
    type: String,
    required: false,
    default: "",
  });
  showCopyButton = prop<boolean>({
    type: Boolean,
    required: false,
    default: true,
  });
}

@Options({})
export default class ToolTextarea extends Vue.with(Props) {

...

handleChange(event: Event) {
  if (
      event &&
      event.target &&
      event.target instanceof HTMLTextAreaElement &&
      event.target.value
    ) {
      this.$emit("update:modelValue", event.target.value);
    }
  }

...

}
</code>```

I then put a few of these components on another component. The point here is to create a UI for URL encoding/Decoding, but that's the important part. Here is the relevant code for that component:

UrlEncoding.vue

<template>

...

  <ToolTextarea
    id="input"
    label="Unencoded"
    :value="input"
    textareaCssClass="tall"
    @update:modelValue="handleInputUpdate"
  />

...

  <button @click="encode">

    Encode
  </button>
  <button @click="decode">

    Decode
  </button>

...

  <ToolTextarea
    id="output"
    label="Encoded"
    :value="output"
    textareaCssClass="tall"
    @update:modelValue="handleOutputUpdate"
  />

</template>
```
<p><em>UrlEncodung.tx</em></p>
<pre class="lang-js prettyprint-override"><code>import { Options, Vue } from "vue-class-component";
import ToolTextarea from "../ToolTextarea/ToolTextarea.vue";

@Options({
  components: {
    ToolTextarea,
  },
})
export default class UrlEncoding extends Vue {
  input = "";
  output = "";

...

  handleInputUpdate(event: string) {
    this.input = event;
  }

  handleOutputUpdate(event: string) {
    this.output = event;
  }

...

  encode() {
    console.log("this.input", this.input);
    console.log("this.output", this.output);
    let encoded = this.urlComponent
      ? encodeURIComponent(this.input)
      : encodeURI(this.input);

    ...

    this.output = encoded;
  }

  decode() {
    console.log("this.input", this.input);
    console.log("this.output", this.output);
    let decoded = this.urlComponent
      ? decodeURIComponent(this.output)
      : decodeURI(this.output);

    ...

    this.input = decoded;
  }
}
</code>```

Ok, now that all the code is out there, here's the actual issue I am having.

When I type a value in the input (Unencoded) field and click the "Encode" button, the code runs as expected and the url encoded value is displayed in the output (Encoded) field. Great!

However, if I delete the content from the input field, and click the "Decode" button, I would expect the decoded value to be displayed in the input field, but it does not.

If I were to modify the output field in some way, say, ad a space to the end, then click the decode button, it works just fine.

I guess I just don't understand the model state in vue very well. This is going to be a super lightweight app and I don't want to use a heavy state manager. I also want to keep this as close to native JS as possible.

Thanks in advance for any help with this.

Body:
I'm fairly new to vue so I'm sure this is just a dumb mistake on my part...

I am using vue 3 with vue-class-component and typescript.

I have a component that is essentially a wrapper for a <textarea>. It will eventually be a lightweight code editing component but for now, I'm just adding a "copy" button to it. Here is the relevant code:

ToolTextArea.vue

<template>

    {{ label }}

        <button @click="copy" class="copy-button">copy</button>

        <textarea
          autocapitalize="false"
          autocomplete="false"
          spellcheck="false"
          :class="cssClasses"
          :id="id"
          data-gramm="false"
          data-gramm_editor="false"
          data-enable-grammarly="false"
          :value="value"
          @input="handleChange"
          @keydown="handleKeydownEvent"
        ></textarea>

</template>

ToolTextarea.ts

import { Options, Vue, prop } from "vue-class-component";

...

class Props {
  label = prop<string>({ type: String, required: true });
  id = prop<string>({ type: String, required: true });
  value = prop<string>({ type: String, required: false, default: "" });
  textareaCssClass = prop<string>({
    type: String,
    required: false,
    default: "",
  });
  showCopyButton = prop<boolean>({
    type: Boolean,
    required: false,
    default: true,
  });
}

@Options({})
export default class ToolTextarea extends Vue.with(Props) {

...

handleChange(event: Event) {
  if (
      event &&
      event.target &&
      event.target instanceof HTMLTextAreaElement &&
      event.target.value
    ) {
      this.$emit("update:modelValue", event.target.value);
    }
  }

...

}

I then put a few of these components on another component. The point here is to create a UI for URL encoding/Decoding, but that's the important part. Here is the relevant code for that component:

UrlEncoding.vue

<template>

...

  <ToolTextarea
    id="input"
    label="Unencoded"
    :value="input"
    textareaCssClass="tall"
    @update:modelValue="handleInputUpdate"
  />

...

  <button @click="encode">

    Encode
  </button>
  <button @click="decode">

    Decode
  </button>

...

  <ToolTextarea
    id="output"
    label="Encoded"
    :value="output"
    textareaCssClass="tall"
    @update:modelValue="handleOutputUpdate"
  />

</template>

UrlEncodung.tx

import { Options, Vue } from "vue-class-component";
import ToolTextarea from "../ToolTextarea/ToolTextarea.vue";

@Options({
  components: {
    ToolTextarea,
  },
})
export default class UrlEncoding extends Vue {
  input = "";
  output = "";

...

  handleInputUpdate(event: string) {
    this.input = event;
  }

  handleOutputUpdate(event: string) {
    this.output = event;
  }

...

  encode() {
    console.log("this.input", this.input);
    console.log("this.output", this.output);
    let encoded = this.urlComponent
      ? encodeURIComponent(this.input)
      : encodeURI(this.input);

    ...

    this.output = encoded;
  }

  decode() {
    console.log("this.input", this.input);
    console.log("this.output", this.output);
    let decoded = this.urlComponent
      ? decodeURIComponent(this.output)
      : decodeURI(this.output);

    ...

    this.input = decoded;
  }
}

Ok, now that all the code is out there, here's the actual issue I am having.

When I type a value in the input (Unencoded) field and click the "Encode" button, the code runs as expected and the url encoded value is displayed in the output (Encoded) field. Great!

However, if I delete the content from the input field, and click the "Decode" button, I would expect the decoded value to be displayed in the input field, but it does not.

If I were to modify the output field in some way, say, ad a space to the end, then click the decode button, it works just fine.

I guess I just don't understand the model state in vue very well. This is going to be a super lightweight app and I don't want to use a heavy state manager. I also want to keep this as close to native JS as possible.

Thanks in advance for any help with this.


问:
Add a slider for interactive binding in python - plotly
I try to add a slicer in my histogram. Something like this, but with the diference that I can determine the number of binds of the histogram.I work in Microsoft Azure - Databricks

Here, it is my code:

```<code>from pyspark.sql.functions import *
from pyspark.sql.functions import last
from pyspark.sql.functions import arrays_zip
from pyspark.sql.types import *
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
</code>```
```<code>data = [["1", "Amit", "DU", "I", "8", "6"],
        ["2", "Mohit", "DU", "I", "4", "2"],
        ["3", "rohith", "BHU", "I", "5", "3"],
        ["4", "sridevi", "LPU", "I", "1", "6"],
        ["1", "sravan", "KLMP", "M", "2", "4"],
        ["5", "gnanesh", "IIT", "M", "6", "8"],
        ["6", "gnadesh", "KLM", "c", "0", "9"]]

columns = ['ID', 'NAME', 'college', 'metric', 'x', 'y']

dataframe = spark.createDataFrame(data, columns)
dataframe = dataframe.withColumn("x",dataframe.x.cast(DoubleType()))
data = dataframe.toPandas()
</code>```
```<code>from plotly.offline import plot
import plotly.express as px

p = plot(
    px.histogram(data_frame = data,x='x',nbins=25, text_auto=True),
    output_type='div'
    )

displayHTML(p)
</code>```

Body:
I try to add a slicer in my histogram. Something like this, but with the diference that I can determine the number of binds of the histogram.I work in Microsoft Azure - Databricks

Here, it is my code:

from pyspark.sql.functions import *
from pyspark.sql.functions import last
from pyspark.sql.functions import arrays_zip
from pyspark.sql.types import *
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

data = [["1", "Amit", "DU", "I", "8", "6"],
        ["2", "Mohit", "DU", "I", "4", "2"],
        ["3", "rohith", "BHU", "I", "5", "3"],
        ["4", "sridevi", "LPU", "I", "1", "6"],
        ["1", "sravan", "KLMP", "M", "2", "4"],
        ["5", "gnanesh", "IIT", "M", "6", "8"],
        ["6", "gnadesh", "KLM", "c", "0", "9"]]

columns = ['ID', 'NAME', 'college', 'metric', 'x', 'y']

dataframe = spark.createDataFrame(data, columns)
dataframe = dataframe.withColumn("x",dataframe.x.cast(DoubleType()))
data = dataframe.toPandas()

from plotly.offline import plot
import plotly.express as px

p = plot(
    px.histogram(data_frame = data,x='x',nbins=25, text_auto=True),
    output_type='div'
    )

displayHTML(p)


问:
AWS quicksight filtering data from dataset using unique values from 2 columns
I want to show a table of customer details using AWS quicksight.

The customer details dataset is updated every hour.

I created a customer details table which shows

First name, 2. Last name, 3, age, 4. sales_revenue

I want to create a control that would filter the customer details based on the country they are from.
But the problem is there are two columns country1, country2 present in the actual dataset.
I want unique values out of both the columns, and use that list in the control, so that the records would be listed if either country1 or country2 is present in the row. Is there any workaround for this approach?

I checked the parameters passed and the way the controls are mapped with the parameters but that did not help.


问:
Next 13 Jest test fails using 'next/headers'
I am using Next.JS 13, and have a component which is using

import { cookies } from 'next/headers';
```
<p>The simplified component:</p>
<pre class="lang-js prettyprint-override"><code>import { cookies } from 'next/headers';

function Simple() {
  console.log({ cookies });
  return <div>Simple</div>;
}

export default Simple;
</code>```

and the simplified test:

import { render } from '@testing-library/react';

import Simple from './Simple';

describe('<Simple />', () => {
  it('should render Simple component', () => {
    render(<Simple />);
  });
});
```
<p>When I have any reference to the <code>cookies</code>, in this case</p>
<pre class="lang-js prettyprint-override"><code>  console.log({ cookies });
</code>```

I always get the following error when running jest tests:

```<code>     x NEXT_RSC_ERR_CLIENT_IMPORT: next/headers
       ,-[1:1]
     1 | import { cookies } from 'next/headers';
       : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     2 |
     3 | function Simple() {
     4 |   console.log({ cookies });
</code>```

Any ideas how to fix it?

I have tried mocking the 'next/headers' with jest.mock, like so, but to no avail:

jest.mock('next/headers', () => ({
  cookies: jest.fn(),
}));
```
<p>My <code>jest.config.js</code></p>
<pre class="lang-js prettyprint-override"><code>const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

const customJestConfig = {
  setupFilesAfterEnv: ['./.jest/setup.js'],
  testEnvironment: 'jest-environment-jsdom',
};

module.exports = async () => ({
  ...(await createJestConfig(customJestConfig)()),
});
</code>```

My ./jest/setup.js

require('jest-fetch-mock').enableMocks();

import '@testing-library/jest-dom';
```
<p>Package versions</p>
<pre class="lang-json prettyprint-override"><code>    "next": "13.1.0",
    "jest": "^29.3.1",
    "jest-environment-jsdom": "^29.3.1",
    "jest-fetch-mock": "^3.0.3",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
</code>```

Body:
I am using Next.JS 13, and have a component which is using

import { cookies } from 'next/headers';

The simplified component:

import { cookies } from 'next/headers';

function Simple() {
  console.log({ cookies });
  return
Simple
;
}

export default Simple;

and the simplified test:

import { render } from '@testing-library/react';

import Simple from './Simple';

describe('<Simple />', () => {
  it('should render Simple component', () => {
    render(<Simple />);
  });
});

When I have any reference to the cookies, in this case

  console.log({ cookies });

I always get the following error when running jest tests:

     x NEXT_RSC_ERR_CLIENT_IMPORT: next/headers
       ,-[1:1]
     1 | import { cookies } from 'next/headers';
       : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     2 |
     3 | function Simple() {
     4 |   console.log({ cookies });

Any ideas how to fix it?

I have tried mocking the 'next/headers' with jest.mock, like so, but to no avail:

jest.mock('next/headers', () => ({
  cookies: jest.fn(),
}));

My jest.config.js

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

const customJestConfig = {
  setupFilesAfterEnv: ['./.jest/setup.js'],
  testEnvironment: 'jest-environment-jsdom',
};

module.exports = async () => ({
  ...(await createJestConfig(customJestConfig)()),
});

My ./jest/setup.js

require('jest-fetch-mock').enableMocks();

import '@testing-library/jest-dom';

Package versions

    "next": "13.1.0",
    "jest": "^29.3.1",
    "jest-environment-jsdom": "^29.3.1",
    "jest-fetch-mock": "^3.0.3",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",


问:
Using LDR assembly instruction for ARM v7 on Keil Uvision
I am trying to write a simple program to find the largest integer in an array. I actually got this code from a textbook so it's not my own, but anyways when I simulate it in keil simulator it doesn't run as expected. I don't think the problem is in the code itself, but here it is:

`

```<code>        AREA myData,DATA
        ALIGN
array   DCD -1,5,3,8,10,23,6,5,2,-10
size    DCD 10

        AREA findmax,CODE
        EXPORT __main
        ALIGN
        ENTRY

__main  PROC

        ;Identify array size
        LDR r6, =size
        LDR r6,[r6]
        SUB r6,r6,#1

        ;Initialize maxvalue and maxlocation
        LDR r7,=array
        LDR r3,[r7]     ;Default max
        MOV r4,#0       ;Max location

        ;loop function
        MOV r5,#0       ;Loop index
loop    CMP r5,r6
        BGE stop
        LDR r8, [r7, r5, LSL#2]     ;Load r8 with array[i]
        CMP r8,r3
        MOVGT r3,r8     ;Update max value if array(i)>max. Conditionally executed instruction
        MOVGT r4,r5     ;Update max location. Conditionally executed instruction
        ADD r5,r5,#1
        B   loop

stop    B   stop

        ENDP
        END

</code>```

`

<s>
 I am looking in the debugger and it seems the problem is this line of code:

LDR r6,[r6]

is read as

LDR r6,[0x00]

as you can see here
</s>

It works if use 'MOV' instruction and type in the value myself but not with LDR.

What am I doing wrong?

As it has been pointed out in the comments I should verify the ldr, =size indeed loads the memory address, and I think it does (Honestly I'm not entirely sure how to view it but in the memory window that memory space has no value. The program still doesn't run properly. The program branches and stops at the first iteration of the loop because the size of the array stored in r6 is 0

Body:
I am trying to write a simple program to find the largest integer in an array. I actually got this code from a textbook so it's not my own, but anyways when I simulate it in keil simulator it doesn't run as expected. I don't think the problem is in the code itself, but here it is:

`

        AREA myData,DATA
        ALIGN
array   DCD -1,5,3,8,10,23,6,5,2,-10
size    DCD 10

        AREA findmax,CODE
        EXPORT __main
        ALIGN
        ENTRY

__main  PROC

        ;Identify array size
        LDR r6, =size
        LDR r6,[r6]
        SUB r6,r6,#1

        ;Initialize maxvalue and maxlocation
        LDR r7,=array
        LDR r3,[r7]     ;Default max
        MOV r4,#0       ;Max location

        ;loop function
        MOV r5,#0       ;Loop index
loop    CMP r5,r6
        BGE stop
        LDR r8, [r7, r5, LSL#2]     ;Load r8 with array[i]
        CMP r8,r3
        MOVGT r3,r8     ;Update max value if array(i)>max. Conditionally executed instruction
        MOVGT r4,r5     ;Update max location. Conditionally executed instruction
        ADD r5,r5,#1
        B   loop

stop    B   stop

        ENDP
        END

`

<s>
 I am looking in the debugger and it seems the problem is this line of code:

LDR r6,[r6]

is read as

LDR r6,[0x00]

as you can see here
</s>

It works if use 'MOV' instruction and type in the value myself but not with LDR.

What am I doing wrong?

As it has been pointed out in the comments I should verify the ldr, =size indeed loads the memory address, and I think it does (Honestly I'm not entirely sure how to view it but in the memory window that memory space has no value. The program still doesn't run properly. The program branches and stops at the first iteration of the loop because the size of the array stored in r6 is 0


问:
How to properly export template class in dll file
I'm trying to create a DLL file with the following code:
the header:

```<code>
#pragma once

#ifdef PRO_ONE
#define DLLFUNC _declspec(dllexport)
#else
#define DLLFUNC _declspec(dllimport)
#endif
#include <vector>
#include <string>

using namespace std;

template <class T>
class interAlgo {
public:
    virtual void summaryRanges(vector<int>& nums) = 0;
    virtual T getAlgoFirst() = 0;

};

template <class T>
class  firstSul : public interAlgo<T> {
private:
     T resultVec;
public:
     firstSul();
     void summaryRanges(vector<int>& nums);
     T getAlgoFirst();

};

template <class T>
extern "C" DLLFUNC  interAlgo<T>* _cdecl  CreateAlgoObject(); //issue is here!!!!!!!!!!!!!!!!

</code>```

cpp file:

```<code>#include "pch.h"
#include "progone.h"
#include <sstream>
#include <map>

template<class T>
firstSul<T>::firstSul()
{

}

template <class T>
void firstSul<T>::summaryRanges(vector<int>& nums) {
    this->resultVec.clear();
    const int n = nums.size();

    int i = 0;

    for (int j = 0; j < n; ++j) {
        string range = "";
        if (j + 1 == n || nums[j] + 1 != nums[j + 1]) {
            if (i == j) {
                range = to_string(nums[i]);
            }
            else {
                range = to_string(nums[i]) + "->" + to_string(nums[j]);
            }
           resultVec.push_back(range);
            i = j + 1;
        }
    }
}

template <class T>
T firstSul<T>::getAlgoFirst() {
    return this->resultVec;
}

template <class T>
interAlgo<T>* CreateAlgoObject() {
    return new firstSul<T>();
}
</code>```

the error's are:
E0335   linkage specification is not allowed
C2955   'interAlgo': use of class template requires template argument list

Why is this happening, and how can the problem be fixed?

Body:
I'm trying to create a DLL file with the following code:
the header:

#pragma once

#ifdef PRO_ONE
#define DLLFUNC _declspec(dllexport)
#else
#define DLLFUNC _declspec(dllimport)
#endif
#include <vector>
#include <string>

using namespace std;

template <class T>
class interAlgo {
public:
    virtual void summaryRanges(vector<int>& nums) = 0;
    virtual T getAlgoFirst() = 0;

};

template <class T>
class  firstSul : public interAlgo<T> {
private:
     T resultVec;
public:
     firstSul();
     void summaryRanges(vector<int>& nums);
     T getAlgoFirst();

};

template <class T>
extern "C" DLLFUNC  interAlgo<T>* _cdecl  CreateAlgoObject(); //issue is here!!!!!!!!!!!!!!!!

cpp file:

#include "pch.h"
#include "progone.h"
#include <sstream>
#include <map>

template<class T>
firstSul<T>::firstSul()
{

}

template <class T>
void firstSul<T>::summaryRanges(vector<int>& nums) {
    this->resultVec.clear();
    const int n = nums.size();

    int i = 0;

    for (int j = 0; j < n; ++j) {
        string range = "";
        if (j + 1 == n || nums[j] + 1 != nums[j + 1]) {
            if (i == j) {
                range = to_string(nums[i]);
            }
            else {
                range = to_string(nums[i]) + "->" + to_string(nums[j]);
            }
           resultVec.push_back(range);
            i = j + 1;
        }
    }
}

template <class T>
T firstSul<T>::getAlgoFirst() {
    return this->resultVec;
}

template <class T>
interAlgo<T>* CreateAlgoObject() {
    return new firstSul<T>();
}

the error's are:
E0335   linkage specification is not allowed
C2955   'interAlgo': use of class template requires template argument list

Why is this happening, and how can the problem be fixed?


问:
Vue CLI compiling vagmi library fails with 'Unexpected token'
I am having an issue compiling the vagmi Vue library in the Vue CLI. It works with Vite but when I try to use Vue CLI, which I have to use for his project, it errors:

```<code> INFO  Starting development server...
98% after emitting CopyPlugin

 ERROR  Failed to compile with 1 errors                                                                                8:44:29 PM

 error  in ./node_modules/vagmi/dist/index.mjs

Module parse failed: Unexpected token (149:31)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|       config = {
|         chainId: getMaybeRefValue(chainId2),
>         connector: connector_ ?? getMaybeRefValue(connector)
|       };
|     } else {

 @ ./src/main.js 38:0-50 40:13-25 44:57-68
 @ multi (webpack)-dev-server/client?http://192.168.0.228:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
</code>```

I do not know if it is an issue with my Vue CLI setup or a problem with the Vagmi library. I reported it  issue: https://github.com/wobsoriano/vagmi/issues/36 but I don't see anyone else having the problem.

Body:
I am having an issue compiling the vagmi Vue library in the Vue CLI. It works with Vite but when I try to use Vue CLI, which I have to use for his project, it errors:

 INFO  Starting development server...
98% after emitting CopyPlugin

 ERROR  Failed to compile with 1 errors                                                                                8:44:29 PM

 error  in ./node_modules/vagmi/dist/index.mjs

Module parse failed: Unexpected token (149:31)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|       config = {
|         chainId: getMaybeRefValue(chainId2),
>         connector: connector_ ?? getMaybeRefValue(connector)
|       };
|     } else {

 @ ./src/main.js 38:0-50 40:13-25 44:57-68
 @ multi (webpack)-dev-server/client?http://192.168.0.228:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

I do not know if it is an issue with my Vue CLI setup or a problem with the Vagmi library. I reported it  issue: https://github.com/wobsoriano/vagmi/issues/36 but I don't see anyone else having the problem.


问:
Combine certificate.pem file and encryptedPrivateKey into usable keystore or jks file
I was provided a certificate.pem file and a separate encryptedPrivateKey (no file extension) and I need to turn them into either a .keystore or .jks file to be able to bundle my app for the Google Play store. How would I go about combining those files?</p>


问:
How to access database docker image, stored in Azure Container Registry, from a pipeline?
I have created and executed a pipeline, which creates a MariaDB docker image, fills the data from another database dump in it, and pushes it into the Azure Container Registry. I see in the logs of the pipeline the following:

```<code>/usr/bin/docker push <some_registry_name>.azurecr.io/databasedump:7387
The push refers to repository [<some_registry_name>.azurecr.io/databasedump]
</code>```

and later:

```<code>createdBy:/bin/sh -c #(nop)  ENV MARIADB_DATABASE=smdb-dev1;
createdBy:/bin/sh -c #(nop)  ENV MARIADB_PASSWORD=<some_password>;
createdBy:/bin/sh -c #(nop)  ENV MARIADB_USER=<some_user>;
createdBy:/bin/sh -c #(nop)  ENV MARIADB_ROOT_PASSWORD=<some_password>;
createdBy:/bin/sh -c #(nop)  CMD ["mysqld"];
createdBy:/bin/sh -c #(nop)  EXPOSE 3306;
createdBy:/bin/sh -c #(nop)  ENTRYPOINT ["docker-entrypoint.sh"]; layerId:<missing>
createdBy:/bin/sh -c #(nop)  VOLUME [/var/lib/mysql]; layerId:<missing>

</code>```

But i want to use this docker image in some integration tests.
These tests are run into another Azure pipeline.
So i have to pull this docker image and to run it. But i do not find reliable information how to do this?
The script for running the tests in the azure-pipeline.yaml file is the following:

```<code>- script: |
      echo "VARIABLE_FILE: $VARIABLE_FILE"

      pdm run pytest \
        --variables "$VARIABLE_FILE" \
        --test-run-title="$TEST_TITLE" \
        --napoleon-docstrings \
        --doctest-modules \
        --color=yes \
        --junitxml=junit/test-results.xml \
        integration
    displayName: 'Tests'
    env:
      VARIABLE_FILE: "variables.${{ parameters.environment }}.json"
      TEST_TITLE: "C8Y-INTEGRATION-TEST-BE | ${{ parameters.environment }}: $(build.buildNumber)"
      DB_HOST: $(DB_HOST)
      DB_DATABASE_NAME: $(DB_DATABASE_NAME)
      DB_USER: $(DB_USER)
      DB_PASSWORD: $(DB_PASSWORD)
</code>```

Where the db stuff points to the docker image, which runs on the docker on my local machine.

Body:
I have created and executed a pipeline, which creates a MariaDB docker image, fills the data from another database dump in it, and pushes it into the Azure Container Registry. I see in the logs of the pipeline the following:

/usr/bin/docker push <some_registry_name>.azurecr.io/databasedump:7387
The push refers to repository [<some_registry_name>.azurecr.io/databasedump]

and later:

createdBy:/bin/sh -c #(nop)  ENV MARIADB_DATABASE=smdb-dev1;
createdBy:/bin/sh -c #(nop)  ENV MARIADB_PASSWORD=<some_password>;
createdBy:/bin/sh -c #(nop)  ENV MARIADB_USER=<some_user>;
createdBy:/bin/sh -c #(nop)  ENV MARIADB_ROOT_PASSWORD=<some_password>;
createdBy:/bin/sh -c #(nop)  CMD ["mysqld"];
createdBy:/bin/sh -c #(nop)  EXPOSE 3306;
createdBy:/bin/sh -c #(nop)  ENTRYPOINT ["docker-entrypoint.sh"]; layerId:<missing>
createdBy:/bin/sh -c #(nop)  VOLUME [/var/lib/mysql]; layerId:<missing>

But i want to use this docker image in some integration tests.
These tests are run into another Azure pipeline.
So i have to pull this docker image and to run it. But i do not find reliable information how to do this?
The script for running the tests in the azure-pipeline.yaml file is the following:

- script: |
      echo "VARIABLE_FILE: $VARIABLE_FILE"

      pdm run pytest \
        --variables "$VARIABLE_FILE" \
        --test-run-title="$TEST_TITLE" \
        --napoleon-docstrings \
        --doctest-modules \
        --color=yes \
        --junitxml=junit/test-results.xml \
        integration
    displayName: 'Tests'
    env:
      VARIABLE_FILE: "variables.${{ parameters.environment }}.json"
      TEST_TITLE: "C8Y-INTEGRATION-TEST-BE | ${{ parameters.environment }}: $(build.buildNumber)"
      DB_HOST: $(DB_HOST)
      DB_DATABASE_NAME: $(DB_DATABASE_NAME)
      DB_USER: $(DB_USER)
      DB_PASSWORD: $(DB_PASSWORD)

Where the db stuff points to the docker image, which runs on the docker on my local machine.


问:
I cannot create a virtualbox with Terraform provider shekeriev/virtualbox
I'm using this provider - [shekeriev/virtualbox/0.0.4][1]

```<code>terraform -v
Terraform v1.3.6
on windows_amd64
+ provider registry.terraform.io/shekeriev/virtualbox v0.0.4
</code>```

my configuration file main.tf

```<code>terraform {
  required_providers {
    virtualbox = {
      source = "shekeriev/virtualbox"
      version = "0.0.4"
    }
  }
}

provider "virtualbox" {
  # Configuration options
}

resource "virtualbox_vm" "node" {
  count     = 1
  name      = format("node-%02d", count.index + 1)
  image     = "https://app.vagrantup.com/ubuntu/boxes/xenial64/versions/20190507.0.0/providers/virtualbox.box"
  cpus      = 1
  memory    = "512 mib"

  network_adapter {
    type           = "hostonly"
    device         = "IntelPro1000MTDesktop"
    host_interface = "VirtualBox Host-Only Ethernet Adapter"
  }
}
</code>```

them i'm typing

```<code>terraform init
terraform plan
terraform apply
yes
</code>```

and getting this error!

```<code>Error: failed to unpack image https://app.vagrantup.com/ubuntu/boxes/xenial64/versions/20190507.0.0/providers/virtualbox.box: error unpacking gold image virtualbox.box: exit status 2
│
│   with virtualbox_vm.node[0],
│   on main.tf line 18, in resource "virtualbox_vm" "node":
│   18: resource "virtualbox_vm" "node" {
</code>```

I've tried different images and provider terra-farm but after all they returning this error.
[1]: https://registry.terraform.io/providers/shekeriev/virtualbox/0.0.4

Body:
I'm using this provider - [shekeriev/virtualbox/0.0.4][1]

terraform -v
Terraform v1.3.6
on windows_amd64
+ provider registry.terraform.io/shekeriev/virtualbox v0.0.4

my configuration file main.tf

terraform {
  required_providers {
    virtualbox = {
      source = "shekeriev/virtualbox"
      version = "0.0.4"
    }
  }
}

provider "virtualbox" {
  # Configuration options
}

resource "virtualbox_vm" "node" {
  count     = 1
  name      = format("node-%02d", count.index + 1)
  image     = "https://app.vagrantup.com/ubuntu/boxes/xenial64/versions/20190507.0.0/providers/virtualbox.box"
  cpus      = 1
  memory    = "512 mib"

  network_adapter {
    type           = "hostonly"
    device         = "IntelPro1000MTDesktop"
    host_interface = "VirtualBox Host-Only Ethernet Adapter"
  }
}

them i'm typing

terraform init
terraform plan
terraform apply
yes

and getting this error!

Error: failed to unpack image https://app.vagrantup.com/ubuntu/boxes/xenial64/versions/20190507.0.0/providers/virtualbox.box: error unpacking gold image virtualbox.box: exit status 2
│
│   with virtualbox_vm.node[0],
│   on main.tf line 18, in resource "virtualbox_vm" "node":
│   18: resource "virtualbox_vm" "node" {

I've tried different images and provider terra-farm but after all they returning this error.
[1]: https://registry.terraform.io/providers/shekeriev/virtualbox/0.0.4


问:
Send a TTS message to a text channel when a person joins a specific voice channel
I'm trying to create my first bot with TypeScript for discord. I'm trying to achieve a bot that sends a message to a text channel when a person joins a specific voice channel.

My code:

const { Client, Intents } = require('discord.js');

const client = new Client({
  token: 'thetokenisfilled:D',
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_VOICE_STATES,
  ],
});

client.on('voiceStateUpdate', async (oldState, newState) => {
  console.log ("funciona");
  const DISCORDIOS_ID = '500010831535276032';
  const DISCORDIOSTXT_ID = '505856553623224334';
  // if there is no newState channel, the user has just left a channel
  const USER_LEFT = !newState.channel;
  // if there is no oldState channel, the user has just joined a channel
  const USER_JOINED = !oldState.channel;
  // if there are oldState and newState channels, but the IDs are different,
  // user has just switched voice channels
  const USER_SWITCHED = newState.channel?.id !== oldState.channel?.id;

  // if a user has just left a channel, stop executing the code
  if (USER_LEFT)
    return;

  if (
    // if a user has just joined or switched to a voice channel
    (USER_JOINED || USER_SWITCHED) &&
    // and the new voice channel is the same as the support channel
    newState.channel.id === DISCORDIOS_ID
  ) {
    try {
      let logChannel = await client.channels.fetch(DISCORDIOSTXT_ID);
      logChannel.send(`joined the support channel`);
      //logChannel.send(`${newState.member.displayName} joined the support channel`, { tts: true });

    } catch (err) {
      console.error('❌ Error finding the log channel, check the error below');
      console.error(err);
      return;
    }
  }
});
```

For some reason the bot runs but it's not doing nothing in the channels. It's not sending the simple message or the TTS message.

Body:
I'm trying to create my first bot with TypeScript for discord. I'm trying to achieve a bot that sends a message to a text channel when a person joins a specific voice channel.

My code:

const { Client, Intents } = require('discord.js');

const client = new Client({
  token: 'thetokenisfilled:D',
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_VOICE_STATES,
  ],
});

client.on('voiceStateUpdate', async (oldState, newState) => {
  console.log ("funciona");
  const DISCORDIOS_ID = '500010831535276032';
  const DISCORDIOSTXT_ID = '505856553623224334';
  // if there is no newState channel, the user has just left a channel
  const USER_LEFT = !newState.channel;
  // if there is no oldState channel, the user has just joined a channel
  const USER_JOINED = !oldState.channel;
  // if there are oldState and newState channels, but the IDs are different,
  // user has just switched voice channels
  const USER_SWITCHED = newState.channel?.id !== oldState.channel?.id;

  // if a user has just left a channel, stop executing the code
  if (USER_LEFT)
    return;

  if (
    // if a user has just joined or switched to a voice channel
    (USER_JOINED || USER_SWITCHED) &&
    // and the new voice channel is the same as the support channel
    newState.channel.id === DISCORDIOS_ID
  ) {
    try {
      let logChannel = await client.channels.fetch(DISCORDIOSTXT_ID);
      logChannel.send(`joined the support channel`);
      //logChannel.send(`${newState.member.displayName} joined the support channel`, { tts: true });

    } catch (err) {
      console.error('❌ Error finding the log channel, check the error below');
      console.error(err);
      return;
    }
  }
});

For some reason the bot runs but it's not doing nothing in the channels. It's not sending the simple message or the TTS message.


问:
Making only some columns editable on streamlit-aggrid?
I'm new to streamlit-aggrid.
I have a CSV file I want to load to a dynamic table and allow editions to only some of the columns.
I saw this example:

```<code>import streamlit as st
import pandas as pd
from st_aggrid import AgGrid

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
grid_return = AgGrid(df, editable=True)
new_df = grid_return['data']
</code>```

So I've followed it, but let's say that instead of editable=True, that allows both col1 and col2 values to be modified, I want to allow modifications on one of them (not important which one).

How can I do that please?
Thanks!

I tried to pass a columns subset into the editable args but it is only accepting boolean values.

Body:
I'm new to streamlit-aggrid.
I have a CSV file I want to load to a dynamic table and allow editions to only some of the columns.
I saw this example:

import streamlit as st
import pandas as pd
from st_aggrid import AgGrid

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
grid_return = AgGrid(df, editable=True)
new_df = grid_return['data']

So I've followed it, but let's say that instead of editable=True, that allows both col1 and col2 values to be modified, I want to allow modifications on one of them (not important which one).

How can I do that please?
Thanks!

I tried to pass a columns subset into the editable args but it is only accepting boolean values.


问:
sudoedit non interactive with password and editor input from script
(I'm a beginner in linux and shell)

I need to run a sudoedit -u from a non interactive bash script
I have the password in a variable and the input for the editor
My challenge is to give password AND editor inputs to sudoedit

For the context, I need to make a kind of automatic unit tests for sudoers commands.
So my actual strategy is to run the main script with a user A. In that script I need to switch to a second user B (su) to run a subscript that run the sudoedit command (sudoedit -u userC). And I need to get the $? of the sudoedit for my main script report.

I have tested many things without success. Is there a way to give both password and editor input ? (Or an other way to perform what I need to do ?)

I tried that :

#!/bin/bash
# master script
userB=userB
userBpassword=xxx
export userBpassword
su - userB bash child.sh >/dev/null 2>&1 < <(echo $userBpassword)
isSuccess=$? # I need the information of success or not for file edition
```
<pre class="lang-bash prettyprint-override"><code>#!/bin/bash
sudoedit -u userC file.txt >/dev/null 2>&1 < <(echo ":wq") # I must inject userBpassword here but how ?
return $?
</code>```

I must do that non interactive (just asking logins and passwords once at start)
Ideally I should have 0 if sudoedit is success or anithing else if there is a failure (no right or missing file)

Thanks in advance for reading and help

Body:
(I'm a beginner in linux and shell)

I need to run a sudoedit -u from a non interactive bash script
I have the password in a variable and the input for the editor
My challenge is to give password AND editor inputs to sudoedit

For the context, I need to make a kind of automatic unit tests for sudoers commands.
So my actual strategy is to run the main script with a user A. In that script I need to switch to a second user B (su) to run a subscript that run the sudoedit command (sudoedit -u userC). And I need to get the $? of the sudoedit for my main script report.

I have tested many things without success. Is there a way to give both password and editor input ? (Or an other way to perform what I need to do ?)

I tried that :

#!/bin/bash
# master script
userB=userB
userBpassword=xxx
export userBpassword
su - userB bash child.sh >/dev/null 2>&1 < <(echo $userBpassword)
isSuccess=$? # I need the information of success or not for file edition

#!/bin/bash
sudoedit -u userC file.txt >/dev/null 2>&1 < <(echo ":wq") # I must inject userBpassword here but how ?
return $?

I must do that non interactive (just asking logins and passwords once at start)
Ideally I should have 0 if sudoedit is success or anithing else if there is a failure (no right or missing file)

Thanks in advance for reading and help


问:
Sign In for Web styling issues with Google Identity
I have implemented the updated Google Sign In for Web into my website however, I am unable to style to be responsive of the browser size and screen its displayed on. I have the following code right now:

```<code><div id="g_id_onload"
  data-client_id="CLIENT_ID"
  data-context="signup"
  data-ux_mode="redirect"
  data-login_uri="signup-with-google.php">
</div>
<div class="g_id_signin mb-6"
  data-type="standard"
  data-shape="pill"
  data-theme="outline"
  data-text="signup_with"
  data-size="large"
  data-logo_alignment="center"
  data-width="400">
</div>
</code>```

Firstly, I have tried adjusting the data-width attribute and it works fine when my website is viewed on a monitor or laptop screen. However, on a mobile screen, the button goes out of the container. I am unable to make it responsive.

I have tried styling it using css as per the other components of my website, however, it seems that the styling is forced by google and I'm unable to change it.

Also, there's this weird forced layout bug that I'm having when I refresh the page. The signin button appears bigger and then shrinks down on every page reload.

Any help would be appreciated. Thank you very much.

Body:
I have implemented the updated Google Sign In for Web into my website however, I am unable to style to be responsive of the browser size and screen its displayed on. I have the following code right now:

Firstly, I have tried adjusting the data-width attribute and it works fine when my website is viewed on a monitor or laptop screen. However, on a mobile screen, the button goes out of the container. I am unable to make it responsive.

I have tried styling it using css as per the other components of my website, however, it seems that the styling is forced by google and I'm unable to change it.

Also, there's this weird forced layout bug that I'm having when I refresh the page. The signin button appears bigger and then shrinks down on every page reload.

Any help would be appreciated. Thank you very much.


问:
Mui IconButton not focusing when adding class
How can I get an Mui IconButton to show the focusVisible styling similar to when a user navigates to the button with a keyboard?

Right now, if you navigate with the keyboard it will show the focus styling on the button. However, when I try to add the 'Mui-focusVisible' class to the button, nothing happens. I checked the DOM and it shows the class was added, but it has no effect on the styling.

Current implementation:

I have a hook that gets the last actively clicked button:

```<code>const activeElement = useActiveInputElement();
</code>```

I then have a useEffect that adds the focus class based on some conditions.

```<code>useEffect(() => {
    if (lastFocusedElementId) {
      window.setTimeout(() => document.getElementById(lastFocusedElementId)?.focus(), 0);
    }
  }, []);
</code>```

Here's the icon button

```<code><IconButton
      id={props.id}
      sx={props.sx}
    >
      {icon}
    </IconButton>
</code>```

When I console.log activeElement and lastFocusedElementId, I get the correct element but no styling changes are applied when I add the class. Any ideas?

Body:
How can I get an Mui IconButton to show the focusVisible styling similar to when a user navigates to the button with a keyboard?

Right now, if you navigate with the keyboard it will show the focus styling on the button. However, when I try to add the 'Mui-focusVisible' class to the button, nothing happens. I checked the DOM and it shows the class was added, but it has no effect on the styling.

Current implementation:

I have a hook that gets the last actively clicked button:

const activeElement = useActiveInputElement();

I then have a useEffect that adds the focus class based on some conditions.

useEffect(() => {
    if (lastFocusedElementId) {
      window.setTimeout(() => document.getElementById(lastFocusedElementId)?.focus(), 0);
    }
  }, []);

Here's the icon button

<IconButton
      id={props.id}
      sx={props.sx}
    >
      {icon}
    </IconButton>

When I console.log activeElement and lastFocusedElementId, I get the correct element but no styling changes are applied when I add the class. Any ideas?


问:
Android Library Interface Design
I am building an Android library that is packaged up in an AAR and distributed. The library does camera and image processing work. This type of work often results in memory pressure for the application that consumes the library. The consumer of the library sets up callbacks to handle responses from the library. The interface of the library takes the callbacks and starts the libraries activity by calling startActivity(intent). I have seen memory pressure cause the activity, that the library was called from, to be destroyed. The calling activity being destroyed causes the application to be unpredictable when the library returns. Image of Current Library Setup Flow

I have looked into the new Activity Result APIs (registerForActivityResult()). I could see how creating a custom contract would fix some of the problems I am seeing, since the system will guarantee reconstruction of the activity.

Is it possible to put this in the interface of my library to keep the requirements on the user of the library similar to what they are now? Should I cut out the middle interface layer and have consumers of the library create Custom contracts to use with my libraries main activity? Is there possibly another, better solution?

Title: Android Library Interface Design


问:
Is it possible to move a page from one parent to another using Notion API client?
I can't find anything in the Notion API documentation that would allow me to move a page, block, or database. Is this possible?</p>


问:
How to Get Live Stream On www.chaojidianshi.net
How to get live stream url, using PHP program or other scripting language, can look up the source code seems to be encrypted from www.chaojidianshi.net

I can only use wireshark to capture packets to the m3u8 address, not PHP scripts


问:
Is Mobiscroll compatible with React Native?
Because mobiscroll is a non-free product, before using it I need to know if it is compatible with react native. The official website says that it is compatible with react but no mention of react native.

Any information would be appreciated :)

I already searched on the official website and googled a bit, but nothing about a possible compatibility or the opposite.
I emailed the company, I'll post here there response if any :)

EDIT:

I had an answer from the company: "React native is not supported at the moment. I know the team is exploring it though, but can't give you any timeline on it." 23/12/2022


问:
The "key" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, KeyObject, or CryptoKey. Received null
I am running npm run dev code in vscode to start my site and I am getting the following error how do I solve it?

```<code>TypeError: The "key" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, KeyObject, or CryptoKey. Received null
    at new NodeError (node:internal/errors:372:5)
    at prepareSecretKey (node:internal/crypto/keys:580:11)
    at new Hmac (node:internal/crypto/hash:132:9)
    at Object.createHmac (node:crypto:162:10)
    at hmacSha256 (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:191:17)
    at Hi (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:195:13)
    at Object.continueSession (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:40:24)
    at Client._handleAuthSASLContinue (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\client.js:257:10)
    at Connection.emit (node:events:527:28)
    at Connection.emit (node:domain:475:12)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

I didn't do anything because I don't know the solution to the error.

Body:
I am running npm run dev code in vscode to start my site and I am getting the following error how do I solve it?

TypeError: The "key" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, KeyObject, or CryptoKey. Received null
    at new NodeError (node:internal/errors:372:5)
    at prepareSecretKey (node:internal/crypto/keys:580:11)
    at new Hmac (node:internal/crypto/hash:132:9)
    at Object.createHmac (node:crypto:162:10)
    at hmacSha256 (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:191:17)
    at Hi (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:195:13)
    at Object.continueSession (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\sasl.js:40:24)
    at Client._handleAuthSASLContinue (C:\Users\gulct\Desktop\mappix\MapPix-Backend-V0.0.1 Beta\node_modules\pg\lib\client.js:257:10)
    at Connection.emit (node:events:527:28)
    at Connection.emit (node:domain:475:12)
[nodemon] app crashed - waiting for file changes before starting...

I didn't do anything because I don't know the solution to the error.


问:
Getting rid of element refreshing twice
So I made a navbar with animation when I scoll down. If I scroll lower the javascript overwrites the css.

I cannot upload the backgrounds but codepen:
Js:

```<code>//line animation
document.querySelector(':root').style.setProperty('--contwidth',$(".container").width()+'px');
//line animation end

//navbar

$(function navscroll() {
    $(window).on("scroll", function() {
      const navline = document.querySelector('.navline');
      const header = document.querySelector('header');
       if($(window).scrollTop() >= 100) {
           navline.style.width = '100%';
           navline.style.backgroundColor = 'var(--sec-transparent-color)';
           header.style.backgroundColor = 'var(--bg-transparent-color)';
       } else {
           navline.style.width = $(".container").width()+'px';
           navline.style.backgroundColor = 'var(--text-color)';
           header.style.backgroundColor = 'transparent';
       }
     });
   });
//navbar end

//scroll top
$(document).ready(function(){
  $(window).scrollTop(0);

});

CSS
.navline {
    background-color: #fff;
    bottom: 0;
    height: 0.1rem;
    width: var(--contwidth);
    transition: all 0.5s ease;
    margin: auto;
}

:root{
    --bg-color: #030303;
    --bg-transparent-color:rgba(0,0,0,0.93);
    --text-color: #E8E8E8;
    --main-color: #B71A24;
    --sec-color:#dd003f;
    --sec-transparent-color: rgba(221,0,63,0.93) !important;
    --contwidth: x;
}
</code>```

Codepen

The problem is that I'm using a function to roll back the site to top after refreshing but if I refresh it the css loads in first then the javascript overwrites the css so my white line changes to red then after it reaches the top it become white again

Title: Getting rid of element refreshing twice

Body:
So I made a navbar with animation when I scoll down. If I scroll lower the javascript overwrites the css.

I cannot upload the backgrounds but codepen:
Js:

//line animation
document.querySelector(':root').style.setProperty('--contwidth',$(".container").width()+'px');
//line animation end

//navbar

$(function navscroll() {
    $(window).on("scroll", function() {
      const navline = document.querySelector('.navline');
      const header = document.querySelector('header');
       if($(window).scrollTop() >= 100) {
           navline.style.width = '100%';
           navline.style.backgroundColor = 'var(--sec-transparent-color)';
           header.style.backgroundColor = 'var(--bg-transparent-color)';
       } else {
           navline.style.width = $(".container").width()+'px';
           navline.style.backgroundColor = 'var(--text-color)';
           header.style.backgroundColor = 'transparent';
       }
     });
   });
//navbar end

//scroll top
$(document).ready(function(){
  $(window).scrollTop(0);

});

CSS
.navline {
    background-color: #fff;
    bottom: 0;
    height: 0.1rem;
    width: var(--contwidth);
    transition: all 0.5s ease;
    margin: auto;
}

:root{
    --bg-color: #030303;
    --bg-transparent-color:rgba(0,0,0,0.93);
    --text-color: #E8E8E8;
    --main-color: #B71A24;
    --sec-color:#dd003f;
    --sec-transparent-color: rgba(221,0,63,0.93) !important;
    --contwidth: x;
}

Codepen

The problem is that I'm using a function to roll back the site to top after refreshing but if I refresh it the css loads in first then the javascript overwrites the css so my white line changes to red then after it reaches the top it become white again


问:
Output for an implementation of a Monte Carlo numerical solver for a 1D potential well doesn't match expected output
I am trying to implement a numerical solver for a 1D Harmonic well's ground state using the Metropolis algorithm and the Feynman Path Integral technique in Python. When I run my program, I end with a distribution of the different points that my particle has gone to; this distribution ought to match up with that of a particle trapped in a 1D harmonic well. It does not. I have gone through and rewritten my code; I have checked it to similar code used for the same purpose; it all looks like it should work, yet it doesn't.

In blue is the histogram of my results, with Density set to True; the orange line is the function describing the expected distribution
As can be seen in the image, what I have ended up with is a distribution that isn't dissimilar to what I was expecting, but it isn't the correct distribution. The code I used (see below), is based on Lepage (2005) work on the same topic, although I used a slightly different formula to describe the same physical system.

```<code>import numpy as np
import random
import matplotlib.pyplot as plt

time = 4        #time over which we evolve our function
steps = 7       #number of steps we take
epsilon = 3     #the pos & neg bounds of our rand variable
N_cor = 100     #the number of times we need to thermalise our function before we take a path
N_cf = 20000    #the number of paths we take

def S(x, j, t, s):  #the action of our potential well
    e = t / s
    return (1/(2*e))*(x[j] - x[j - 1])**2 + ((x[j] + x[j-1])/2)**2/2

def update(x, t, s, eps):
    for j in range(0, s):
        old_x = x[j]                                    #old x value
        old_Sj = S(x, j, t, s)                          #original action value
        x[j] = x[j] + random.uniform(-eps,eps)          #new x value
        dS = S(x, j, t, s) - old_Sj                     #change in action
        if dS > 0 and np.exp(-dS) < random.uniform(0,1):    #check for Metropolis alg
            x[j] = old_x
    return x

def gamma(t, s, eps, thermal_num, num_paths):
    zeros = np.zeros(s)                 #our initial path with s steps
    gamma_arr = np.empty(0)             #our initial empty result
    for i in range(0, 10*thermal_num):  #thermalisation
        zeros = update(zeros, t, s, eps)
    for j in range(0, num_paths):
        for i in range(0, thermal_num):                 #thermalising again
            zeros = update(zeros, t, s, eps)
        gamma_arr = np.append(gamma_arr, zeros)         #add new path post thermalising
        #print(zeros)
        #print(gamma_arr)
    return gamma_arr

test = gamma(time, steps, epsilon, N_cor, N_cf)

x = np.arange(-4, 4, 0.1)
y = 1/np.sqrt(np.pi)*np.exp(-(x**2))    #expected result

plt.hist(test, bins= 500, density = True)
plt.plot(x, y)
plt.show()
</code>```

Body:
I am trying to implement a numerical solver for a 1D Harmonic well's ground state using the Metropolis algorithm and the Feynman Path Integral technique in Python. When I run my program, I end with a distribution of the different points that my particle has gone to; this distribution ought to match up with that of a particle trapped in a 1D harmonic well. It does not. I have gone through and rewritten my code; I have checked it to similar code used for the same purpose; it all looks like it should work, yet it doesn't.

In blue is the histogram of my results, with Density set to True; the orange line is the function describing the expected distribution
As can be seen in the image, what I have ended up with is a distribution that isn't dissimilar to what I was expecting, but it isn't the correct distribution. The code I used (see below), is based on Lepage (2005) work on the same topic, although I used a slightly different formula to describe the same physical system.

import numpy as np
import random
import matplotlib.pyplot as plt

time = 4        #time over which we evolve our function
steps = 7       #number of steps we take
epsilon = 3     #the pos & neg bounds of our rand variable
N_cor = 100     #the number of times we need to thermalise our function before we take a path
N_cf = 20000    #the number of paths we take

def S(x, j, t, s):  #the action of our potential well
    e = t / s
    return (1/(2*e))*(x[j] - x[j - 1])**2 + ((x[j] + x[j-1])/2)**2/2

def update(x, t, s, eps):
    for j in range(0, s):
        old_x = x[j]                                    #old x value
        old_Sj = S(x, j, t, s)                          #original action value
        x[j] = x[j] + random.uniform(-eps,eps)          #new x value
        dS = S(x, j, t, s) - old_Sj                     #change in action
        if dS > 0 and np.exp(-dS) < random.uniform(0,1):    #check for Metropolis alg
            x[j] = old_x
    return x

def gamma(t, s, eps, thermal_num, num_paths):
    zeros = np.zeros(s)                 #our initial path with s steps
    gamma_arr = np.empty(0)             #our initial empty result
    for i in range(0, 10*thermal_num):  #thermalisation
        zeros = update(zeros, t, s, eps)
    for j in range(0, num_paths):
        for i in range(0, thermal_num):                 #thermalising again
            zeros = update(zeros, t, s, eps)
        gamma_arr = np.append(gamma_arr, zeros)         #add new path post thermalising
        #print(zeros)
        #print(gamma_arr)
    return gamma_arr

test = gamma(time, steps, epsilon, N_cor, N_cf)

x = np.arange(-4, 4, 0.1)
y = 1/np.sqrt(np.pi)*np.exp(-(x**2))    #expected result

plt.hist(test, bins= 500, density = True)
plt.plot(x, y)
plt.show()


问:
Is AsyncLocal must survive thread hop in asp.net?
In my asp.net (4.7.2) application sometimes occur thread hop. I have used HttpContext.Current to deal with it. But some ago AsyncLocal come, but I find out it is null after thread hop. Is it right behavior or I should use f.e. net 4.8?

update

Thread hop have another name - thread agility. The fenomen is described f.e in post:

What is the meaning of thread-agility in ASP.Net?


问:
How do I change the host of the "Run Project" button in Netbeans?
I am using Apache NetBeans IDE 15 with Java 17.

When clicking the "Run Project" (F6) button the browser successfully opens to :

https://localhost:8443/myProject

however I would like to have it go to :

https://localhost.xyz.edu:8443/myProject

How can this be done?

I was hoping this could have been changed via the Web Browsers Manager tool inside of Netbeans. However I am not sure what arguments are available besides URL.

screen shot of the Web Browsers Manager tool


问:
Pod tag during predownload is different from installed
I have been trying to install a private pod in ios project. But the tag metioned in podfile is different from the one being installed. Also the tag mentioned during pre download is same as podfile but some other tag is mentioned during installation. Attaching screenshot.