问:
How to download my div of chart as image using jquery
I have a chart I am downloading it using external library as image but it is not downloading correctly .

I am using the following code

```<code> <a id="downloadImage">
  <img src="~/Content/images/imgae-icon.jpg" alt="" />
 </a>
 <div id="InflationChart" style="height: 400px;"> </div>
 <div id="previewImage" hidden></div>
</code>```

The InflationChart div contains the actual chart. as below

I am using javascript code to download this div as image .

```<code>$("#downloadImage").on('click', function () {
    element = $("#InflationChart");
    html2canvas(element, {
        onrendered: function (canvas) {
            $("#previewImage").append(canvas);
            getCanvas = canvas;
        }
    });
    var imgageData = getCanvas.toDataURL("image/png");
    // Now browser starts downloading it instead of just showing it
    var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
    $("#downloadImage").attr("download", "image.png").attr("href", newData);
});
</code>```

The donloaded image is not as actual image . the downloaded image is below

Body:
I have a chart I am downloading it using external library as image but it is not downloading correctly .

I am using the following code

The InflationChart div contains the actual chart. as below

I am using javascript code to download this div as image .

$("#downloadImage").on('click', function () {
    element = $("#InflationChart");
    html2canvas(element, {
        onrendered: function (canvas) {
            $("#previewImage").append(canvas);
            getCanvas = canvas;
        }
    });
    var imgageData = getCanvas.toDataURL("image/png");
    // Now browser starts downloading it instead of just showing it
    var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
    $("#downloadImage").attr("download", "image.png").attr("href", newData);
});

The donloaded image is not as actual image . the downloaded image is below


来源: stackexchange

问:
Test if active document in Rstudio is RMarkdown
I want to add a small function to my RStudio AddIn which extracts all chunks from an Rmarkdown document, does some transformation and displays it as new editor window in RStudio. Basically, that will be a thin wrapper around knitr::purl. The function will eventually be called via the AddIns interface in RStudio and should consider the currently opened editor window as input.

What I was wondering though, is how to include a check whether the current editor window shows indeed an RMarkdown document.

I could use the file extension like this:

if (grepl("\\.Rmd$", rstudioapi::getSourceEditorContext()$path)) {
   ## Rmarkdown -> do knitr::purl
} else {
   ## No Rmarkdown -> give a warning
}
```

But this feels hackish and a new Rmarkdown document, which is not saved yet (and opened via File -> New File -> RMarkdown...) will fail this check.

As RStudio itself does somehow recognize whether a file is meant to be an Rmarkdown document (creating a file as highlighted will add the Knit button for example, even if it not saved yet), I was wondering how I would ultimately find out the "file" type of an editor window?

I skimmed through the Admin Guide Appendix hoping to find a function like isRMarkdown to be called via rstudioApi::executeCommand but to no avail.

What would be a reliable way to check the file type associated to the current editor window in RStudio?

ContentLicense: CC BY-SA 4.0

Body:
I want to add a small function to my RStudio AddIn which extracts all chunks from an Rmarkdown document, does some transformation and displays it as new editor window in RStudio. Basically, that will be a thin wrapper around knitr::purl. The function will eventually be called via the AddIns interface in RStudio and should consider the currently opened editor window as input.

What I was wondering though, is how to include a check whether the current editor window shows indeed an RMarkdown document.

I could use the file extension like this:

if (grepl("\\.Rmd$", rstudioapi::getSourceEditorContext()$path)) {
   ## Rmarkdown -> do knitr::purl
} else {
   ## No Rmarkdown -> give a warning
}

But this feels hackish and a new Rmarkdown document, which is not saved yet (and opened via File -> New File -> RMarkdown...) will fail this check.

As RStudio itself does somehow recognize whether a file is meant to be an Rmarkdown document (creating a file as highlighted will add the Knit button for example, even if it not saved yet), I was wondering how I would ultimately find out the "file" type of an editor window?

I skimmed through the Admin Guide Appendix hoping to find a function like isRMarkdown to be called via rstudioApi::executeCommand but to no avail.

What would be a reliable way to check the file type associated to the current editor window in RStudio?


问:
What types to use for Chart.js tooltip?
I have troubles with TS for bar chart options.

Here is my function that returns the options object for the chart.

```<code>export const getChartOptions = (
  isSingleSample: boolean,
  labels: string[],
  customTooltip: (context: unknown) => void,
) => {
  const options: BarProps['options'] = {
    plugins: {
      datalabels: {
        display: false,
      },
      tooltip: {
        // Disable the built-in on-canvas tooltip
        enabled:  false,
        external: customTooltip,
        //@ts-expect-error
        events:   ['touchmove', 'click'],
      },
    },
    scales: {
      x: {
        grid: {
          display: false,
        },
        border: {
          display: false,
        },
        ticks: {
          color: FONT_COLOR,
          font:  {
            family: FONT_FAMILY,
            size:   FONT_SIZE,
          },
        },
      },
      y: {
        border:   {
          display: false,
        },
        ticks: {
          color: FONT_COLOR,
          font:  {
            family: FONT_FAMILY,
            size:   FONT_SIZE,
          },
          callback: function(value, index, ticks) {
            return labels[index];
          },
          labelOffset: -10,
          stepSize:    1,
          mirror:      true,
        },
      },
    },
    responsive:          true,
    maintainAspectRatio: false,

    //this will switch bars width if it is a single sample or all of them
    barPercentage:       isSingleSample ? 0.8 : 0.6,
    categoryPercentage:  isSingleSample ? 0.8 : 0.6,
  };

  return options;
};
</code>```

I am having trouble only with the tooltip part.
No matter how hard I try, but I can't find proper types for:

events

This is what I get if I remove //@ts-expect-error

```<code>Type '{ enabled: false; external: (context: unknown) => void; events: string[]; }' is not assignable to type '_DeepPartialObject<TooltipOptions<"bar">>'.
  Object literal may only specify known properties, and 'events' does not exist in type '_DeepPartialObject<TooltipOptions<"bar">>'.  TS2322

    64 |         external: customTooltip,
    65 |
  > 66 |         events: ['touchmove', 'click'],
       |         ^
    67 |       },
    68 |     },
    69 |     scales: {
</code>```

My external tooltip function customTooltip

My customTooltip simply changes the state, and doesn't do anything to canvas.

```<code>  const customTooltip = (context: any) => {
    setTooltipData(context.tooltip);
    setTooltipOpacity(context.tooltip.opacity);
  };
</code>```

The problem here is context type.

It all works fine, I just can't defeat TS.

This is the second day I am playing with the Chart.js types, but still can't get the correct one.

Title: What types to use for Chart.js tooltip?

Body:
I have troubles with TS for bar chart options.

Here is my function that returns the options object for the chart.

export const getChartOptions = (
  isSingleSample: boolean,
  labels: string[],
  customTooltip: (context: unknown) => void,
) => {
  const options: BarProps['options'] = {
    plugins: {
      datalabels: {
        display: false,
      },
      tooltip: {
        // Disable the built-in on-canvas tooltip
        enabled:  false,
        external: customTooltip,
        //@ts-expect-error
        events:   ['touchmove', 'click'],
      },
    },
    scales: {
      x: {
        grid: {
          display: false,
        },
        border: {
          display: false,
        },
        ticks: {
          color: FONT_COLOR,
          font:  {
            family: FONT_FAMILY,
            size:   FONT_SIZE,
          },
        },
      },
      y: {
        border:   {
          display: false,
        },
        ticks: {
          color: FONT_COLOR,
          font:  {
            family: FONT_FAMILY,
            size:   FONT_SIZE,
          },
          callback: function(value, index, ticks) {
            return labels[index];
          },
          labelOffset: -10,
          stepSize:    1,
          mirror:      true,
        },
      },
    },
    responsive:          true,
    maintainAspectRatio: false,

    //this will switch bars width if it is a single sample or all of them
    barPercentage:       isSingleSample ? 0.8 : 0.6,
    categoryPercentage:  isSingleSample ? 0.8 : 0.6,
  };

  return options;
};

I am having trouble only with the tooltip part.
No matter how hard I try, but I can't find proper types for:

events

This is what I get if I remove //@ts-expect-error

Type '{ enabled: false; external: (context: unknown) => void; events: string[]; }' is not assignable to type '_DeepPartialObject<TooltipOptions<"bar">>'.
  Object literal may only specify known properties, and 'events' does not exist in type '_DeepPartialObject<TooltipOptions<"bar">>'.  TS2322

    64 |         external: customTooltip,
    65 |
  > 66 |         events: ['touchmove', 'click'],
       |         ^
    67 |       },
    68 |     },
    69 |     scales: {

My external tooltip function customTooltip

My customTooltip simply changes the state, and doesn't do anything to canvas.

  const customTooltip = (context: any) => {
    setTooltipData(context.tooltip);
    setTooltipOpacity(context.tooltip.opacity);
  };

The problem here is context type.

It all works fine, I just can't defeat TS.

This is the second day I am playing with the Chart.js types, but still can't get the correct one.


问:
Failed to build Flutter app in iOS emulator for architecture arm64
I am encounter this error when first time I build my flutter app in iOS simulator (it works normally on android)

Device: MacbookAir M1
Flutter: 3.3.10
Xcode: 14.2

```<code>In
/Users/paramaartha/Documents/Flutter/komplekku_user/ios/Pods/Sodium/Sodium/libsodium/libsodium-io
s.a(libsodium_la-aead_chacha20poly1305.o), building for iOS Simulator, but linking in object file
built for iOS, file
'/Users/paramaartha/Documents/Flutter/komplekku_user/ios/Pods/Sodium/Sodium/libsodium/libsodium-i
os.a' for architecture arm64
</code>```

Anyone know how to fix it?

I tried to add exclude architecture and run Xcode in rosseta but nothing work

Body:
I am encounter this error when first time I build my flutter app in iOS simulator (it works normally on android)

Device: MacbookAir M1
Flutter: 3.3.10
Xcode: 14.2

In
/Users/paramaartha/Documents/Flutter/komplekku_user/ios/Pods/Sodium/Sodium/libsodium/libsodium-io
s.a(libsodium_la-aead_chacha20poly1305.o), building for iOS Simulator, but linking in object file
built for iOS, file
'/Users/paramaartha/Documents/Flutter/komplekku_user/ios/Pods/Sodium/Sodium/libsodium/libsodium-i
os.a' for architecture arm64

Anyone know how to fix it?

I tried to add exclude architecture and run Xcode in rosseta but nothing work


问:
Plotly - update the chart without open it in new tab over and over again
How can I update the chart in real-time instead of re-opening it again and again ? I have used plotly only and it looks like fig.show() keep re-opening a new tab instead of just updating the chart..

```<code>import ibapi
import pandas
import plotly.graph_objects as go
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

import threading
import time

class IBapi(EWrapper, EClient):
      def __init__(self):
           EClient.__init__(self, self)
           self.data = [] #Initialize variable to store candle
      def historicalData(self, reqId, bar):
           print(f'Time: {bar.date} High: {bar.high} Low: {bar.low} Open: {bar.open} Close :
                                                                             {bar.close}')
           self.data.append([bar.date, bar.high, bar.low, bar.open, bar.close])

def run_loop():
    app.run()

app = IBapi()
app.connect('127.0.0.1', 7496, 123)

#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

time.sleep(1)

#contract object
eurusd_contract = Contract()
eurusd_contract.symbol = 'EUR'
eurusd_contract.secType = 'CASH'
eurusd_contract.exchange = 'IDEALPRO'
eurusd_contract.currency = 'USD'

i=1
while i==1:
    app.reqHistoricalData(1, eurusd_contract, '', '2 D', '1 hour', 'BID', 1, 2, False, [])
    time.sleep(5)  #sleep to allow enough time for data to be returned

    df = pandas.DataFrame(app.data, index=None, columns=['DateTime','High', 'Low', 'Open',
                                                     'Close'])
    df['DateTime'] = pandas.to_datetime(df['DateTime'],unit='s')
    df.to_csv('EURUSD_Hourly.csv')
    #print(df)
    time.sleep(5)

    fig = go.Figure(data=[
          go.Candlestick(
          x=df['DateTime'],
          open=df['Open'],
          high=df['High'],
          low=df['Low'],
          close=df['Close'])])

    fig = fig.update_layout(title= 'INTERACTIVE CHART',
                            yaxis_title = eurusd_contract.symbol)

    fig.show()
    time.sleep(10)
</code>```

The chart is being opened every update on different tab, how can i update it without open a new tab?

Body:
How can I update the chart in real-time instead of re-opening it again and again ? I have used plotly only and it looks like fig.show() keep re-opening a new tab instead of just updating the chart..

import ibapi
import pandas
import plotly.graph_objects as go
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

import threading
import time

class IBapi(EWrapper, EClient):
      def __init__(self):
           EClient.__init__(self, self)
           self.data = [] #Initialize variable to store candle
      def historicalData(self, reqId, bar):
           print(f'Time: {bar.date} High: {bar.high} Low: {bar.low} Open: {bar.open} Close :
                                                                             {bar.close}')
           self.data.append([bar.date, bar.high, bar.low, bar.open, bar.close])

def run_loop():
    app.run()

app = IBapi()
app.connect('127.0.0.1', 7496, 123)

#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

time.sleep(1)

#contract object
eurusd_contract = Contract()
eurusd_contract.symbol = 'EUR'
eurusd_contract.secType = 'CASH'
eurusd_contract.exchange = 'IDEALPRO'
eurusd_contract.currency = 'USD'

i=1
while i==1:
    app.reqHistoricalData(1, eurusd_contract, '', '2 D', '1 hour', 'BID', 1, 2, False, [])
    time.sleep(5)  #sleep to allow enough time for data to be returned

    df = pandas.DataFrame(app.data, index=None, columns=['DateTime','High', 'Low', 'Open',
                                                     'Close'])
    df['DateTime'] = pandas.to_datetime(df['DateTime'],unit='s')
    df.to_csv('EURUSD_Hourly.csv')
    #print(df)
    time.sleep(5)

    fig = go.Figure(data=[
          go.Candlestick(
          x=df['DateTime'],
          open=df['Open'],
          high=df['High'],
          low=df['Low'],
          close=df['Close'])])

    fig = fig.update_layout(title= 'INTERACTIVE CHART',
                            yaxis_title = eurusd_contract.symbol)

    fig.show()
    time.sleep(10)

The chart is being opened every update on different tab, how can i update it without open a new tab?


问:
Keras Neural Net Loss Function
I've encountered a problem while writing Siamese net. Definition of the net takes as an input 2 vectors which represents 2 pieces of text. The vectors length is padded and different with respect to batches (in batch 1: vectors length = 32, in batch 2: vectors length = 64 and so on).

```<code># model definition
def create_model(vocab_size=512, d_model=128):
    def normalize(x):
        norm = tf.norm(x, axis=-1, keepdims=True)
        return tf.divide(x, norm)

    component = tf.keras.Sequential([
        tf.keras.layers.Embedding(vocab_size, d_model),
        tf.keras.layers.LSTM(d_model),
        tf.keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis=1)),
        tf.keras.layers.Lambda(normalize),
    ])
    # due to the variability in text, input shape differs with respect to batch
    inputs = [tf.keras.Input(shape=(None,)) for _ in range(2)]
    outputs = tf.tuple([component(ins) for ins in inputs])

    return tf.keras.Model(inputs=inputs, outputs=outputs)

# loss function
class MyLoss(tf.keras.losses.Loss):

    def __init__(self):
        super().__init__(name='TripletLoss')

    def call(self, y_true, y_pred):
        # >>> HERE IS THE PROBLEM, y_pred has different shape then I'd expect,
        # its shape is (batch_size,) instead of (2, batch_size)
        l, r = y_pred
        # compute and return loss
        return loss
</code>```

When calling Model#fit(loss=MyLoss(), ...) the parameter passed to the MyLoss#call is a projection of the first coordinate of the model prediction, i.e. model.predict(z) returns [x, y] where x, y are vectors with length equal to the batch size. I'd expected that y_pred passed as a parameter to Loss#call would have had that exact value, that is [x,y], but it equals to the first vector of the given list, that is x. Furthermore I've looked up at the call stack and I've spotted that before y_pred is passed to the MyLoss#call it has expected value ([x,y]) which changes to the x in the keras' Loss.__call__ body.

I tried to reshape input, but other problems arised.

Title: Keras Neural Net Loss Function

Body:
I've encountered a problem while writing Siamese net. Definition of the net takes as an input 2 vectors which represents 2 pieces of text. The vectors length is padded and different with respect to batches (in batch 1: vectors length = 32, in batch 2: vectors length = 64 and so on).

# model definition
def create_model(vocab_size=512, d_model=128):
    def normalize(x):
        norm = tf.norm(x, axis=-1, keepdims=True)
        return tf.divide(x, norm)

    component = tf.keras.Sequential([
        tf.keras.layers.Embedding(vocab_size, d_model),
        tf.keras.layers.LSTM(d_model),
        tf.keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis=1)),
        tf.keras.layers.Lambda(normalize),
    ])
    # due to the variability in text, input shape differs with respect to batch
    inputs = [tf.keras.Input(shape=(None,)) for _ in range(2)]
    outputs = tf.tuple([component(ins) for ins in inputs])

    return tf.keras.Model(inputs=inputs, outputs=outputs)

# loss function
class MyLoss(tf.keras.losses.Loss):

    def __init__(self):
        super().__init__(name='TripletLoss')

    def call(self, y_true, y_pred):
        # >>> HERE IS THE PROBLEM, y_pred has different shape then I'd expect,
        # its shape is (batch_size,) instead of (2, batch_size)
        l, r = y_pred
        # compute and return loss
        return loss

When calling Model#fit(loss=MyLoss(), ...) the parameter passed to the MyLoss#call is a projection of the first coordinate of the model prediction, i.e. model.predict(z) returns [x, y] where x, y are vectors with length equal to the batch size. I'd expected that y_pred passed as a parameter to Loss#call would have had that exact value, that is [x,y], but it equals to the first vector of the given list, that is x. Furthermore I've looked up at the call stack and I've spotted that before y_pred is passed to the MyLoss#call it has expected value ([x,y]) which changes to the x in the keras' Loss.__call__ body.

I tried to reshape input, but other problems arised.


问:
blendMode.dstATop makes screen black on my Android Phone
I have an app where I put the Scaffold of the screen inside a container, the container has a BoxDecoration with a DecorationImage, I want to reduce the opacity of the image, so here is the code:

```<code>decoration: BoxDecoration(
          image: DecorationImage(
              image: const AssetImage('assets/images/building.jpg'),
              colorFilter: ColorFilter.mode(
                  Colors.black.withOpacity(0.2), BlendMode.dstATop),
              fit: BoxFit.cover)),
</code>```

This works well on the web browser, but if I try it on my android phone the screen has a black tone like it is dimmed.

I tried replacing the color with white which didn't seem to make a difference, I also tried to higher the opacity and it made the background image not transparent, which makes it hard to see text.

Body:
I have an app where I put the Scaffold of the screen inside a container, the container has a BoxDecoration with a DecorationImage, I want to reduce the opacity of the image, so here is the code:

decoration: BoxDecoration(
          image: DecorationImage(
              image: const AssetImage('assets/images/building.jpg'),
              colorFilter: ColorFilter.mode(
                  Colors.black.withOpacity(0.2), BlendMode.dstATop),
              fit: BoxFit.cover)),

This works well on the web browser, but if I try it on my android phone the screen has a black tone like it is dimmed.

I tried replacing the color with white which didn't seem to make a difference, I also tried to higher the opacity and it made the background image not transparent, which makes it hard to see text.


问:
While running Spring Boot project getting error like null pointer exception for eureka server
I have Spring boot project with the version 3.0.1 and also i am using eureka dependency
and while running getting error as below . Could you please help on this ?

```<code>'''<dependency>
    <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
       <exclusions>
        <exclusion>
         <groupId>javax.ws.rs</groupId>
        <artifactId>jsr311-api</artifactId>
       </exclusion>
     </exclusions>
 </dependency>
 <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
 </dependency>'''

  Error:
    '''org.springframework.context.ApplicationContextException: Failed to start bean   'eurekaAutoServiceRegistration'; nested exception is java.lang.NullPointerException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181)
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
at java.lang.Iterable.forEach(Iterable.java:75)
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at com.hm.bob.odata.BobOdataApplication.main(BobOdataApplication.java:17)
</code>```

Caused by: java.lang.NullPointerException: null
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.maybeInitializeClient(EurekaServiceRegistry.java:54)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(EurekaServiceRegistry.java:38)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:83)
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
... 14 common frames omitted'''

```<code>  Could you please help on this?
</code>```

Body:
I have Spring boot project with the version 3.0.1 and also i am using eureka dependency
and while running getting error as below . Could you please help on this ?

'''<dependency>
    <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
       <exclusions>
        <exclusion>
         <groupId>javax.ws.rs</groupId>
        <artifactId>jsr311-api</artifactId>
       </exclusion>
     </exclusions>
 </dependency>
 <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
 </dependency>'''

  Error:
    '''org.springframework.context.ApplicationContextException: Failed to start bean   'eurekaAutoServiceRegistration'; nested exception is java.lang.NullPointerException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181)
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
at java.lang.Iterable.forEach(Iterable.java:75)
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295)
at com.hm.bob.odata.BobOdataApplication.main(BobOdataApplication.java:17)

Caused by: java.lang.NullPointerException: null
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.maybeInitializeClient(EurekaServiceRegistry.java:54)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(EurekaServiceRegistry.java:38)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:83)
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
... 14 common frames omitted'''

  Could you please help on this?


问:
Symfony 6: embedded form collection, add only new elements and omit existing elements
I have a FormType which contains an embedded collection of another FormType, all is working properly and done according to How to Embed a Collection of Forms.

My embedded FormType is an attachment list, which has title and file upload.

AttachmentType:

```<code>builder
        ->add('title', null, ['label' => 'Title', 'required' => true])
        ->add('attachmentFile', FileType::class, [
            'label' => 'File',
            'mapped' => false,
            'required' => true,
            'constraints' => [
                new File([
                    'maxSize' => '1024k',
                ])
            ],
        ])
</code>```

The problem is, when editing the parent object, I want to allow new attachments but I don't want to edit previous attachments, as it would be forcing me to upload the same files every time I edit the parent object.

All elements and javascript are done according to the docs linked, I don't find any property for CollectionType that would allow add but wouldn't allow edit or something similar. The javascript seems too dependent on external stuff to allow some modification.

Javascript

```<code>// assets/controllers/form-collection_controller.js

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    static targets = ["collectionContainer"]

    static values = {
        index    : Number,
        prototype: String,
    }

    addCollectionElement(event)
    {
        const item = document.createElement('li');
        item.innerHTML = this.prototypeValue.replace(/__name__/g, this.indexValue);
        this.collectionContainerTarget.appendChild(item);
        this.indexValue++;
    }
}
</code>```

Twig template

```<code><div {{ stimulus_controller('form-collection') }}
        data-form-collection-index-value="{{ form.attachments|length > 0 ? form.attachments|last.vars.name + 1 : 0 }}"
        data-form-collection-prototype-value="{{ form_widget(form.attachments.vars.prototype)|e('html_attr') }}"
    >
    <ul {{ stimulus_target('form-collection', 'collectionContainer') }}></ul>
    <button type="button" class="btn btn-secondary" {{ stimulus_action('form-collection', 'addCollectionElement') }}>Añadir adjunto</button>
</div>
</code>```

Body:
I have a FormType which contains an embedded collection of another FormType, all is working properly and done according to How to Embed a Collection of Forms.

My embedded FormType is an attachment list, which has title and file upload.

AttachmentType:

builder
        ->add('title', null, ['label' => 'Title', 'required' => true])
        ->add('attachmentFile', FileType::class, [
            'label' => 'File',
            'mapped' => false,
            'required' => true,
            'constraints' => [
                new File([
                    'maxSize' => '1024k',
                ])
            ],
        ])

The problem is, when editing the parent object, I want to allow new attachments but I don't want to edit previous attachments, as it would be forcing me to upload the same files every time I edit the parent object.

All elements and javascript are done according to the docs linked, I don't find any property for CollectionType that would allow add but wouldn't allow edit or something similar. The javascript seems too dependent on external stuff to allow some modification.

Javascript

// assets/controllers/form-collection_controller.js

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    static targets = ["collectionContainer"]

    static values = {
        index    : Number,
        prototype: String,
    }

    addCollectionElement(event)
    {
        const item = document.createElement('li');
        item.innerHTML = this.prototypeValue.replace(/__name__/g, this.indexValue);
        this.collectionContainerTarget.appendChild(item);
        this.indexValue++;
    }
}

Twig template

 0 ? form.attachments|last.vars.name + 1 : 0 }}"
        data-form-collection-prototype-value="{{ form_widget(form.attachments.vars.prototype)|e('html_attr') }}"
    >

    <button type="button" class="btn btn-secondary" {{ stimulus_action('form-collection', 'addCollectionElement') }}>Añadir adjunto</button>


问:
Responsiveness with Tailwind css in React
Hello everyone for a bootcamp project I have created a blog page and while trying to make it responsive, I messed up styling too. I am attaching the figma version, my code and what I get as a reflection. I need your help with styling and responsiveness please.
figma version

what I get

rest of what i get]

```<code>import React from 'react';
import meditation from './images/meditation.png';
import trauma from './images/trauma.png';
import anxiety from './images/anxiety.png';
import SubsInput from '../../shared/subsInput/SubsInput';

function Blog() {
  return (
    <div className=" mx-auto text-justify md:m-0 ">
      <img
        className="justify-center rounded mx-auto py-7 p-12"
        src={meditation}
        alt="meditation"
      />
      <div className="max-w-[800px] mt-[90px] w-full h-screen mx-auto  flex flex-col justify-center ">
        <h1 className="py-14 mt-6 text-bold text-3xl">
          MENTAL HEALTH AND TECHNOLOGY
        </h1>
        <p className="uppercase mb-4">
          Technology and mental well-being might seem like profoundly
          antagonistic terms. However, there are excellent digital tools to help
          you reach mindfulness and to practice meditation. You can even use
          smartphone apps, virtual reality solutions and digital devices as a
          form of relieving stressing and achieving digital detox – as, after a
          while, you will be able to practice all types of anti-anxiety skills
          on your own. So, let The Medical Futurist show you how you can enhance
          your mental and emotional health with the help of technology.
        </p>
        <h3 className="uppercase py-5 text-xl ">
          THE NEED FOR TAKING CARE OF OUR EMOTIONAL HEALTH
        </h3>
        <p className="uppercase">
          “Just as we observe physical hygiene to stay well, we need to
          cultivate a kind of emotional hygiene too,” wrote the Dalai Lama on
          his Twitter-feed. There are three crucial points around His Holiness’
          statement. First and foremost, the popularity of health-enhancing,
          physically active lifestyle is soaring worldwide. Nevertheless,
          there’s always room for improvement: the WHO says that globally, 23
          percent of adults and 81 percent of school-going adolescents are not
          active enough. According to the organization, adults aged 18-64 should
          do at least 150 minutes of moderately intense physical activity each
          week, which is not unaccomplishable. Moreover, the numerically and
          statistically driven 21st-century mind could take a great inspiration
          and power from the various fitness trackers and wearables.
        </p>
        <p className="uppercase py-6">
          Secondly, emotional hygiene seems to be thrown into the shade
          nowadays. Somehow, the culture of busyness prevents us from squeezing
          some time for mental health into our packed schedules. Information is
          pouring on us from millions of communication channels; we are
          connecting with hundreds of ‘friends’ on social media, we are obsessed
          with data due to the fear of missing out and time management slices up
          our days into meetings and to-do-lists.
        </p>
        <p className="uppercase">
          The pressure to perform and the stress to achieve is the air every
          busy-bee is breathing. However, turbulent lifestyle comes with a
          price. No wonder so many people have mental health issues. In the US,
          that means one in five adults – more than 40 million Americans! On the
          old continent, 27 percent of the population has to cope with mental
          disorders, which means 83 million struggling Europeans. In Asia, the
          prevalence of depression is 20 percent in Thailand, 19.9 percent in
          Taiwan, 19.4 percent in Korea, 17.5 in Malaysia and 16.5 percent in
          China.
        </p>
      </div>
      <div className="max-w-[800px] mt-[-200px] w-full h-screen mx-auto  flex flex-col justify-center">
        <h3 className="uppercase text-xl font-weight:600 sm:m-0">
          Sign up for The Healing blog
        </h3>
        <h6 className="uppercase mb-4 py-2 font-weight:600">
          A weekly, ad-free Blog that helps you stay in the know.
        </h6>

        <SubsInput className="" />
      </div>

      <div className="flex justify-center mb-10">
        <div className="w-5/6 flex flex-col lg:flex-row justify-between gap-4">
          <div className="w-full lg:w-6/12 relative">
            <img
              className=" "
              title="HEAL FROM TRAUMA"
              src={trauma}
              alt="trauma"
            />
            <span className="absolute bottom-1/4 left-5 w-max ">
              <p className="text-white text-start text-2xl font-bold bg-slate-400 opacity-90">
                HEAL FROM
              </p>
              <p className="text-white text-start text-2xl font-bold bg-slate-400 opacity-90 mt-1">
                TRAUMA
              </p>
            </span>
          </div>
          <div className="w-full lg:w-6/12 relative">
            <img className="" src={anxiety} alt="anxiety" />
            <span className="absolute top-5 left-3 w-2/6">
              <p className="font-medium text-sm md:text-lg text-start">
                TELL ME ALL I NEED TO KNOW ABOUT ANXIETY
              </p>
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Blog;
</code>```

I need to meet the deadline I would be very happy if I get help with styling and responsiveness.

Body:
Hello everyone for a bootcamp project I have created a blog page and while trying to make it responsive, I messed up styling too. I am attaching the figma version, my code and what I get as a reflection. I need your help with styling and responsiveness please.
figma version

what I get

rest of what i get]

import React from 'react';
import meditation from './images/meditation.png';
import trauma from './images/trauma.png';
import anxiety from './images/anxiety.png';
import SubsInput from '../../shared/subsInput/SubsInput';

function Blog() {
  return (

          MENTAL HEALTH AND TECHNOLOGY

          Technology and mental well-being might seem like profoundly
          antagonistic terms. However, there are excellent digital tools to help
          you reach mindfulness and to practice meditation. You can even use
          smartphone apps, virtual reality solutions and digital devices as a
          form of relieving stressing and achieving digital detox – as, after a
          while, you will be able to practice all types of anti-anxiety skills
          on your own. So, let The Medical Futurist show you how you can enhance
          your mental and emotional health with the help of technology.

          THE NEED FOR TAKING CARE OF OUR EMOTIONAL HEALTH

          “Just as we observe physical hygiene to stay well, we need to
          cultivate a kind of emotional hygiene too,” wrote the Dalai Lama on
          his Twitter-feed. There are three crucial points around His Holiness’
          statement. First and foremost, the popularity of health-enhancing,
          physically active lifestyle is soaring worldwide. Nevertheless,
          there’s always room for improvement: the WHO says that globally, 23
          percent of adults and 81 percent of school-going adolescents are not
          active enough. According to the organization, adults aged 18-64 should
          do at least 150 minutes of moderately intense physical activity each
          week, which is not unaccomplishable. Moreover, the numerically and
          statistically driven 21st-century mind could take a great inspiration
          and power from the various fitness trackers and wearables.

          Secondly, emotional hygiene seems to be thrown into the shade
          nowadays. Somehow, the culture of busyness prevents us from squeezing
          some time for mental health into our packed schedules. Information is
          pouring on us from millions of communication channels; we are
          connecting with hundreds of ‘friends’ on social media, we are obsessed
          with data due to the fear of missing out and time management slices up
          our days into meetings and to-do-lists.

          The pressure to perform and the stress to achieve is the air every
          busy-bee is breathing. However, turbulent lifestyle comes with a
          price. No wonder so many people have mental health issues. In the US,
          that means one in five adults – more than 40 million Americans! On the
          old continent, 27 percent of the population has to cope with mental
          disorders, which means 83 million struggling Europeans. In Asia, the
          prevalence of depression is 20 percent in Thailand, 19.9 percent in
          Taiwan, 19.4 percent in Korea, 17.5 in Malaysia and 16.5 percent in
          China.

          Sign up for The Healing blog

          A weekly, ad-free Blog that helps you stay in the know.

        <SubsInput className="" />

                HEAL FROM

                TRAUMA

                TELL ME ALL I NEED TO KNOW ABOUT ANXIETY

  );
}

export default Blog;

I need to meet the deadline I would be very happy if I get help with styling and responsiveness.


问:
Coverage for instance of method
Welcome
Please help how to test the following code

```<code>       if (hazelcastInstance instanceof DummyHazelcastInstance) {
            return joinPoint.proceed();
        }
</code>```

I need to test the scenario when the condition is true

In the test class HazelcastInstance was mocked as below

```<code>    @MockBean(name = "hazelcastClientInstance")
    private HazelcastInstance hazelcastInstance;
</code>```

Title: Coverage for instance of method

Body:
Welcome
Please help how to test the following code

       if (hazelcastInstance instanceof DummyHazelcastInstance) {
            return joinPoint.proceed();
        }

I need to test the scenario when the condition is true

In the test class HazelcastInstance was mocked as below

    @MockBean(name = "hazelcastClientInstance")
    private HazelcastInstance hazelcastInstance;


问:
Change Redirect URI of Identity Provider in Keycloak
Whenever we configure Identity Provider in KeyCloak, it automatically sets Redirect URI like

http://keyclaok:8080/auth/realms/{MY_REALM}/broker/google/endpoint

I am implementing multi-tenancy in the project. For every tenant, I will have a separate realm and in turn, have a separate Redirect URI.

For this to work, I need to configure the same URL in "Authorized Redirect URLs" in Google Cloud Platform Console.

To ensure KeyCloak's IDP Redirect URI and Google console's configured Authorized URL match, there are 2 possible options

Dynamically(programmatically) configure Authorized Redirect URL in Google console when new tenant/realm is created. As far as I know, there is no way to dynamically set this authorized redirect URL. So this doesn't look like a viable option.

Configure custom redirect URI in KeyCloak. However, Keycloak doesn't seem to allow changing Redirect URI for Identity Provider.

Any solution, workaround or hints would be appreciated. I feel this is not a unique problem that I am solving. It must be already done and solved by many.


问:
Show Laravel Horizon jobs data
After I configured Horizon to run jobs from Redis queue I can't see any logs from my jobs but I found the some suitable for me view on Horizon dashboard. I want to show there some data that I printed before to a job's log. How to configure a job to set the data field on the screenshoot?

Job's handle method just return some data but it isn't got to the view. The job's code is:

```<code>class UpdateBalanceValuesAnalyticsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the middleware the job should pass through.
     *
     * @return array
     */
    public function middleware()
    {
        return [(new WithoutOverlapping('UpdateBalanceValuesAnalyticsJob'))->dontRelease()];
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $hbs = HistoricalBalance::where('watch', true)->get();

        $needProcNum =
            $hbs->map(function($hb) {
                return
                    $hb->values()->hasNotAnalytics()
                    ->orWhere(function ($query) {
                        $query->analyticsInvalidated();
                    })
                    ->count();
            })->sum();

        Log::channel('job')->info('handle UpdateBalanceValuesAnalyticsJob, processing '
            .$needProcNum.' HistoryBalanceValues');

        $alreadyReady = 0;
        foreach($hbs as $hb) {
            $userAnalytics = $hb->analytics();
            $values = $userAnalytics->valuesWithAnalyticsCalculateIncr();
            $alreadyReady += $values->count();
            Log::channel('job')->info("[$alreadyReady / $needProcNum] UpdateBalanceValuesAnalyticsJob", [
                'status' => 'calculation updated'
            ]);
        }

        Log::channel('job')->info('finish handle UpdateBalanceValuesAnalyticsJob');
        return 123;
    }
}
</code>```

And Horizon config is:

```<code>'defaults' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['default'],
            'balance' => 'auto',
            'maxProcesses' => 1,
            'maxTime' => 0,
            'maxJobs' => 0,
            'memory' => 128,
            'tries' => 1,
            'timeout' => 60,
            'nice' => 0,
        ],
    ],

    'environments' => [
        'production' => [
            'supervisor-1' => [
                'maxProcesses' => 10,
                'balanceMaxShift' => 1,
                'balanceCooldown' => 3,
            ],
        ],

        'local' => [
            'supervisor-1' => [
                'maxProcesses' => 3,
            ],
        ],
    ],
</code>```

Title: Show Laravel Horizon jobs data

Body:
After I configured Horizon to run jobs from Redis queue I can't see any logs from my jobs but I found the some suitable for me view on Horizon dashboard. I want to show there some data that I printed before to a job's log. How to configure a job to set the data field on the screenshoot?

Job's handle method just return some data but it isn't got to the view. The job's code is:

class UpdateBalanceValuesAnalyticsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the middleware the job should pass through.
     *
     * @return array
     */
    public function middleware()
    {
        return [(new WithoutOverlapping('UpdateBalanceValuesAnalyticsJob'))->dontRelease()];
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $hbs = HistoricalBalance::where('watch', true)->get();

        $needProcNum =
            $hbs->map(function($hb) {
                return
                    $hb->values()->hasNotAnalytics()
                    ->orWhere(function ($query) {
                        $query->analyticsInvalidated();
                    })
                    ->count();
            })->sum();

        Log::channel('job')->info('handle UpdateBalanceValuesAnalyticsJob, processing '
            .$needProcNum.' HistoryBalanceValues');

        $alreadyReady = 0;
        foreach($hbs as $hb) {
            $userAnalytics = $hb->analytics();
            $values = $userAnalytics->valuesWithAnalyticsCalculateIncr();
            $alreadyReady += $values->count();
            Log::channel('job')->info("[$alreadyReady / $needProcNum] UpdateBalanceValuesAnalyticsJob", [
                'status' => 'calculation updated'
            ]);
        }

        Log::channel('job')->info('finish handle UpdateBalanceValuesAnalyticsJob');
        return 123;
    }
}

And Horizon config is:

'defaults' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['default'],
            'balance' => 'auto',
            'maxProcesses' => 1,
            'maxTime' => 0,
            'maxJobs' => 0,
            'memory' => 128,
            'tries' => 1,
            'timeout' => 60,
            'nice' => 0,
        ],
    ],

    'environments' => [
        'production' => [
            'supervisor-1' => [
                'maxProcesses' => 10,
                'balanceMaxShift' => 1,
                'balanceCooldown' => 3,
            ],
        ],

        'local' => [
            'supervisor-1' => [
                'maxProcesses' => 3,
            ],
        ],
    ],


问:
C GCC Prevent name conflict between enum and macro
This question is a searching for robust approach to prevent such errors in existing and new projects. A code bellow illustrate the problem. GCC compiler show warning only if macro are conflicts but when it enum vs macro - no.

I can't found gcc -Wxxx options to get warnings for such conflicts.

It's possible to use macro with __COUNTER__ instead of enum.

It's possible to change format rules for enum names.

But it's helpful solutions only for new projects.

What I can do with old projects ?

enum my_enum {
    NONE = -1,
// #define NONE -1

    ONE = 1,
    TWO,
    THREE,
};

// use name NONE something else in included header
#define NONE 2

#include "stdio.h"

int main(void)
{
    printf("NONE is %d, it's %s\n",
        NONE,
        (-1 == NONE) ? "OK" : "FAIL");

    return 0;
}
```
<p>So result with commented macro <code>NONE -1</code>:</p>
```gcc ./c-test.c -o c-test && ./c-test
NONE is 2, it's FAIL
```
<p>And uncommented.</p>
```gcc ./c-test.c -o c-test && ./c-test
./c-test.c:11: warning: "NONE" redefined
   11 | #define NONE 2
      |
./c-test.c:4: note: this is the location of the previous definition
    4 | #define NONE -1
      |
```

Env:

Linux 5.4.0-132-generic #148-Ubuntu

gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0

Body:
This question is a searching for robust approach to prevent such errors in existing and new projects. A code bellow illustrate the problem. GCC compiler show warning only if macro are conflicts but when it enum vs macro - no.

I can't found gcc -Wxxx options to get warnings for such conflicts.

It's possible to use macro with __COUNTER__ instead of enum.

It's possible to change format rules for enum names.

But it's helpful solutions only for new projects.

What I can do with old projects ?

enum my_enum {
    NONE = -1,
// #define NONE -1

    ONE = 1,
    TWO,
    THREE,
};

// use name NONE something else in included header
#define NONE 2

#include "stdio.h"

int main(void)
{
    printf("NONE is %d, it's %s\n",
        NONE,
        (-1 == NONE) ? "OK" : "FAIL");

    return 0;
}

So result with commented macro NONE -1:

gcc ./c-test.c -o c-test && ./c-test
NONE is 2, it's FAIL

And uncommented.

gcc ./c-test.c -o c-test && ./c-test
./c-test.c:11: warning: "NONE" redefined
   11 | #define NONE 2
      |
./c-test.c:4: note: this is the location of the previous definition
    4 | #define NONE -1
      |

Env:

Linux 5.4.0-132-generic #148-Ubuntu

gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0


问:
How to parallelly send data from pyspark dataframe to kinesis putRecord using boto3 in AWS Glue
Trying to send json data from pyspark dataframe to kinesis putrecord using boto3.

Was able to write a for loop for the same here's the code

```<code>for value in DataFrame.toJSON().toLocalIterator():
jsondict=json.loads(value)
#   Send message to Kinesis DataStream
client = boto3.client('kinesis')
response = client.put_record(
    StreamName = "kinesisStreamname",
    Data = bytes(json.dumps(jsondict), 'utf-8'),
    PartitionKey = str('part_key')
    )
</code>```

But since for-loop is being executed in master node it does not run parallely in worker node.

Tried map and foreach of pyspark dataframe but It's not yet working.
Here's the sample code I tried.

```<code>def pushToKinesis(value):
#  jsondict=json.loads(value)
 client = boto3.client('kinesis')
 response = client.put_record(
     StreamName = "kinesis_streamName",
     Data = bytes(json.dumps("test"), 'utf-8'),
     PartitionKey = str('part_key')
    )

rdd = jsonMapDataFrame.toJSON().map(pushToKinesis)
</code>```

Running in Aws glue and sending data to kinesis using Boto3

Body:
Trying to send json data from pyspark dataframe to kinesis putrecord using boto3.

Was able to write a for loop for the same here's the code

for value in DataFrame.toJSON().toLocalIterator():
jsondict=json.loads(value)
#   Send message to Kinesis DataStream
client = boto3.client('kinesis')
response = client.put_record(
    StreamName = "kinesisStreamname",
    Data = bytes(json.dumps(jsondict), 'utf-8'),
    PartitionKey = str('part_key')
    )

But since for-loop is being executed in master node it does not run parallely in worker node.

Tried map and foreach of pyspark dataframe but It's not yet working.
Here's the sample code I tried.

def pushToKinesis(value):
#  jsondict=json.loads(value)
 client = boto3.client('kinesis')
 response = client.put_record(
     StreamName = "kinesis_streamName",
     Data = bytes(json.dumps("test"), 'utf-8'),
     PartitionKey = str('part_key')
    )

rdd = jsonMapDataFrame.toJSON().map(pushToKinesis)

Running in Aws glue and sending data to kinesis using Boto3


问:
Problem when uploading XML (mixed properties)
I have a little problem when I try to upload XML file to BaseLinker.
The problem is that the properties in XML are mixed, for example one time property name of price is 4th, next time is 6th or 8th. Because of it BaseLinker didn't upload it correctly.

Some of my XML :

```<code><property name="grubość">1</property>
<property name="grubość ścianki">1</property>
<property name="średnica">400</property>
<property name="wysokość">400</property>
<property name="Pojemność (l)">50</property>
<property name="opis">400</property>
<property name="wymiary zewnętrzne">400</property>
<property name="waga">50</property>
<property name="wymiary">1</property>
<property name="moc">1</property>
<property name="napięcie">400x/400h</property>
<property name="categoryId">194</property>
<property name="productCode">832806</property>
<property name="largeSize">0</property>
<property name="tillStockLasts">0</property>
<property name="basePrice">749.00</property>
<property name="productId">950</property>
</code>```

other line :

```<code><property name="wysokość">450</property>
<property name="wymiary zewnętrzne">śr. 450x(H) 450 </property>
<property name="Pojemność (l)">70</property>
<property name="wymiary">śr.450x(H)450</property>
<property name="categoryId">194</property>
<property name="productCode">832929</property>
<property name="largeSize">0</property>
<property name="tillStockLasts">0</property>
<property name="basePrice">849.00</property>
<property name="productId">950</property>
</code>```

Is it possible to parse it or use java program that can sort it in correct order?
For example I wanna have XML of properties like :
property name="wysokość" property name="szerokosc" property name="productCode" property name="productID"

and so on...

Body:
I have a little problem when I try to upload XML file to BaseLinker.
The problem is that the properties in XML are mixed, for example one time property name of price is 4th, next time is 6th or 8th. Because of it BaseLinker didn't upload it correctly.

Some of my XML :

<property name="grubość">1</property>
<property name="grubość ścianki">1</property>
<property name="średnica">400</property>
<property name="wysokość">400</property>
<property name="Pojemność (l)">50</property>
<property name="opis">400</property>
<property name="wymiary zewnętrzne">400</property>
<property name="waga">50</property>
<property name="wymiary">1</property>
<property name="moc">1</property>
<property name="napięcie">400x/400h</property>
<property name="categoryId">194</property>
<property name="productCode">832806</property>
<property name="largeSize">0</property>
<property name="tillStockLasts">0</property>
<property name="basePrice">749.00</property>
<property name="productId">950</property>

other line :

<property name="wysokość">450</property>
<property name="wymiary zewnętrzne">śr. 450x(H) 450 </property>
<property name="Pojemność (l)">70</property>
<property name="wymiary">śr.450x(H)450</property>
<property name="categoryId">194</property>
<property name="productCode">832929</property>
<property name="largeSize">0</property>
<property name="tillStockLasts">0</property>
<property name="basePrice">849.00</property>
<property name="productId">950</property>

Is it possible to parse it or use java program that can sort it in correct order?
For example I wanna have XML of properties like :
property name="wysokość" property name="szerokosc" property name="productCode" property name="productID"

and so on...


问:
Http request boundaries getting caught in pdf decoding process
I'm trying to decode a base64 pdf file and send it to another endpoint.
I used a python policy for the decoding part and here's the code

```<code>import base64

pdfB64 = flow.getVariable("request.content")

pdfFile = base64.b64decode(pdfB64)
flow.setVariable("pdfFileDecoded",pdfFile)
</code>```

Now, when I send my http post request which is below

```<code>headers :
Accept : */*
boundary : --Boundaryy

--Boundaryy
Content-Disposition: form-data; name="testdu12janvier"; filename="testdu12janvier.pdf"

Content-Type: application/pdf

<< Heres is sensitive data which is basically a base64 encoded pdf file >>

--Boundaryy--
</code>```

When I send this POST request and trace it in Apigee Edge, I notice that something else is encoded before the pdf file I think its either the boundary or one of the headers. This makes a corrupt pdf file which can't be read.

How do I isolate the pdf file from the request body without removing boundaries? as I'll need to send multiple in near future.

Body:
I'm trying to decode a base64 pdf file and send it to another endpoint.
I used a python policy for the decoding part and here's the code

import base64

pdfB64 = flow.getVariable("request.content")

pdfFile = base64.b64decode(pdfB64)
flow.setVariable("pdfFileDecoded",pdfFile)

Now, when I send my http post request which is below

headers :
Accept : */*
boundary : --Boundaryy

--Boundaryy
Content-Disposition: form-data; name="testdu12janvier"; filename="testdu12janvier.pdf"

Content-Type: application/pdf

<< Heres is sensitive data which is basically a base64 encoded pdf file >>

--Boundaryy--

When I send this POST request and trace it in Apigee Edge, I notice that something else is encoded before the pdf file I think its either the boundary or one of the headers. This makes a corrupt pdf file which can't be read.

How do I isolate the pdf file from the request body without removing boundaries? as I'll need to send multiple in near future.


问:
How to work with NugetPackage and LocalProject at same time?
I got an issue working with Nuget packages and local projects.

I am working on a .Net Framework solution, with many projects and many of them are packaged with Nuget in a private repository. I am using PackageReferences to resolve nuget packages. I am working on solution with that kind of dependency tree.

StartUpProject

Project1(LocalProject)

Project2 v1.0.0(NugetPackage)

Project3 v1.0.0(NugetPackage)

Project3 v1.0.1(LocalProject)

When I want to debug or upgrade functionality of packaged project, I remove Nuget package and add that assembly as local project.

When I am navigating in the source code if I try to go to some function from the modified project, Visual Studio open the code as external assembly and does not resolve like local project.

Maybe the problem is other Nuget package (Project2) depends from I removed Nuget package (Project3) and Visual Studio still resolving that assembly as Nuget package.

The error that Visual Studio throws at compilation is CS0433: The type 'MyType' exist in both'Project3 , Version=1.0.0, ...' and in 'Project3, Version=1.0.1, ...'

What is way to work in that cases?
Is any way to force to use local project than dependency nuget package?

Thank you!


问:
How to upload existing .tgz file into nexus3
I have already created an npm repository in Nexus3. According to my scenario, I have a build command to run then it is created as a dist folder. Under this folder, I have .tgz file. I need to upload this .tgz file to Nexus. I set up my package.json file as follows,

```<code>  "publishConfig": {
    "registry": "http://localhost:8081/repository/npm-private/"
  },
  "bin": "./dist/apps/theme-builder-app/my-theme-builder-0.0.3.tgz"
</code>```

my .npmrc file is also working correctly.

Then I ran the command npm publish. After that whole project was uploaded into the nexus except my files :(

Then I configured the .npmignore as follows,

```<code>*
!./dist/apps/theme-builder-app/bst-theme-builder-0.0.3.tgz

!*/bst-theme-builder-0.0.3.tgz
</code>```

That also not working.

I have attached my folder structure below, and I figured out which file I want to upload to the nexus3.

Body:
I have already created an npm repository in Nexus3. According to my scenario, I have a build command to run then it is created as a dist folder. Under this folder, I have .tgz file. I need to upload this .tgz file to Nexus. I set up my package.json file as follows,

  "publishConfig": {
    "registry": "http://localhost:8081/repository/npm-private/"
  },
  "bin": "./dist/apps/theme-builder-app/my-theme-builder-0.0.3.tgz"

my .npmrc file is also working correctly.

Then I ran the command npm publish. After that whole project was uploaded into the nexus except my files :(

Then I configured the .npmignore as follows,

*
!./dist/apps/theme-builder-app/bst-theme-builder-0.0.3.tgz

!*/bst-theme-builder-0.0.3.tgz

That also not working.

I have attached my folder structure below, and I figured out which file I want to upload to the nexus3.


问:
Is there any option to exclude certain stdout(print statements) based on keyword in pytest
I am using -s option while executing pytest script.
I get lot of statements outputted to my command line due to a tool setup which is imported in pytest script.
I want to exclude those statements from printing, For example: I want to exclude statements with words like "Info". Is there any way to do it?


问:
Login to website to download a file (credential required, session_id required, javascript form)
I am trying to login to a website remotely and download a file which is stored on website and downloadable after login. As I realized, the form is in javascript and there can be a problem with login via invoke-weburl. Can you guys help me please?

```<code>`$webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession
 $webrequest.Forms['login_form'].Fields['login'] = $username
 $webrequest.Forms['login_form'].Fields['heslo'] = $password
 $cookies = $websession.Cookies.GetCookies($url)

 # Portal login URL
 $url = "https://velkoobchod.brwcz.cz"

 # Feed URL and local destination to save a file
 $xml = "https://velkoobchod.brwcz.cz/cs/ostatni/export?akce=stahniXml"
 $dest = "C:\Users\xxx\brwcz.xml"

 # Define username and password
 $username = 'username'
 $password = 'login'

 # Convert to SecureString
 $secPassword = ConvertTo-SecureString $password -AsPlainText -Force

 # Create Credential Object
 $cred = New-Object System.Management.Automation.PSCredential ($username, $secPassword)

 $webrequest = Invoke-WebRequest -Uri $url -UseBasicParsing -SessionVariable websession
 $cookies = $websession.Cookies.GetCookies($url)

 # Login
 $result = Invoke-WebRequest -Uri ($url + $form.Action) -UseBasicParsing -WebSession $websession -Method 'post' -Credential $cred
 $result.ParsedHtml

 Write-Output $cookies
 $webrequest.InputFields
 $result.StatusCode
 `
</code>```

I can't pass the login form.

If a file is downloaded, the is still a login form with a comment that I have to enable javascript.

Body:
I am trying to login to a website remotely and download a file which is stored on website and downloadable after login. As I realized, the form is in javascript and there can be a problem with login via invoke-weburl. Can you guys help me please?

`$webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession
 $webrequest.Forms['login_form'].Fields['login'] = $username
 $webrequest.Forms['login_form'].Fields['heslo'] = $password
 $cookies = $websession.Cookies.GetCookies($url)

 # Portal login URL
 $url = "https://velkoobchod.brwcz.cz"

 # Feed URL and local destination to save a file
 $xml = "https://velkoobchod.brwcz.cz/cs/ostatni/export?akce=stahniXml"
 $dest = "C:\Users\xxx\brwcz.xml"

 # Define username and password
 $username = 'username'
 $password = 'login'

 # Convert to SecureString
 $secPassword = ConvertTo-SecureString $password -AsPlainText -Force

 # Create Credential Object
 $cred = New-Object System.Management.Automation.PSCredential ($username, $secPassword)

 $webrequest = Invoke-WebRequest -Uri $url -UseBasicParsing -SessionVariable websession
 $cookies = $websession.Cookies.GetCookies($url)

 # Login
 $result = Invoke-WebRequest -Uri ($url + $form.Action) -UseBasicParsing -WebSession $websession -Method 'post' -Credential $cred
 $result.ParsedHtml

 Write-Output $cookies
 $webrequest.InputFields
 $result.StatusCode
 `

I can't pass the login form.

If a file is downloaded, the is still a login form with a comment that I have to enable javascript.


问:
Why does my docker container have files from a different image?
My application requires two docker files. I am building them with docker compose. The compose file is like this

```<code>version: '3.4'
services:
  cors:
    container_name: cors
    image: cors:latest
    build:
      context: ./compose/cors-anywhere
      dockerfile: Dockerfile
    user: "node"
    ports:
      - 8081:8081
    command: node server.js
  vite:
    container_name: vite
    image: vite:lts
    build:
      context: ./compose/vite
    user: "node"
    tty: true
    working_dir: /app
    ports:
      - "5173:5173"
    volumes:
      - ./vite/:/app
    command: /start
</code>```

cors' Dockerfile is like this

```<code>ARG NODE_VERSION=lts

FROM node:${NODE_VERSION}

ENV NODE_ENV=production
ENV NODE_PATH=/usr/local/lib/node_modules
ARG version=latest
RUN npm install -g cors-anywhere@$version
COPY server.js .
CMD ["node", "server.js"]

EXPOSE 8081
</code>```

and vite's docker file is like this

```<code>ARG NODE_VERSION=latest

FROM node:${NODE_VERSION}

RUN npm install -g npm@latest

COPY ./entrypoint /entrypoint
RUN sed -i 's/\r$//g' /entrypoint
RUN chmod +x /entrypoint

COPY ./start /start
RUN sed -i 's/\r$//g' /start
RUN chmod +x /start

ENTRYPOINT ["/entrypoint"]
</code>```

vite's entrypoint script is like this

```<code>#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset

until cd /app && npm install
do
    echo "Retrying npm install"
done

exec "$@"
</code>```

After the images have been built, when the cors container comes 'up' it logs lots of errors because it is trying to run vite's entrypoint script. I don't understand why entrypoint has been copied to the cors image. Here is the file structure for the cors container

```<code>node@d960251bf35e:/$ ls -l
total 80
drwxr-xr-x   1 root root 4096 Jan 11 03:25 bin
drwxr-xr-x   2 root root 4096 Dec  9 19:15 boot
drwxr-xr-x   5 root root  340 Jan 12 10:52 dev
-rwxr-xr-x   1 root root  139 Jan 11 21:59 entrypoint
drwxr-xr-x   1 root root 4096 Jan 12 10:52 etc
drwxr-xr-x   1 root root 4096 Jan 11 07:59 home
drwxr-xr-x   1 root root 4096 Jan 11 03:25 lib
drwxr-xr-x   2 root root 4096 Jan  9 00:00 media
drwxr-xr-x   2 root root 4096 Jan  9 00:00 mnt
drwxr-xr-x   1 root root 4096 Jan 11 07:59 opt
dr-xr-xr-x 211 root root    0 Jan 12 10:52 proc
drwx------   1 root root 4096 Jan 11 07:59 root
drwxr-xr-x   3 root root 4096 Jan  9 00:00 run
drwxr-xr-x   1 root root 4096 Jan 11 03:24 sbin
-rw-r--r--   1 root root 2023 Jan 11 15:24 server.js
drwxr-xr-x   2 root root 4096 Jan  9 00:00 srv
-rwxr-xr-x   1 root root   71 Jan 11 21:59 start
dr-xr-xr-x  13 root root    0 Jan 12 10:52 sys
drwxrwxrwt   1 root root 4096 Jan 11 07:59 tmp
drwxr-xr-x   1 root root 4096 Jan  9 00:00 usr
drwxr-xr-x   1 root root 4096 Jan  9 00:00 var
</code>```

What am I not understanding?

Body:
My application requires two docker files. I am building them with docker compose. The compose file is like this

version: '3.4'
services:
  cors:
    container_name: cors
    image: cors:latest
    build:
      context: ./compose/cors-anywhere
      dockerfile: Dockerfile
    user: "node"
    ports:
      - 8081:8081
    command: node server.js
  vite:
    container_name: vite
    image: vite:lts
    build:
      context: ./compose/vite
    user: "node"
    tty: true
    working_dir: /app
    ports:
      - "5173:5173"
    volumes:
      - ./vite/:/app
    command: /start

cors' Dockerfile is like this

ARG NODE_VERSION=lts

FROM node:${NODE_VERSION}

ENV NODE_ENV=production
ENV NODE_PATH=/usr/local/lib/node_modules
ARG version=latest
RUN npm install -g cors-anywhere@$version
COPY server.js .
CMD ["node", "server.js"]

EXPOSE 8081

and vite's docker file is like this

ARG NODE_VERSION=latest

FROM node:${NODE_VERSION}

RUN npm install -g npm@latest

COPY ./entrypoint /entrypoint
RUN sed -i 's/\r$//g' /entrypoint
RUN chmod +x /entrypoint

COPY ./start /start
RUN sed -i 's/\r$//g' /start
RUN chmod +x /start

ENTRYPOINT ["/entrypoint"]

vite's entrypoint script is like this

#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset

until cd /app && npm install
do
    echo "Retrying npm install"
done

exec "$@"

After the images have been built, when the cors container comes 'up' it logs lots of errors because it is trying to run vite's entrypoint script. I don't understand why entrypoint has been copied to the cors image. Here is the file structure for the cors container

node@d960251bf35e:/$ ls -l
total 80
drwxr-xr-x   1 root root 4096 Jan 11 03:25 bin
drwxr-xr-x   2 root root 4096 Dec  9 19:15 boot
drwxr-xr-x   5 root root  340 Jan 12 10:52 dev
-rwxr-xr-x   1 root root  139 Jan 11 21:59 entrypoint
drwxr-xr-x   1 root root 4096 Jan 12 10:52 etc
drwxr-xr-x   1 root root 4096 Jan 11 07:59 home
drwxr-xr-x   1 root root 4096 Jan 11 03:25 lib
drwxr-xr-x   2 root root 4096 Jan  9 00:00 media
drwxr-xr-x   2 root root 4096 Jan  9 00:00 mnt
drwxr-xr-x   1 root root 4096 Jan 11 07:59 opt
dr-xr-xr-x 211 root root    0 Jan 12 10:52 proc
drwx------   1 root root 4096 Jan 11 07:59 root
drwxr-xr-x   3 root root 4096 Jan  9 00:00 run
drwxr-xr-x   1 root root 4096 Jan 11 03:24 sbin
-rw-r--r--   1 root root 2023 Jan 11 15:24 server.js
drwxr-xr-x   2 root root 4096 Jan  9 00:00 srv
-rwxr-xr-x   1 root root   71 Jan 11 21:59 start
dr-xr-xr-x  13 root root    0 Jan 12 10:52 sys
drwxrwxrwt   1 root root 4096 Jan 11 07:59 tmp
drwxr-xr-x   1 root root 4096 Jan  9 00:00 usr
drwxr-xr-x   1 root root 4096 Jan  9 00:00 var

What am I not understanding?


问:
How to set the right type for PayloadAction?
I'm trying to set the type for PayloadAction<LoginError> as the payload for when I get an error from logging in is:

```<code>{
    message: string,
    status: number,
}
</code>```

In my code, I defined a type for that payload as LoginError, and added it as the type for login.rejected

```<code>type LoginResponse = {
    data: UserLogin
}

type LoginError = {
    status: number;
    message: string;
}

export interface AuthInterface {
    loading: boolean;
    userToken: boolean | null;
    error: LoginError | null;
    success: boolean;
}

export interface AuthState {
    auth: AuthInterface;
}

const initialState: AuthState = {
    auth: {
        loading: false,
        userToken: null,
        error: null,
        success: false,
    }
}

export const login = createAsyncThunk(
    "auth/login",
    async (loginData: LoginData, thunkAPI: any) => {
        try {
            const { email, password } = loginData;
            //config, data, headers, request, status, statusText
            //{ data: resData, headers: resHeaders }
            const { data: resData, headers: resHeaders } = await serveraxios.post<LoginResponse>(
                "/login",
                {
                    email: email,
                    password: password,
                },
                {
                    withCredentials: true
                }
            );
            console.log(resData);
            console.log(resHeaders);
            return resData;
        }
        catch (error: any) {
            console.log(error);
            console.log(thunkAPI.rejectWithValue(error.message));
            return thunkAPI.rejectWithValue({
                status: error.response.data.status,
                message: error.response.data.message,
            });
        }
    }
)

export const logout = createAsyncThunk(
    "auth/logout",
    async() => {
        const res = await serveraxios.post(
            "logout",
            undefined,
            {
                withCredentials: true
            }
        );
        console.log(res);
    }
)

export const authSlice = createSlice({
    name: "auth",
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
        .addCase(login.fulfilled, (state, action: PayloadAction<UserLogin>) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = true;
        })
        .addCase(login.rejected, (state, action: PayloadAction<LoginError>) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = false;
            state.auth.error = action.payload;
        })

    }
});

export const selectAuth = (state: RootState) => state.auth.auth;
export default authSlice.reducer;
</code>```

However, i get the following error:

```<code>No overload matches this call.
  Overload 1 of 2, '(actionCreator: AsyncThunkRejectedActionCreator<LoginData, AsyncThunkConfig>, reducer: CaseReducer<AuthState, PayloadAction<...>>): ActionReducerMapBuilder<...>', gave the following error.
    Argument of type '(state: WritableDraft<AuthState>, action: { payload: LoginError; type: string; }) => void' is not assignable to parameter of type 'CaseReducer<AuthState, PayloadAction<unknown, string, { arg: LoginData; requestId: string; requestStatus: "rejected"; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true; } | ({ ...; } & {})), SerializedError>>'.
      Types of parameters 'action' and 'action' are incompatible.
        Type 'PayloadAction<unknown, string, { arg: LoginData; requestId: string; requestStatus: "rejected"; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true; } | ({ rejectedWithValue: false; } & {})), SerializedError>' is not assignable to type '{ payload: LoginError; type: string; }'.
          Types of property 'payload' are incompatible.
            Type 'unknown' is not assignable to type 'LoginError'.
  Overload 2 of 2, '(type: string, reducer: CaseReducer<AuthState, { payload: LoginError; type: string; }>): ActionReducerMapBuilder<AuthState>', gave the following error.
    Argument of type 'AsyncThunkRejectedActionCreator<LoginData, AsyncThunkConfig>' is not assignable to parameter of type 'string'.ts(2769)
</code>```

However when I assign the type to PayloadAction as any as in: PayloadAction<any> I dont get any error.

Could someone explain to me how to set the correct type for my PayloadAction?

Body:
I'm trying to set the type for PayloadAction<LoginError> as the payload for when I get an error from logging in is:

{
    message: string,
    status: number,
}

In my code, I defined a type for that payload as LoginError, and added it as the type for login.rejected

type LoginResponse = {
    data: UserLogin
}

type LoginError = {
    status: number;
    message: string;
}

export interface AuthInterface {
    loading: boolean;
    userToken: boolean | null;
    error: LoginError | null;
    success: boolean;
}

export interface AuthState {
    auth: AuthInterface;
}

const initialState: AuthState = {
    auth: {
        loading: false,
        userToken: null,
        error: null,
        success: false,
    }
}

export const login = createAsyncThunk(
    "auth/login",
    async (loginData: LoginData, thunkAPI: any) => {
        try {
            const { email, password } = loginData;
            //config, data, headers, request, status, statusText
            //{ data: resData, headers: resHeaders }
            const { data: resData, headers: resHeaders } = await serveraxios.post<LoginResponse>(
                "/login",
                {
                    email: email,
                    password: password,
                },
                {
                    withCredentials: true
                }
            );
            console.log(resData);
            console.log(resHeaders);
            return resData;
        }
        catch (error: any) {
            console.log(error);
            console.log(thunkAPI.rejectWithValue(error.message));
            return thunkAPI.rejectWithValue({
                status: error.response.data.status,
                message: error.response.data.message,
            });
        }
    }
)

export const logout = createAsyncThunk(
    "auth/logout",
    async() => {
        const res = await serveraxios.post(
            "logout",
            undefined,
            {
                withCredentials: true
            }
        );
        console.log(res);
    }
)

export const authSlice = createSlice({
    name: "auth",
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
        .addCase(login.fulfilled, (state, action: PayloadAction<UserLogin>) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = true;
        })
        .addCase(login.rejected, (state, action: PayloadAction<LoginError>) => {
            console.log(action.payload);
            state.auth.loading = false;
            state.auth.success = false;
            state.auth.error = action.payload;
        })

    }
});

export const selectAuth = (state: RootState) => state.auth.auth;
export default authSlice.reducer;

However, i get the following error:

No overload matches this call.
  Overload 1 of 2, '(actionCreator: AsyncThunkRejectedActionCreator<LoginData, AsyncThunkConfig>, reducer: CaseReducer<AuthState, PayloadAction<...>>): ActionReducerMapBuilder<...>', gave the following error.
    Argument of type '(state: WritableDraft<AuthState>, action: { payload: LoginError; type: string; }) => void' is not assignable to parameter of type 'CaseReducer<AuthState, PayloadAction<unknown, string, { arg: LoginData; requestId: string; requestStatus: "rejected"; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true; } | ({ ...; } & {})), SerializedError>>'.
      Types of parameters 'action' and 'action' are incompatible.
        Type 'PayloadAction<unknown, string, { arg: LoginData; requestId: string; requestStatus: "rejected"; aborted: boolean; condition: boolean; } & ({ rejectedWithValue: true; } | ({ rejectedWithValue: false; } & {})), SerializedError>' is not assignable to type '{ payload: LoginError; type: string; }'.
          Types of property 'payload' are incompatible.
            Type 'unknown' is not assignable to type 'LoginError'.
  Overload 2 of 2, '(type: string, reducer: CaseReducer<AuthState, { payload: LoginError; type: string; }>): ActionReducerMapBuilder<AuthState>', gave the following error.
    Argument of type 'AsyncThunkRejectedActionCreator<LoginData, AsyncThunkConfig>' is not assignable to parameter of type 'string'.ts(2769)

However when I assign the type to PayloadAction as any as in: PayloadAction<any> I dont get any error.

Could someone explain to me how to set the correct type for my PayloadAction?


问:
Migration from tomcat 7 to tomcat 10
For migration, I updated javax imports to corresponding jakarta. It's failing with 500 internal server error while calling POST service

Code snippet from service class

```<code>import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/m1")
    @POST
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public String sayHello(AcceptRequest request, @HeaderParam("Accept") String contentType) {
        logger.info("Invoked API : /sayHello");
        return "Hello";

    }
</code>```

Code snippet of DAO

```<code>import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementWrapper;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlAccessType;
@XmlRootElement(name="feature")
@XmlAccessorType(XmlAccessType.FIELD)
public class AcceptRequest {
    private static final Logger logger = LogManager.getLogger(AcceptRequest.class);

    @XmlElement(required = true)
    public String a;

    @XmlElement(required = true)
    public String b;

    @XmlElement(required = true)
    public String c;
}

</code>```

During execution we are not even getting  "Invoked API : /sayHello" logger line.

Title: Migration from tomcat 7 to tomcat 10

Body:
For migration, I updated javax imports to corresponding jakarta. It's failing with 500 internal server error while calling POST service

Code snippet from service class

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/m1")
    @POST
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public String sayHello(AcceptRequest request, @HeaderParam("Accept") String contentType) {
        logger.info("Invoked API : /sayHello");
        return "Hello";

    }

Code snippet of DAO

import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementWrapper;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlAccessType;
@XmlRootElement(name="feature")
@XmlAccessorType(XmlAccessType.FIELD)
public class AcceptRequest {
    private static final Logger logger = LogManager.getLogger(AcceptRequest.class);

    @XmlElement(required = true)
    public String a;

    @XmlElement(required = true)
    public String b;

    @XmlElement(required = true)
    public String c;
}

During execution we are not even getting  "Invoked API : /sayHello" logger line.


问:
Get url path from guzzleHttp requestAsync after setup
I've a problem using guzzleHttp with multiple requests. I want to get the path of an url after setup the request but before sending it. Here's my code:

```<code>include "../../vendor/autoload.php";

use GuzzleHttp\Client;

/* Initiate Guzzle Client */
$client = new Client([
    "verify" => false, // disable ssl certificate verification
    "timeout" => 30, // maximum timeout for requests
    "http_errors" => false, // disable exceptions
    ]);

$requests      = [];
$requests["a"] = $client->requestAsync('GET', "https://www.aaa.de/aaa.html");
$requests["b"] = $client->requestAsync('GET', "https://www.bbb.de/bbb.html");
$requests["c"] = $client->requestAsync('GET', "https://www.ccc.de/ccc.html");

$content = performMultiRequest($requests);

function performMultiRequest($requests)
{

    foreach ($requests as $key => $object) {
        print_r($object);
        exit;
    }

    /**
     * here comes more to send the requests, but that doesn't care for this problem
     */
}
</code>```

In this case I get a GuzzleHttp\Promise\Promise Object. My goal is to get only the path /aaa.html from $object. It must be found inside the function performMultiRequest(). There's no chance to read and parse the url before, e.g. when the requestAsync() is used.

This is the relevant part of $object I need:

I tried SO, Guzzle documentation, google, trail & error... nothing found... any ideas?

Body:
I've a problem using guzzleHttp with multiple requests. I want to get the path of an url after setup the request but before sending it. Here's my code:

include "../../vendor/autoload.php";

use GuzzleHttp\Client;

/* Initiate Guzzle Client */
$client = new Client([
    "verify" => false, // disable ssl certificate verification
    "timeout" => 30, // maximum timeout for requests
    "http_errors" => false, // disable exceptions
    ]);

$requests      = [];
$requests["a"] = $client->requestAsync('GET', "https://www.aaa.de/aaa.html");
$requests["b"] = $client->requestAsync('GET', "https://www.bbb.de/bbb.html");
$requests["c"] = $client->requestAsync('GET', "https://www.ccc.de/ccc.html");

$content = performMultiRequest($requests);

function performMultiRequest($requests)
{

    foreach ($requests as $key => $object) {
        print_r($object);
        exit;
    }

    /**
     * here comes more to send the requests, but that doesn't care for this problem
     */
}

In this case I get a GuzzleHttp\Promise\Promise Object. My goal is to get only the path /aaa.html from $object. It must be found inside the function performMultiRequest(). There's no chance to read and parse the url before, e.g. when the requestAsync() is used.

This is the relevant part of $object I need:

I tried SO, Guzzle documentation, google, trail & error... nothing found... any ideas?


问:
Get the actual truncated string from label
I have a UILabel with an attributed string, where the content text is e.g. "abcdefghijklmnopqrstuvwxyz", and and the numberOfLines property is 2. For this scenario the label displays as follows (truncating the tail of the string):

abcdefghijkl

mnopqrstu...

Is there a way to request displayed "abcdefghijklmnopqrstu..." string instead of the whole original one? The content is mixed with English, Chinese, emoji, etc...


问:
Using filter() inside case_when() to fill values from a lookup table
I'm trying to recode one long, complicated dataset into another long, complicated dataset, using a series of case_when() functions. The first consists of a lot of observations of species, some of which have explicit data on where they were found. When they don't, I want to look up a best guess from a lookup table I've prepared.

The problem is this: I'm trying to pull the relevant value, per species out using a piped filter() %>% pull() statement, but I can't work out how to access the species for a given row - rather than the whole vector of species variables - and use it as an argument to filter().

A simplified example:

```<code>library(tibble)
library(dplyr)

animal_lookup <- tibble(species_lookup = c("rat", "otter", "pigeon"),
habitat = c("land", "river", "sky"))

animal_observations <- tibble(day = c("monday", "tuesday", "tuesday", "friday"),
species_seen = c("rat", "rat", "rat", "pigeon"))

# case_when can access species_seen as a single value, tidy-style
animal_observations_habitat <- animal_observations %>%
mutate(habitat = case_when(species_seen %in% animal_lookup$species_lookup ~ species_seen))

# however, when species_seen is inside filter(), it compares the whole vector
animal_observations_habitat <- animal_observations %>%
    mutate(habitat = case_when(species_seen %in% animal_lookup$species_lookup ~ filter(animal_lookup, species_lookup == species_seen) %>% pull(var = 1)))
</code>```

I'd like to stick with using case_when() here, as I've written 100+ lines that already rely on it. But I'm open to suggestions along the lines of "you're doing this completely wrong" if that's the right answer.

Body:
I'm trying to recode one long, complicated dataset into another long, complicated dataset, using a series of case_when() functions. The first consists of a lot of observations of species, some of which have explicit data on where they were found. When they don't, I want to look up a best guess from a lookup table I've prepared.

The problem is this: I'm trying to pull the relevant value, per species out using a piped filter() %>% pull() statement, but I can't work out how to access the species for a given row - rather than the whole vector of species variables - and use it as an argument to filter().

A simplified example:

library(tibble)
library(dplyr)

animal_lookup <- tibble(species_lookup = c("rat", "otter", "pigeon"),
habitat = c("land", "river", "sky"))

animal_observations <- tibble(day = c("monday", "tuesday", "tuesday", "friday"),
species_seen = c("rat", "rat", "rat", "pigeon"))

# case_when can access species_seen as a single value, tidy-style
animal_observations_habitat <- animal_observations %>%
mutate(habitat = case_when(species_seen %in% animal_lookup$species_lookup ~ species_seen))

# however, when species_seen is inside filter(), it compares the whole vector
animal_observations_habitat <- animal_observations %>%
    mutate(habitat = case_when(species_seen %in% animal_lookup$species_lookup ~ filter(animal_lookup, species_lookup == species_seen) %>% pull(var = 1)))

I'd like to stick with using case_when() here, as I've written 100+ lines that already rely on it. But I'm open to suggestions along the lines of "you're doing this completely wrong" if that's the right answer.


问:
Where to create .aws/config in my django project?
how to add .aws/config in django project on this file structure

Hello I'm Studying Front-End Development and I was proceeding E-commerse Project with

pre-made API, and Design. but they suddenly shut down the server and gave me away the

backend Code without any explaination. the thing is I have no idea what to do.

So I excute following command from README

Install Virtual Environment & Dependency

```<code># ./backend
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python manage.py githooks
</code>```

once I excute python manage.py githooks

it says

botocore.exceptions.NoCredentialsError: Unable to locate credentials

Set AWS Profile

vi ~/.aws/config

```<code>...
[profile incourse-commerce]
aws_access_key_id=**
aws_secret_access_key=**
region = ap-northeast-2
</code>```

I think I should add my IAM credentials on this application but I dont know

where to add ./aws/config on this file structure

enter image description here

please help ㅠㅠ

Body:
how to add .aws/config in django project on this file structure

Hello I'm Studying Front-End Development and I was proceeding E-commerse Project with

pre-made API, and Design. but they suddenly shut down the server and gave me away the

backend Code without any explaination. the thing is I have no idea what to do.

So I excute following command from README

Install Virtual Environment & Dependency

# ./backend
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python manage.py githooks

once I excute python manage.py githooks

it says

botocore.exceptions.NoCredentialsError: Unable to locate credentials

Set AWS Profile

vi ~/.aws/config

...
[profile incourse-commerce]
aws_access_key_id=**
aws_secret_access_key=**
region = ap-northeast-2

I think I should add my IAM credentials on this application but I dont know

where to add ./aws/config on this file structure

enter image description here

please help ㅠㅠ


问:
Why I get inherited from div.toolbar in developer tools and how can i override it
I have div which is shown when I click on some button.
That div is hidden behind other div - there are options inside him that needs to be shown.

First that came to my mind is z-index: 99999 !important.
But it did not work. After that inspected the HTML tree inside developer tools and I found out that I have inherited from div.toolbar from vendor file xecm-webapp-vendor.1963d620.css

Why i get inherited css from this vendor file ?

My html looks like this

```<code><div class="addAnnotationButton select-button-with-togglable-item toolbarButton ng-scope ng-isolate-scope"
        style="display: flex; width: 67px; padding: 0px;" title="Add shape annotation"
        on-item-change="onShapeChange(item)" items="shapeList" ng-if="!displayMode && isEnableAnnotationFeature"
        selected-item="selectedShape"> <button class="previous-selected-button toolbarButton"
            style="margin: 0 0!important;" ng-class="{'has-selected-item': selectedItem}"
            ng-click="vm.onClickPreviousSelectedItemButton()"> <i class="btr bt-square" aria-hidden="true"
                style="float: left"></i> </button>
        <div class="items-wrapper toolbarButton" style="height: auto; width: auto; margin: 0 0 !important;"
            ng-class="{'has-selected-item': selectedItem}" ng-click="vm.onClickArrowButton()"> <i
                class="fa fa-caret-down" aria-hidden="true" style="color:white!important; float:right"></i>
            <div class="floatPanelWrapper"
                style="box-sizing: border-box; padding-top: 10px; position: absolute; width: 50px; background: rgb(71, 71, 71); border: 1px solid white; top: 100%; z-index: 2147483647 !important;"
                ng-show="vm.isShowPanel"> <!-- ngRepeat: item in items -->
                <div ng-repeat="item in items" ng-click="vm.onClickItem(item)" class="float-panelitem ng-scope"
                    ng-class="{'selected': item.isSelected}" style="margin-bottom:10px"> <i class="btr bt-square"
                        aria-hidden="true"></i> </div><!-- end ngRepeat: item in items -->
                <div ng-repeat="item in items" ng-click="vm.onClickItem(item)" class="float-panelitem ng-scope"
                    ng-class="{'selected': item.isSelected}" style="margin-bottom:10px"> <i class="btr bt-circle"
                        aria-hidden="true"></i> </div><!-- end ngRepeat: item in items -->
                <div ng-repeat="item in items" ng-click="vm.onClickItem(item)" class="float-panelitem ng-scope"
                    ng-class="{'selected': item.isSelected}" style="margin-bottom:10px"> <i class="btr bt-pencil"
                        aria-hidden="true"></i> </div><!-- end ngRepeat: item in items -->
            </div>
        </div>
        <div></div>
    </div>
</code>```

the div with class floatPanelWrapper is the one that I try to attach z-index.
When i de-select the z-index from this inherited .toolbar then my div is shown and it's z-index is taken into consideration.

How can I override this .toolbar safely ?
In order to not break some things because it is coming from vendor ( third party dependency )
how can I make my html div with class floatPanelWrapper to "win" this z-index battle ?

Body:
I have div which is shown when I click on some button.
That div is hidden behind other div - there are options inside him that needs to be shown.

First that came to my mind is z-index: 99999 !important.
But it did not work. After that inspected the HTML tree inside developer tools and I found out that I have inherited from div.toolbar from vendor file xecm-webapp-vendor.1963d620.css

Why i get inherited css from this vendor file ?

My html looks like this

 <button class="previous-selected-button toolbarButton"
            style="margin: 0 0!important;" ng-class="{'has-selected-item': selectedItem}"
            ng-click="vm.onClickPreviousSelectedItemButton()">  </button>

the div with class floatPanelWrapper is the one that I try to attach z-index.
When i de-select the z-index from this inherited .toolbar then my div is shown and it's z-index is taken into consideration.

How can I override this .toolbar safely ?
In order to not break some things because it is coming from vendor ( third party dependency )
how can I make my html div with class floatPanelWrapper to "win" this z-index battle ?