问:
Encountering error while trying to dockerize Rust app in multiple steps
When I try to put my rust app in a Docker container with multiple build steps to reduce size I get the following error:

```<code>error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
</code>```

My Cargo.toml is the following:

```<code>[package]
name = "communcation_service"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1.0"
serde = "1.0"
lapin = "2.1.1" # Kinda big
futures-lite = "1.12.0"
tracing = "0.1.37"
tracing-subscriber = "0.3.16" # Kinda big
dotenv = "0.15.0"
base64 = "0.13.1"
async-trait = "0.1.58"
web-push = "0.9.3"
sentry = "0.23.0"
lettre = { version = "0.10.0-beta.2", default-features = false, features = ["smtp-transport", "tokio1-rustls-tls", "hostname", "r2d2", "builder"] }
</code>```

And my Dockerfile is the following

```<code>FROM rust as build

WORKDIR /app

RUN cargo init .
RUN ls && rm ./Cargo.toml

# copy over your manifests
COPY ./Cargo.lock ./Cargo.lock
COPY ./Cargo.toml ./Cargo.toml

# this build step will cache your dependencies
RUN cargo build --release
RUN rm src/*.rs

# copy your source tree
COPY ./src ./src

# build for release
RUN rm ./target/release/deps/communcation_service*
RUN cargo build --release
#CMD ["./target/release/communcation_service"]
# our final base
FROM gcr.io/distroless/cc-debian10
#FROM ubuntu

WORKDIR /app

# copy the build artifact from the build stage
COPY --from=build /app/target/release/communcation_service /app

# set the startup command to run your binary
CMD ["./communcation_service"]
</code>```

My program works if I do not use multiple build steps and instead run the program in the build container, with this Dockerfile

```<code>FROM rust as build

WORKDIR /app

RUN cargo init .
RUN ls && rm ./Cargo.toml

# copy over your manifests
COPY ./Cargo.lock ./Cargo.lock
COPY ./Cargo.toml ./Cargo.toml

# this build step will cache your dependencies
RUN cargo build --release
RUN rm src/*.rs

# copy your source tree
COPY ./src ./src

# build for release
RUN rm ./target/release/deps/communcation_service*
RUN cargo build --release
CMD ["./target/release/communcation_service"]
</code>```

Do anyone know how to solve my error while still running the application in a smaller container?

Body:
When I try to put my rust app in a Docker container with multiple build steps to reduce size I get the following error:

error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory

My Cargo.toml is the following:

[package]
name = "communcation_service"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1.0"
serde = "1.0"
lapin = "2.1.1" # Kinda big
futures-lite = "1.12.0"
tracing = "0.1.37"
tracing-subscriber = "0.3.16" # Kinda big
dotenv = "0.15.0"
base64 = "0.13.1"
async-trait = "0.1.58"
web-push = "0.9.3"
sentry = "0.23.0"
lettre = { version = "0.10.0-beta.2", default-features = false, features = ["smtp-transport", "tokio1-rustls-tls", "hostname", "r2d2", "builder"] }

And my Dockerfile is the following

FROM rust as build

WORKDIR /app

RUN cargo init .
RUN ls && rm ./Cargo.toml

# copy over your manifests
COPY ./Cargo.lock ./Cargo.lock
COPY ./Cargo.toml ./Cargo.toml

# this build step will cache your dependencies
RUN cargo build --release
RUN rm src/*.rs

# copy your source tree
COPY ./src ./src

# build for release
RUN rm ./target/release/deps/communcation_service*
RUN cargo build --release
#CMD ["./target/release/communcation_service"]
# our final base
FROM gcr.io/distroless/cc-debian10
#FROM ubuntu

WORKDIR /app

# copy the build artifact from the build stage
COPY --from=build /app/target/release/communcation_service /app

# set the startup command to run your binary
CMD ["./communcation_service"]

My program works if I do not use multiple build steps and instead run the program in the build container, with this Dockerfile

FROM rust as build

WORKDIR /app

RUN cargo init .
RUN ls && rm ./Cargo.toml

# copy over your manifests
COPY ./Cargo.lock ./Cargo.lock
COPY ./Cargo.toml ./Cargo.toml

# this build step will cache your dependencies
RUN cargo build --release
RUN rm src/*.rs

# copy your source tree
COPY ./src ./src

# build for release
RUN rm ./target/release/deps/communcation_service*
RUN cargo build --release
CMD ["./target/release/communcation_service"]

Do anyone know how to solve my error while still running the application in a smaller container?


来源: stackexchange

问:
connecting Metatrader 4 platform
Connecting broker MT4 to metatrader4 is giving error is 'Invalid credential' but in case of connecting broker MT5 to  metatrader5 is successfully connected. Can any one suggests

want to connect MT4 terminal to in server

ContentLicense: CC BY-SA 4.0

Title: connecting Metatrader 4 platform


问:
ExcelWriter() function is mainly used for ".xlsm" file , is there any alternative to work with ".ods " file in python using pandas?
I want to append my output in .ods file to the next empty column, the file has a large size.

Please provide a solution, I am trying to debug this since

```<code>import pandas as pd
df = pd.read_csv("BB-20_C.csv", low_memory=False)
std_deviation = df.std(axis=1,ddof=0, skipna=True)
AVRG = std_deviation. Sum()/len(df)
print("Average value of std is " ,AVRG)

with pd.ExcelWriter('Standard procedure_Lynred approved (1).ods',engine="odf", mode="a",if_sheet_exists="overlay") as writer:
    std_deviation.to_excel(writer,sheet_name="Sheet2",index=None, header=False)

Average value of std is  2.878316682932528

Traceback (most recent call last):
  File "C:\Users\vvdn\PycharmProjects\pythonProject\EXCEL_AUTOMATION\BB20.py", line 21, in <module>
    with pd.ExcelWriter('Standard procedure_Lynred approved (1).ods',engine="odf", mode="a",if_sheet_exists="overlay") as writer:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\vvdn\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\excel\_odswriter.py", line 51, in __init__
    raise ValueError("Append mode is not supported with odf!")
ValueError: Append mode is not supported with odf!

Process finished with exit code 1
</code>```

Body:
I want to append my output in .ods file to the next empty column, the file has a large size.

Please provide a solution, I am trying to debug this since

import pandas as pd
df = pd.read_csv("BB-20_C.csv", low_memory=False)
std_deviation = df.std(axis=1,ddof=0, skipna=True)
AVRG = std_deviation. Sum()/len(df)
print("Average value of std is " ,AVRG)

with pd.ExcelWriter('Standard procedure_Lynred approved (1).ods',engine="odf", mode="a",if_sheet_exists="overlay") as writer:
    std_deviation.to_excel(writer,sheet_name="Sheet2",index=None, header=False)

Average value of std is  2.878316682932528

Traceback (most recent call last):
  File "C:\Users\vvdn\PycharmProjects\pythonProject\EXCEL_AUTOMATION\BB20.py", line 21, in <module>
    with pd.ExcelWriter('Standard procedure_Lynred approved (1).ods',engine="odf", mode="a",if_sheet_exists="overlay") as writer:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\vvdn\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\io\excel\_odswriter.py", line 51, in __init__
    raise ValueError("Append mode is not supported with odf!")
ValueError: Append mode is not supported with odf!

Process finished with exit code 1


问:
Spring webflux session management on login
I'm trying to implement a classic /login webservice with spring webflux.
But globally I'm struggling to understand how it works.

Here is some code parts :

```<code>@RestController
@RequestMapping("auth")
class AuthWebservice(
    private val reactiveAuthenticationManager: ReactiveAuthenticationManager,
    private val serverSecurityContextRepository: ServerSecurityContextRepository,
) {

    @GetMapping("me")
    fun me(exchange: ServerWebExchange): Mono<Principal> {
        return exchange.getPrincipal<Principal>()
    }

    @PostMapping("login")
    fun login(@RequestBody dto: LoginDto, exchange: ServerWebExchange): Mono<Unit> {

        return reactiveAuthenticationManager.authenticate(
            UsernamePasswordAuthenticationToken(
                dto.email, dto.password
            )
        ).map { authentication ->
            serverSecurityContextRepository.save(exchange, SecurityContextImpl(authentication))
                .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
        }
    }
}
</code>```

And on the configuration :

```<code>@Bean
fun serverSecurityContextRepository() = WebSessionServerSecurityContextRepository()
</code>```

At this end, I expect to have a session id in the set-cookie.
But after reading the code of WebSessionServerSecurityContextRepository I see that there will be no session created if no session exists, which looks odd to me.

What am I missing ?

Body:
I'm trying to implement a classic /login webservice with spring webflux.
But globally I'm struggling to understand how it works.

Here is some code parts :

@RestController
@RequestMapping("auth")
class AuthWebservice(
    private val reactiveAuthenticationManager: ReactiveAuthenticationManager,
    private val serverSecurityContextRepository: ServerSecurityContextRepository,
) {

    @GetMapping("me")
    fun me(exchange: ServerWebExchange): Mono<Principal> {
        return exchange.getPrincipal<Principal>()
    }

    @PostMapping("login")
    fun login(@RequestBody dto: LoginDto, exchange: ServerWebExchange): Mono<Unit> {

        return reactiveAuthenticationManager.authenticate(
            UsernamePasswordAuthenticationToken(
                dto.email, dto.password
            )
        ).map { authentication ->
            serverSecurityContextRepository.save(exchange, SecurityContextImpl(authentication))
                .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
        }
    }
}

And on the configuration :

@Bean
fun serverSecurityContextRepository() = WebSessionServerSecurityContextRepository()

At this end, I expect to have a session id in the set-cookie.
But after reading the code of WebSessionServerSecurityContextRepository I see that there will be no session created if no session exists, which looks odd to me.

What am I missing ?


问:
Error - There is no explicit mapping for the categories 'Hangfire.Server.ServerJobCancellationWatcher'
My project required to update the versions of Hangfire.core and Hangfire.SqlServer from 1.6.7 to 1.7.31 . After updating these dlls, I am finding build issues in the below method- "Cannot convert from Microsoft.Practices.Unity.IUnityContainer to Unity.IUnityContainer."

I modified the code as below

Added new class -

The build was succeeded by while running the application I am seeing this issue -

Message: There is no explicit mapping for the categories 'Hangfire.Server.ServerJobCancellationWatcher'. The log entry was:
Timestamp: 07.12.2022 12:12:55
Message: Checking for aborted jobs...
Category: Hangfire.Server.ServerJobCancellationWatcher
Priority: -1
EventId: 0
Severity: Verbose
Title:
ProcessId: 2876
Process Name: c:\windows\system32\inetsrv\w3wp.exe
Thread Name: ServerJobCancellationWatcher #1
Win32 ThreadId:25488
Extended Properties:

Can someone please help m understand why I am seeing this error ? Many Thanks In Advance !


问:
Alternate method of merging 2 csv using cancat
I have 2 dataset as
dataset 1:

```<code>query category
apple  {'24'}
orage  {'31'}
</code>```

dataset 2:

```<code>query category
apple  {'24','25'}
</code>```

I'm merging them and my output is

```<code>query category
apple  {'24','25'}
orage  {'31'}
</code>```

I'm looking for an alternative approach from what I have implemented.

My approach:

```<code>df1 = pd.read_csv("data1.csv")
df2 = pd.read_csv("data2.csv")
df = pd.merge(df1, df2, on='query', how='outer')
df['category_x'] = df['category_y'].combine_first(df['category_x'])
del df["category_y"]
df.rename(columns = {'category_x':'category'}, inplace = True)
</code>```

The method is working fine but is not efficient. Looking for better approaches.

Body:
I have 2 dataset as
dataset 1:

query category
apple  {'24'}
orage  {'31'}

dataset 2:

query category
apple  {'24','25'}

I'm merging them and my output is

query category
apple  {'24','25'}
orage  {'31'}

I'm looking for an alternative approach from what I have implemented.

My approach:

df1 = pd.read_csv("data1.csv")
df2 = pd.read_csv("data2.csv")
df = pd.merge(df1, df2, on='query', how='outer')
df['category_x'] = df['category_y'].combine_first(df['category_x'])
del df["category_y"]
df.rename(columns = {'category_x':'category'}, inplace = True)

The method is working fine but is not efficient. Looking for better approaches.


问:
C#: Add and HTTP method in AWS without configuring API Gateway. Is this a valid approach?
I've been working with AWS Lambda in C# a bit, and I need to create an HTTP endpoint inside of lambda. The lambda is currently triggered by cloudwatch, and I need to add an HTTP endpoint for an additional task, so I was wondering what's the most simple way to add an HTTP endpoint to AWS lambda? I found this solution, which seems to be okay, but what do you think? Maybe you have worked with it and found some great solutions? Thank you for your time.</p>
```<code>[HttpPost]
[Route("RouteToHandler")]
public APIGatewayProxyResponse RequestHandler(ILambdaContext context)
{
    var response = new APIGatewayProxyResponse
    {
        StatusCode = 200,
        Body = JsonConvert.SerializeObject("something")
    };

    return response;
}
</code>```

Body:
I've been working with AWS Lambda in C# a bit, and I need to create an HTTP endpoint inside of lambda. The lambda is currently triggered by cloudwatch, and I need to add an HTTP endpoint for an additional task, so I was wondering what's the most simple way to add an HTTP endpoint to AWS lambda? I found this solution, which seems to be okay, but what do you think? Maybe you have worked with it and found some great solutions? Thank you for your time.

[HttpPost]
[Route("RouteToHandler")]
public APIGatewayProxyResponse RequestHandler(ILambdaContext context)
{
    var response = new APIGatewayProxyResponse
    {
        StatusCode = 200,
        Body = JsonConvert.SerializeObject("something")
    };

    return response;
}


问:
BroadcastHub instances on Websocket connection are not cleaned up after disconnect
I have a web applications that is only available on an intranet.
It serves data to the frontend asynchronously via Websocket.
However, running it for a while will create multiple instances of BroadcastHub and not clean all of them up.
Furthermore, the cache of the BroadcastHub fills up on some connections.
This points to the client being disconnected.
Over time this will exhaust the memory of the Java VM.
I already use the poisonPill and from the logs it looks like its correctly invoked.
But the BroadcastHub and its cache stay alive and are not cleaned up by the GC.

Can anyone help?

Here is the code that create the Flow for handling Websocket data.

```<code>val (actor, source) =
      // producer is materialized ActorRef
      Source.actorRef[String](10, akka.stream.OverflowStrategy.dropTail)
      .named(WebServer.socketWelcomeFlowName)
      // attach a BroadcastHub Sink to the producer
      .toMat(BroadcastHub.sink[String])(Keep.both)
      // By running/materializing the producer, we get back a Source, which
      // gives us access to the elements published by the producer
      .run()

connectedClients += 1
log.info(s"New client session with path: ${actor.path}.")
communication.welcomeNewClient(actor, log)(10 seconds, IO.contextShift(blockingIO)).unsafeRunAsync(_ => {})
communication.tellTopUserActor(log)(GenericMessageGalliumAdapterActor.name, GenericMessageGalliumAdapterActor.NewClientConnected).unsafeRunSync()

Flow[ws.Message]
  .watchTermination() { (m, f) =>
    f.onComplete(_ => {
      log.info(s"Client session '${actor.path}' left.")
      actor ! PoisonPill
      connectedClients -= 1
      }
    )
    m
  }
  .merge(source)
  .map {
    case TextMessage.Strict(tm) => handleMessage(actor, tm).map(Future.successful)
    case PassThroughMessage(tm) => Some(Future.successful(tm))
    case _ => Some(Future.successful(TextMessage.Strict("Gallium can only handle TextMessages for now!")))
  }
  .filter(_.isDefined)
  .map(_.get)
  .mapAsync(parallelism = 3)(identity)
</code>```

After feedback, I updated it to:

```<code>  Source.actorRef[String]({
      case akka.actor.Status.Success(s: CompletionStrategy) => s
      case akka.actor.Status.Success(_)                     => CompletionStrategy.immediately
      case akka.actor.Status.Success                        => CompletionStrategy.immediately
      case akka.actor.Status.Failure                        => CompletionStrategy.immediately
    }, { case akka.actor.Status.Failure(cause)              => cause }
      , 10, OverflowStrategy.fail)
</code>```

Body:
I have a web applications that is only available on an intranet.
It serves data to the frontend asynchronously via Websocket.
However, running it for a while will create multiple instances of BroadcastHub and not clean all of them up.
Furthermore, the cache of the BroadcastHub fills up on some connections.
This points to the client being disconnected.
Over time this will exhaust the memory of the Java VM.
I already use the poisonPill and from the logs it looks like its correctly invoked.
But the BroadcastHub and its cache stay alive and are not cleaned up by the GC.

Can anyone help?

Here is the code that create the Flow for handling Websocket data.

val (actor, source) =
      // producer is materialized ActorRef
      Source.actorRef[String](10, akka.stream.OverflowStrategy.dropTail)
      .named(WebServer.socketWelcomeFlowName)
      // attach a BroadcastHub Sink to the producer
      .toMat(BroadcastHub.sink[String])(Keep.both)
      // By running/materializing the producer, we get back a Source, which
      // gives us access to the elements published by the producer
      .run()

connectedClients += 1
log.info(s"New client session with path: ${actor.path}.")
communication.welcomeNewClient(actor, log)(10 seconds, IO.contextShift(blockingIO)).unsafeRunAsync(_ => {})
communication.tellTopUserActor(log)(GenericMessageGalliumAdapterActor.name, GenericMessageGalliumAdapterActor.NewClientConnected).unsafeRunSync()

Flow[ws.Message]
  .watchTermination() { (m, f) =>
    f.onComplete(_ => {
      log.info(s"Client session '${actor.path}' left.")
      actor ! PoisonPill
      connectedClients -= 1
      }
    )
    m
  }
  .merge(source)
  .map {
    case TextMessage.Strict(tm) => handleMessage(actor, tm).map(Future.successful)
    case PassThroughMessage(tm) => Some(Future.successful(tm))
    case _ => Some(Future.successful(TextMessage.Strict("Gallium can only handle TextMessages for now!")))
  }
  .filter(_.isDefined)
  .map(_.get)
  .mapAsync(parallelism = 3)(identity)

After feedback, I updated it to:

  Source.actorRef[String]({
      case akka.actor.Status.Success(s: CompletionStrategy) => s
      case akka.actor.Status.Success(_)                     => CompletionStrategy.immediately
      case akka.actor.Status.Success                        => CompletionStrategy.immediately
      case akka.actor.Status.Failure                        => CompletionStrategy.immediately
    }, { case akka.actor.Status.Failure(cause)              => cause }
      , 10, OverflowStrategy.fail)


问:
How to get data from excel workbook to VBA in Word Document?
I am trying to output each page of my word document to separate pdfs. For that I have this module code.

```<code>Sub SaveAsSeparatePDFs()
    Dim I As Long
    Dim xStr As String
    Dim xPathStr As Variant
    Dim xDictoryStr As String
    Dim xFileDlg As FileDialog
    Dim xStartPage, xEndPage As Long
    Dim xStartPageStr, xEndPageStr As String

    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)

    xPathStr = xFileDlg.SelectedItems(1)

    xStartPageStr = InputBox("Begin saving PDFs starting with page __? " & vbNewLine & "(ex: 1)")
    xEndPageStr = InputBox("Save PDFs until page __?" & vbNewLine & "(ex: 7)")

    If Not (IsNumeric(xStartPageStr) And IsNumeric(xEndPageStr)) Then
        MsgBox "The entered start page and end page should be in integer format", vbInformation
        Exit Sub
    End If

    xStartPage = CInt(xStartPageStr)
    xEndPage = CInt(xEndPageStr)

    If xStartPage > xEndPage Then
        MsgBox "The start page number can't be larger than end page", vbInformation
        Exit Sub
    End If

    If xEndPage > ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) Then
        xEndPage = ActiveDocument.BuiltInDocumentProperties(wdPropertyPages)
    End If

    For I = xStartPage To xEndPage
        ActiveDocument.ExportAsFixedFormat xPathStr & "\Page_" & I & ".pdf", _
        wdExportFormatPDF, False, wdExportOptimizeForPrint, wdExportFromTo, I, I, wdExportDocumentWithMarkup, _
        False, False, wdExportCreateHeadingBookmarks, True, False, False
    Next
End Sub
</code>```

Here this module saves the file names as such

```<code> ActiveDocument.ExportAsFixedFormat xPathStr & "\Page_" & I & ".pdf", _ ....
</code>```

So the name of files are Page_1, Page_2...

I am new to VBA and I wrote this code after looking at tutorials.

Now I just want is list from excel table so that each file will be saved as string as filename in table.
Such as Intro.pdf , Abstract.pdf, Details.pdf
How can I do that?

Body:
I am trying to output each page of my word document to separate pdfs. For that I have this module code.

Sub SaveAsSeparatePDFs()
    Dim I As Long
    Dim xStr As String
    Dim xPathStr As Variant
    Dim xDictoryStr As String
    Dim xFileDlg As FileDialog
    Dim xStartPage, xEndPage As Long
    Dim xStartPageStr, xEndPageStr As String

    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)

    xPathStr = xFileDlg.SelectedItems(1)

    xStartPageStr = InputBox("Begin saving PDFs starting with page __? " & vbNewLine & "(ex: 1)")
    xEndPageStr = InputBox("Save PDFs until page __?" & vbNewLine & "(ex: 7)")

    If Not (IsNumeric(xStartPageStr) And IsNumeric(xEndPageStr)) Then
        MsgBox "The entered start page and end page should be in integer format", vbInformation
        Exit Sub
    End If

    xStartPage = CInt(xStartPageStr)
    xEndPage = CInt(xEndPageStr)

    If xStartPage > xEndPage Then
        MsgBox "The start page number can't be larger than end page", vbInformation
        Exit Sub
    End If

    If xEndPage > ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) Then
        xEndPage = ActiveDocument.BuiltInDocumentProperties(wdPropertyPages)
    End If

    For I = xStartPage To xEndPage
        ActiveDocument.ExportAsFixedFormat xPathStr & "\Page_" & I & ".pdf", _
        wdExportFormatPDF, False, wdExportOptimizeForPrint, wdExportFromTo, I, I, wdExportDocumentWithMarkup, _
        False, False, wdExportCreateHeadingBookmarks, True, False, False
    Next
End Sub

Here this module saves the file names as such

 ActiveDocument.ExportAsFixedFormat xPathStr & "\Page_" & I & ".pdf", _ ....

So the name of files are Page_1, Page_2...

I am new to VBA and I wrote this code after looking at tutorials.

Now I just want is list from excel table so that each file will be saved as string as filename in table.
Such as Intro.pdf , Abstract.pdf, Details.pdf
How can I do that?


问:
Customizing the OpenAPI details of the request body with Spring Cloud Open Service Broker
I am looking for a way to describe the parameter map of my Spring Cloud Open Service Broker API implementation for Swagger/OpenAPI in more detail. For example, I want to define an Example list of all parameters.

Since I have no control over the rest controller, I cannot use OpenAPI annotations. Also I cannot extend the CreateServiceInstanceRequest class, because the ServiceInstanceService class does not allow this. So I don`t really see a solution for this.

Has anyone had the same requirements and found a solution to define these request bodies more precisely for the Swagger UI?


问:
Coverage is showing different for full pytest and single app in django using pytest
I have created a project in Django, and I'm writing test cases in pytest. Now, to use coverage I generally use cmd coverage run -m pytest. And to check coverage for a specific app, I report/create html files with coverage html, so this will create html files with red and green markers. Recently, I experimented with different combinations of configurations of coverage and pytest and found that when running a full pytest with coverage like coverage run -m pytest  it will not cover all lines, and mark some lines as missing which are actually running while pytest. But when I use pytest with some argument with coverage like coverage run -m pytest accounts, it is covering all perfectly and not showing the missing files as I expected.

I have tried running the whole project with coverage run -m pytest  and then running coverage html  to see in the browser. I got all files' coverage, and to see coverage of specific apps for example restaurant, I searched in the top right search box and it's shown below.

Full Pytest Coverage

Full pytest coverage with searched result

Now, I have to run coverage for a specific app so I can do it like:

```<code>coverage run -m pytest restaurant
</code>```

So this will only run for the restaurant app, then I ran coverage html  to see in the browser. Below is an image of the results.

Restaurant app's Pytest

Restaurant app's Pytest with search result

Both are different even though I simultaneously ran them.

I have already used:

coverage erase  before every execution.

Body:
I have created a project in Django, and I'm writing test cases in pytest. Now, to use coverage I generally use cmd coverage run -m pytest. And to check coverage for a specific app, I report/create html files with coverage html, so this will create html files with red and green markers. Recently, I experimented with different combinations of configurations of coverage and pytest and found that when running a full pytest with coverage like coverage run -m pytest  it will not cover all lines, and mark some lines as missing which are actually running while pytest. But when I use pytest with some argument with coverage like coverage run -m pytest accounts, it is covering all perfectly and not showing the missing files as I expected.

I have tried running the whole project with coverage run -m pytest  and then running coverage html  to see in the browser. I got all files' coverage, and to see coverage of specific apps for example restaurant, I searched in the top right search box and it's shown below.

Full Pytest Coverage

Full pytest coverage with searched result

Now, I have to run coverage for a specific app so I can do it like:

coverage run -m pytest restaurant

So this will only run for the restaurant app, then I ran coverage html  to see in the browser. Below is an image of the results.

Restaurant app's Pytest

Restaurant app's Pytest with search result

Both are different even though I simultaneously ran them.

I have already used:

coverage erase  before every execution.


问:
How to create sample data for this Code and input inside the .cpp file to just run It and get results?
I have this cpp Code.
How can I create a sample data and input directly in this file to just run It and get expected results?

This is an path-finder algorithm to find shortest and more profitable pairs path.

```<code>#include "readGraph.hpp"
#include "ShortestPath.hpp"
#include <limits>
#include <fstream>
#include <string>
#include <iostream>
#include <cmath>
#include <chrono>
using namespace std;

int main(int argc, char** argv){

    ifstream fin(argv[1]);
    ofstream fout(argv[2]);

    double cost = atof(argv[5]);

    int** edgeL;
    double* weights;

    int numEdges;
    double totalDist;

    string* e; //eLabels
    string* v; //vLabels

    /* edgeList version of readGraph */
    int numVertices = readGraph(fin,edgeL,weights,numEdges,v, e);

    string sourceV = argv[3];
    string destV = argv[4];

    /* Checking input source and destination vertices and assigning their corresponding integer values */
    int source, dest;
    for(int i = 0; i < numVertices; i ++){
        if(sourceV == v[i]){
            source = i;
        }
        if(destV == v[i]){
            dest = i;
        }
    }

    int* prev;
    double* dist;
    int* path;
    int* cycle;

    /*Prepping the weights for bellmanFord by taking setting w[i] = -log(temp*(1-cost)) */
    for(int i = 0; i < numEdges; i ++){
        double temp = weights[i];
        weights[i] = -1*log(temp*(1-cost));
        cout << weights[i] << endl;
    }

    /* Setting timers and invoking bellmanFord to catch arbitrage opportunity */
    auto t1 = std::chrono::system_clock::now();
    int x = bellmanFord(edgeL, weights, numVertices, numEdges, source, dist, prev);
    auto t2 = std::chrono::system_clock::now();
    auto dur = t2-t1;
    auto durns = std::chrono::duration_cast<std::chrono::microseconds>(dur);
    double elapsed = durns.count();

    /** If there is a negative loop, there is an arbitrage opportunity.
     *  A path is derived using the appropriate getCycle method.
     *  The path is printed to fout and meta data printed to the terminal.
    */
    if(x != -1){
        int cycleSize = getCycle(x, prev, numVertices, cycle);
        fout << numVertices << " " << cycleSize << endl;

        for(int i = 0; i < numVertices; i ++){
            fout << v[i] << endl;
        }

        int idx = 0;
        for(int i = 0; i < cycleSize; i ++){
            for(int j = 0; j < numEdges; j ++){
                if(edgeL[j][0] == cycle[i] && edgeL[j][1] == cycle[i+1]){
                    totalDist += weights[j];
                    fout << cycle[i] << " " << cycle[i+1] << " " << exp(-1*weights[j]) << " " << e[j] << endl;
                    idx = j;
                }
            }
        }

        cout << "Arbitrage Opportunity Detected!" << endl;
        cout << "Effective Exchange Rate: " << exp(-1*totalDist) << endl;
        cout << "Runtime: " << elapsed << " Microseconds" << endl;

    delete[] cycle;
    for (int i=0; i<numEdges; i++){
        delete[] edgeL[i];
    }
    }

    /** If there is no negative cycle.
     *  The path is simply printed to fout and meta data printed to terminal.
     */
    else if(x == -1){

    int pathSize = getPath(source, dest, prev, path);
    fout << numVertices << " " << pathSize - 1 << endl;

    for(int i = 0; i < numVertices; i++){
        fout << v[i] << endl;
    }

    int temp;

    for(int i = 0; i < pathSize-1; i++){
        temp = path[i];
        for(int j = 0; j < numEdges; j ++){
            if(edgeL[j][0] == path[i] && edgeL[j][1] == path[i+1]){
                totalDist += weights[j];
                fout << temp << " " << path[i+1] << " " << exp(-1*weights[j]) << " " << e[j] << endl;
            }
        }
    }
    cout << "Effective Exchange Rate: " << exp(-1*totalDist) << endl;
    cout << "Runtime: " << elapsed << " " << "Microseconds" << endl;

    delete[] path;
    for (int i=0; i<numEdges; i++){
        delete[] edgeL[i];
    }
    }

    delete[] dist;
    delete[] prev;
    delete[] e;
    delete[] v;
    delete[] weights;
    delete[] edgeL;

}
</code>```

This is an example of data, but how to input inside the same file.

Sample data 1:

```<code> 6 1

GBP

EUR

JPY

CHF

USD

GLD

0 1 1.45543 GBP->EUR
</code>```

Sample data 2:

```<code>6 30

GBP

EUR

JPY

CHF

USD

GLD

0 1 1.4599 GBP->EUR

0 2 189.05 GBP->JPY

0 3 2.1904 GBP->CHF

0 4 1.5714 GBP->USD

0 5 0.004816 GBP->GLD

1 0 0.684978 EUR->GBP

1 2 129.52 EUR->JPY

1 3 1.4978 EUR->CHF

1 4 1.0752 EUR->USD

1 5 0.003295 EUR->GLD

2 0 0.00528961 JPY->GBP

2 1 0.00772082 JPY->EUR

2 3 0.011574 JPY->CHF

2 4 0.008309 JPY->USD

2 5 0.0000255 JPY->GLD

3 0 0.456538 CHF->GBP

3 1 0.667646 CHF->EUR

3 2 86.4006 CHF->JPY

3 4 0.7182 CHF->USD

3 5 0.002201 CHF->GLD

4 0 0.636375 USD->GBP

4 1 0.93006 USD->EUR

4 2 120.351 USD->JPY

4 3 1.39237 USD->CHF

4 5 0.003065 USD->GLD

5 0 207.641 GLD->GBP

5 1 303.49 GLD->EUR

5 2 39215.7 GLD->JPY

5 3 454.339 GLD->CHF

5 4 326.264 GLD->USD
</code>```

Ive still not tried any option because I don't know how to create this array.

Body:
I have this cpp Code.
How can I create a sample data and input directly in this file to just run It and get expected results?

This is an path-finder algorithm to find shortest and more profitable pairs path.

#include "readGraph.hpp"
#include "ShortestPath.hpp"
#include <limits>
#include <fstream>
#include <string>
#include <iostream>
#include <cmath>
#include <chrono>
using namespace std;

int main(int argc, char** argv){

    ifstream fin(argv[1]);
    ofstream fout(argv[2]);

    double cost = atof(argv[5]);

    int** edgeL;
    double* weights;

    int numEdges;
    double totalDist;

    string* e; //eLabels
    string* v; //vLabels

    /* edgeList version of readGraph */
    int numVertices = readGraph(fin,edgeL,weights,numEdges,v, e);

    string sourceV = argv[3];
    string destV = argv[4];

    /* Checking input source and destination vertices and assigning their corresponding integer values */
    int source, dest;
    for(int i = 0; i < numVertices; i ++){
        if(sourceV == v[i]){
            source = i;
        }
        if(destV == v[i]){
            dest = i;
        }
    }

    int* prev;
    double* dist;
    int* path;
    int* cycle;

    /*Prepping the weights for bellmanFord by taking setting w[i] = -log(temp*(1-cost)) */
    for(int i = 0; i < numEdges; i ++){
        double temp = weights[i];
        weights[i] = -1*log(temp*(1-cost));
        cout << weights[i] << endl;
    }

    /* Setting timers and invoking bellmanFord to catch arbitrage opportunity */
    auto t1 = std::chrono::system_clock::now();
    int x = bellmanFord(edgeL, weights, numVertices, numEdges, source, dist, prev);
    auto t2 = std::chrono::system_clock::now();
    auto dur = t2-t1;
    auto durns = std::chrono::duration_cast<std::chrono::microseconds>(dur);
    double elapsed = durns.count();

    /** If there is a negative loop, there is an arbitrage opportunity.
     *  A path is derived using the appropriate getCycle method.
     *  The path is printed to fout and meta data printed to the terminal.
    */
    if(x != -1){
        int cycleSize = getCycle(x, prev, numVertices, cycle);
        fout << numVertices << " " << cycleSize << endl;

        for(int i = 0; i < numVertices; i ++){
            fout << v[i] << endl;
        }

        int idx = 0;
        for(int i = 0; i < cycleSize; i ++){
            for(int j = 0; j < numEdges; j ++){
                if(edgeL[j][0] == cycle[i] && edgeL[j][1] == cycle[i+1]){
                    totalDist += weights[j];
                    fout << cycle[i] << " " << cycle[i+1] << " " << exp(-1*weights[j]) << " " << e[j] << endl;
                    idx = j;
                }
            }
        }

        cout << "Arbitrage Opportunity Detected!" << endl;
        cout << "Effective Exchange Rate: " << exp(-1*totalDist) << endl;
        cout << "Runtime: " << elapsed << " Microseconds" << endl;

    delete[] cycle;
    for (int i=0; i<numEdges; i++){
        delete[] edgeL[i];
    }
    }

    /** If there is no negative cycle.
     *  The path is simply printed to fout and meta data printed to terminal.
     */
    else if(x == -1){

    int pathSize = getPath(source, dest, prev, path);
    fout << numVertices << " " << pathSize - 1 << endl;

    for(int i = 0; i < numVertices; i++){
        fout << v[i] << endl;
    }

    int temp;

    for(int i = 0; i < pathSize-1; i++){
        temp = path[i];
        for(int j = 0; j < numEdges; j ++){
            if(edgeL[j][0] == path[i] && edgeL[j][1] == path[i+1]){
                totalDist += weights[j];
                fout << temp << " " << path[i+1] << " " << exp(-1*weights[j]) << " " << e[j] << endl;
            }
        }
    }
    cout << "Effective Exchange Rate: " << exp(-1*totalDist) << endl;
    cout << "Runtime: " << elapsed << " " << "Microseconds" << endl;

    delete[] path;
    for (int i=0; i<numEdges; i++){
        delete[] edgeL[i];
    }
    }

    delete[] dist;
    delete[] prev;
    delete[] e;
    delete[] v;
    delete[] weights;
    delete[] edgeL;

}

This is an example of data, but how to input inside the same file.

Sample data 1:

 6 1

GBP

EUR

JPY

CHF

USD

GLD

0 1 1.45543 GBP->EUR

Sample data 2:

6 30

GBP

EUR

JPY

CHF

USD

GLD

0 1 1.4599 GBP->EUR

0 2 189.05 GBP->JPY

0 3 2.1904 GBP->CHF

0 4 1.5714 GBP->USD

0 5 0.004816 GBP->GLD

1 0 0.684978 EUR->GBP

1 2 129.52 EUR->JPY

1 3 1.4978 EUR->CHF

1 4 1.0752 EUR->USD

1 5 0.003295 EUR->GLD

2 0 0.00528961 JPY->GBP

2 1 0.00772082 JPY->EUR

2 3 0.011574 JPY->CHF

2 4 0.008309 JPY->USD

2 5 0.0000255 JPY->GLD

3 0 0.456538 CHF->GBP

3 1 0.667646 CHF->EUR

3 2 86.4006 CHF->JPY

3 4 0.7182 CHF->USD

3 5 0.002201 CHF->GLD

4 0 0.636375 USD->GBP

4 1 0.93006 USD->EUR

4 2 120.351 USD->JPY

4 3 1.39237 USD->CHF

4 5 0.003065 USD->GLD

5 0 207.641 GLD->GBP

5 1 303.49 GLD->EUR

5 2 39215.7 GLD->JPY

5 3 454.339 GLD->CHF

5 4 326.264 GLD->USD

Ive still not tried any option because I don't know how to create this array.


问:
Bulk clean SVGs from API
I'm building a Flutter app and getting a bunch of svg images from an APi. Some contain the  tags that cause errors to the flutter_svg package. I've searched but only found ways to fix this issue when it's an individual file like use some tools online to clean up the svg.

══╡ EXCEPTION CAUGHT BY SVG ╞═══════════════════════════════════════════════════════════════════════

The following UnimplementedError was thrown in parseSvgElement:

The  element is not implemented in this library.

Style elements are not supported by this library and the requested SVG may not render as intended.

If possible, ensure the SVG uses inline styles and/or attributes (which are supported), or use a

preprocessing utility such as svgcleaner to inline the styles for you.

Title: Bulk clean SVGs from API


问:
Is there an interface "ISingleton" I could use for creating a singleton class?
As mentioned in this other question, I'm looking for a way not to create always another instance of a class. I know this can be done, using a singleton.

As I've seen that quite some design patterns are handled by C# libraries, I believe this should be the case for the singleton design pattern, but I don't find an ISingleton interface, which I could implement.

Does anybody know in which library using which_library; I can find an ISingleton interface or should I create a singleton class from scratch?


问:
After upgrading middleman from 3.4.1 -> 4.4.3, ".js.coffee" files are not loading
added activate :sprockets in config.rb, configure :development section.
Few .js and .js.coffee files are not loading, although the paths of files are same which was there with middleman 3.4.1.

Ruby version: 2.6.10

Middleman version: 4.4.3

Middleman Sprockets version: 4.1.1

OS version: macOS Monterey 12.6


问:
Application.properties taking previous database instead of new one
I am using spring boot application in this previously, I had different database and now I am using new database within the same sql server means both this databases is in the same sql server but when I am trying to running my project with new database in the same sql server I am getting Invalid object name CorporateData error but I am not using this database i want to use xyz database. I am also tried to clear cache of browser and eclipse both and application.properties is also right.

I want to connect my project to new database without any error.


问:
JQuery ajax not running, suspected url issue
I am trying to post my record into database by using ajax. I can see there is some error in network tab under inspect. I tried many way of assigning the url value, unfortunately, I am failed to figure out. Is anyone can help?

I will show some of my code below.

this is one of my control, they are duplicated

```<code><li style="text-align:left">
<asp:Label runat="server" >Sex : </asp:Label>
<asp:RadioButtonList ID="rblSex" runat="server"></asp:RadioButtonList>
 </li>
</code>```

this is my button

<button class="btnSubmit" type="submit" > Submit</button>

Below is my javascript to insert data into database

```<code>$(document).ready(function(){
    $('.btnSubmit').click(function (e) {

        e.preventDefault();
        var firstName = document.getElementById('<%=txtFirstName.ClientID%>').value;
        var lastName = document.getElementById('<%=txtSecondName.ClientID%>').value;
        var age = document.getElementById('<%=txtAge.ClientID%>').value;
        var sex = getSelectedSexValue();
        var title = document.getElementById('<%=txtTitle.ClientID%>').value;

    try{

        jQuery.ajax({
            url: '@(Url.Action("InsertStatement","Home"))',
            datatype: "json",
            //contentType: "application/json: charset=utf-8",
            data: JSON.stringify({
                firstName: firstName, secName: lastName,
                age: age, sex: sex, title: title
            }),
            type: 'post',
            success: function (json) {

            },

            failure: function (errMsg) {
                alert(errMsg);
            }
        });

    }catch(e){
                    alert(e.message);
             }

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

Below is my code to under controller

```<code>public JsonResult InsertStatement(string firstName, string secName, int age, string sex, string title)
    {

        try
        {

            SqlConnection con = new SqlConnection(conn);
            con.Open();

            string sqlStatement = "insert into Employee values ( '" + firstName + "', '" + secName + "', '" + age + "', '" + sex + "', '" + title + "' )";
            SqlCommand sql = new SqlCommand(sqlStatement, con);
            sql.ExecuteNonQuery();

            con.Close();

            return Json("success", JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("Failure", JsonRequestBehavior.AllowGet);
        }

    }
</code>```

I found that there is an error under network tab
[Error please refer to this image]
(https://i.stack.imgur.com/xxb5c.png)

Thank you for reading my question and would be highly appreciated if I can get some ideas from here. Thank you!

Body:
I am trying to post my record into database by using ajax. I can see there is some error in network tab under inspect. I tried many way of assigning the url value, unfortunately, I am failed to figure out. Is anyone can help?

I will show some of my code below.

this is one of my control, they are duplicated

<asp:Label runat="server" >Sex : </asp:Label>
<asp:RadioButtonList ID="rblSex" runat="server"></asp:RadioButtonList>

this is my button

<button class="btnSubmit" type="submit" > Submit</button>

Below is my javascript to insert data into database

$(document).ready(function(){
    $('.btnSubmit').click(function (e) {

        e.preventDefault();
        var firstName = document.getElementById('<%=txtFirstName.ClientID%>').value;
        var lastName = document.getElementById('<%=txtSecondName.ClientID%>').value;
        var age = document.getElementById('<%=txtAge.ClientID%>').value;
        var sex = getSelectedSexValue();
        var title = document.getElementById('<%=txtTitle.ClientID%>').value;

    try{

        jQuery.ajax({
            url: '@(Url.Action("InsertStatement","Home"))',
            datatype: "json",
            //contentType: "application/json: charset=utf-8",
            data: JSON.stringify({
                firstName: firstName, secName: lastName,
                age: age, sex: sex, title: title
            }),
            type: 'post',
            success: function (json) {

            },

            failure: function (errMsg) {
                alert(errMsg);
            }
        });

    }catch(e){
                    alert(e.message);
             }

    });
    });`

Below is my code to under controller

public JsonResult InsertStatement(string firstName, string secName, int age, string sex, string title)
    {

        try
        {

            SqlConnection con = new SqlConnection(conn);
            con.Open();

            string sqlStatement = "insert into Employee values ( '" + firstName + "', '" + secName + "', '" + age + "', '" + sex + "', '" + title + "' )";
            SqlCommand sql = new SqlCommand(sqlStatement, con);
            sql.ExecuteNonQuery();

            con.Close();

            return Json("success", JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("Failure", JsonRequestBehavior.AllowGet);
        }

    }

I found that there is an error under network tab
[Error please refer to this image]
(https://i.stack.imgur.com/xxb5c.png)

Thank you for reading my question and would be highly appreciated if I can get some ideas from here. Thank you!


问:
how to find and fix non utf8 character in oracle tables and fix the data for migration to postgres
oracle database have data in columns which are non utf8 it seems but have no issue in current oracle usage. but when we try to do ora2pg it gives error like unicode surrogate illegal. we dont know what all tables will have this issue and which column. we have around 400+ tables and most of tables have more than 100GB of data.

we need help on how to find which table and whcih column have this issue and how to fix it at source before running ora2pg tool to export the data. such that export file is all utf8 and can be easily imported in postgres.

i have tried finding non utf characters in a table specific column using below query. but this is per column and after getting to know failed rows but not sure how to fix. also if i have to do this for each table and mostly all columns are varchar in 400+ tables it will be painfull. any query which can give all erroneous columns in a table if not whole database that will help.

```<code>select hold_release_rsn,CASE
            INSTR (
                  RAWTOHEX (
                      utl_raw.cast_to_raw (
                          utl_i18n.raw_to_char (
                                utl_raw.cast_to_raw ( hold_release_rsn )
                              , 'utf8'
                          )
                      )
                  )
                , 'EFBFBD'
            )
        WHEN 0 THEN 'OK'
        ELSE 'FAIL'
        END as testcase from req_hold.
</code>```

Body:
oracle database have data in columns which are non utf8 it seems but have no issue in current oracle usage. but when we try to do ora2pg it gives error like unicode surrogate illegal. we dont know what all tables will have this issue and which column. we have around 400+ tables and most of tables have more than 100GB of data.

we need help on how to find which table and whcih column have this issue and how to fix it at source before running ora2pg tool to export the data. such that export file is all utf8 and can be easily imported in postgres.

i have tried finding non utf characters in a table specific column using below query. but this is per column and after getting to know failed rows but not sure how to fix. also if i have to do this for each table and mostly all columns are varchar in 400+ tables it will be painfull. any query which can give all erroneous columns in a table if not whole database that will help.

select hold_release_rsn,CASE
            INSTR (
                  RAWTOHEX (
                      utl_raw.cast_to_raw (
                          utl_i18n.raw_to_char (
                                utl_raw.cast_to_raw ( hold_release_rsn )
                              , 'utf8'
                          )
                      )
                  )
                , 'EFBFBD'
            )
        WHEN 0 THEN 'OK'
        ELSE 'FAIL'
        END as testcase from req_hold.


问:
{% load gTTS %} in template make mistake 'gTTS' is not a registered tag library
I make a quiz app with Django I want to add text-to-speech advantage with google I recive the below error message:

```<code>gTTS' is not a registered tag library
</code>```

when I write in the template

{% load gTTS %}
<audio
    src="{% say 'en-us' {{question.question}}  %}"
    controls
></audio>
```
<p>I install <strong><code>gTTS</code></strong> and I add a line in <strong><code>setting.py</code></strong>:</p>
<pre class="lang-py prettyprint-override"><code>INSTALLED_APPS = [
    'gTTS',
    ...
</code>```

I make the application gTTS without any code on it I depend on this page django-gtts-pypi, Why did not work?

Body:
I make a quiz app with Django I want to add text-to-speech advantage with google I recive the below error message:

gTTS' is not a registered tag library

when I write in the template

{% load gTTS %}
<audio
    src="{% say 'en-us' {{question.question}}  %}"
    controls
></audio>

I install gTTS and I add a line in setting.py:

INSTALLED_APPS = [
    'gTTS',
    ...

I make the application gTTS without any code on it I depend on this page django-gtts-pypi, Why did not work?


问:
How do i make Supabase Auth work in supabase console?
Hi i built supabase for my toy but suddenly supabase auth not work. Even in supabase console, i cannot send magic link(Error: Failed to send magic link: An error has occurred: Failed to fetch). But i can call other tables in my supabase, only about auth not work.  What is wrong with my supabase console?

I call auth.SignOut()/auth.SignIn() func in svelte, and click send magic link in supabase console. But it doesn't work.

I want to call auth functions for my toy program.


问:
android spinner in recyclerview
RecyclerView is using a spinner.

For example, if you have three items,
The second item is made of TEMP through a spinner. (The default is test.)

EX)

test

temp

test

When the delete button of the first position is pressed,
I want the contents I want to be displayed as below.

test

test

But in reality,

test

temp

I deleted the temp, but why does the temp keep being exposed?

What should I do?

RecycleItemadapter.kt

```<code>@SuppressLint("MissingPermission") class RecycleItemAdapter(val calculateWeight: (MutableList<RecycleDropDownData>, Int) -> Unit,
private val itemList: MutableList<RecycleDropDownData>) : RecyclerView.Adapter<RecycleItemAdapter.DevicesAdapterViewHolder>() {

private var recycleItemList = mutableListOf<RecycleDropDownData>()

@SuppressLint("NewApi")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DevicesAdapterViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.item_recycler, parent, false)
    return DevicesAdapterViewHolder(view)
}

@SuppressLint("RecyclerView", "NotifyDataSetChanged")
override fun onBindViewHolder(holder: DevicesAdapterViewHolder, pos: Int) {
    holder.recycleItem.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            val weight = recycleItemList[pos].weight
            recycleItemList[pos] = itemList[position]
            recycleItemList[pos].weight = weight
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    }

    holder.recycleWeight.text = recycleItemList[pos].weight

    // TODO
    holder.recycleDelete.setOnClickListener {
        recycleItemList.removeAt(pos)
        notifyDataSetChanged()
    }
}

fun setData(recyclerList: MutableList<RecycleDropDownData>) {
    this.recycleItemList = recyclerList
}

fun getData(): MutableList<RecycleDropDownData> {
    return recycleItemList
}

override fun getItemCount(): Int {
    return recycleItemList.size
}

inner class DevicesAdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val recycleWeight: TextView
    private val recycleCalculate: Button
    val recycleDelete: Button
    val recycleItem: Spinner

    init {
        recycleItem = itemView.findViewById(R.id.recycle_item_spinner)
        recycleItem.adapter = ArrayAdapter(itemView.context, R.layout.item_drop_down, itemList)

        recycleWeight = itemView.findViewById(R.id.recycler_item_weight)
        recycleCalculate = itemView.findViewById(R.id.recycler_item_weight_calculate)
        recycleDelete = itemView.findViewById(R.id.recycler_item_delete)
    }
}
</code>```

}

item_recycler

```<code><Spinner
    android:id="@+id/recycle_item_spinner"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:listitem="@layout/item_drop_down" />

<TextView
    android:id="@+id/recycler_item_weight"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@id/recycle_item_spinner"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/recycler_item_weight_calculate"
    style="@style/station_detail_item_passenger_button"
    android:background="@color/color_mint_code_75f8ff"
    android:text="무게"

    app:layout_constraintLeft_toRightOf="@id/recycler_item_weight"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/recycler_item_delete"
    style="@style/station_detail_item_passenger_button"
    android:text="삭제"

    app:layout_constraintLeft_toRightOf="@id/recycler_item_weight"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/recycler_item_weight_calculate" />
</code>```

Title: android spinner in recyclerview

Body:
RecyclerView is using a spinner.

For example, if you have three items,
The second item is made of TEMP through a spinner. (The default is test.)

EX)

test

temp

test

When the delete button of the first position is pressed,
I want the contents I want to be displayed as below.

test

test

But in reality,

test

temp

I deleted the temp, but why does the temp keep being exposed?

What should I do?

RecycleItemadapter.kt

@SuppressLint("MissingPermission") class RecycleItemAdapter(val calculateWeight: (MutableList<RecycleDropDownData>, Int) -> Unit,
private val itemList: MutableList<RecycleDropDownData>) : RecyclerView.Adapter<RecycleItemAdapter.DevicesAdapterViewHolder>() {

private var recycleItemList = mutableListOf<RecycleDropDownData>()

@SuppressLint("NewApi")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DevicesAdapterViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.item_recycler, parent, false)
    return DevicesAdapterViewHolder(view)
}

@SuppressLint("RecyclerView", "NotifyDataSetChanged")
override fun onBindViewHolder(holder: DevicesAdapterViewHolder, pos: Int) {
    holder.recycleItem.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            val weight = recycleItemList[pos].weight
            recycleItemList[pos] = itemList[position]
            recycleItemList[pos].weight = weight
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    }

    holder.recycleWeight.text = recycleItemList[pos].weight

    // TODO
    holder.recycleDelete.setOnClickListener {
        recycleItemList.removeAt(pos)
        notifyDataSetChanged()
    }
}

fun setData(recyclerList: MutableList<RecycleDropDownData>) {
    this.recycleItemList = recyclerList
}

fun getData(): MutableList<RecycleDropDownData> {
    return recycleItemList
}

override fun getItemCount(): Int {
    return recycleItemList.size
}

inner class DevicesAdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val recycleWeight: TextView
    private val recycleCalculate: Button
    val recycleDelete: Button
    val recycleItem: Spinner

    init {
        recycleItem = itemView.findViewById(R.id.recycle_item_spinner)
        recycleItem.adapter = ArrayAdapter(itemView.context, R.layout.item_drop_down, itemList)

        recycleWeight = itemView.findViewById(R.id.recycler_item_weight)
        recycleCalculate = itemView.findViewById(R.id.recycler_item_weight_calculate)
        recycleDelete = itemView.findViewById(R.id.recycler_item_delete)
    }
}

}

item_recycler

<Spinner
    android:id="@+id/recycle_item_spinner"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:listitem="@layout/item_drop_down" />

<TextView
    android:id="@+id/recycler_item_weight"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@id/recycle_item_spinner"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/recycler_item_weight_calculate"
    style="@style/station_detail_item_passenger_button"
    android:background="@color/color_mint_code_75f8ff"
    android:text="무게"

    app:layout_constraintLeft_toRightOf="@id/recycler_item_weight"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/recycler_item_delete"
    style="@style/station_detail_item_passenger_button"
    android:text="삭제"

    app:layout_constraintLeft_toRightOf="@id/recycler_item_weight"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/recycler_item_weight_calculate" />


问:
cdbootstrap stepper showing error like this- export 'CDBStepper' (imported as 'CDBStepper') was not found in 'cdbreact'
WARNING in ./src/egamestudio/host/dashboard/sample/sample.jsx 141:97-107
export 'CDBStepper' (imported as 'CDBStepper') was not found in 'cdbreact' (possible exports: CDBAccordion, CDBAlert, CDBAnimation, CDBBadge, CDBBox, CDBBreadcrumb, CDBBtn, CDBBtnGrp, CDBBtnTb, CDBCard, CDBCardBody, CDBCarousel, CDBCarouselInner, CDBCarouselItem, CDBCloseIcon, CDBCol, CDBCollapse, CDBContainer, CDBDataTable, CDBDropDown, CDBDropDownItem, CDBDropDownMenu, CDBDropDownToggle, CDBFooter, CDBFooterLink, CDBHamburgerToggler, CDBIcon, CDBIframe, CDBInput, CDBInputGroup, CDBJumbotron, CDBLink, CDBListGroup, CDBListGroupItem, CDBMask, CDBModal, CDBModalBody, CDBModalFooter, CDBModalHeader, CDBNavBrand, CDBNavItem, CDBNavLink, CDBNavToggle, CDBNavbar, CDBNavbarNav, CDBPageItem, CDBPageLink, CDBPagination, CDBProgress, CDBRating, CDBRow, CDBSelect, CDBSidebar, CDBSidebarContent, CDBSidebarFooter, CDBSidebarHeader, CDBSidebarMenu, CDBSidebarMenuItem, CDBSlider, CDBSmoothScroll, CDBSpinner, CDBSwitch, CDBTable, CDBTableBody, CDBTableHeader, CDBView)

```<code>import React, { useState } from "react";
import {CDBStepper,CDBStep} from "cdbreact";
import Login from "../../users/login";

export const Sample = () => {
  const [active, setActive] = useState(1);

  const handleNextPrevClick = a => {
    setActive(a);
  };
    return (
      <>

             <CDBStepper direction="vertical" >
        <CDBStep
          id={1}
          icon="pencil-alt"
          name="Basic Information"
          handleClick={() => handleNextPrevClick(1)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
        <CDBStep
          id={2}
          icon="info-circle"
          name="Personal Data"
          handleClick={() => handleNextPrevClick(2)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
        <CDBStep
          id={3}
          icon="book-reader"
          name="Terms and Conditions"
          handleClick={() => handleNextPrevClick(3)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
        <CDBStep
          id={4}
          icon="check"
          name="Finish"
          handleClick={() => handleNextPrevClick(4)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
      </CDBStepper>
      </>

  );
};

export default Sample;
</code>```

I'm using the react js and getting the error like this -export 'CDBStepper' (imported as 'CDBStepper') was not found in 'cdbreact'
enter image description here

Body:
WARNING in ./src/egamestudio/host/dashboard/sample/sample.jsx 141:97-107
export 'CDBStepper' (imported as 'CDBStepper') was not found in 'cdbreact' (possible exports: CDBAccordion, CDBAlert, CDBAnimation, CDBBadge, CDBBox, CDBBreadcrumb, CDBBtn, CDBBtnGrp, CDBBtnTb, CDBCard, CDBCardBody, CDBCarousel, CDBCarouselInner, CDBCarouselItem, CDBCloseIcon, CDBCol, CDBCollapse, CDBContainer, CDBDataTable, CDBDropDown, CDBDropDownItem, CDBDropDownMenu, CDBDropDownToggle, CDBFooter, CDBFooterLink, CDBHamburgerToggler, CDBIcon, CDBIframe, CDBInput, CDBInputGroup, CDBJumbotron, CDBLink, CDBListGroup, CDBListGroupItem, CDBMask, CDBModal, CDBModalBody, CDBModalFooter, CDBModalHeader, CDBNavBrand, CDBNavItem, CDBNavLink, CDBNavToggle, CDBNavbar, CDBNavbarNav, CDBPageItem, CDBPageLink, CDBPagination, CDBProgress, CDBRating, CDBRow, CDBSelect, CDBSidebar, CDBSidebarContent, CDBSidebarFooter, CDBSidebarHeader, CDBSidebarMenu, CDBSidebarMenuItem, CDBSlider, CDBSmoothScroll, CDBSpinner, CDBSwitch, CDBTable, CDBTableBody, CDBTableHeader, CDBView)

import React, { useState } from "react";
import {CDBStepper,CDBStep} from "cdbreact";
import Login from "../../users/login";

export const Sample = () => {
  const [active, setActive] = useState(1);

  const handleNextPrevClick = a => {
    setActive(a);
  };
    return (
      <>

             <CDBStepper direction="vertical" >
        <CDBStep
          id={1}
          icon="pencil-alt"
          name="Basic Information"
          handleClick={() => handleNextPrevClick(1)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
        <CDBStep
          id={2}
          icon="info-circle"
          name="Personal Data"
          handleClick={() => handleNextPrevClick(2)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
        <CDBStep
          id={3}
          icon="book-reader"
          name="Terms and Conditions"
          handleClick={() => handleNextPrevClick(3)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
        <CDBStep
          id={4}
          icon="check"
          name="Finish"
          handleClick={() => handleNextPrevClick(4)}
          active={active}
          component={<Login handleNextPrevClick={handleNextPrevClick} />}
        />
      </CDBStepper>
      </>

  );
};

export default Sample;

I'm using the react js and getting the error like this -export 'CDBStepper' (imported as 'CDBStepper') was not found in 'cdbreact'
enter image description here


问:
How to solve errors in DTD?

```<code>Errors in file DTD.dtd:
    1:  49  A ')' is required in the declaration of element type "hobby".

</code>```

I get some errors in DTD validator and I do not know What should I repaire in file?
Picture of error in link below

Fragment of DTD below

```<code><!ELEMENT hobby (gry,mechatronika,wprowadzenie,źródła)>
<!ELEMENT źródła (link)>
<!ELEMENT link (#PCDATA)>
<!ELEMENT gry (strategie,shooter)>
<!ELEMENT strategie (HeartsOfIron4)>
<!ELEMENT HeartsOfIron4 (studio,(dlc|mody))>
<!ELEMENT studio (#PCDATA)>
<!ELEMENT dlc ((nazwa, wydanie)+)>
<!ELEMENT nazwa (#PCDATA)>

</code>```

What should be fixed to well wokr?

Title: How to solve errors in DTD?

Body:
Errors in file DTD.dtd:
    1:  49  A ')' is required in the declaration of element type "hobby".

I get some errors in DTD validator and I do not know What should I repaire in file?
Picture of error in link below

Fragment of DTD below

<!ELEMENT hobby (gry,mechatronika,wprowadzenie,źródła)>
<!ELEMENT źródła (link)>
<!ELEMENT link (#PCDATA)>
<!ELEMENT gry (strategie,shooter)>
<!ELEMENT strategie (HeartsOfIron4)>
<!ELEMENT HeartsOfIron4 (studio,(dlc|mody))>
<!ELEMENT studio (#PCDATA)>
<!ELEMENT dlc ((nazwa, wydanie)+)>
<!ELEMENT nazwa (#PCDATA)>

What should be fixed to well wokr?


问:
Debian packaging: How to set the path in the script telling where the debian packages needs to be installed
I created a debian package and successfully installed it but the problem is, it is not accessible.
So that I want to write a script to tell where my debian package needs to be installed.

Package is installed but it is not being accessible. I need a executable desktop app so that when it is opened my script runs.


问:
ReactJS - Antd - More specific on TreeSelect.SHOW_CHILD
i'm currently use Antd TreeSelect for my components in React.

I got 1 problem 'bout this.

I had a treeData like the picture below. Especialy Parent 3 was a parent without any child.

It's look like folder and file for easier imaging. (Parent == folders & Child == files)

So if i use option showCheckedStrategy: TreeSelect.SHOW_CHILD then it gonna show Parent 3 as child too.

Which i want is Child options only. Any solution for this ?
Click here for img

Thank you for reading and have a nice day if you see this.

Tried every thing in my best and still cant handle it, hope to see one.


问:
Mac Catalyst - Make window NSToolbar transparent

Problem

Hi All,

I need help to make my window NSToolbar transparent, however, I still need to be able to use a toolbar within the window scene titlebar. Currently, you can set a titlebar to be transparent by either hiding your toolbar or not having one at all, but even though I will not be adding any actual tools within the toolbar, there needs to be one so that I can reposition the window traffic light buttons using the UITitlebarToolbarStyle property - I know that from Electron 8, developers are able to reposition the traffic light buttons (is this also possible in Swift?)

Any help is much appreciated

Current Code
- this is situated within the AppDelegate

```<code>guard let windowScene = (scene as? UIWindowScene) else { return }

#if targetEnvironment(macCatalyst)
windowScene.sizeRestrictions?.minimumSize = CGSize(width: 1366 * 0.9, height: 1024 * 0.9)
if let titlebar = windowScene.titlebar {
    let customToolbar = NSToolbar()
    titlebar.titleVisibility = .hidden
    titlebar.toolbar = customToolbar
    titlebar.toolbarStyle = .unified
    titlebar.autoHidesToolbarInFullScreen = true
}
#endif

window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.makeKeyAndVisible()
</code>```

Solution

I was able to work out how to make the titlebar transparent - it will however require you to install a library called Dynamic. This library allows you to access private hidden APIs for MacOS apps  because...

"Apple only made a very small portion of the macOS AppKit API visible to Catalyst apps"

To edit the transparency of the toolbar within MacOS Catalyst, follow these instructions - you should only need to do the following within your SceneDelegate file.

(1) Outside your Scene Delegate, add the following (make sure that the Dynamic library is installed). SPM: https://github.com/mhdhejazi/Dynamic.git

```<code>#if targetEnvironment(macCatalyst)
import Cocoa
import Dynamic

extension UIWindow {
    var nsWindow: NSObject? {
        var nsWindow = Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(self)
        if #available(macOS 11, *) {
            nsWindow = nsWindow.attachedWindow
        }
        return nsWindow.asObject
    }
}
#endif
</code>```

(2) Inside your SceneDelegate, add the following lines of code within the delegate method that connects your scene to the window...

```<code>guard let windowScene = (scene as? UIWindowScene) else { return }

window = UIWindow(frame: windowScene.coordinateSpace.bounds)

#if targetEnvironment(macCatalyst)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [self] in
    windowScene.sizeRestrictions?.minimumSize = CGSize(width: 1366 * 0.9, height: 1024 * 0.9)
    if let titlebar = windowScene.titlebar {
        titlebar.titleVisibility = .hidden
        titlebar.toolbar = NSToolbar()
    }

    let nswindow = Dynamic(window?.nsWindow)
    nswindow.titlebarAppearsTransparent = true
    nswindow.backgroundColor = Dynamic.NSColor.clearColor
}
#endif

window?.windowScene = windowScene
window?.makeKeyAndVisible()
</code>```

Final Code

```<code>#if targetEnvironment(macCatalyst)
import Cocoa
import Dynamic

extension UIWindow {
    var nsWindow: NSObject? {
        var nsWindow = Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(self)
        if #available(macOS 11, *) {
            nsWindow = nsWindow.attachedWindow
        }
        return nsWindow.asObject
    }
}
#endif

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }

        window = UIWindow(frame: windowScene.coordinateSpace.bounds)

        #if targetEnvironment(macCatalyst)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [self] in
            windowScene.sizeRestrictions?.minimumSize = CGSize(width: 1366 * 0.9, height: 1024 * 0.9)
            if let titlebar = windowScene.titlebar {
                titlebar.titleVisibility = .hidden
                titlebar.toolbar = NSToolbar()
            }

            let nswindow = Dynamic(window?.nsWindow)
            nswindow.titlebarAppearsTransparent = true
            nswindow.backgroundColor = Dynamic.NSColor.clearColor
        }
        #endif

        window?.windowScene = windowScene
        window?.makeKeyAndVisible()
    }
}
</code>```

Extra ✨

If you want to hide (or disable) the window traffic light buttons, you can access them with nswindow.standardWindowButton(x), where 'x' represents the traffic light button you want to edit. For example...

```<code>let nswindow = Dynamic(window?.nsWindow)
nswindow.standardWindowButton(0).isHidden = true //close
nswindow.standardWindowButton(1).isHidden = true //minimise
nswindow.standardWindowButton(2).isHidden = true //expand
</code>```

Body:
Problem

Hi All,

I need help to make my window NSToolbar transparent, however, I still need to be able to use a toolbar within the window scene titlebar. Currently, you can set a titlebar to be transparent by either hiding your toolbar or not having one at all, but even though I will not be adding any actual tools within the toolbar, there needs to be one so that I can reposition the window traffic light buttons using the UITitlebarToolbarStyle property - I know that from Electron 8, developers are able to reposition the traffic light buttons (is this also possible in Swift?)

Any help is much appreciated

Current Code
- this is situated within the AppDelegate

guard let windowScene = (scene as? UIWindowScene) else { return }

#if targetEnvironment(macCatalyst)
windowScene.sizeRestrictions?.minimumSize = CGSize(width: 1366 * 0.9, height: 1024 * 0.9)
if let titlebar = windowScene.titlebar {
    let customToolbar = NSToolbar()
    titlebar.titleVisibility = .hidden
    titlebar.toolbar = customToolbar
    titlebar.toolbarStyle = .unified
    titlebar.autoHidesToolbarInFullScreen = true
}
#endif

window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.makeKeyAndVisible()

Solution

I was able to work out how to make the titlebar transparent - it will however require you to install a library called Dynamic. This library allows you to access private hidden APIs for MacOS apps  because...

"Apple only made a very small portion of the macOS AppKit API visible to Catalyst apps"

To edit the transparency of the toolbar within MacOS Catalyst, follow these instructions - you should only need to do the following within your SceneDelegate file.

(1) Outside your Scene Delegate, add the following (make sure that the Dynamic library is installed). SPM: https://github.com/mhdhejazi/Dynamic.git

#if targetEnvironment(macCatalyst)
import Cocoa
import Dynamic

extension UIWindow {
    var nsWindow: NSObject? {
        var nsWindow = Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(self)
        if #available(macOS 11, *) {
            nsWindow = nsWindow.attachedWindow
        }
        return nsWindow.asObject
    }
}
#endif

(2) Inside your SceneDelegate, add the following lines of code within the delegate method that connects your scene to the window...

guard let windowScene = (scene as? UIWindowScene) else { return }

window = UIWindow(frame: windowScene.coordinateSpace.bounds)

#if targetEnvironment(macCatalyst)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [self] in
    windowScene.sizeRestrictions?.minimumSize = CGSize(width: 1366 * 0.9, height: 1024 * 0.9)
    if let titlebar = windowScene.titlebar {
        titlebar.titleVisibility = .hidden
        titlebar.toolbar = NSToolbar()
    }

    let nswindow = Dynamic(window?.nsWindow)
    nswindow.titlebarAppearsTransparent = true
    nswindow.backgroundColor = Dynamic.NSColor.clearColor
}
#endif

window?.windowScene = windowScene
window?.makeKeyAndVisible()

Final Code

#if targetEnvironment(macCatalyst)
import Cocoa
import Dynamic

extension UIWindow {
    var nsWindow: NSObject? {
        var nsWindow = Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(self)
        if #available(macOS 11, *) {
            nsWindow = nsWindow.attachedWindow
        }
        return nsWindow.asObject
    }
}
#endif

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }

        window = UIWindow(frame: windowScene.coordinateSpace.bounds)

        #if targetEnvironment(macCatalyst)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [self] in
            windowScene.sizeRestrictions?.minimumSize = CGSize(width: 1366 * 0.9, height: 1024 * 0.9)
            if let titlebar = windowScene.titlebar {
                titlebar.titleVisibility = .hidden
                titlebar.toolbar = NSToolbar()
            }

            let nswindow = Dynamic(window?.nsWindow)
            nswindow.titlebarAppearsTransparent = true
            nswindow.backgroundColor = Dynamic.NSColor.clearColor
        }
        #endif

        window?.windowScene = windowScene
        window?.makeKeyAndVisible()
    }
}

Extra ✨

If you want to hide (or disable) the window traffic light buttons, you can access them with nswindow.standardWindowButton(x), where 'x' represents the traffic light button you want to edit. For example...

let nswindow = Dynamic(window?.nsWindow)
nswindow.standardWindowButton(0).isHidden = true //close
nswindow.standardWindowButton(1).isHidden = true //minimise
nswindow.standardWindowButton(2).isHidden = true //expand


问:
Select multiple text in 1 combo box (span) suing send.keys
I am new to python and I am struggling to get multiple text in combo box (span) in web browser. It's taking single text or value in the list which I am applying. I tried with the lists, dict, select_by_visible text, Send.keys. still the same.

```<code>Logistics_Group =(driver.find_element(By.XPATH,'/html/body/table/tbody/tr[2]/td/table/tbody/tr/td/form/table[2]/tbody[2]/tr[1]/td/table[1]/tbody/tr[2]/td[4]/span/span')) Logistics_Group.send_keys("Disney Stores", "Casper", "Disney Theatrical", "MacLean", "Natureworks", "Net App","Sioux City", "Trinity Health", "XPO Direct", "XPO Logistics Group", "Young Living Essential Oils")
</code>```

I cannot use select method in this. Is there any way to get multiple text in 1 combo box (Span).

Note: If doing manually I can select multiple texts using the ctrl key

Body:
I am new to python and I am struggling to get multiple text in combo box (span) in web browser. It's taking single text or value in the list which I am applying. I tried with the lists, dict, select_by_visible text, Send.keys. still the same.

Logistics_Group =(driver.find_element(By.XPATH,'/html/body/table/tbody/tr[2]/td/table/tbody/tr/td/form/table[2]/tbody[2]/tr[1]/td/table[1]/tbody/tr[2]/td[4]/span/span')) Logistics_Group.send_keys("Disney Stores", "Casper", "Disney Theatrical", "MacLean", "Natureworks", "Net App","Sioux City", "Trinity Health", "XPO Direct", "XPO Logistics Group", "Young Living Essential Oils")

I cannot use select method in this. Is there any way to get multiple text in 1 combo box (Span).

Note: If doing manually I can select multiple texts using the ctrl key


问:
File can not be attached to the Email when we try to send an email with Kotlin?
The following code is working while using Jetpack Kotlin.

But there is a little problem it can not attach pdf file.

When email button clicked opened view with Gmail and Drive icon at bottom shows
the pdf file name as test.pdf at top.

But when we choose gmail at bottom everything filled correctly except test.pdf.
It is not attached to the email form and then can not be emailed.

```<code>           Button(onClick = {

             val i = Intent(Intent.ACTION_SEND)
             i.type = "vnd.android.cursor.dir/email"

            val emailAddress = arrayOf("testEmailAddress@gmail.com")
            i.putExtra(Intent.EXTRA_EMAIL,emailAddress)
            val name = FileWorks().createFileName(context = cx, dirName = "calc", fileName = "test.pdf")
            val contentUri = name.toURI()

            i.putExtra(Intent.EXTRA_STREAM, Uri.parse(name.toString()))
            i.putExtra(Intent.EXTRA_SUBJECT,"subject")
            i.putExtra(Intent.EXTRA_TEXT,"body")
            i.setType("message/rfc822")
            ctx.startActivity(Intent.createChooser(i,"Choose an Email client : "))
}
</code>```

Body:
The following code is working while using Jetpack Kotlin.

But there is a little problem it can not attach pdf file.

When email button clicked opened view with Gmail and Drive icon at bottom shows
the pdf file name as test.pdf at top.

But when we choose gmail at bottom everything filled correctly except test.pdf.
It is not attached to the email form and then can not be emailed.

           Button(onClick = {

             val i = Intent(Intent.ACTION_SEND)
             i.type = "vnd.android.cursor.dir/email"

            val emailAddress = arrayOf("testEmailAddress@gmail.com")
            i.putExtra(Intent.EXTRA_EMAIL,emailAddress)
            val name = FileWorks().createFileName(context = cx, dirName = "calc", fileName = "test.pdf")
            val contentUri = name.toURI()

            i.putExtra(Intent.EXTRA_STREAM, Uri.parse(name.toString()))
            i.putExtra(Intent.EXTRA_SUBJECT,"subject")
            i.putExtra(Intent.EXTRA_TEXT,"body")
            i.setType("message/rfc822")
            ctx.startActivity(Intent.createChooser(i,"Choose an Email client : "))
}


问:
If I only send PostgreSQL WAL(write ahead log) files from primary server to another server, PITR will work?
my database size is 100 GB and it takes time to send this big size dump to another server. I am doing WAL log archiving(incremental backup) of the primary database right now. Is it possible if only send the updated WAL files to the secondary server and the secondary server will contain as same data as the primary?</p>


问:
Is there a way to let the Git option in Azure Data Factory "Publish (from ADF Studio)" to be saved in Git?
When working in with the relatively new option to use automatic publish in ADF, it could be beneficial to be able to turn off the option "Publish (from ADF Studio)", so that we're not overwriting anything published via CI/CD.

However, with each PR to - in my case - 'dev', this option gets overwritten each time to 'enabled' even though I manually set this to 'disabled'. This leads me to think that this is a setting saved within the ADF infrastructure code, but after setting this to 'enabled', the following PR recognizes no changes.

Does anyone have a clue how to continuously overwrite this option to 'disabled'?

Many thanks.

I've tried to set this option to disabled, but after every PR the option reverts back to enabled.


问:
how to Dockerize Python FastAPI uvicorn application and deploy to container app
Azure Devblogs
as referred in above document, I'm trying to dockerize the above application and want to push to Azure container app

GitHub repo used

This is my Dockerfile:

```<code>FROM python:3.9
#FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
WORKDIR /cosmosdb-python-fastapi
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "--reload", "main:app","--host","0.0.0.0","--port", "80"]
</code>```

not sure what’s wrong in it: while running locally its seems to be okay, but when I deploy in azure container app I can’t see the changes.

I'm expecting this Python application be deployed in Azure container app and the image should be built based on dockerfile.

Body:
Azure Devblogs
as referred in above document, I'm trying to dockerize the above application and want to push to Azure container app

GitHub repo used

This is my Dockerfile:

FROM python:3.9
#FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
WORKDIR /cosmosdb-python-fastapi
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "--reload", "main:app","--host","0.0.0.0","--port", "80"]

not sure what’s wrong in it: while running locally its seems to be okay, but when I deploy in azure container app I can’t see the changes.

I'm expecting this Python application be deployed in Azure container app and the image should be built based on dockerfile.


问:
display all the corresponding item values in dropdown based on another text field dropdown in django
Here In the modal pop up when i enter the Order number as 1307 it need to display the all the items of that order number

Here I am attaching the screenshot of my Items list that need to be displayed in my drop down when i enter the order number

Here in dropdown i need to see items(laptops, Note books,Samsung Note 3) When i give this order number

Here is my html code

```<code><div class="modal-body">
        <form class="form-horizontal" id="adhoc-form" method="GET">
            {% csrf_token %}
            <fieldset>
                <div class="control-group">
                    <label class="control-label pull-left" for="capacity">Date</label>
                    <div class="controls">
                        <input name="date_manual" type="date">
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label pull-left" for="capacity">Process</label>
                    <div class="controls">
                        <select name="p_process">
                            <option value="">----------</option>
                            {% for process in production_process %}
                            <option value="{{process.id}}">{{process.name}}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label pull-left" for="capacity">Sales order</label>
                    <div class="controls">
                        <input name="order_number" type="text">
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label pull-left" for="capacity">Items</label>
                    <div class="controls">

                        <select name="item_part">
                            <option value="">-----</option>

                        </select>
                    </div>
                </div>
            </fieldset>
            <div id="form-buttons-container" class="form-actions" style="padding-left: 0px;">
                <div class="controls">
                    <input type="submit" class="btn btn-primary btn-medium" value="Submit">
                </div>
            </div>
        </form>
    </div>
</code>```

In the above code i need to display those 3 items of this order in label - Items

Please help me out to write view and script

Body:
Here In the modal pop up when i enter the Order number as 1307 it need to display the all the items of that order number

Here I am attaching the screenshot of my Items list that need to be displayed in my drop down when i enter the order number

Here in dropdown i need to see items(laptops, Note books,Samsung Note 3) When i give this order number

Here is my html code

        <form class="form-horizontal" id="adhoc-form" method="GET">
            {% csrf_token %}
            <fieldset>

                    Date

                        <input name="date_manual" type="date">

                    Process

                        <select name="p_process">
                            <option value="">----------</option>
                            {% for process in production_process %}
                            <option value="{{process.id}}">{{process.name}}</option>
                            {% endfor %}
                        </select>

                    Sales order

                        <input name="order_number" type="text">

                    Items

                        <select name="item_part">
                            <option value="">-----</option>

                        </select>

            </fieldset>

                    <input type="submit" class="btn btn-primary btn-medium" value="Submit">

        </form>

In the above code i need to display those 3 items of this order in label - Items

Please help me out to write view and script


问:
How to query and update value in firebase realtime database based on a specific condition?

In this database, timeout is null right now so it isn't showing. When I click a particular button I want timeout to update in the particular database. But in the future this db will be populated by tons of device so I want to sort through the database and look for device with a particular name and update timeout for only a particular device where timeout is null.

I am not able to figure how to sort through the database with unique keys and update where timeout is null for a specific devicename. I thought I would do something like this:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("userName").equalTo("Nick123");
query.addValueEventListener(/\* ... \*/);
</code>```

And then nest something similar for timeout inside this, but how would get the corresponding key of the timeout filed that was null. Even if i save the key while pushing it it just doesn't make sense. Can anyone please help me through this?

Body:
In this database, timeout is null right now so it isn't showing. When I click a particular button I want timeout to update in the particular database. But in the future this db will be populated by tons of device so I want to sort through the database and look for device with a particular name and update timeout for only a particular device where timeout is null.

I am not able to figure how to sort through the database with unique keys and update where timeout is null for a specific devicename. I thought I would do something like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("userName").equalTo("Nick123");
query.addValueEventListener(/\* ... \*/);

And then nest something similar for timeout inside this, but how would get the corresponding key of the timeout filed that was null. Even if i save the key while pushing it it just doesn't make sense. Can anyone please help me through this?


问:
Ansible inventory file in google cloud won't parse with any playbooks
My inventory file won't work for any of my playbooks I've tested it on multiple playbooks including ones that have worked for me in the past. I can't seem to figure out what's misconfigured or where the issue might be. The inventory file is fairly simple, and I have all of the requisites for getting ansible to run, ansible is up to date, and I'm positive the credentials file is fine since it's been working on my terraform configuration. Any input is appreciated!

Inventory file:

plugin: gcp_compute
projects:
  - projectName
auth_kind: serviceaccount
service_account_file: /home/.../.config/gcloud/application_default_credentials.json
keyed_groups:
  - prefix: gcp
    key: labels
  - prefix: tags
    key: tags
```
<p>Error that comes up when I try to use inventory:</p>
```  config file = None
  configured module search path = ['/home/.../.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/.../.local/lib/python3.10/site-packages/ansible
  ansible collection location = /home/.../.ansible/collections:/usr/share/ansible/collections
  executable location = /home/.../.local/bin/ansible-playbook
  python version = 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] (/usr/bin/python3)
  jinja version = 3.0.3
  libyaml = True
No config file found; using defaults
host_list declined parsing /home/.../inventory.gcp.yaml as it did not pass its verify_file() method
redirecting (type: inventory) ansible.builtin.gcp_compute to google.cloud.gcp_compute
Using inventory plugin 'ansible_collections.google.cloud.plugins.inventory.gcp_compute' to process inventory source '/home/.../inventory.gcp.yaml'
toml declined parsing /home/.../inventory.gcp.yaml as it did not pass its verify_file() method
[WARNING]:  * Failed to parse /home/.../inventory.gcp.yaml with script plugin: problem running
/home/.../inventory.gcp.yaml --list ([Errno 8] Exec format error:
'/home/.../inventory.gcp.yaml')
  File "/home/.../.local/lib/python3.10/site-packages/ansible/inventory/manager.py", line 293, in parse_source
    plugin.parse(self._inventory, self._loader, source, cache=cache)
 ...
    plugin.parse(self._inventory, self._loader, source, cache=cache)
  File "/home/.../.local/lib/python3.10/site-packages/ansible/plugins/inventory/yaml.py", line 114, in parse
    raise AnsibleParserError('Plugin configuration YAML file, not YAML inventory')
[WARNING]:  * Failed to parse /home/.../inventory.gcp.yaml with ini plugin: Invalid host pattern
'plugin:' supplied, ending in ':' is not allowed, this character is reserved to provide a port.
  File "/home/.../.local/lib/python3.10/site-packages/ansible/inventory/manager.py", line 293, in parse_source
    plugin.parse(self._inventory, self._loader, source, cache=cache)
  File "/home/.../.local/lib/python3.10/site-packages/ansible/plugins/inventory/ini.py", line 137, in parse
    raise AnsibleParserError(e)
[WARNING]: Unable to parse /home/.../inventory.gcp.yaml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit
```

Body:
My inventory file won't work for any of my playbooks I've tested it on multiple playbooks including ones that have worked for me in the past. I can't seem to figure out what's misconfigured or where the issue might be. The inventory file is fairly simple, and I have all of the requisites for getting ansible to run, ansible is up to date, and I'm positive the credentials file is fine since it's been working on my terraform configuration. Any input is appreciated!

Inventory file:

plugin: gcp_compute
projects:
  - projectName
auth_kind: serviceaccount
service_account_file: /home/.../.config/gcloud/application_default_credentials.json
keyed_groups:
  - prefix: gcp
    key: labels
  - prefix: tags
    key: tags

Error that comes up when I try to use inventory:

  config file = None
  configured module search path = ['/home/.../.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/.../.local/lib/python3.10/site-packages/ansible
  ansible collection location = /home/.../.ansible/collections:/usr/share/ansible/collections
  executable location = /home/.../.local/bin/ansible-playbook
  python version = 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] (/usr/bin/python3)
  jinja version = 3.0.3
  libyaml = True
No config file found; using defaults
host_list declined parsing /home/.../inventory.gcp.yaml as it did not pass its verify_file() method
redirecting (type: inventory) ansible.builtin.gcp_compute to google.cloud.gcp_compute
Using inventory plugin 'ansible_collections.google.cloud.plugins.inventory.gcp_compute' to process inventory source '/home/.../inventory.gcp.yaml'
toml declined parsing /home/.../inventory.gcp.yaml as it did not pass its verify_file() method
[WARNING]:  * Failed to parse /home/.../inventory.gcp.yaml with script plugin: problem running
/home/.../inventory.gcp.yaml --list ([Errno 8] Exec format error:
'/home/.../inventory.gcp.yaml')
  File "/home/.../.local/lib/python3.10/site-packages/ansible/inventory/manager.py", line 293, in parse_source
    plugin.parse(self._inventory, self._loader, source, cache=cache)
 ...
    plugin.parse(self._inventory, self._loader, source, cache=cache)
  File "/home/.../.local/lib/python3.10/site-packages/ansible/plugins/inventory/yaml.py", line 114, in parse
    raise AnsibleParserError('Plugin configuration YAML file, not YAML inventory')
[WARNING]:  * Failed to parse /home/.../inventory.gcp.yaml with ini plugin: Invalid host pattern
'plugin:' supplied, ending in ':' is not allowed, this character is reserved to provide a port.
  File "/home/.../.local/lib/python3.10/site-packages/ansible/inventory/manager.py", line 293, in parse_source
    plugin.parse(self._inventory, self._loader, source, cache=cache)
  File "/home/.../.local/lib/python3.10/site-packages/ansible/plugins/inventory/ini.py", line 137, in parse
    raise AnsibleParserError(e)
[WARNING]: Unable to parse /home/.../inventory.gcp.yaml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit


问:
How to create multiple tables(like test1-test100 in a sequence) from a sourcetable 'test' in Athena?
I know create table as select * from table (CTA)S works for 1 table here but, I need to CTAS 1-100 tables in a single command with no data,Can someone help here to give a script that works in ATHENA.

I tried a for loop that works with oracle but here in Athena it doesnt work as single statement

```<code>begin
    for idx in 1..100 loop
        execute immediate
            'Create table test'|| idx ||' AS
                Select *
                FROM test2 WITH NO DATA'
    end loop;
end;
</code>```

Body:
I know create table as select * from table (CTA)S works for 1 table here but, I need to CTAS 1-100 tables in a single command with no data,Can someone help here to give a script that works in ATHENA.

I tried a for loop that works with oracle but here in Athena it doesnt work as single statement

begin
    for idx in 1..100 loop
        execute immediate
            'Create table test'|| idx ||' AS
                Select *
                FROM test2 WITH NO DATA'
    end loop;
end;


问:
How to execute CMake custom command without building any target?
I have a CMakeLists.txt file with add_custom_command that adds a command to unite all the project source files and generate one output unit.cc file. Is there a way to just run this command without building any target that depends on it? Like cmake -E ... does. I need to sloc the file and don't wanna wait the long compilation.

I tried to look at the docs but they said, IIUC, that I can run commands only when they depend on some target.


问:
Using amplify react components in a Svelte-kit project
I've been trying to import and use @amplify/ui-react componetns inside a svelte kit file.
However, when I import the components i get the error:
"Cannot use import statement outside a module"

My code is shown below, and the error only occurs while the import {authenticator} line is present. Meaning its unique to ui-react components.

I've tried messing around with files and extensions, aswell as differnet component versions but I can't seem to shake this error. Any help with this would be greatly appreciated.

Code

error