问:
Why do I get "end of line without line continuation" when trying to draw a rectangle around all the candles between a certain time?
I've seen many indicators that mark the range of forex trading sessions.

In a similar manner I'd like to draw a rectangle around all the candles between 15:00 - 18:00 GMT+2.

I'd like the top of the rectangle to be on top of the high in that range and the bottom at the low of the range.

I've tried looking at the code that they used in some of the forex trading session indicators but I'm new to all this and it went over my head. I'm also still becoming accustomed to using documentation and being able to practically create implementations from documentation.

I've tried the following:

```<code>//@version=5
indicator('My Indicator', overlay = true)

// Define the start and end times for the rectangle
startTime = timestamp(year, month, day, 10, 0, 0) - time('50D')
endTime = timestamp(year, month, day, 11, 0, 0) - time('50D')

// Use a for loop to iterate over the days in the data
for i = 0 to 49
  // Get the high and low values for the rectangle
  highValue = highest(high[range(startTime, endTime)])
  lowValue = lowest(low[range(startTime, endTime)])

  // Draw the top and bottom lines of the rectangle
  hline(highValue, startTime, endTime, color=color.orange)
  hline(lowValue, startTime, endTime, color=color.orange)

  // Draw the left and right lines of the rectangle
  vline(startTime, highValue, lowValue, color=color.orange)
  vline(endTime, highValue, lowValue, color=color.orange)

  // Increment the start and end times to the next day
  startTime := startTime + time('1D')
</code>```

But I received the error:

10:11:36 PM — Compilation error. Line 12: Mismatched input 'highValue' expecting 'end of line without line continuation'

How can I get this to work?

Body:
I've seen many indicators that mark the range of forex trading sessions.

In a similar manner I'd like to draw a rectangle around all the candles between 15:00 - 18:00 GMT+2.

I'd like the top of the rectangle to be on top of the high in that range and the bottom at the low of the range.

I've tried looking at the code that they used in some of the forex trading session indicators but I'm new to all this and it went over my head. I'm also still becoming accustomed to using documentation and being able to practically create implementations from documentation.

I've tried the following:

//@version=5
indicator('My Indicator', overlay = true)

// Define the start and end times for the rectangle
startTime = timestamp(year, month, day, 10, 0, 0) - time('50D')
endTime = timestamp(year, month, day, 11, 0, 0) - time('50D')

// Use a for loop to iterate over the days in the data
for i = 0 to 49
  // Get the high and low values for the rectangle
  highValue = highest(high[range(startTime, endTime)])
  lowValue = lowest(low[range(startTime, endTime)])

  // Draw the top and bottom lines of the rectangle
  hline(highValue, startTime, endTime, color=color.orange)
  hline(lowValue, startTime, endTime, color=color.orange)

  // Draw the left and right lines of the rectangle
  vline(startTime, highValue, lowValue, color=color.orange)
  vline(endTime, highValue, lowValue, color=color.orange)

  // Increment the start and end times to the next day
  startTime := startTime + time('1D')

But I received the error:

10:11:36 PM — Compilation error. Line 12: Mismatched input 'highValue' expecting 'end of line without line continuation'

How can I get this to work?


来源: stackexchange

问:
ASP.NET MVC Rotativa ViewAsPDF vastly different between debug and production
I am using Rotativa ViewAsPdf to turn a .cshtml page into PDF.

When I run the code as debug, the PDF turns out the way I want. The page has tables and an image on the top.

Whenever I publish the application and try to generate the PDF as a different entry, the tables lines that separate columns from rows aren't there, and everything is mashed together, and the image will not display.

This is the POST details in question.

```<code>public async Task<IActionResult> PrintDetails(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var wC_Inbox = await _context.WC_Inbox
                                 .FirstOrDefaultAsync(m => m.ID == id);

    var report = new ViewAsPdf("Details", wC_Inbox)
                     {
                         FileName = "InitialInbox.pdf"
                     };
    return report;
}
</code>```

Here are the differences between the two PDFs that get generated. The one on the left is what is generated when running on debug, and the one on the right is the messed up one that gets generated on the production.

(https://i.stack.imgur.com/b14nb.png)

ContentLicense: CC BY-SA 4.0

Body:
I am using Rotativa ViewAsPdf to turn a .cshtml page into PDF.

When I run the code as debug, the PDF turns out the way I want. The page has tables and an image on the top.

Whenever I publish the application and try to generate the PDF as a different entry, the tables lines that separate columns from rows aren't there, and everything is mashed together, and the image will not display.

This is the POST details in question.

public async Task<IActionResult> PrintDetails(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var wC_Inbox = await _context.WC_Inbox
                                 .FirstOrDefaultAsync(m => m.ID == id);

    var report = new ViewAsPdf("Details", wC_Inbox)
                     {
                         FileName = "InitialInbox.pdf"
                     };
    return report;
}

Here are the differences between the two PDFs that get generated. The one on the left is what is generated when running on debug, and the one on the right is the messed up one that gets generated on the production.

(https://i.stack.imgur.com/b14nb.png)


问:
mapActions,mapGetters,created how to used in <sript steup>?
```<code><script setup>
import { ref, onMounted, onBeforeMount } from 'vue';

const products = ref(null);

methods: {
      ...mapActions(["fetchUsers",])
    },
    computed: mapGetters(["usersList"]),
    created() {
      this.fetchUsers()
    }

onBeforeMount(() => {
    initFilters();
});
onMounted(() => {
    fetchCalculators();
});

</script>
</code>```
```<code>methods: {
      ...mapActions(["fetchUsers",])
    },
    computed: mapGetters(["usersList"]),
    created() {
      this.fetchUsers()
    }
</code>```

this part mapActions,mapGetters,created how to used in
vue3?

this part mapActions,mapGetters,created how to used in
vue3?this part mapActions,mapGetters,created how to used in
vue3?

Body:
methods: {
      ...mapActions(["fetchUsers",])
    },
    computed: mapGetters(["usersList"]),
    created() {
      this.fetchUsers()
    }

this part mapActions,mapGetters,created how to used in
vue3?

this part mapActions,mapGetters,created how to used in
vue3?this part mapActions,mapGetters,created how to used in
vue3?


问:
Tailwindcss class not taking effect when added with javascript
I added a tailwindcss class to my content div using javascript. It is added but doesn't take effect unless I add that class manually to the div and then remove it.

I made a fixed header using Tailwind CSS and needed to add margin to the main content div equal to the height of the header.
The height of the header changes depending on the screen size so I used Javascript for changing the margin equal to the header's height.
The class is applied to the div but it doesn't take effect.
Here's my code:
main content html
Javascript:
Javascript for adding the margin
As you can see in the inspect the margin class 'mt-[88px]' is added but the main-content div has no margin at all.
Inspect
It works If I add the margin manually once and then remove it but I don't know why it doesn't work from the get-go.
Even if I add the margin manually once I have to do it for each header height. For instance it's 88px on larger screens so I add mt-[88px] and then just remove it and add mt-[104px] for smaller screens and then remove the class.
My tailwindcss config file:
tailwind.config.js


问:
svelte with electron is not showing html or not rendering svelte code properly
I am creating svelte app with electron, did basic setup and tried to run app after some initial error solving, now I am able to generate window with electron but I am not getting HTML output from svelte app.html page.

its showing me %sveltekit.head% %sveltekit.body% as an output instead of Welcome to SvelteKit and paragraph Visit kit.svelte.dev to read the documentation which is default output anyone ill get if they start svelte project using npm run dev.

if you add "type: "commonjs" in package.json, it is not allowing me to use import statememt, if i changed it to commonjs, it working and creating window but then it's not rendering svelte code in html output.

here is Whole code, you can clone and npm install && npm run start :
Download from GIT REPO .

I am not sure but I think "type":"commonjs" is the problem, but if I change it to "type":"module", then my electron/index.js is causing problem.

need your help guys.


问:
When I try to import an HTML file into React, I get an error
I saw one beautiful star animation in codesandbox link I want to apply it in my project, for this I created a separate HTML file and put the code from the link. Now i am trying to render html file in my jsx

```<code>import htmlFile from 'Assets/Styles/Test.html';

function Page () {
   return <iframe src={htmlFile}></iframe>
}
</code>```

But I am getting this kind of error

What is it connected with? How can I solve this problem?

Body:
I saw one beautiful star animation in codesandbox link I want to apply it in my project, for this I created a separate HTML file and put the code from the link. Now i am trying to render html file in my jsx

import htmlFile from 'Assets/Styles/Test.html';

function Page () {
   return
}

But I am getting this kind of error

What is it connected with? How can I solve this problem?


问:
How to create a Friend Request system with mongoDB and Express?
In my social media application, I want to introduce a friend request system that is similar to Instagram:

user A can follow user B, but user B doesn't have to follow user A back

if user B is a private user, then user B should receive a follow request from user A which they can either approve or decline. On approval, user A is registered as a follower of user B

How could this be achieved using mongoDB (including Mongoose) and Express?

I currently have some simple User, UserFollower and UserFollowing schemas that allow simple follow/unfollow updates to take place. They are configured as below:

```<code>const userSchema = new Schema({
  email: String,
  // isPrivate: Boolean,
});

const userFollowerSchema = new Schema({
  userId: Schema.Types.ObjectId,
  followerIds: [Schema.Types.ObjectId],
});

const userFollowingSchema = new Schema({
  userId: Schema.Types.ObjectId,
  followingIds: [Schema.Types.ObjectId],
});
</code>```

At the moment, user A is able to follow user B freely, with their ID getting added to user B's followerIds on demand. However, as per the commented path, I want a permission to be granted from user B if their isPrivate => true.

Obviously, this is quite a basic implementation so far, but I'm happy to restructure it completely to make it more scalable to include features such as blocking users etc.

Body:
In my social media application, I want to introduce a friend request system that is similar to Instagram:

user A can follow user B, but user B doesn't have to follow user A back

if user B is a private user, then user B should receive a follow request from user A which they can either approve or decline. On approval, user A is registered as a follower of user B

How could this be achieved using mongoDB (including Mongoose) and Express?

I currently have some simple User, UserFollower and UserFollowing schemas that allow simple follow/unfollow updates to take place. They are configured as below:

const userSchema = new Schema({
  email: String,
  // isPrivate: Boolean,
});

const userFollowerSchema = new Schema({
  userId: Schema.Types.ObjectId,
  followerIds: [Schema.Types.ObjectId],
});

const userFollowingSchema = new Schema({
  userId: Schema.Types.ObjectId,
  followingIds: [Schema.Types.ObjectId],
});

At the moment, user A is able to follow user B freely, with their ID getting added to user B's followerIds on demand. However, as per the commented path, I want a permission to be granted from user B if their isPrivate => true.

Obviously, this is quite a basic implementation so far, but I'm happy to restructure it completely to make it more scalable to include features such as blocking users etc.


问:
How to fix "Unable to determine the relationship" in C#
I'm getting the following error when trying to establish the database relationship. But I couldn't establish a relationship:

Unable to determine the relationship represented by navigation 'Event.ApplicationUser' of type 'ApplicationUser'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

A user can participate in more than one event.

A user can have multiple events.

An event can have multiple participants.

An event can be created by only one user.

public class Event : EntitySoftDeletableIntKey
{
    public string Title { get; set; }
    public string ShortContent { get; set; }
    public string Place { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int EventDetailId { get; set; }
    public EventDetail EventDetail { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public List<Tag> Tags { get; set; } = new List<Tag>();
    public List<Comment> Comments { get; set; } = new List<Comment>();
    //This event was published by one user.
    public ApplicationUser ApplicationUser { get; set; }
    public int ApplicationUserId { get; set; }
    //Multiple participants attended this event.
    public List<ApplicationUser> Attendees { get; set; } = new List<ApplicationUser>();
    public List<FavoriteEvent> FavoriteEvents { get; set; }

}
```
<pre class="lang-cs prettyprint-override"><code>public class ApplicationUser : IdentityUser<int>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<FavoriteEvent> FavoriteEvents { get; set; } = new List<FavoriteEvent>();
    //This user has posted multiple events.
    public List<Event> Events { get; set; } = new List<Event>();
    //this user has attended more then one events
    public List<Event> AttendedEvents { get; set; } = new List<Event>();

}
</code>```

Thank you for answers...

Body:
I'm getting the following error when trying to establish the database relationship. But I couldn't establish a relationship:

Unable to determine the relationship represented by navigation 'Event.ApplicationUser' of type 'ApplicationUser'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

A user can participate in more than one event.

A user can have multiple events.

An event can have multiple participants.

An event can be created by only one user.

public class Event : EntitySoftDeletableIntKey
{
    public string Title { get; set; }
    public string ShortContent { get; set; }
    public string Place { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int EventDetailId { get; set; }
    public EventDetail EventDetail { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public List<Tag> Tags { get; set; } = new List<Tag>();
    public List<Comment> Comments { get; set; } = new List<Comment>();
    //This event was published by one user.
    public ApplicationUser ApplicationUser { get; set; }
    public int ApplicationUserId { get; set; }
    //Multiple participants attended this event.
    public List<ApplicationUser> Attendees { get; set; } = new List<ApplicationUser>();
    public List<FavoriteEvent> FavoriteEvents { get; set; }

}

public class ApplicationUser : IdentityUser<int>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<FavoriteEvent> FavoriteEvents { get; set; } = new List<FavoriteEvent>();
    //This user has posted multiple events.
    public List<Event> Events { get; set; } = new List<Event>();
    //this user has attended more then one events
    public List<Event> AttendedEvents { get; set; } = new List<Event>();

}

Thank you for answers...


问:
Slow assembly using a large include file in MASM
Recently split a large MASM project consisting of 50 included assembly files into separate translation units. However, the assembly time increased from 1 min to 10 mins! The reason for this dramatic increase was tracked down to a LARGE include file with 60,000 constants (built from parsing Windows/Linux C header files for constants, then massaged into the MASM syntax)

WindowsLinux.inc

```<code>ERROR_SUCCESS                                       EQU       0
ERROR_INVALID_FUNCTION                              EQU       1
ERROR_FILE_NOT_FOUND                                EQU       2
ERROR_PATH_NOT_FOUND                                EQU       3
ERROR_TOO_MANY_OPEN_FILES                           EQU       4
ERROR_ACCESS_DENIED                                 EQU       5
...
</code>```

For example, created this simple timing test when including WindowsLinux.inc for the constant ERROR_SUCCESS

slow.asm

```<code>option casemap:none

extrn printf:proc

IFDEF SLOW
   include WindowsLinux.inc
ELSE
   ERROR_SUCCESS EQU 0
ENDIF

.data

     szError db 'ERROR_SUCCESS = %d',0ah,0

.code

main proc
     mov     rdx,ERROR_SUCCESS
     mov     rcx,offset szError
     call    printf

     ret

main endp

end
</code>```

Assembled slow.asm passing a defined text macro /DSLOW to include WindowsLinux.inc

```<code>@ECHO %TIME%
ml64.exe /DSLOW /c slow.asm
@ECHO %TIME%
</code>```

The output below shows it took ~ 8 seconds.

9:15:52.17

C:\masm32>ml64.exe /DSLOW /c slow.asm

Microsoft (R) Macro Assembler (x64) Version 14.29.30146.0

Copyright (C) Microsoft Corporation.  All rights reserved.

Assembling: slow.asm

9:15:59.43

Reassembled slow.asm removing the defined text macro /DSLOW

```<code>@ECHO %TIME%
ml64.exe /c slow.asm
@ECHO %TIME%
</code>```

The output below shows it took ~ 3 milliseconds.

9:35:55.12

C:\masm32>ml64.exe /c slow.asm

Microsoft (R) Macro Assembler (x64) Version 14.29.30146.0

Copyright (C) Microsoft Corporation.  All rights reserved.

Assembling: slow.asm

9:35:55.15

To resolve the slow include file issue, the number of constants was reduced from 60,000 to 250.
However, this requires constantly updating the include file each time a new constant is added to the source code. Perhaps there's a better approach?

Question

Do any assemblers have a similar concept to C/C++ Precompiled headers which can  significantly reduce compilation time?

Body:
Recently split a large MASM project consisting of 50 included assembly files into separate translation units. However, the assembly time increased from 1 min to 10 mins! The reason for this dramatic increase was tracked down to a LARGE include file with 60,000 constants (built from parsing Windows/Linux C header files for constants, then massaged into the MASM syntax)

WindowsLinux.inc

ERROR_SUCCESS                                       EQU       0
ERROR_INVALID_FUNCTION                              EQU       1
ERROR_FILE_NOT_FOUND                                EQU       2
ERROR_PATH_NOT_FOUND                                EQU       3
ERROR_TOO_MANY_OPEN_FILES                           EQU       4
ERROR_ACCESS_DENIED                                 EQU       5
...

For example, created this simple timing test when including WindowsLinux.inc for the constant ERROR_SUCCESS

slow.asm

option casemap:none

extrn printf:proc

IFDEF SLOW
   include WindowsLinux.inc
ELSE
   ERROR_SUCCESS EQU 0
ENDIF

.data

     szError db 'ERROR_SUCCESS = %d',0ah,0

.code

main proc
     mov     rdx,ERROR_SUCCESS
     mov     rcx,offset szError
     call    printf

     ret

main endp

end

Assembled slow.asm passing a defined text macro /DSLOW to include WindowsLinux.inc

@ECHO %TIME%
ml64.exe /DSLOW /c slow.asm
@ECHO %TIME%

The output below shows it took ~ 8 seconds.

9:15:52.17

C:\masm32>ml64.exe /DSLOW /c slow.asm

Microsoft (R) Macro Assembler (x64) Version 14.29.30146.0

Copyright (C) Microsoft Corporation.  All rights reserved.

Assembling: slow.asm

9:15:59.43

Reassembled slow.asm removing the defined text macro /DSLOW

@ECHO %TIME%
ml64.exe /c slow.asm
@ECHO %TIME%

The output below shows it took ~ 3 milliseconds.

9:35:55.12

C:\masm32>ml64.exe /c slow.asm

Microsoft (R) Macro Assembler (x64) Version 14.29.30146.0

Copyright (C) Microsoft Corporation.  All rights reserved.

Assembling: slow.asm

9:35:55.15

To resolve the slow include file issue, the number of constants was reduced from 60,000 to 250.
However, this requires constantly updating the include file each time a new constant is added to the source code. Perhaps there's a better approach?

Question

Do any assemblers have a similar concept to C/C++ Precompiled headers which can  significantly reduce compilation time?


问:
Distributing static package data as separate Python package?
My Python + Django application has quite a lot of CSS/JS dependencies, which change quite seldom.

I was thinking about separating the two. My package with the dependencies takes 2x more space than without them (with deps 8.7 MB, without deps about 4.3 MB).

Those dependencies are crucial to run the application and I would not exactly like the idea of building them on a production server, as it introduces another possible point of failure. Also, having a comfort of pip install or even pipx install is a valuable thing for an application, so I thought about making them a dependency of the "main" app package.

Are there any official, sanctioned methods to build separate static data package for an app? Or, are there any other sensible ways of building such data? I was looking into building another, separate static-data package with Poetry, but it does not look like an easy task.

I would also like to build that data-package from the same source tree, as Django already collects the static files for me. In my Django app I already use an approach similar to django-yarnpkg , which is I keep a list of yarn-installable packages and use a custom FilesystemFinder


Title: Open Geo Data (GDAL Translate XYZ -> GeoTiff)

Body:
Analyze the data structure
Q: What is in the columns of the XYZ file?
Q: Which unit does each column have?
Q: Which coordinate reference system (CRS) is used?

322000.00 5728999.00 17.22  322001.00 5728999.00 17.09  322002.00 5728999.00 17.06  322003.00 5728999.00 17.04  322004.00 5728999.00 17.01  322005.00 5728999.00 17.05  322006.00 5728999.00 17.12  322007.00 5728999.00 17.08  322008.00 5728999.00 17.11  322009.00 5728999.00 17.10  322010.00 5728999.00 17.10  322011.00 5728999.00 17.11  322012.00 5728999.00 17.14

I can't figure out what is this. I am new in OpenGeo Data. Could you help me out with this problem?


问:
Display message from function as text in a shiny app
I have the shiny app below in which Im trying to display as text the result of the function detect_time_anomalies2. The result is something like: For 0 rows in the activity log (0%), an anomaly is detected.

```<code>## app.R ##
library(shiny)
library(shinydashboard)
library(bupaR)
library(daqapo)

hospital<-structure(list(patient_visit_nr = c(510, 512, 510, 512, 512,
                                          510, 517, 518, 518, 518, 519, 519, 520, 519, 521, 521, 519, 522,
                                          522, 523, 524, 525, 526, 523, 527, 527, 527, 528, 528, 523),
                     activity = c("registration", "Registration", "Triage", "Triage",
                                  "Clinical exam", "Clinical exam", "Triage", "Registration",
                                  "Registration", "Registration", "Registration", "Triage",
                                  "Trage", "Clinical exam", "Triage", "Registration", "Treatment",
                                  "Registration", "Triaga", "Registration", "Triage", "Triage",
                                  "Triage", "Triage", "Registration", "Triage", "Clinical exam",
                                  "Registration", "Triage", "Clinical exam"), originator = c("Clerk 9",
                                                                                "Clerk 12", "Nurse 27", "Nurse 27", "Doctor 7", "Doctor 7",
                                                                                "Nurse 17", "Clerk 12", "Clerk 6", "Clerk 9", "Clerk 12",
                                                                                "Nurse 17", "Nurse 17", "Doctor 4", "Nurse 17", "Clerk 3",
                                                                                "Nurse 17", "Clerk 3", "Nurse 5", "Clerk 9", "Nurse 5", "Nurse 5",
                                                                                "Nurse 5", "Nurse 27", "Clerk 6", "Nurse 5", "Doctor 4",
                                                                                "Nurse 6", "Nurse 6", "Doctor 4"), start = structure(c(1511173097,
                                                                                1511173994, 1511174048, 1511174652, 1511177232, 1511177701,
                                                                                1511264116, 1511264716, 1511264716, 1511264716, 1511265581,
                                                                                1511270783, 1511271796, 1511272354, 1511272924, 1511273120,
                                                                                1511275132, 1511277137, 1511277325, 1511282528, 1511283843,
                                                                                1511283853, 1511283855, 1511285190, 1511287330, 1511287331,
                                                                                1511287333, 1511287817, 1511288105, 1511288209), tzone = "UTC", class = c("POSIXct",
                                                                                "POSIXt")), complete = structure(c(1511173206, 1511174220,
                                                                                1511174508, 1511175017, 1511177637, 1511177769, 1511264340,
                                                                                1511263336, 1511263336, 1511263336, 1511265952, 1511271138,
                                                                                1511271540, 1511272954, 1511273169, 1511290800, 1511275761,
                                                                                1511277499, 1511277484, 1511283119, 1511283965, 1511283968,
                                                                                1511283970, 1511287261, 1511287447, 1511287448, 1511287450,
                                                                                1511288104, 1511288412, 1511288528), tzone = "UTC", class = c("POSIXct",
                                                                                "POSIXt")), triagecode = c(3, 3, 3, 3, 3, NA, 3, 4, 4, 4,
                                                                                4, 4, 5, 4, 2, 2, 4, 2, 2, 3, 3, 3, 4, 3, 2, 2, 2, 3, 3,
                                                                                3), specialization = c("TRAU", "URG", "TRAU", "URG", "URG",
                                                                                "URG", "URG", "PED", "PED", "PED", "PED", "PED", "URG", "PED",
                                                                                "URG", "URG", "PED", "URG", "URG", "URG", "URG", "URG", "URG",
                                                                                "URG", "URG", "URG", "URG", "TRAU", "TRAU", "URG"), .order = 1:30), row.names = c(NA,
                                                                                -30L), class = c("activitylog", "log", "tbl_df", "tbl", "data.frame"
                                                                                ), case_id = "patient_visit_nr", activity_id = "activity", resource_id = "originator", timestamps = c("start",
                                                                                "complete"))

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
  ),
  dashboardBody(
    textOutput("print")
    )
)

server <- function(input, output) {

  detect_time_anomalies2 <- function(activitylog, anomaly_type = c("both", "negative","zero") ,
                                     details = TRUE, filter_condition = NULL){

    # Predefine variables
    type <- NULL
    duration <- NULL
    activity <- NULL
    complete <- NULL
    start <- NULL
    anomaly_type <- match.arg(anomaly_type)
    # Generate warning if inappropriate anomaly type is selected

    # Apply filter condition when specified
    filter_specified <- FALSE
    tryCatch({
      is.null(filter_condition)
    }, error = function(e) {
      filter_specified <<- TRUE
    }
    )

    if(!filter_specified) {
      # geen filter gespecifieerd.

    } else {
      filter_condition_q <- enquo(filter_condition)
      activitylog <- APPLY_FILTER(activitylog, filter_condition_q = filter_condition_q)
    }

    # Calculate durations
    activitylog %>%
      mutate(duration = as.double(complete - start, units = "mins")) -> anomalies

    # Determine time anomalies
    if(anomaly_type == "negative"){
      anomalies <- anomalies %>% filter(duration < 0)
    } else if(anomaly_type == "zero"){
      anomalies <- anomalies %>% filter(duration == 0)
    } else{
      anomalies <- anomalies %>% filter(duration <= 0) %>%
        mutate(type = ifelse(duration < 0, "negative duration", "zero duration"))
    }

    output <- list()

    # Print output
    message("Selected anomaly type: ", anomaly_type, "\n")
    output$anomaly_type <- anomaly_type

    message("*** OUTPUT ***")
    output$percent_anomalies <- round(nrow(anomalies) / nrow(activitylog) * 100, 2)
    output$num_anomalies <- nrow(anomalies)
    message("For ", nrow(anomalies), " rows in the activity log (", output$percent_anomalies, "%), an anomaly is detected.")

    if(nrow(anomalies) > 0){
      message("The anomalies are spread over the activities as follows:")
      if(anomaly_type == "both"){
        output$both <- anomalies %>% group_by(!!activity_id_(activitylog), type) %>% summarize(n = n()) %>% arrange(desc(n))
        print(output$both)
      } else{
        output$other <- anomalies %>% group_by(!!activity_id_(activitylog)) %>% summarize(n = n()) %>% arrange(desc(n))
        print(output$other)
      }

      if(details == TRUE){
        message("Anomalies are found in the following rows:")
        output$details <- anomalies
        return(output$details)
      }
    }
  }
  output$print<-renderText({
    hospital%>%detect_time_anomalies2()
  })

}

shinyApp(ui, server)
</code>```

Body:
I have the shiny app below in which Im trying to display as text the result of the function detect_time_anomalies2. The result is something like: For 0 rows in the activity log (0%), an anomaly is detected.

## app.R ##
library(shiny)
library(shinydashboard)
library(bupaR)
library(daqapo)

hospital<-structure(list(patient_visit_nr = c(510, 512, 510, 512, 512,
                                          510, 517, 518, 518, 518, 519, 519, 520, 519, 521, 521, 519, 522,
                                          522, 523, 524, 525, 526, 523, 527, 527, 527, 528, 528, 523),
                     activity = c("registration", "Registration", "Triage", "Triage",
                                  "Clinical exam", "Clinical exam", "Triage", "Registration",
                                  "Registration", "Registration", "Registration", "Triage",
                                  "Trage", "Clinical exam", "Triage", "Registration", "Treatment",
                                  "Registration", "Triaga", "Registration", "Triage", "Triage",
                                  "Triage", "Triage", "Registration", "Triage", "Clinical exam",
                                  "Registration", "Triage", "Clinical exam"), originator = c("Clerk 9",
                                                                                "Clerk 12", "Nurse 27", "Nurse 27", "Doctor 7", "Doctor 7",
                                                                                "Nurse 17", "Clerk 12", "Clerk 6", "Clerk 9", "Clerk 12",
                                                                                "Nurse 17", "Nurse 17", "Doctor 4", "Nurse 17", "Clerk 3",
                                                                                "Nurse 17", "Clerk 3", "Nurse 5", "Clerk 9", "Nurse 5", "Nurse 5",
                                                                                "Nurse 5", "Nurse 27", "Clerk 6", "Nurse 5", "Doctor 4",
                                                                                "Nurse 6", "Nurse 6", "Doctor 4"), start = structure(c(1511173097,
                                                                                1511173994, 1511174048, 1511174652, 1511177232, 1511177701,
                                                                                1511264116, 1511264716, 1511264716, 1511264716, 1511265581,
                                                                                1511270783, 1511271796, 1511272354, 1511272924, 1511273120,
                                                                                1511275132, 1511277137, 1511277325, 1511282528, 1511283843,
                                                                                1511283853, 1511283855, 1511285190, 1511287330, 1511287331,
                                                                                1511287333, 1511287817, 1511288105, 1511288209), tzone = "UTC", class = c("POSIXct",
                                                                                "POSIXt")), complete = structure(c(1511173206, 1511174220,
                                                                                1511174508, 1511175017, 1511177637, 1511177769, 1511264340,
                                                                                1511263336, 1511263336, 1511263336, 1511265952, 1511271138,
                                                                                1511271540, 1511272954, 1511273169, 1511290800, 1511275761,
                                                                                1511277499, 1511277484, 1511283119, 1511283965, 1511283968,
                                                                                1511283970, 1511287261, 1511287447, 1511287448, 1511287450,
                                                                                1511288104, 1511288412, 1511288528), tzone = "UTC", class = c("POSIXct",
                                                                                "POSIXt")), triagecode = c(3, 3, 3, 3, 3, NA, 3, 4, 4, 4,
                                                                                4, 4, 5, 4, 2, 2, 4, 2, 2, 3, 3, 3, 4, 3, 2, 2, 2, 3, 3,
                                                                                3), specialization = c("TRAU", "URG", "TRAU", "URG", "URG",
                                                                                "URG", "URG", "PED", "PED", "PED", "PED", "PED", "URG", "PED",
                                                                                "URG", "URG", "PED", "URG", "URG", "URG", "URG", "URG", "URG",
                                                                                "URG", "URG", "URG", "URG", "TRAU", "TRAU", "URG"), .order = 1:30), row.names = c(NA,
                                                                                -30L), class = c("activitylog", "log", "tbl_df", "tbl", "data.frame"
                                                                                ), case_id = "patient_visit_nr", activity_id = "activity", resource_id = "originator", timestamps = c("start",
                                                                                "complete"))

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
  ),
  dashboardBody(
    textOutput("print")
    )
)

server <- function(input, output) {

  detect_time_anomalies2 <- function(activitylog, anomaly_type = c("both", "negative","zero") ,
                                     details = TRUE, filter_condition = NULL){

    # Predefine variables
    type <- NULL
    duration <- NULL
    activity <- NULL
    complete <- NULL
    start <- NULL
    anomaly_type <- match.arg(anomaly_type)
    # Generate warning if inappropriate anomaly type is selected

    # Apply filter condition when specified
    filter_specified <- FALSE
    tryCatch({
      is.null(filter_condition)
    }, error = function(e) {
      filter_specified <<- TRUE
    }
    )

    if(!filter_specified) {
      # geen filter gespecifieerd.

    } else {
      filter_condition_q <- enquo(filter_condition)
      activitylog <- APPLY_FILTER(activitylog, filter_condition_q = filter_condition_q)
    }

    # Calculate durations
    activitylog %>%
      mutate(duration = as.double(complete - start, units = "mins")) -> anomalies

    # Determine time anomalies
    if(anomaly_type == "negative"){
      anomalies <- anomalies %>% filter(duration < 0)
    } else if(anomaly_type == "zero"){
      anomalies <- anomalies %>% filter(duration == 0)
    } else{
      anomalies <- anomalies %>% filter(duration <= 0) %>%
        mutate(type = ifelse(duration < 0, "negative duration", "zero duration"))
    }

    output <- list()

    # Print output
    message("Selected anomaly type: ", anomaly_type, "\n")
    output$anomaly_type <- anomaly_type

    message("*** OUTPUT ***")
    output$percent_anomalies <- round(nrow(anomalies) / nrow(activitylog) * 100, 2)
    output$num_anomalies <- nrow(anomalies)
    message("For ", nrow(anomalies), " rows in the activity log (", output$percent_anomalies, "%), an anomaly is detected.")

    if(nrow(anomalies) > 0){
      message("The anomalies are spread over the activities as follows:")
      if(anomaly_type == "both"){
        output$both <- anomalies %>% group_by(!!activity_id_(activitylog), type) %>% summarize(n = n()) %>% arrange(desc(n))
        print(output$both)
      } else{
        output$other <- anomalies %>% group_by(!!activity_id_(activitylog)) %>% summarize(n = n()) %>% arrange(desc(n))
        print(output$other)
      }

      if(details == TRUE){
        message("Anomalies are found in the following rows:")
        output$details <- anomalies
        return(output$details)
      }
    }
  }
  output$print<-renderText({
    hospital%>%detect_time_anomalies2()
  })

}

shinyApp(ui, server)


问:
Xamarin Forms: Video is not working on Android version 12 and above with MediaElement
I am using MediaElement for playing video in my xamarin forms application. It is working fine on android version 11 and below. But on android version 12 and above, after playing a video, if we tap on the pause option, the app breaks with the below exception:

Exception:

[InputEventReceiver] java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
[InputEventReceiver]    at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:636)
[InputEventReceiver]    at android.view.View.dispatchPointerEvent(View.java:14964)
[InputEventReceiver]    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:6992)
[InputEventReceiver]    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:6758)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6208)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6275)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6236)
[InputEventReceiver]    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:6409)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6244)
[InputEventReceiver]    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:6466)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6212)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:6275)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:6236)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:6244)
[InputEventReceiver]    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:6212)
[InputEventReceiver]    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:9339)
[InputEventReceiver]    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:9290)
[InputEventReceiver]    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:9234)
[InputEventReceiver]    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:9480)
[InputEventReceiver]    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:276)
[InputEventReceiver]    at android.os.MessageQueue.nativePollOnce(Native Method)
[InputEventReceiver]    at android.os.MessageQueue.next(MessageQueue.java:339)
[InputEventReceiver]    at android.os.Looper.loopOnce(Looper.java:186)
[InputEventReceiver]    at android.os.Looper.loop(Looper.java:334)
[InputEventReceiver]    at android.app.ActivityThread.main(ActivityThread.java:8501)
[InputEventReceiver]    at java.lang.reflect.Method.invoke(Native Method)
[InputEventReceiver]    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
[InputEventReceiver]    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)

My Versions:

Xamarin forms: 5.0.0.2291

Xamarin.CommunityToolkit: 1.3.1

Visual Studio: 17.4.3

I tried updating the xamarin toolkit package to the latest, but no luck. Is it a known issue?


问:
Subprocess not receiving SIGINT on ubuntu: asyncio
I have written code using asyncio that runs a process and after a condition tries to safely interrupt it by sending sigint and waiting for it to close. I tested this on a oracle cloud server with the Oracle Linux 8 image and it worked as I expected. Once I moved over to my main server running Ubuntu 22.04 Everything worked the same except the process never receives the SIGINT signal. I've tried sending other signals and nothing reaches the process.

Code Example:

async def openProc(...):
    ...
    proc = await asyncio.create_subprocess_shell(STARTCOMMAND,
    stdout=asyncio.subprocess.PIPE,
    stderr=asyncio.subprocess.STDOUT,
    stdin=asyncio.subprocess.PIPE)

    try:
        await stop_request.wait()
        proc.send_signal(signal.SIGINT) # The signal that works on one OS but not the other
    finally:
        await safe_quit.wait()
        response = await server.sendData({"request":"STATE", "data":"STOPPED", "returncode":proc.returncode})
        logger.info(response)
```

It just passes straight through the proc.send_signal(..) with no error message.

Body:
I have written code using asyncio that runs a process and after a condition tries to safely interrupt it by sending sigint and waiting for it to close. I tested this on a oracle cloud server with the Oracle Linux 8 image and it worked as I expected. Once I moved over to my main server running Ubuntu 22.04 Everything worked the same except the process never receives the SIGINT signal. I've tried sending other signals and nothing reaches the process.

Code Example:

async def openProc(...):
    ...
    proc = await asyncio.create_subprocess_shell(STARTCOMMAND,
    stdout=asyncio.subprocess.PIPE,
    stderr=asyncio.subprocess.STDOUT,
    stdin=asyncio.subprocess.PIPE)

    try:
        await stop_request.wait()
        proc.send_signal(signal.SIGINT) # The signal that works on one OS but not the other
    finally:
        await safe_quit.wait()
        response = await server.sendData({"request":"STATE", "data":"STOPPED", "returncode":proc.returncode})
        logger.info(response)

It just passes straight through the proc.send_signal(..) with no error message.


问:
DeviceIoControl (kernel32.lib)
Inspired by balena.io's drivelist, I create a Rust version. The idea is simple, using Windows' Setup API to read all connected storages list (with mount points/drive letters), using winapi crate

///file main.rs
use core::{slice, ffi};
use std::{ptr::{null_mut, addr_of, null}, mem::{zeroed, size_of, MaybeUninit, align_of, transmute}, str::from_utf8};

use winapi::{um::{setupapi::{SetupDiGetClassDevsA, DIGCF_PRESENT, DIGCF_DEVICEINTERFACE, SP_DEVINFO_DATA, SetupDiEnumDeviceInfo, HDEVINFO, PSP_DEVINFO_DATA, SetupDiGetDeviceRegistryPropertyW, SPDRP_FRIENDLYNAME, SPDRP_REMOVAL_POLICY, SPDRP_ENUMERATOR_NAME, SetupDiDestroyDeviceInfoList, SP_DEVICE_INTERFACE_DATA, SetupDiEnumDeviceInterfaces, SetupDiGetDeviceInterfaceDetailW, PSP_DEVICE_INTERFACE_DETAIL_DATA_W, SP_DEVICE_INTERFACE_DETAIL_DATA_W}, winioctl::{GUID_DEVINTERFACE_DISK, VOLUME_DISK_EXTENTS, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, PVOLUME_DISK_EXTENTS}, handleapi::{INVALID_HANDLE_VALUE, CloseHandle}, cfgmgr32::{CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL, CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL}, errhandlingapi::GetLastError, fileapi::{CreateFileW, OPEN_EXISTING}, winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_ATTRIBUTE_NORMAL}, ioapiset::DeviceIoControl}, shared::{minwindef::MAX_PATH, winerror::{ERROR_NO_MORE_ITEMS, ERROR_INSUFFICIENT_BUFFER}}, ctypes::c_void};

fn get_detail_data(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA)
{
    let mut h_device=INVALID_HANDLE_VALUE;
    let mut index=0_u32;

    unsafe{
        loop {
            if h_device!= INVALID_HANDLE_VALUE {
                CloseHandle(h_device);
                h_device=INVALID_HANDLE_VALUE;
            }

            let mut device_interface_data:SP_DEVICE_INTERFACE_DATA=zeroed();
            device_interface_data.cbSize=size_of::<SP_DEVICE_INTERFACE_DATA>() as _;

            if SetupDiEnumDeviceInterfaces(h_dev_info, device_info_data, &GUID_DEVINTERFACE_DISK, index, &mut device_interface_data) == 0 {
                let error_code=GetLastError();

                if error_code!=ERROR_NO_MORE_ITEMS {
                    panic!("SetupDiEnumDeviceInterfaces: Error {}",error_code);
                }

                break;
            } else {
                let mut size={
                    let mut required_size=MaybeUninit::<u32>::uninit();

                    if SetupDiGetDeviceInterfaceDetailW(h_dev_info, &mut device_interface_data, null_mut(), 0, required_size.as_mut_ptr(), null_mut())==0 {
                        if GetLastError()==ERROR_INSUFFICIENT_BUFFER {
                            required_size.assume_init()
                        } else {
                            panic!("Error SetupDiGetDeviceInterfaceDetailW");
                        }
                    } else {
                        0
                    }
                };
                let mut buf:Vec<u8>=Vec::with_capacity(TryInto::<usize>::try_into(size).unwrap() + align_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>()-1);
                let align_offset=buf.as_mut_ptr().align_offset(align_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>());
                let device_iface_detail =&mut *(buf.as_mut_ptr().offset(align_offset.try_into().unwrap()) as *mut MaybeUninit<SP_DEVICE_INTERFACE_DETAIL_DATA_W>);
                device_iface_detail.write(SP_DEVICE_INTERFACE_DETAIL_DATA_W {
                    cbSize: size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>().try_into().unwrap(),
                    DevicePath: [0],
                });

                if SetupDiGetDeviceInterfaceDetailW(h_dev_info, &mut device_interface_data, device_iface_detail.as_mut_ptr(), size, &mut size, null_mut())==0 {
                    println!("Error {}, Couldn't SetupDiGetDeviceInterfaceDetailW",GetLastError());
                    break;
                }

                let device_detail_data=device_iface_detail.assume_init_ref();
                h_device=CreateFileW(device_detail_data.DevicePath.as_ptr(), 0, FILE_SHARE_READ,  null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, null_mut());

                if h_device==INVALID_HANDLE_VALUE {
                    println!("Couldn't open handle to device: Error {}",GetLastError());
                    break;
                }

                get_device_number(h_device);
            }

            index+=1;
        }

        if h_device!= INVALID_HANDLE_VALUE {
            CloseHandle(h_device);
            h_device=INVALID_HANDLE_VALUE;
        }
    }
}

fn get_device_number(h_device:*mut c_void)
{
    unsafe {
        let mut size=0_u32;

        let mut disk_extents=MaybeUninit::<VOLUME_DISK_EXTENTS>::uninit();
        disk_extents.write(zeroed());
        let result=DeviceIoControl(h_device, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, null_mut(), 0, disk_extents.as_mut_ptr() as _, size_of::<VOLUME_DISK_EXTENTS>() as _, &mut size, null_mut());
/* It returns 0!! */
        println!("Bytes returned: {}",size);

        if result!=0 {
            println!("Success");
        } else {
/* This will be executed */
            println!("get_device_number fail. Error {}",GetLastError());
        }
    }
}

fn get_enumerator_name(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA) -> String
{
    unsafe {
        let mut buffer:[u8;MAX_PATH]=zeroed();

        if SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_ENUMERATOR_NAME, null_mut(), &mut buffer as _, (size_of::<u8>() * MAX_PATH) as _, null_mut()) != 0 {
            ansi_to_string(&buffer)
        } else {
            "".to_string()
        }
    }
}

fn get_friendly_name(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA) -> String
{
    unsafe {
        let mut buffer:[u8;MAX_PATH]=zeroed();

        if SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_FRIENDLYNAME, null_mut(), &mut buffer as _, (size_of::<u8>() * MAX_PATH) as _, null_mut()) != 0 {
            ansi_to_string(&buffer)
        } else {
            "".to_string()
        }
    }
}

fn is_removable(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA)->bool
{
    unsafe {
        let mut result=0_u8;
        SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_REMOVAL_POLICY, null_mut(), &mut result as _, size_of::<u32>() as _, null_mut());

        match result as u32
        {
            CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL|CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL =>true,
            _=>false
        }
    }
}

fn is_usb_drive(enumerator_name:&str) -> bool
{
    ["USBSTOR", "UASPSTOR", "VUSBSTOR","RTUSER", "CMIUCR", "EUCR","ETRONSTOR", "ASUSSTPT"].contains(&enumerator_name)
}

fn ansi_to_string(unsafe_utf8:&[u8])->String
{
    match from_utf8(&unsafe_utf8.iter().filter(|c| **c != 0).map(|c| *c).collect::<Vec<u8>>() as _)
    {
        Err(err)=>{
            println!("Error {}",err);
            "".to_string()
        },
        Ok(res)=>res.trim().to_string()
    }
}

fn main() {
    unsafe {
        let h_device_info=SetupDiGetClassDevsA(&GUID_DEVINTERFACE_DISK, null_mut(), null_mut(), DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);

        if h_device_info!=INVALID_HANDLE_VALUE {
            let mut i=0;
            let mut device_info_data:SP_DEVINFO_DATA=zeroed();
            device_info_data.cbSize=size_of::<SP_DEVINFO_DATA>() as _;

            while SetupDiEnumDeviceInfo(h_device_info, i, &mut device_info_data)!=0
            {
                let enumerator_name=get_enumerator_name(h_device_info, &mut device_info_data);
                let friendly_name=get_friendly_name(h_device_info, &mut device_info_data);

                if friendly_name.is_empty() {
                    continue;
                }

                println!("Name: {}",friendly_name);
                println!("Is USB drive: {}",is_usb_drive(&enumerator_name));
                println!("Is removable: {}",is_removable(h_device_info, &mut device_info_data));

                get_detail_data(h_device_info, &mut device_info_data);
                i+=1;
            }
        }

        SetupDiDestroyDeviceInfoList(h_device_info);
    }
}

```
<p>Terminal output:</p>
```Name: SKHynix_HFM512GDHTNI-87A0B
Is USB drive: false
Is removable: false
DevicePath: \\?\scsi#disk&ven_nvme&prod_skhynix_hfm512gd#5&8980ef4&0&000000#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
Bytes returned: 0
get_device_number fail. Error 1
```

Everything went fine until DeviceIoControl always returns 0 and GetLastError() returns 1 (inside get_device_number() function). Can someone guide me figuring out what went wrong?
Thanks in advance

Title: DeviceIoControl (kernel32.lib)

Body:
Inspired by balena.io's drivelist, I create a Rust version. The idea is simple, using Windows' Setup API to read all connected storages list (with mount points/drive letters), using winapi crate

///file main.rs
use core::{slice, ffi};
use std::{ptr::{null_mut, addr_of, null}, mem::{zeroed, size_of, MaybeUninit, align_of, transmute}, str::from_utf8};

use winapi::{um::{setupapi::{SetupDiGetClassDevsA, DIGCF_PRESENT, DIGCF_DEVICEINTERFACE, SP_DEVINFO_DATA, SetupDiEnumDeviceInfo, HDEVINFO, PSP_DEVINFO_DATA, SetupDiGetDeviceRegistryPropertyW, SPDRP_FRIENDLYNAME, SPDRP_REMOVAL_POLICY, SPDRP_ENUMERATOR_NAME, SetupDiDestroyDeviceInfoList, SP_DEVICE_INTERFACE_DATA, SetupDiEnumDeviceInterfaces, SetupDiGetDeviceInterfaceDetailW, PSP_DEVICE_INTERFACE_DETAIL_DATA_W, SP_DEVICE_INTERFACE_DETAIL_DATA_W}, winioctl::{GUID_DEVINTERFACE_DISK, VOLUME_DISK_EXTENTS, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, PVOLUME_DISK_EXTENTS}, handleapi::{INVALID_HANDLE_VALUE, CloseHandle}, cfgmgr32::{CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL, CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL}, errhandlingapi::GetLastError, fileapi::{CreateFileW, OPEN_EXISTING}, winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_ATTRIBUTE_NORMAL}, ioapiset::DeviceIoControl}, shared::{minwindef::MAX_PATH, winerror::{ERROR_NO_MORE_ITEMS, ERROR_INSUFFICIENT_BUFFER}}, ctypes::c_void};

fn get_detail_data(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA)
{
    let mut h_device=INVALID_HANDLE_VALUE;
    let mut index=0_u32;

    unsafe{
        loop {
            if h_device!= INVALID_HANDLE_VALUE {
                CloseHandle(h_device);
                h_device=INVALID_HANDLE_VALUE;
            }

            let mut device_interface_data:SP_DEVICE_INTERFACE_DATA=zeroed();
            device_interface_data.cbSize=size_of::<SP_DEVICE_INTERFACE_DATA>() as _;

            if SetupDiEnumDeviceInterfaces(h_dev_info, device_info_data, &GUID_DEVINTERFACE_DISK, index, &mut device_interface_data) == 0 {
                let error_code=GetLastError();

                if error_code!=ERROR_NO_MORE_ITEMS {
                    panic!("SetupDiEnumDeviceInterfaces: Error {}",error_code);
                }

                break;
            } else {
                let mut size={
                    let mut required_size=MaybeUninit::<u32>::uninit();

                    if SetupDiGetDeviceInterfaceDetailW(h_dev_info, &mut device_interface_data, null_mut(), 0, required_size.as_mut_ptr(), null_mut())==0 {
                        if GetLastError()==ERROR_INSUFFICIENT_BUFFER {
                            required_size.assume_init()
                        } else {
                            panic!("Error SetupDiGetDeviceInterfaceDetailW");
                        }
                    } else {
                        0
                    }
                };
                let mut buf:Vec<u8>=Vec::with_capacity(TryInto::<usize>::try_into(size).unwrap() + align_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>()-1);
                let align_offset=buf.as_mut_ptr().align_offset(align_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>());
                let device_iface_detail =&mut *(buf.as_mut_ptr().offset(align_offset.try_into().unwrap()) as *mut MaybeUninit<SP_DEVICE_INTERFACE_DETAIL_DATA_W>);
                device_iface_detail.write(SP_DEVICE_INTERFACE_DETAIL_DATA_W {
                    cbSize: size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>().try_into().unwrap(),
                    DevicePath: [0],
                });

                if SetupDiGetDeviceInterfaceDetailW(h_dev_info, &mut device_interface_data, device_iface_detail.as_mut_ptr(), size, &mut size, null_mut())==0 {
                    println!("Error {}, Couldn't SetupDiGetDeviceInterfaceDetailW",GetLastError());
                    break;
                }

                let device_detail_data=device_iface_detail.assume_init_ref();
                h_device=CreateFileW(device_detail_data.DevicePath.as_ptr(), 0, FILE_SHARE_READ,  null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, null_mut());

                if h_device==INVALID_HANDLE_VALUE {
                    println!("Couldn't open handle to device: Error {}",GetLastError());
                    break;
                }

                get_device_number(h_device);
            }

            index+=1;
        }

        if h_device!= INVALID_HANDLE_VALUE {
            CloseHandle(h_device);
            h_device=INVALID_HANDLE_VALUE;
        }
    }
}

fn get_device_number(h_device:*mut c_void)
{
    unsafe {
        let mut size=0_u32;

        let mut disk_extents=MaybeUninit::<VOLUME_DISK_EXTENTS>::uninit();
        disk_extents.write(zeroed());
        let result=DeviceIoControl(h_device, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, null_mut(), 0, disk_extents.as_mut_ptr() as _, size_of::<VOLUME_DISK_EXTENTS>() as _, &mut size, null_mut());
/* It returns 0!! */
        println!("Bytes returned: {}",size);

        if result!=0 {
            println!("Success");
        } else {
/* This will be executed */
            println!("get_device_number fail. Error {}",GetLastError());
        }
    }
}

fn get_enumerator_name(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA) -> String
{
    unsafe {
        let mut buffer:[u8;MAX_PATH]=zeroed();

        if SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_ENUMERATOR_NAME, null_mut(), &mut buffer as _, (size_of::<u8>() * MAX_PATH) as _, null_mut()) != 0 {
            ansi_to_string(&buffer)
        } else {
            "".to_string()
        }
    }
}

fn get_friendly_name(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA) -> String
{
    unsafe {
        let mut buffer:[u8;MAX_PATH]=zeroed();

        if SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_FRIENDLYNAME, null_mut(), &mut buffer as _, (size_of::<u8>() * MAX_PATH) as _, null_mut()) != 0 {
            ansi_to_string(&buffer)
        } else {
            "".to_string()
        }
    }
}

fn is_removable(h_dev_info:HDEVINFO,device_info_data:PSP_DEVINFO_DATA)->bool
{
    unsafe {
        let mut result=0_u8;
        SetupDiGetDeviceRegistryPropertyW(h_dev_info, device_info_data, SPDRP_REMOVAL_POLICY, null_mut(), &mut result as _, size_of::<u32>() as _, null_mut());

        match result as u32
        {
            CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL|CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL =>true,
            _=>false
        }
    }
}

fn is_usb_drive(enumerator_name:&str) -> bool
{
    ["USBSTOR", "UASPSTOR", "VUSBSTOR","RTUSER", "CMIUCR", "EUCR","ETRONSTOR", "ASUSSTPT"].contains(&enumerator_name)
}

fn ansi_to_string(unsafe_utf8:&[u8])->String
{
    match from_utf8(&unsafe_utf8.iter().filter(|c| **c != 0).map(|c| *c).collect::<Vec<u8>>() as _)
    {
        Err(err)=>{
            println!("Error {}",err);
            "".to_string()
        },
        Ok(res)=>res.trim().to_string()
    }
}

fn main() {
    unsafe {
        let h_device_info=SetupDiGetClassDevsA(&GUID_DEVINTERFACE_DISK, null_mut(), null_mut(), DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);

        if h_device_info!=INVALID_HANDLE_VALUE {
            let mut i=0;
            let mut device_info_data:SP_DEVINFO_DATA=zeroed();
            device_info_data.cbSize=size_of::<SP_DEVINFO_DATA>() as _;

            while SetupDiEnumDeviceInfo(h_device_info, i, &mut device_info_data)!=0
            {
                let enumerator_name=get_enumerator_name(h_device_info, &mut device_info_data);
                let friendly_name=get_friendly_name(h_device_info, &mut device_info_data);

                if friendly_name.is_empty() {
                    continue;
                }

                println!("Name: {}",friendly_name);
                println!("Is USB drive: {}",is_usb_drive(&enumerator_name));
                println!("Is removable: {}",is_removable(h_device_info, &mut device_info_data));

                get_detail_data(h_device_info, &mut device_info_data);
                i+=1;
            }
        }

        SetupDiDestroyDeviceInfoList(h_device_info);
    }
}

Terminal output:

Name: SKHynix_HFM512GDHTNI-87A0B
Is USB drive: false
Is removable: false
DevicePath: \\?\scsi#disk&ven_nvme&prod_skhynix_hfm512gd#5&8980ef4&0&000000#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
Bytes returned: 0
get_device_number fail. Error 1

Everything went fine until DeviceIoControl always returns 0 and GetLastError() returns 1 (inside get_device_number() function). Can someone guide me figuring out what went wrong?
Thanks in advance


问:
Frappe save objects in another doctype based on the base doctype?
I am tring to trigger an event to save doctype data based on another doctype.

This is how my doctype are:

Employee has a Job Role.

Job Role has tow doctypes as Table 'Job Role Course Item' and 'Job Role Skill Item'.

'Job Role Course Item' is a Table type linked with 'Course Template'.

'Job Role Skill Item' ia a Table type linked with 'Skill'.

What I want to achiave is this:

When use saves data into db usign Frappe in the Employee DocType I want to save the data also into another two DocTypes 'Course Assignment' and 'Employee Skill'.

This will achive by using the Job Role that is linked with the Employee DocType as Table field.

Also I have another issue is that when I save the DocType for the first time it tells me that DocType doesn't exsists.

Please Note:

My code is working and what I need is to replace the inner for to search just for the Courses or Skills in the 'Job Role', 'Course Assignmant' or 'Employee Skill' that is not prsented in the 'Course Assignmant' and 'Employee Skill' based on name and employee.

This is my whole code for the Employee DocType.

```<code>import frappe
from frappe import _
from frappe.model.document import Document

class Employee(Document):
    def before_save(self):
        if not self.full_name:
            self.full_name = ((self.first_name + ' ' if self.first_name else '') + (self.middle_name + ' ' if self.middle_name else '') + (self.last_name if self.last_name else '')).strip()
        if self._doc_before_save:
            if self._doc_before_save.job_roles != self.job_roles: self.trigger_job_roles()
        # DocType dosn't exsists if the DocType of saved as first time.
        else: self.trigger_job_roles()

    def validate(self):
        if (self.work_start_date and self.work_end_date):
            if (self.work_start_date >= self.work_end_date):
                frappe.throw(_('The Work End Date should be greater than the Work Start Date'))

    def trigger_job_roles(self):
        frappe.enqueue(
            "medad_tms.trainee_management.doctype.employee.employee.assign_employee",
            doc=self,
        )

def assign_employee(doc):
    try:
        for job_role in doc.job_roles:
            for course in frappe.get_doc("Job Role", job_role.job_role).required_courses: # I want to replace this to enhance the code performace.
                if not frappe.db.exists("Course Assignment", f"{course.course}-{doc.related_user}"):
                    course_doc = frappe.new_doc("Course Assignment")
                    course_doc.trainee = doc.related_user
                    course_doc.course = course.course
                    course_doc.source = "Job Role"
                    course_doc.due_date = frappe.get_doc("Course Template", course.course).start_date
                    course_doc.insert()
            for skill in frappe.get_doc("Job Role", job_role.job_role).required_skills: # I want to replace this to enhance the code performace.
                if not frappe.db.exists("Employee Skill", f"{doc.name}-{skill.skill}"):
                    skill_doc = frappe.new_doc("Employee Skill")
                    skill_doc.employee = doc.name
                    skill_doc.skill = skill.skill
                    skill_doc.skill_type = "Training Programs"
                    skill_doc.proficiency_scale_level = 1
                    skill_doc.required_scale_level = 5
                    skill_doc.insert()
        frappe.db.commit()
        frappe.publish_realtime(
            "assign_employee",
            {"progress": 1, "total": 3,
                "message": "Assigning Courses and Skills to Employee"},
            user=frappe.session.user,
            after_commit=True,
        )
    except Exception:
        frappe.db.rollback()
        frappe.log_error(frappe.get_traceback(), "Employee")
        frappe.throw(_("Error in Assigning Courses and Skills to Employee"))

</code>```

Body:
I am tring to trigger an event to save doctype data based on another doctype.

This is how my doctype are:

Employee has a Job Role.

Job Role has tow doctypes as Table 'Job Role Course Item' and 'Job Role Skill Item'.

'Job Role Course Item' is a Table type linked with 'Course Template'.

'Job Role Skill Item' ia a Table type linked with 'Skill'.

What I want to achiave is this:

When use saves data into db usign Frappe in the Employee DocType I want to save the data also into another two DocTypes 'Course Assignment' and 'Employee Skill'.

This will achive by using the Job Role that is linked with the Employee DocType as Table field.

Also I have another issue is that when I save the DocType for the first time it tells me that DocType doesn't exsists.

Please Note:

My code is working and what I need is to replace the inner for to search just for the Courses or Skills in the 'Job Role', 'Course Assignmant' or 'Employee Skill' that is not prsented in the 'Course Assignmant' and 'Employee Skill' based on name and employee.

This is my whole code for the Employee DocType.

import frappe
from frappe import _
from frappe.model.document import Document

class Employee(Document):
    def before_save(self):
        if not self.full_name:
            self.full_name = ((self.first_name + ' ' if self.first_name else '') + (self.middle_name + ' ' if self.middle_name else '') + (self.last_name if self.last_name else '')).strip()
        if self._doc_before_save:
            if self._doc_before_save.job_roles != self.job_roles: self.trigger_job_roles()
        # DocType dosn't exsists if the DocType of saved as first time.
        else: self.trigger_job_roles()

    def validate(self):
        if (self.work_start_date and self.work_end_date):
            if (self.work_start_date >= self.work_end_date):
                frappe.throw(_('The Work End Date should be greater than the Work Start Date'))

    def trigger_job_roles(self):
        frappe.enqueue(
            "medad_tms.trainee_management.doctype.employee.employee.assign_employee",
            doc=self,
        )

def assign_employee(doc):
    try:
        for job_role in doc.job_roles:
            for course in frappe.get_doc("Job Role", job_role.job_role).required_courses: # I want to replace this to enhance the code performace.
                if not frappe.db.exists("Course Assignment", f"{course.course}-{doc.related_user}"):
                    course_doc = frappe.new_doc("Course Assignment")
                    course_doc.trainee = doc.related_user
                    course_doc.course = course.course
                    course_doc.source = "Job Role"
                    course_doc.due_date = frappe.get_doc("Course Template", course.course).start_date
                    course_doc.insert()
            for skill in frappe.get_doc("Job Role", job_role.job_role).required_skills: # I want to replace this to enhance the code performace.
                if not frappe.db.exists("Employee Skill", f"{doc.name}-{skill.skill}"):
                    skill_doc = frappe.new_doc("Employee Skill")
                    skill_doc.employee = doc.name
                    skill_doc.skill = skill.skill
                    skill_doc.skill_type = "Training Programs"
                    skill_doc.proficiency_scale_level = 1
                    skill_doc.required_scale_level = 5
                    skill_doc.insert()
        frappe.db.commit()
        frappe.publish_realtime(
            "assign_employee",
            {"progress": 1, "total": 3,
                "message": "Assigning Courses and Skills to Employee"},
            user=frappe.session.user,
            after_commit=True,
        )
    except Exception:
        frappe.db.rollback()
        frappe.log_error(frappe.get_traceback(), "Employee")
        frappe.throw(_("Error in Assigning Courses and Skills to Employee"))


问:
doing project about movieticket management system, giving errors named cannot find the symbol for all buttons and textfields on initComponents method
here is the code

```<code>import java.sql.*;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import java.sql.PreparedStatement;
import javax.swing.JTextField;
public class register extends javax.swing.JFrame {
Connection conn=null;

    /**
     * Creates new form register
     */
    public register() {
        initComponents();
        conn=MyConnection.getConnection();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel1.setText("NAME");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(135, 128, 110, 29);

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel2.setText("EMAIL ID");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(135, 184, 140, 29);

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel3.setText("PASSWORD");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(135, 309, 150, 29);

        jTextField1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField1);
        jTextField1.setBounds(340, 130, 190, 35);

        jTextField2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        getContentPane().add(jTextField2);
        jTextField2.setBounds(340, 190, 190, 30);

        jTextField4.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField4);
        jTextField4.setBounds(343, 310, 190, 30);

        jButton1.setFont(new java.awt.Font("Algerian", 1, 24)); // NOI18N
        jButton1.setText("SIGN UP");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(200, 380, 220, 41);

        jLabel4.setFont(new java.awt.Font("Algerian", 1, 36)); // NOI18N
        jLabel4.setText("NEW REGISTER");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(160, 30, 300, 48);

        jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel5.setText("PHONE NUMBER");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(135, 250, 200, 29);

        jTextField3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        getContentPane().add(jTextField3);
        jTextField3.setBounds(340, 240, 200, 30);

        pack();
    }// </editor-fold>

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

        String a=jTextField1.getText();
        String b=jTextField2.getText();
        String c=jTextField3.getText();
        String d=jTextField4.getText();

       if("".equals(a) && "".equals(b) && "".equals(c) &&"".equals(d))
       {
           JOptionPane.showMessageDialog(this,"please enter valid details");
       }
       else {

       PreparedStatement ps;
       String query =("insert into register(Name, EmailID, Number, Password) values(?,?,?,?)");
         try{

          ps = MyConnection.getConnection().prepareStatement(query);
          ps.setString(1,a);
          ps.setString(2,b);
          ps.setString(3,c);
          ps.setString(4,d);
          if(ps.executeUpdate()>0) {
              JOptionPane.showMessageDialog(null,"New Register Succes!");
          }

        }
         catch(SQLException e) {
           Logger.getLogger(register.class.getName()).log(Level.SEVERE,null,e);  }

      this.setVisible(false);   new login().setVisible(true);

        // TODO add your handling code here:
    }
       {
    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
}

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new register().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration

    private ResultSet executeQuery(String select__from_register) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private void While(boolean b) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}  }
</code>```

I used private to identifier for textfields but it gives error on every button and textfields and I checked the names at design, same name. Funny thing is I runned the code before it gives these error and it started with no error after closed the run, it gives these error.  Also it gives illegal start of expression and class enum expected errors after the jTextField4ActionPerformed method. Any help will be appreciated

Body:
here is the code

import java.sql.*;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import java.sql.PreparedStatement;
import javax.swing.JTextField;
public class register extends javax.swing.JFrame {
Connection conn=null;

    /**
     * Creates new form register
     */
    public register() {
        initComponents();
        conn=MyConnection.getConnection();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel1.setText("NAME");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(135, 128, 110, 29);

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel2.setText("EMAIL ID");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(135, 184, 140, 29);

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel3.setText("PASSWORD");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(135, 309, 150, 29);

        jTextField1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField1);
        jTextField1.setBounds(340, 130, 190, 35);

        jTextField2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        getContentPane().add(jTextField2);
        jTextField2.setBounds(340, 190, 190, 30);

        jTextField4.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField4);
        jTextField4.setBounds(343, 310, 190, 30);

        jButton1.setFont(new java.awt.Font("Algerian", 1, 24)); // NOI18N
        jButton1.setText("SIGN UP");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(200, 380, 220, 41);

        jLabel4.setFont(new java.awt.Font("Algerian", 1, 36)); // NOI18N
        jLabel4.setText("NEW REGISTER");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(160, 30, 300, 48);

        jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel5.setText("PHONE NUMBER");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(135, 250, 200, 29);

        jTextField3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        getContentPane().add(jTextField3);
        jTextField3.setBounds(340, 240, 200, 30);

        pack();
    }// </editor-fold>

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

        String a=jTextField1.getText();
        String b=jTextField2.getText();
        String c=jTextField3.getText();
        String d=jTextField4.getText();

       if("".equals(a) && "".equals(b) && "".equals(c) &&"".equals(d))
       {
           JOptionPane.showMessageDialog(this,"please enter valid details");
       }
       else {

       PreparedStatement ps;
       String query =("insert into register(Name, EmailID, Number, Password) values(?,?,?,?)");
         try{

          ps = MyConnection.getConnection().prepareStatement(query);
          ps.setString(1,a);
          ps.setString(2,b);
          ps.setString(3,c);
          ps.setString(4,d);
          if(ps.executeUpdate()>0) {
              JOptionPane.showMessageDialog(null,"New Register Succes!");
          }

        }
         catch(SQLException e) {
           Logger.getLogger(register.class.getName()).log(Level.SEVERE,null,e);  }

      this.setVisible(false);   new login().setVisible(true);

        // TODO add your handling code here:
    }
       {
    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
}

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(register.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new register().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration

    private ResultSet executeQuery(String select__from_register) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private void While(boolean b) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}  }

I used private to identifier for textfields but it gives error on every button and textfields and I checked the names at design, same name. Funny thing is I runned the code before it gives these error and it started with no error after closed the run, it gives these error.  Also it gives illegal start of expression and class enum expected errors after the jTextField4ActionPerformed method. Any help will be appreciated


问:
AWS Batch from on prem
I have an on premises schedule that's too dense and there are a lot of errors.  I'd like to explore options for migrating some of the workload to the cloud.  Can I connect to on-premises resources using AWS Batch? I'd to connect to on prem database/warehouse and run some of these jobs in the cloud using Spot instances and drop the output into S3 but wasn't sure if I used AWS Batch or AWS Glue or a combination of the two.  Is there a different option?</p>

Title: AWS Batch from on prem


问:
Able to upload image in AWS S3 and ActiveStorage but returns nil when trying to access it
I have a backend rails app that serves serialized json responses.

IN PRODUCTION:

I have two actions in my profile_controller.rb:

# profile_controller.rb

# GET /profile
def show
  authorize current_user, policy_class: ProfilePolicy

  render json: Api::V1::UserSerializer.new(current_user)
end

# POST /profile/upload_image
def upload_image
  authorize current_user, policy_class: ProfilePolicy

  current_user.image.purge if current_user.image.present?
  current_user.update!(image: params[:image])

  render json: Api::V1::UserSerializer.new(current_user), status: :ok
end
```
<ul>
<li>When image is uploaded at <code>/profile/upload_image</code>, I get the the User with correct <code>image</code> url that I can even visit (and other attributes).</li>
<li>When <code>GET /profile</code> is fetched, I get the the User with <code>image</code> atrribute as <code>nil</code> (and other attributes).</li>
</ul>
<p><strong>Api::V1::UserSerializer:</strong></p>
<pre class="lang-rb prettyprint-override"><code>class Api::V1::UserSerializer < Api::V1::ApplicationSerializer
  attributes :email,
    :id,
    :mobile,
    :first_name,
    :last_name,
    :address

    attribute :image do |record|
      if record.image.present?
        Rails.application.routes.url_helpers.cdn_image_url(record.image)
      else
        nil
      end
    end
end

</code>```

It seems that record.image.present? is false for GET /profile BUT true for POST /profile/upload_image. (in UserSerializer at line Api::V1::UserSerializer.rb:10)

Thinking that it is an AWS issue I tried changing config.active_storage.service for development.rb:

# config.active_storage.service = :local
config.active_storage.service = :amazon
```
<p>Runnig AWS storage IN DEVELOPMENT:</p>
<ul>
<li>I get the the User with correct <code>image</code> url that I can even visit (and other attributes) for both the actions. (EXPECTED RESPONSE).</li>
</ul>
<p>I am not sure what I am doing wrong here. What am I missing here?</p>
<p>Why do I get image URL as response for uploading the image and not when fetch the profile?</p>
<p>Can you help me please?</p>
<p><strong>Gemfile:</strong></p>
<pre class="lang-rb prettyprint-override"><code>..
ruby '3.1.2'
gem 'rails', '~> 7.0.4'
gem 'aws-sdk-s3', '~> 1.114'
..

</code>```

Body:
I have a backend rails app that serves serialized json responses.

IN PRODUCTION:

I have two actions in my profile_controller.rb:

# profile_controller.rb

# GET /profile
def show
  authorize current_user, policy_class: ProfilePolicy

  render json: Api::V1::UserSerializer.new(current_user)
end

# POST /profile/upload_image
def upload_image
  authorize current_user, policy_class: ProfilePolicy

  current_user.image.purge if current_user.image.present?
  current_user.update!(image: params[:image])

  render json: Api::V1::UserSerializer.new(current_user), status: :ok
end

When image is uploaded at /profile/upload_image, I get the the User with correct image url that I can even visit (and other attributes).

When GET /profile is fetched, I get the the User with image atrribute as nil (and other attributes).

Api::V1::UserSerializer:

class Api::V1::UserSerializer < Api::V1::ApplicationSerializer
  attributes :email,
    :id,
    :mobile,
    :first_name,
    :last_name,
    :address

    attribute :image do |record|
      if record.image.present?
        Rails.application.routes.url_helpers.cdn_image_url(record.image)
      else
        nil
      end
    end
end

It seems that record.image.present? is false for GET /profile BUT true for POST /profile/upload_image. (in UserSerializer at line Api::V1::UserSerializer.rb:10)

Thinking that it is an AWS issue I tried changing config.active_storage.service for development.rb:

# config.active_storage.service = :local
config.active_storage.service = :amazon

Runnig AWS storage IN DEVELOPMENT:

I get the the User with correct image url that I can even visit (and other attributes) for both the actions. (EXPECTED RESPONSE).

I am not sure what I am doing wrong here. What am I missing here?

Why do I get image URL as response for uploading the image and not when fetch the profile?

Can you help me please?

Gemfile:

..
ruby '3.1.2'
gem 'rails', '~> 7.0.4'
gem 'aws-sdk-s3', '~> 1.114'
..


问:
String won't send through socket communication between Unity and MATLAB
I have the following lines of code. I am trying to set "MouseLook.hit" to either the gameObject.name or to "no" if the raycast does not hit. The if statement works, such that the MouseLook.hit prints in Unity. However, I can never receive the object on the other side (it is received in MATLAB). BUT, the "no" in the else statement is received in MATLAB. ALSO, I sometimes receive the message for some of the objects that I have in my Unity environment, but not for the specific ones I want (I have tried swithching to either mesh or box colider). Can you see something wrong with the code? Thank you!

```<code>ray = new Ray(transform.position, transform.forward);

        if (Physics.Raycast(ray, out raycastHit))
        {
        MouseLook.hit = raycastHit.collider.gameObject.name;
        print(MouseLook.hit);

        }
        else
        {
        MouseLook.hit = "no";
        }

        Byte[] sendBytes5 = Encoding.UTF8.GetBytes(MouseLook.hit);
        mySocket1.GetStream().Write(sendBytes5, 0, sendBytes5.Length);
        Byte[] sendBytes6 = Encoding.UTF8.GetBytes("  ");
        mySocket1.GetStream().Write(sendBytes6, 0, sendBytes6.Length);

</code>```

I tried to change the encoding, I tried to change the objects in the hierarchy, I tried to change the if and else if statement, I tried to change to meshcolider to boc colider for the objects I am aiming at in the game.

Body:
I have the following lines of code. I am trying to set "MouseLook.hit" to either the gameObject.name or to "no" if the raycast does not hit. The if statement works, such that the MouseLook.hit prints in Unity. However, I can never receive the object on the other side (it is received in MATLAB). BUT, the "no" in the else statement is received in MATLAB. ALSO, I sometimes receive the message for some of the objects that I have in my Unity environment, but not for the specific ones I want (I have tried swithching to either mesh or box colider). Can you see something wrong with the code? Thank you!

ray = new Ray(transform.position, transform.forward);

        if (Physics.Raycast(ray, out raycastHit))
        {
        MouseLook.hit = raycastHit.collider.gameObject.name;
        print(MouseLook.hit);

        }
        else
        {
        MouseLook.hit = "no";
        }

        Byte[] sendBytes5 = Encoding.UTF8.GetBytes(MouseLook.hit);
        mySocket1.GetStream().Write(sendBytes5, 0, sendBytes5.Length);
        Byte[] sendBytes6 = Encoding.UTF8.GetBytes("  ");
        mySocket1.GetStream().Write(sendBytes6, 0, sendBytes6.Length);

I tried to change the encoding, I tried to change the objects in the hierarchy, I tried to change the if and else if statement, I tried to change to meshcolider to boc colider for the objects I am aiming at in the game.


问:
ElastiCache Redis, Django celery, how to on EC2 instance AWS?
So I have set up redis with django celery on aws so that when I run the task manually
eg: $ python manage.py shell

from myapp.tasks import my_task

it works fine.

Now of course I want to run that on deploy and perhaps making sure they always run especially on deploy .

But when I start the beat from ym ec2 the same way I do locally it starts but triggers are not happening .

why exactly

I would like to run those at deploy for example :

command : /var/app/current/celery -A project worker -l info

command : /var/app/current/celery -A project beat -l info


问:
How can I use cloudfront to have images hosted by prismic come from my own domain?
I am using prismic headless CMS which hosts images on its own cdn.

Images have a name that is not SEO friendly and they are hosted on an external domain.

Prismic does not offer a way to set up a custom domain for images.

Our website also uses cloudfront which caches pages.

Is there a way to parse html content and rewrite image urls so that they come from our own domain?

Thanks for your help !