问:
C# Deserialize lists within a .dat file to a text box
I have created an application that will save lists to a .dat file using a binary formatter and serializing the list.

I wish to then de serialize this list and display this within a text box.

Furthermore, I have tried using a for each loop to get every object from the list, but it won't continue through the rest of the lists and stops at the first list stored within the file.

I have been tasked with binary formatter even though Ive been informed its obsolete.

```<code>`public InPerson(int iId, string sDate, string sTime, string sDuration, string sPatientname, string
sPhonenumber, string sDoctorid, string sRoomnumber, string sNurseid)
{
    this.iId = iId;
    this.sDate = sDate;
    this.sTime = sTime;
    this.sDuration = sDuration;
    this.sPatientname = sPatientname;
    this.sPhonenumber = sPhonenumber;
    this.sDoctorid = sDoctorid;
    this.sRoomnumber = sRoomnumber;
    this.sNurseid = sNurseid;
}

//To String method for saving
        public override string ToString()
        {
        return "In Person Apppointment:  " + iId + System.Environment.NewLine +
        "Date:  " + sDate + System.Environment.NewLine +
        "Time:  " + sTime + System.Environment.NewLine +
        "Duration:  " + sDuration + System.Environment.NewLine +
        "Patients Name: " + sPatientname + System.Environment.NewLine +     "Patients Number: " + sPhonenumber + System.Environment.NewLine +
    "Doctors ID:  " + sDoctorid + System.Environment.NewLine +
    "Room Number: " + sRoomnumber + System.Environment.NewLine +
    "Nurse id:  " + sNurseid + System.Environment.NewLine + "";
}

InPerson NewInPersonApp = new InPerson(Convert.ToInt32(txtID.Text), dateTimePickerBooking.Text, txtTime.Text, txtDuration.Text, txtPatientName.Text, txtPhoneNumber.Text, txtDoctorID.Text, txtRoomAllocated.Text, txtNurseID.Text);

    List<InPerson> InPersonList = new List<InPerson>();

    InPersonList.Add(NewInPersonApp);

    const String filename = "appointments.dat";

    FileStream outFile;

    BinaryFormatter bFormatter = new BinaryFormatter();

    outFile = new FileStream(filename, FileMode.Append, FileAccess.Write);

    bFormatter.Serialize(outFile, InPersonList);

    outFile.Close();`
`

I wish to use this code to loop every list out from the file.

`InPersonList = (List<InPerson>)bFormatter.Deserialize(inFile);

foreach (InPerson a in InPersonList)
{
    txtBookings.Text += a.ToString();
}`
</code>```

Body:
I have created an application that will save lists to a .dat file using a binary formatter and serializing the list.

I wish to then de serialize this list and display this within a text box.

Furthermore, I have tried using a for each loop to get every object from the list, but it won't continue through the rest of the lists and stops at the first list stored within the file.

I have been tasked with binary formatter even though Ive been informed its obsolete.

`public InPerson(int iId, string sDate, string sTime, string sDuration, string sPatientname, string
sPhonenumber, string sDoctorid, string sRoomnumber, string sNurseid)
{
    this.iId = iId;
    this.sDate = sDate;
    this.sTime = sTime;
    this.sDuration = sDuration;
    this.sPatientname = sPatientname;
    this.sPhonenumber = sPhonenumber;
    this.sDoctorid = sDoctorid;
    this.sRoomnumber = sRoomnumber;
    this.sNurseid = sNurseid;
}

//To String method for saving
        public override string ToString()
        {
        return "In Person Apppointment:  " + iId + System.Environment.NewLine +
        "Date:  " + sDate + System.Environment.NewLine +
        "Time:  " + sTime + System.Environment.NewLine +
        "Duration:  " + sDuration + System.Environment.NewLine +
        "Patients Name: " + sPatientname + System.Environment.NewLine +     "Patients Number: " + sPhonenumber + System.Environment.NewLine +
    "Doctors ID:  " + sDoctorid + System.Environment.NewLine +
    "Room Number: " + sRoomnumber + System.Environment.NewLine +
    "Nurse id:  " + sNurseid + System.Environment.NewLine + "";
}

InPerson NewInPersonApp = new InPerson(Convert.ToInt32(txtID.Text), dateTimePickerBooking.Text, txtTime.Text, txtDuration.Text, txtPatientName.Text, txtPhoneNumber.Text, txtDoctorID.Text, txtRoomAllocated.Text, txtNurseID.Text);

    List<InPerson> InPersonList = new List<InPerson>();

    InPersonList.Add(NewInPersonApp);

    const String filename = "appointments.dat";

    FileStream outFile;

    BinaryFormatter bFormatter = new BinaryFormatter();

    outFile = new FileStream(filename, FileMode.Append, FileAccess.Write);

    bFormatter.Serialize(outFile, InPersonList);

    outFile.Close();`
`

I wish to use this code to loop every list out from the file.

`InPersonList = (List<InPerson>)bFormatter.Deserialize(inFile);

foreach (InPerson a in InPersonList)
{
    txtBookings.Text += a.ToString();
}`


来源: stackexchange

问:
Laravel + InertiaJS + Vue 3: Play transition on page BEFORE navigation with Link, button, etc
TL;DR: In a Laravel + InertiaJS + Vue 3 developed application, how can I achieve to have a transition between "pages" loaded within a persistent layout  section - for example, have that section animate (say, fade out) before loading the next page, then animate (fade) that new page in - when using standard Inertia routing for navigation? I have managed to do it on entering/showing the page, but have found no way to animate before navigation happens.

LONG(ish): The Way I'm trying to do it

Let's assume there is an application (developed with Laravel + InertiaJS + Vue 3).

I have an element in the markup of an Inertia persistent layout that is conditionally shown if a value is true (v-if="shouldAnimate") that is initially set to false when declared, and when onMounted fires, it sets that value to true which in turn triggers the animation to run (doesn't really matter how the animation works, but just in case, I have options to use either GSAP or anime.js).

Up to this point, all is good: every time I navigate to a page (using Inertia-adequate methods such as the Link component) the animation triggers and I am a happy guy.

BUT: I would very much like to be able to play another animation (the reverse of the previous one) before, say, navigation to the next page occurs. I have tried almost everything I can think of and have not been successful. Here's what got the closest to what I need:

I tried hooking into the InertiaJS event Inertia.on('before', ...): effectively, the event fires up right before navigation (checked with some good-old console log), so I tried firing up the animation at this point, only to find out that the Inertia event looks like it is destroying the page immediately before the animation has had time to play; no problem: I'll just event.preventDefault() it, run the animation and THEN, using a setTimeout timed to the length of the animation (300ms) I'll resume navigation, say, by using Inertia.visit.

Doesn't work. Somehow, the default behaviour is prevented (stops the navigation), the animation plays back, but when it comes to the "resume navigation part" I have had mixed results depending on what I use:

Code looks roughly like this:

let removeListener = Inertia.on('before', (event) => {

    event.preventDefault()

    // Play animation here

    setTimeout(() => {
        // SOME INERTIA ACTION DESCRIBED BELOW
    }, 300)

})

```

Independently of whether I use Inertia.get(event.detail.visit.url) or Inertia.visit(event.detail.visit.url) what happens is the animation runs its course, and then the timer runs out and this whole code RUNS AGAIN AND AGAIN in intervals equal to the timer. I also tried to do this using the complete event of the animation to trigger the navigation but it behaves the same.

I know this is related to me being an ignorant about how both Inertia and events work, and I am sure there is a proper (correct? right?) way to achieve what I need, but either I have failed in using the correct terms to look for it, or I am approaching this the wrong way. Hopefully this information is enough to explain my issue.

Any help or pointer would be GREATLY appreciated, so thanks in advance.

ContentLicense: CC BY-SA 4.0

Body:
TL;DR: In a Laravel + InertiaJS + Vue 3 developed application, how can I achieve to have a transition between "pages" loaded within a persistent layout  section - for example, have that section animate (say, fade out) before loading the next page, then animate (fade) that new page in - when using standard Inertia routing for navigation? I have managed to do it on entering/showing the page, but have found no way to animate before navigation happens.

LONG(ish): The Way I'm trying to do it

Let's assume there is an application (developed with Laravel + InertiaJS + Vue 3).

I have an element in the markup of an Inertia persistent layout that is conditionally shown if a value is true (v-if="shouldAnimate") that is initially set to false when declared, and when onMounted fires, it sets that value to true which in turn triggers the animation to run (doesn't really matter how the animation works, but just in case, I have options to use either GSAP or anime.js).

Up to this point, all is good: every time I navigate to a page (using Inertia-adequate methods such as the Link component) the animation triggers and I am a happy guy.

BUT: I would very much like to be able to play another animation (the reverse of the previous one) before, say, navigation to the next page occurs. I have tried almost everything I can think of and have not been successful. Here's what got the closest to what I need:

I tried hooking into the InertiaJS event Inertia.on('before', ...): effectively, the event fires up right before navigation (checked with some good-old console log), so I tried firing up the animation at this point, only to find out that the Inertia event looks like it is destroying the page immediately before the animation has had time to play; no problem: I'll just event.preventDefault() it, run the animation and THEN, using a setTimeout timed to the length of the animation (300ms) I'll resume navigation, say, by using Inertia.visit.

Doesn't work. Somehow, the default behaviour is prevented (stops the navigation), the animation plays back, but when it comes to the "resume navigation part" I have had mixed results depending on what I use:

Code looks roughly like this:

let removeListener = Inertia.on('before', (event) => {

    event.preventDefault()

    // Play animation here

    setTimeout(() => {
        // SOME INERTIA ACTION DESCRIBED BELOW
    }, 300)

})

Independently of whether I use Inertia.get(event.detail.visit.url) or Inertia.visit(event.detail.visit.url) what happens is the animation runs its course, and then the timer runs out and this whole code RUNS AGAIN AND AGAIN in intervals equal to the timer. I also tried to do this using the complete event of the animation to trigger the navigation but it behaves the same.

I know this is related to me being an ignorant about how both Inertia and events work, and I am sure there is a proper (correct? right?) way to achieve what I need, but either I have failed in using the correct terms to look for it, or I am approaching this the wrong way. Hopefully this information is enough to explain my issue.

Any help or pointer would be GREATLY appreciated, so thanks in advance.


问:
How to scale view from top right corner
I'm changing anchor point by methods in this topic:
Changing my CALayer's anchorPoint moves the view but it's not working for me

What I see

The view is misplaced

What I Expect

The grey rectangle must expand from 1.0 in x and 0.0 in y without misplacement

My code:

```<code>private func setAnchorPoint(anchorPoint: CGPoint, view: UIView) {
       let oldOrigin = view.frame.origin
       view.layer.anchorPoint = anchorPoint
       let newOrigin = view.frame.origin
       let translation = CGPoint(x: newOrigin.x - oldOrigin.x, y: newOrigin.y - oldOrigin.y)
       view.center = CGPoint(x: view.center.x - translation.x, y: view.center.y - translation.y)
    }

setAnchorPoint(anchorPoint: CGPoint(x: 1.0, y: 0.0), view: self.actionLayer)
</code>```

What I've tried

Recording in a variable the frame before changing the anchor point and setting again after, same for layer position or view center. Not working.

Title: How to scale view from top right corner

Body:
I'm changing anchor point by methods in this topic:
Changing my CALayer's anchorPoint moves the view but it's not working for me

What I see

The view is misplaced

What I Expect

The grey rectangle must expand from 1.0 in x and 0.0 in y without misplacement

My code:

private func setAnchorPoint(anchorPoint: CGPoint, view: UIView) {
       let oldOrigin = view.frame.origin
       view.layer.anchorPoint = anchorPoint
       let newOrigin = view.frame.origin
       let translation = CGPoint(x: newOrigin.x - oldOrigin.x, y: newOrigin.y - oldOrigin.y)
       view.center = CGPoint(x: view.center.x - translation.x, y: view.center.y - translation.y)
    }

setAnchorPoint(anchorPoint: CGPoint(x: 1.0, y: 0.0), view: self.actionLayer)

What I've tried

Recording in a variable the frame before changing the anchor point and setting again after, same for layer position or view center. Not working.


问:
How to pass '%s' string value in MySQL?
Good day,

I'm working on a XAMPP database using Python and PyMysql. However, I'm having a problem with passing a %s string value when using CONCAT search.

```<code>import pymysql

connect_database = pymysql.connect(host='localhost', user="root", database='treeview_test')
cursor = connect_database.cursor()

search_input = str(input("Enter last name: "))

cursor.execute("SELECT * FROM `information` WHERE `last_name` LIKE CONCAT ('%', '%s', '%')" % (search_input))
data = cursor.fetchall()
print(data)
</code>```

And this is the error:

```<code>cursor.execute("SELECT * FROM `information` WHERE `last_name` LIKE CONCAT ('%', '%s', '%')" % (search_input))
ValueError: unsupported format character ''' (0x27) at index 61
</code>```

Please help, or maybe suggest other workaround on how to do this. I'm trying to create a search function that will search the last_name column even if only part of the string is used as keyword.

Thanks in advance.

Title: How to pass '%s' string value in MySQL?

Body:
Good day,

I'm working on a XAMPP database using Python and PyMysql. However, I'm having a problem with passing a %s string value when using CONCAT search.

import pymysql

connect_database = pymysql.connect(host='localhost', user="root", database='treeview_test')
cursor = connect_database.cursor()

search_input = str(input("Enter last name: "))

cursor.execute("SELECT * FROM `information` WHERE `last_name` LIKE CONCAT ('%', '%s', '%')" % (search_input))
data = cursor.fetchall()
print(data)

And this is the error:

cursor.execute("SELECT * FROM `information` WHERE `last_name` LIKE CONCAT ('%', '%s', '%')" % (search_input))
ValueError: unsupported format character ''' (0x27) at index 61

Please help, or maybe suggest other workaround on how to do this. I'm trying to create a search function that will search the last_name column even if only part of the string is used as keyword.

Thanks in advance.


问:
UIImageView loading from URL with cancellable task and safe to use in a UICollectionView
I am trying to make a UIImageView class / extension that can load an image from a URL.

the image view should not get confused with concurrency when scrolling through a UICollectionView and the data task should be cancellable. Also downloaded images should be cached (I'm not sure if NSCache or URLCache should be used here)

I would like to utilise the latest Swift APIs if possible.

Is this the correct usage of Task?

I have written this code and I am wondering if anybody can spot anything wrong or anything they believe could improve the code:

```<code>import Foundation
import UIKit

class PHImageView: UIImageView {
    static var imageCache = NSCache<AnyObject, AnyObject>()
    var imageURL: URL?
    var currentTask: Task<(), Error>?
    func setImage(url: URL , contentMode: ContentMode = .scaleAspectFit) {
        imageURL = url
        image = nil
        let urlRequest = URLRequest(url: url)
        if let image = PHImageView.imageCache.object(forKey: url.absoluteString as AnyObject) as? UIImage {
            currentTask?.cancel()
            currentTask = nil
            DispatchQueue.main.async {
                self.image = image
                self.contentMode = contentMode
            }
        } else {
            currentTask = Task {
                do {
                    let (data, _) = try await URLSession(configuration: .default).data(for: urlRequest)
                    guard url == self.imageURL else {
                        if let imageURL = imageURL {
                            setImage(url: imageURL, contentMode: contentMode)
                        }
                        return
                    }
                    let image = UIImage(data: data)
                    PHImageView.imageCache.setObject(image as AnyObject, forKey: url.absoluteString as AnyObject)
                    DispatchQueue.main.async {
                        self.image = image
                        self.contentMode = contentMode
                    }
                }
                catch {
                    print(error)
                }
            }
        }
    }
    deinit {
        currentTask?.cancel()
    }
}
</code>```

Body:
I am trying to make a UIImageView class / extension that can load an image from a URL.

the image view should not get confused with concurrency when scrolling through a UICollectionView and the data task should be cancellable. Also downloaded images should be cached (I'm not sure if NSCache or URLCache should be used here)

I would like to utilise the latest Swift APIs if possible.

Is this the correct usage of Task?

I have written this code and I am wondering if anybody can spot anything wrong or anything they believe could improve the code:

import Foundation
import UIKit

class PHImageView: UIImageView {
    static var imageCache = NSCache<AnyObject, AnyObject>()
    var imageURL: URL?
    var currentTask: Task<(), Error>?
    func setImage(url: URL , contentMode: ContentMode = .scaleAspectFit) {
        imageURL = url
        image = nil
        let urlRequest = URLRequest(url: url)
        if let image = PHImageView.imageCache.object(forKey: url.absoluteString as AnyObject) as? UIImage {
            currentTask?.cancel()
            currentTask = nil
            DispatchQueue.main.async {
                self.image = image
                self.contentMode = contentMode
            }
        } else {
            currentTask = Task {
                do {
                    let (data, _) = try await URLSession(configuration: .default).data(for: urlRequest)
                    guard url == self.imageURL else {
                        if let imageURL = imageURL {
                            setImage(url: imageURL, contentMode: contentMode)
                        }
                        return
                    }
                    let image = UIImage(data: data)
                    PHImageView.imageCache.setObject(image as AnyObject, forKey: url.absoluteString as AnyObject)
                    DispatchQueue.main.async {
                        self.image = image
                        self.contentMode = contentMode
                    }
                }
                catch {
                    print(error)
                }
            }
        }
    }
    deinit {
        currentTask?.cancel()
    }
}


问:
GitHub not showing changes on pull request
I have a branch that I want to merge into the develop branch, let's call it feature-branch. I've made changes to one file and opened a PR on GitHub. When viewing the PR, the diffing shows "0 files changed". Viewing the same file on the two respective branches in GitHub's built-in code editor shows the difference between the two branches, but in the PR it remains as "0 files changed".

When diffing the two branches locally with git diff feature-branch..develop, the change is shown. Both local branches are up to date with their remote counterparts, I've tried pulling them and resetting them to remote, but the issue remains - the diff is showing up locally but not on GitHub.

I've tried closing and opening the PR again, deleting feature-branch and pushing it again, and changing the base branch on the PR to a different one then back to develop, but the issue remains - still showing 0 changes. At this point I'm stuck. Any suggestions?

Edit: I've solved the issue by:

Making a new branch from develop

Copying over the changes made previously in said file

Opening a new PR from the new branch

The PR now shows the relevant changes, despite this new branch being identical to the previous one, at least in terms of the file's contents. I'm leaving the question open because I still don't understand how the original issue happened, but this is an okay workaround.


问:
How to retrieve the text from a div element in Javascript using Cheerio?
I've been trying to retrieve the text from the following div:

```<code><div class="col-md-7 order-md-1">
                                <strong>Name: </strong> Adept Rider<br>
                                <strong>Type: </strong> Craftable<br>
                                <strong>Location: </strong> Summerset<br>
                                <strong>Traits needed to craft: </strong> 3<br>
                                <strong>Requires DLC: </strong> Summerset<br>
                                <br><strong>Obtainable items: </strong>
                                <ul>
                                    <li>Weapons</li>
                                    <li>Light Armor</li>
                                    <li>Jewels</li>
                                    <li>Heavy Armor</li>
                                    <li>Medium Armor</li>
                                </ul>
                                <br>
                                <br>
</div>
</code>```

I want a const location to be a String that prints out 'Summerset'. I tried the following approach:

```<code>const location = $('strong:contains("Location:")').text();
console.log(location); // prints: Location:
</code>```

The following approach prints nothing:

```<code>const location = $('strong:contains("Location:")').next().text();
console.log(location); // prints nothing, but expect ' Summerset'
</code>```

Do you folks have any tips on how to approach this?
I think I load the HTML in the correct way since I do get 'Location: ' printed out without the use of the next() call.

Body:
I've been trying to retrieve the text from the following div:

                                Name:  Adept Rider

                                Type:  Craftable

                                Location:  Summerset

                                Traits needed to craft:  3

                                Requires DLC:  Summerset

Obtainable items:

Weapons

Light Armor

Jewels

Heavy Armor

Medium Armor

I want a const location to be a String that prints out 'Summerset'. I tried the following approach:

const location = $('strong:contains("Location:")').text();
console.log(location); // prints: Location:

The following approach prints nothing:

const location = $('strong:contains("Location:")').next().text();
console.log(location); // prints nothing, but expect ' Summerset'

Do you folks have any tips on how to approach this?
I think I load the HTML in the correct way since I do get 'Location: ' printed out without the use of the next() call.


问:
ERROR:device_event_log_impl.cc(215)] [11:32:41.457] USB: usb_device_handle_win.cc:1045
when I run the code below on VSCode I get an error like this

ERROR:device_event_log_impl.cc(215)] [11:32:41.457] USB: usb_device_handle_win.cc:1045 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)

my code is

```<code>from selenium import webdriver

from selenium.webdriver.common.by import By

import time

driver = webdriver.Chrome()

driver.get("https://duckduckgo.com")

time.sleep(5)
</code>```

Body:
when I run the code below on VSCode I get an error like this

ERROR:device_event_log_impl.cc(215)] [11:32:41.457] USB: usb_device_handle_win.cc:1045 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)

my code is

from selenium import webdriver

from selenium.webdriver.common.by import By

import time

driver = webdriver.Chrome()

driver.get("https://duckduckgo.com")

time.sleep(5)


问:
object, Object instead of correct data from object VueJS
I pass the following props in my month component

 props: {
          actionEvents: this.selectedEvent && this.selectedEvent.calendar && this.selectedEvent.id || this.selectedEvent
        }
```

<p>In my ChangeCalendar component I'm trying to update the api by doing the following:</p>
<pre class="lang-js prettyprint-override"><code>        ? this.$api.calendar.update(
          this.actionEvents && this.actionEvents.id && this.actionEvents.calendar || this.actionEvents,
           data
</code>```

I need both Id and calendar for the route to update but the output I get is:
"/calendars/f2User-51-5594439/events/[object Object]". I would expect object Object to return the calendar value (which is a string and is something like: f2User-51-actions).

Does anyone know what I'm doing wrong here? I dont understand why Id does return the expected value but calendar doesn't

When I look into the data and props of my components:

Body:
I pass the following props in my month component

 props: {
          actionEvents: this.selectedEvent && this.selectedEvent.calendar && this.selectedEvent.id || this.selectedEvent
        }

In my ChangeCalendar component I'm trying to update the api by doing the following:

        ? this.$api.calendar.update(
          this.actionEvents && this.actionEvents.id && this.actionEvents.calendar || this.actionEvents,
           data

I need both Id and calendar for the route to update but the output I get is:
"/calendars/f2User-51-5594439/events/[object Object]". I would expect object Object to return the calendar value (which is a string and is something like: f2User-51-actions).

Does anyone know what I'm doing wrong here? I dont understand why Id does return the expected value but calendar doesn't

When I look into the data and props of my components:


问:
Is there a way to fetch order reference when a customer purchase a module published on Odoo app store?
We require Sales order reference of published app on Odoo apps.
For e.g. if we have published one app on Odoo apps 'ABC' and 2 customers have purchased it. We require order reference which Odoo generates for our record purpose.
Is there a way to fetch it somehow?

Any help would be appreciated.

Thanks,


问:
Toolbar on top with weightSum
I have a view with a title bar above (RelativeLayout) and below a LinearLayout with weightSum.
I used the weightSum because I wanted to distribute the three elements (ImageView, TextView, Button ) 100% contained in the page.

Everything works fine, but when I go to write something from the textview the keyboard appears and the bar disappears from the view because it drags over.

I tried various systems to try to insert the scoolview and keep the bar fixed at the top.

I used both the scrollview and the NestedScrollView and I also changed the bar created with the RelativeLayout to a toolbar.
but the content of the LinearLayout with the weightSum stretches a lot.

do you have any suggestion for me?

thank you

```<code><?xml version="1.0" encoding="utf-8"?>
  <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/fond"
android:fillViewport="true"
tools:context=".client.FicheClient">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_gravity="center|top"
        android:gravity="center|top">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:background="@color/surface_l"
            android:orientation="horizontal"
            android:paddingLeft="56dp"
            android:paddingRight="56dp">

            <TextView
                android:id="@+id/txtNomFichier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:ellipsize="end"
                android:fontFamily="@font/inter_bold_700t"
                android:gravity="center_horizontal"
                android:maxLines="1"
                android:text="@string/label_document"
                android:textColor="@color/white"
                android:textSize="14sp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="backList"
            android:paddingStart="16dp"
            android:paddingTop="12dp"
            android:paddingEnd="16dp"
            android:paddingBottom="12dp">

            <ImageView
                android:id="@+id/btn_Back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/icone_arrow_left_blanc" />

        </LinearLayout>

        <Button
            android:id="@+id/btn_share"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="12dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/fond_partage"
            android:fontFamily="@font/inter_regular_400t"
            android:onClick="launchPartage"
            android:text=""
            android:textColor="@color/blanc"
            android:visibility="invisible" />

        <ProgressBar
            android:id="@+id/progressBarTop"
            style="?android:attr/progressBarStyle"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="12dp"
            android:layout_marginEnd="16dp"
            android:theme="@style/colorProgressBarTop" />

    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="100">

        <LinearLayout
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="77"
            android:background="@drawable/radius_gris"
            android:orientation="vertical">

            <ImageView
                android:layout_gravity="center_horizontal|center_vertical"
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <com.github.barteksc.pdfviewer.PDFView
                android:layout_gravity="center_horizontal|center_vertical"
                android:id="@+id/pdfView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="gone" />
        </LinearLayout>

        <LinearLayout
            android:layout_weight="11"
            android:layout_marginRight="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginBottom="16dp"
            android:padding="12sp"
            android:background="@drawable/radius_blanc"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtLibelleNomFichier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/inter_regular_400t"
                android:gravity="left|center_vertical"
                android:text="@string/label_file_name_obligatoire"
                android:textColor="@color/surface_h"
                android:textSize="12sp" />

            <EditText
                android:id="@+id/txtNom"
                android:layout_width="match_parent"
                android:layout_height="18dp"
                android:background="@drawable/textedit_blanc_rounded_corners"
                android:textColor="@color/surface_k"
                android:ellipsize="end"
                android:textSize="12sp"
                android:fontFamily="@font/inter_semi_bold_600t"
                android:gravity="left|center_vertical"
                android:inputType="text"
                android:maxLines="1"
                android:layout_marginTop="2dp"
                android:scrollHorizontally="true" />

        </LinearLayout>

        <LinearLayout
            android:background="@color/blanc"
            android:layout_weight="12"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:gravity="center"
            android:orientation="vertical">

            <Button
                android:id="@+id/btn_upload"
                android:layout_width="match_parent"
                android:layout_height="39dp"
                android:layout_columnWeight="1"
                android:layout_margin="16dp"
                android:textAllCaps="false"
                android:background="@drawable/radius_primary_5"
                android:text="@string/btn_validate"
                android:textColor="@color/blanc" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Title: Toolbar on top with weightSum

Body:
I have a view with a title bar above (RelativeLayout) and below a LinearLayout with weightSum.
I used the weightSum because I wanted to distribute the three elements (ImageView, TextView, Button ) 100% contained in the page.

Everything works fine, but when I go to write something from the textview the keyboard appears and the bar disappears from the view because it drags over.

I tried various systems to try to insert the scoolview and keep the bar fixed at the top.

I used both the scrollview and the NestedScrollView and I also changed the bar created with the RelativeLayout to a toolbar.
but the content of the LinearLayout with the weightSum stretches a lot.

do you have any suggestion for me?

thank you

<?xml version="1.0" encoding="utf-8"?>
  <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/fond"
android:fillViewport="true"
tools:context=".client.FicheClient">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_gravity="center|top"
        android:gravity="center|top">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:background="@color/surface_l"
            android:orientation="horizontal"
            android:paddingLeft="56dp"
            android:paddingRight="56dp">

            <TextView
                android:id="@+id/txtNomFichier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="12dp"
                android:ellipsize="end"
                android:fontFamily="@font/inter_bold_700t"
                android:gravity="center_horizontal"
                android:maxLines="1"
                android:text="@string/label_document"
                android:textColor="@color/white"
                android:textSize="14sp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="backList"
            android:paddingStart="16dp"
            android:paddingTop="12dp"
            android:paddingEnd="16dp"
            android:paddingBottom="12dp">

            <ImageView
                android:id="@+id/btn_Back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/icone_arrow_left_blanc" />

        </LinearLayout>

        <Button
            android:id="@+id/btn_share"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="12dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/fond_partage"
            android:fontFamily="@font/inter_regular_400t"
            android:onClick="launchPartage"
            android:text=""
            android:textColor="@color/blanc"
            android:visibility="invisible" />

        <ProgressBar
            android:id="@+id/progressBarTop"
            style="?android:attr/progressBarStyle"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="12dp"
            android:layout_marginEnd="16dp"
            android:theme="@style/colorProgressBarTop" />

    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="100">

        <LinearLayout
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="77"
            android:background="@drawable/radius_gris"
            android:orientation="vertical">

            <ImageView
                android:layout_gravity="center_horizontal|center_vertical"
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <com.github.barteksc.pdfviewer.PDFView
                android:layout_gravity="center_horizontal|center_vertical"
                android:id="@+id/pdfView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="gone" />
        </LinearLayout>

        <LinearLayout
            android:layout_weight="11"
            android:layout_marginRight="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginBottom="16dp"
            android:padding="12sp"
            android:background="@drawable/radius_blanc"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtLibelleNomFichier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/inter_regular_400t"
                android:gravity="left|center_vertical"
                android:text="@string/label_file_name_obligatoire"
                android:textColor="@color/surface_h"
                android:textSize="12sp" />

            <EditText
                android:id="@+id/txtNom"
                android:layout_width="match_parent"
                android:layout_height="18dp"
                android:background="@drawable/textedit_blanc_rounded_corners"
                android:textColor="@color/surface_k"
                android:ellipsize="end"
                android:textSize="12sp"
                android:fontFamily="@font/inter_semi_bold_600t"
                android:gravity="left|center_vertical"
                android:inputType="text"
                android:maxLines="1"
                android:layout_marginTop="2dp"
                android:scrollHorizontally="true" />

        </LinearLayout>

        <LinearLayout
            android:background="@color/blanc"
            android:layout_weight="12"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:gravity="center"
            android:orientation="vertical">

            <Button
                android:id="@+id/btn_upload"
                android:layout_width="match_parent"
                android:layout_height="39dp"
                android:layout_columnWeight="1"
                android:layout_margin="16dp"
                android:textAllCaps="false"
                android:background="@drawable/radius_primary_5"
                android:text="@string/btn_validate"
                android:textColor="@color/blanc" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>


问:
How to check if value was stored in localStorage after button click with Angular and Jasmine
I have a script that navigates user to the next page after click and also saves a value into the localStorage. I've written a test case that works good, but the issue is I want to be able to make sure that the value is saved in the storage as well and also when the localStorage line is commented out the test should break

.ts file

```<code>  selectOne(item) {
    this.userService.name = item?.suggestedName;
    localStorage.setItem('currentUser', JSON.stringify(this.itemService?.userService));
    this.router.navigate(['/others']);

  }
</code>```

.spec.ts test file

```<code>  it(' should select a username and navigate to others',() => {
    const navigateSpy = spyOn(router, 'navigate');
    const item = {id:4, suggestedName: 'test'};
    component.selectOne(item);
    expect(navigateSpy).toHaveBeenCalledWith(['/others']);
  });
</code>```

Body:
I have a script that navigates user to the next page after click and also saves a value into the localStorage. I've written a test case that works good, but the issue is I want to be able to make sure that the value is saved in the storage as well and also when the localStorage line is commented out the test should break

.ts file

  selectOne(item) {
    this.userService.name = item?.suggestedName;
    localStorage.setItem('currentUser', JSON.stringify(this.itemService?.userService));
    this.router.navigate(['/others']);

  }

.spec.ts test file

  it(' should select a username and navigate to others',() => {
    const navigateSpy = spyOn(router, 'navigate');
    const item = {id:4, suggestedName: 'test'};
    component.selectOne(item);
    expect(navigateSpy).toHaveBeenCalledWith(['/others']);
  });


问:
Theano to tensorflow conversion
What is the tensorflow/keras equivalent of Theano's gt?

Based on Theano's documentation, theano.tensor.gt returns a symbolic 'int8' tensor representing the result of logical greater-than (a>b).

In Theano, I have:

```<code>import theano.tensor as T

posInd1 = T.gt(D1, eps).nonzero()[0]
</code>```

How do I convert it to TensorFlow?

Title: Theano to tensorflow conversion

Body:
What is the tensorflow/keras equivalent of Theano's gt?

Based on Theano's documentation, theano.tensor.gt returns a symbolic 'int8' tensor representing the result of logical greater-than (a>b).

In Theano, I have:

import theano.tensor as T

posInd1 = T.gt(D1, eps).nonzero()[0]

How do I convert it to TensorFlow?


问:
Change backend base URL with osmdroid
I can't find a way how to change the backend URL with https://github.com/MKergall/osmbonuspack.
I am using https://github.com/Project-OSRM/osrm-backend for my backend.

Is it even possible?

Title: Change backend base URL with osmdroid


问:
How to handle new realm app users confirmation with a MongoDB Function?
I tried to create an HTTP Endpoint with a Function, where I tried to install realm-web, I add the realm-web dependency successfully, but when I try to import it with

```<code>import * as Realm from "realm-web";
</code>```

It gives me this response:

error:
failed to execute source for 'node_modules/realm-web/dist/bundle.cjs.js': TypeError: Cannot access member 'name' of undefined
at node_modules/realm-web/dist/bundle.cjs.js:4260:13(847)

Body:
I tried to create an HTTP Endpoint with a Function, where I tried to install realm-web, I add the realm-web dependency successfully, but when I try to import it with

import * as Realm from "realm-web";

It gives me this response:

error:
failed to execute source for 'node_modules/realm-web/dist/bundle.cjs.js': TypeError: Cannot access member 'name' of undefined
at node_modules/realm-web/dist/bundle.cjs.js:4260:13(847)


问:
How can a pre-built Python-installation be modified to work in another directory?
For a project shipping with a pre-built customized Python distribution I need to be able to compile packages from source using pip (within the installed environment).

This is what the file system structure for two installations of the final product might look like:

```<code>/opt
├── my-program-v1
│   ├── some-files
│   ├── custom-python-3.9
├── my-program-v2
│   ├── some-files
│   ├── custom-python-3.11

</code>```

Since the readily installed program (together with its Python installation) might be installed to any directory, pip needs a way to find the header files for the used Python installation.

Just copying the whole Python installation to the desired directory will result in errors when trying to pip install a package that needs to be built from source (e.g. ibm_db):

```<code>$ python3 -m pip install ibm_db
Collecting ibm_db
  Downloading ibm_db-3.1.4.tar.gz (1.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.4/1.4 MB 9.5 MB/s eta 0:00:00
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Detected 64-bit Python
      Detected platform = linux, uname = x86_64
      Downloading https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/linuxx64_odbc_cli.tar.gz
       Downloading DSDriver from url =  https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/linuxx64_odbc_cli.tar.gz
      Pre-requisite check [gcc] : Passed

      No Python.h header file detected.
      Please install python-devel or python3-devel as instructed in "https://github.com/ibmdb/python-ibmdb/blob/master/README.md#KnownIssues" and continue with the installation
      [end of output]
</code>```

Usually, when you build Python from source you would set the final destination folder using configure --prefix=/opt/my-program-v2, which would be stored inside the sysconfigdata of that readily built Python installation.

But how can this be done when you need to pre-build Python and don't know the installation directory in advance?

One possible way is to manually modify the generated sysconfig-data, (usually found in lib/<python-version>/_sysconfigdata__linux_x86_64-linux-gnu.py) but this is not fun (due to the used format) and introduces a step outside of the CI.

How do others do that? Is there an intended way to place/relocate a prebuilt installation of python?

Body:
For a project shipping with a pre-built customized Python distribution I need to be able to compile packages from source using pip (within the installed environment).

This is what the file system structure for two installations of the final product might look like:

/opt
├── my-program-v1
│   ├── some-files
│   ├── custom-python-3.9
├── my-program-v2
│   ├── some-files
│   ├── custom-python-3.11

Since the readily installed program (together with its Python installation) might be installed to any directory, pip needs a way to find the header files for the used Python installation.

Just copying the whole Python installation to the desired directory will result in errors when trying to pip install a package that needs to be built from source (e.g. ibm_db):

$ python3 -m pip install ibm_db
Collecting ibm_db
  Downloading ibm_db-3.1.4.tar.gz (1.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.4/1.4 MB 9.5 MB/s eta 0:00:00
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Detected 64-bit Python
      Detected platform = linux, uname = x86_64
      Downloading https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/linuxx64_odbc_cli.tar.gz
       Downloading DSDriver from url =  https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/linuxx64_odbc_cli.tar.gz
      Pre-requisite check [gcc] : Passed

      No Python.h header file detected.
      Please install python-devel or python3-devel as instructed in "https://github.com/ibmdb/python-ibmdb/blob/master/README.md#KnownIssues" and continue with the installation
      [end of output]

Usually, when you build Python from source you would set the final destination folder using configure --prefix=/opt/my-program-v2, which would be stored inside the sysconfigdata of that readily built Python installation.

But how can this be done when you need to pre-build Python and don't know the installation directory in advance?

One possible way is to manually modify the generated sysconfig-data, (usually found in lib/<python-version>/_sysconfigdata__linux_x86_64-linux-gnu.py) but this is not fun (due to the used format) and introduces a step outside of the CI.

How do others do that? Is there an intended way to place/relocate a prebuilt installation of python?


问:
Finding memory leak at certain point of runtime
I need to find out what objects are not deleted between application states, here is code example:

```<code>#include <vector>
#include <map>

class MyClass {
public:
    int myNum;
};

std::vector<MyClass *> firstStateClasses;
std::map<int, MyClass *> stateClasses;

void MakeFirstState()
{
    for (int i = 0; i < 10; ++i)
    {
        MyClass* firstClass = new MyClass();
        firstStateClasses.push_back(firstClass);
    }
}

void DeleteFirstState()
{
    for (auto p : firstStateClasses)
    {
        delete p;
    }
    firstStateClasses.clear();
}

void MakeState(int state)
{
    MyClass* randomClass = new MyClass();

    stateClasses.insert(std::make_pair(state, randomClass));
}

void DeleteState(int state)
{
    auto itr = stateClasses.find(state);
    if (itr != stateClasses.end())
    {
        delete itr->second;
        stateClasses.erase(itr);
    }
}

int main()
{
    MakeFirstState();
    MakeState(0);
    //Leak is here, state wasnt deleted.
    MakeState(1);
    //I need to know here objects that were made only in MakeState(0) and not deleted.
    DeleteState(1);
    MakeState(2);
    DeleteState(2);
    DeleteFirstState();
}

</code>```

I was trying to use Visual Studio memory heap profiling, but it isnt very usefull since i cant single out only objects that were made in MakeState(0) and were not deleted after MakeState(1).

Body:
I need to find out what objects are not deleted between application states, here is code example:

#include <vector>
#include <map>

class MyClass {
public:
    int myNum;
};

std::vector<MyClass *> firstStateClasses;
std::map<int, MyClass *> stateClasses;

void MakeFirstState()
{
    for (int i = 0; i < 10; ++i)
    {
        MyClass* firstClass = new MyClass();
        firstStateClasses.push_back(firstClass);
    }
}

void DeleteFirstState()
{
    for (auto p : firstStateClasses)
    {
        delete p;
    }
    firstStateClasses.clear();
}

void MakeState(int state)
{
    MyClass* randomClass = new MyClass();

    stateClasses.insert(std::make_pair(state, randomClass));
}

void DeleteState(int state)
{
    auto itr = stateClasses.find(state);
    if (itr != stateClasses.end())
    {
        delete itr->second;
        stateClasses.erase(itr);
    }
}

int main()
{
    MakeFirstState();
    MakeState(0);
    //Leak is here, state wasnt deleted.
    MakeState(1);
    //I need to know here objects that were made only in MakeState(0) and not deleted.
    DeleteState(1);
    MakeState(2);
    DeleteState(2);
    DeleteFirstState();
}

I was trying to use Visual Studio memory heap profiling, but it isnt very usefull since i cant single out only objects that were made in MakeState(0) and were not deleted after MakeState(1).


问:
Yarn usage error: Couldn't find a configuration settings named "proxy"
I'm trying to update yarn proxy configurations but when I launch the command (I'm on Ubuntu 22.04)

```<code>yarn config set proxy my.proxy.url:port
</code>```

I get the error

```<code>Usage Error: Couldn't find a configuration settings named "proxy"
</code>```

All of this because I'm trying to run the yarn install command but all I get is package_name can't be found in the cache and will be fetched from the remote registry for a couple of packages.

I tried to curl some site and it works wonderfully, so it shouldn't be a shell problem (I'm using zsh by the way).

Body:
I'm trying to update yarn proxy configurations but when I launch the command (I'm on Ubuntu 22.04)

yarn config set proxy my.proxy.url:port

I get the error

Usage Error: Couldn't find a configuration settings named "proxy"

All of this because I'm trying to run the yarn install command but all I get is package_name can't be found in the cache and will be fetched from the remote registry for a couple of packages.

I tried to curl some site and it works wonderfully, so it shouldn't be a shell problem (I'm using zsh by the way).


问:
Recommended practice of using dependency injection for injecting multiple instances based on configuration [boost-ext::di]
I have a question regarding how to properly use dependency injection to select one of multiple instances based on configuration (and whether it is actually suitable in this case or not). I am currently using boost-ext::di as the dependency injection framework but I would like to ask this question in more generic form.

I am designing the firmware of a development board. The class SPI was used to abstract the two SPI controller on board, SPI1 and SPI2.

Then, there are multiple SPI devices that can be associated with the SPI Buses. For example,

struct SDCard {
  SDCard (SPI& bus) : bus(bus) {}  // <-- constructor injection by boost-ext::di framework
  SPI& bus;
}
```

My question is, given that the different development board may have different hardware configuration, so

am I supposed to use DI to select which SPI instance should be injected to the SDCard object?

is there a recommended practice to configure which SPIx bus will be injected to the SDCard instance?

Body:
I have a question regarding how to properly use dependency injection to select one of multiple instances based on configuration (and whether it is actually suitable in this case or not). I am currently using boost-ext::di as the dependency injection framework but I would like to ask this question in more generic form.

I am designing the firmware of a development board. The class SPI was used to abstract the two SPI controller on board, SPI1 and SPI2.

Then, there are multiple SPI devices that can be associated with the SPI Buses. For example,

struct SDCard {
  SDCard (SPI& bus) : bus(bus) {}  // <-- constructor injection by boost-ext::di framework
  SPI& bus;
}

My question is, given that the different development board may have different hardware configuration, so

am I supposed to use DI to select which SPI instance should be injected to the SDCard object?

is there a recommended practice to configure which SPIx bus will be injected to the SDCard instance?


问:
How to listen socket.io message without using event Listener in postman
When using postman event listener, I'm getting messages but problem is that,

i don't want to listen to any event, then how can i get messages from the server

I want to get all messages when the server triggers client.send(data).

Is there any way to do this

Thanks.


问:
How to add some jquery functions to show me only episodes specific to a season?
I have been struggling for a few days to discover an option to display only the episodes corresponding to a season when I click on that season.

This is my code...

```<code>

<div id='seasons' class='visible'>

<div class='wrap'>

<div class='tit'>ALEGEȚI UN SEZON</div>

<div class='list bslider undraggable deployed' data-bslider-margin='20' data-bslider-left-margin='0' data-bslider-right-margin='20' data-bslider-item-class='item' data-bslider-nav='false' id='seasonsList' data-single-width='60' data-max-width='201' data-stage-width='1160'><div class='bslider-outer'><div class='bslider-stage' style='width: 1160px; padding-left: 0px;'>

                    <?php
                    $tmdb = get_post_meta($post->ID,'ids',true);
                    $ctrl = get_post_meta($post->ID,'clgnrt',true);
                    $query_seasons = DDbmoviesHelpers::GetAllSeasons($tmdb);
                    if($query_seasons && is_array($query_seasons) && $ctrl == true){
                        $numb = 0;
                        foreach($query_seasons as $season){
                            $senumb = get_post_meta($season,'temporada', true);
                            ?>

<div class="bslider-item" style="padding-right: 20px;"><div class="item" data-season-id="<?php echo $senumb; ?>" id="sezonul-<?php echo $senumb; ?>"><?php echo $senumb; ?></div></div>

                            <?php
                            $numb++;
                        }
                    }
                    ?>

            </div></div></div>

            </div></div>

            <div class='clearfix'></div>

            <div id='episodes' class="active">

            <div class='wrap'>

            <?php

            // Main data
            $tmdb = get_post_meta($post->ID,'ids',true);
            $ctrl = get_post_meta($post->ID,'clgnrt',true);
            /*=====================================================*/
            $query_seasons = DDbmoviesHelpers::GetAllSeasons($tmdb);
            /*=====================================================*/
            // Start Query
            if($query_seasons && is_array($query_seasons) && $ctrl == true){
                $numb = 0;
                foreach($query_seasons as $k => $season){
                    $senumb = get_post_meta($season,'temporada', true);
                    $aidate = get_post_meta($season,'air_date', true);
                    $rating = get_post_meta($season,'_starstruck_avg', true);
                    /*=====================================================*/
                    $query_episodes = DDbmoviesHelpers::GetAllEpisodes($tmdb,$senumb);
                    /*=====================================================*/
                    $mnseo = $numb == 0 ? ' se-o' : false;
                    $dsply = $numb == 0 ? ' style="display:block"' : false;
                    $title = $senumb == '0' ? __d('Specials') : sprintf( __d('Season %s %s'), $senumb, '<i>'.doo_date_compose($aidate, false).'</i>');
                    $nseas = $senumb == '0' ? '<i class="icon-star"></i>' : $senumb;
                    // Continue View HTML
                    if($query_episodes && is_array($query_episodes)){
                        ?>

            <div class='list bslider' data-bslider-margin='20' data-bslider-left-margin='0' data-bslider-right-margin='20' data-bslider-item-class='item' data-bslider-nav='false' id='episodesList-<?php echo $senumb; ?>' data-single-width='220' data-max-width='761' data-stage-width='2000'><div class='bslider-outer'><div class='bslider-stage' style='width: 2000px; padding-left: 0px;'>

                        <?php
                        foreach($query_episodes as $episode){
                            // Post Data
                            $image = dbmovies_get_poster($episode,'dt_episode_a','dt_backdrop','w154');
                            $name  = get_post_meta($episode,'episode_name', true);
                            $episo = get_post_meta($episode,'episodio', true);
                            $edate = get_post_meta($episode,'air_date', true);
                            $edate = doo_date_compose($edate, false);
                            $plink = get_permalink($episode);

                            $title = !empty($name) ? $name : __('Episode').' '.$episo;
                            ?>

            <div class='bslider-item' style='padding-right: 20px;'>

            <div class='item slider-item' slide-number='<?php echo $episo; ?>' data-episode-id='<?php echo $episo; ?>'>

            <div class='poster'>

            <div class='img' style='background-image:url(<?php echo $image ?>);'></div>

            <div class='title'><?php echo $episo; ?>. <?php echo $title; ?></div>

            </div>

            </div>

            </div>

                            <?php
                        }
                        ?>
                        </div></div></div>    </br></br>

                        <?php
                    } else{
                        ?>

                        <div class='title'><?php echo __d('There are still no episodes this season') ?></div>

                        <?php
                    }
                    $numb++;
                }
            }
            ?>

            </div>

            </div>

        <div class="clearfix"></div>

</code>```

I want when I click on a Season to trigger the list of episodes below.

I don't have any js for this, my script show all seasons and episodes perfectly but is all displayed.

Body:
I have been struggling for a few days to discover an option to display only the episodes corresponding to a season when I click on that season.

This is my code...

ALEGEȚI UN SEZON

                    <?php
                    $tmdb = get_post_meta($post->ID,'ids',true);
                    $ctrl = get_post_meta($post->ID,'clgnrt',true);
                    $query_seasons = DDbmoviesHelpers::GetAllSeasons($tmdb);
                    if($query_seasons && is_array($query_seasons) && $ctrl == true){
                        $numb = 0;
                        foreach($query_seasons as $season){
                            $senumb = get_post_meta($season,'temporada', true);
                            ?>

<div class="item" data-season-id="<?php echo $senumb; ?>" id="sezonul-<?php echo $senumb; ?>"><?php echo $senumb; ?>

                            <?php
                            $numb++;
                        }
                    }
                    ?>

            <?php

            // Main data
            $tmdb = get_post_meta($post->ID,'ids',true);
            $ctrl = get_post_meta($post->ID,'clgnrt',true);
            /*=====================================================*/
            $query_seasons = DDbmoviesHelpers::GetAllSeasons($tmdb);
            /*=====================================================*/
            // Start Query
            if($query_seasons && is_array($query_seasons) && $ctrl == true){
                $numb = 0;
                foreach($query_seasons as $k => $season){
                    $senumb = get_post_meta($season,'temporada', true);
                    $aidate = get_post_meta($season,'air_date', true);
                    $rating = get_post_meta($season,'_starstruck_avg', true);
                    /*=====================================================*/
                    $query_episodes = DDbmoviesHelpers::GetAllEpisodes($tmdb,$senumb);
                    /*=====================================================*/
                    $mnseo = $numb == 0 ? ' se-o' : false;
                    $dsply = $numb == 0 ? ' style="display:block"' : false;
                    $title = $senumb == '0' ? __d('Specials') : sprintf( __d('Season %s %s'), $senumb, ''.doo_date_compose($aidate, false).'');
                    $nseas = $senumb == '0' ? '' : $senumb;
                    // Continue View HTML
                    if($query_episodes && is_array($query_episodes)){
                        ?>

            <div class='list bslider' data-bslider-margin='20' data-bslider-left-margin='0' data-bslider-right-margin='20' data-bslider-item-class='item' data-bslider-nav='false' id='episodesList-<?php echo $senumb; ?>' data-single-width='220' data-max-width='761' data-stage-width='2000'>

                        <?php
                        foreach($query_episodes as $episode){
                            // Post Data
                            $image = dbmovies_get_poster($episode,'dt_episode_a','dt_backdrop','w154');
                            $name  = get_post_meta($episode,'episode_name', true);
                            $episo = get_post_meta($episode,'episodio', true);
                            $edate = get_post_meta($episode,'air_date', true);
                            $edate = doo_date_compose($edate, false);
                            $plink = get_permalink($episode);

                            $title = !empty($name) ? $name : __('Episode').' '.$episo;
                            ?>

            <div class='item slider-item' slide-number='<?php echo $episo; ?>' data-episode-id='<?php echo $episo; ?>'>

            <div class='img' style='background-image:url(<?php echo $image ?>);'>

<?php echo $episo; ?>. <?php echo $title; ?>

                            <?php
                        }
                        ?>

                        <?php
                    } else{
                        ?>

<?php echo __d('There are still no episodes this season') ?>

                        <?php
                    }
                    $numb++;
                }
            }
            ?>

I want when I click on a Season to trigger the list of episodes below.

I don't have any js for this, my script show all seasons and episodes perfectly but is all displayed.


问:
Access to anonymous sharepoint link programmatically (by API)
I have only link to sharepoint shared folder https://xxxxx.sharepoint.com/:f:/g/Djzdv2-qFLlFsFSFsfdSFSfsfSfSFsfsdfsfsd-ASDASAS?e=5%3aYfSFrK&at=9 with anonymous access (no login, no password).

I can open the link in a web browser and manually browse the directory structure, download files, create folders and upload new files in web interface.

I need to access this programmatically. Is there .NET library that would allow this?

I've tried to find a solution, but it always requires login credentials, which I don't have and can't have. I only need access through the given link.


问:
Automatic application insights dependency collection for @azure/arm- SDKs
I'm struggling to enable automatic log collection for @azure/arm SDKs. Currently, I'm using @azure/arm-keyvault, @azure/arm-network and @azure/arm-resources. Is there some extra configuration needed? I thought HTTP logs are collected automatically.

@microsoft/microsoft-graph-client, @azure/cosmos and lots of other dependency logs are collected flawlessly. I use node 18LTS and tested 16LTS. applicationinsights  package version is 2.3.6

```<code>appInsights
  .setup(configService.get("APPLICATIONINSIGHTS_CONNECTION_STRING"))
  .setDistributedTracingMode(DistributedTracingModes.AI_AND_W3C)
  .setAutoCollectConsole(false, false)
  .setAutoCollectExceptions(true)
  .setAutoCollectPerformance(true, true)
  .setAutoCollectPreAggregatedMetrics(true)
  .setAutoCollectHeartbeat(true)
  .setAutoCollectRequests(true)
  .setAutoCollectDependencies(true)
  .setAutoDependencyCorrelation(true)
  .setUseDiskRetryCaching(true)
  .setInternalLogging(false, true)
  .setSendLiveMetrics(true)
  .start();
</code>```

In this screenshot one can see the missing dependency logs. The health requests takes 3 second and there are no correlated logs for the last 2 seconds, when arm SDKs are making requests. The logs are missing in the transactions list as well.

Originally posted on AI repo: https://github.com/microsoft/ApplicationInsights-node.js/issues/1055

Body:
I'm struggling to enable automatic log collection for @azure/arm SDKs. Currently, I'm using @azure/arm-keyvault, @azure/arm-network and @azure/arm-resources. Is there some extra configuration needed? I thought HTTP logs are collected automatically.

@microsoft/microsoft-graph-client, @azure/cosmos and lots of other dependency logs are collected flawlessly. I use node 18LTS and tested 16LTS. applicationinsights  package version is 2.3.6

appInsights
  .setup(configService.get("APPLICATIONINSIGHTS_CONNECTION_STRING"))
  .setDistributedTracingMode(DistributedTracingModes.AI_AND_W3C)
  .setAutoCollectConsole(false, false)
  .setAutoCollectExceptions(true)
  .setAutoCollectPerformance(true, true)
  .setAutoCollectPreAggregatedMetrics(true)
  .setAutoCollectHeartbeat(true)
  .setAutoCollectRequests(true)
  .setAutoCollectDependencies(true)
  .setAutoDependencyCorrelation(true)
  .setUseDiskRetryCaching(true)
  .setInternalLogging(false, true)
  .setSendLiveMetrics(true)
  .start();

In this screenshot one can see the missing dependency logs. The health requests takes 3 second and there are no correlated logs for the last 2 seconds, when arm SDKs are making requests. The logs are missing in the transactions list as well.

Originally posted on AI repo: https://github.com/microsoft/ApplicationInsights-node.js/issues/1055


问:
RuntimeError: cuDNN error: CUDNN_STATUS_MAPPING_ERROR

Why is there no way to calculate the loss value? (About CrossEntropyLoss)

My code is a binary classification problem. I try to calculate the loss value in the final test stage, and finally use the loss value to draw a histogram.
However, there will always be errors in the part of calculating the loss value, and there are several times when the data format is different.
Please help, thank you

```<code># when batch size (BATCH) is 1
def eval_model_one(model, test_dataloader, order=None):
    # eval_model_one(model, test, [locate])

    test_dataloader = DataLoader(test_dataloader, shuffle=False, batch_size=1)

    # load well-trained model
    net = model().cuda()

    # evaluation mode
    net.eval()

    with torch.no_grad():
        test_loss = 0
        test_acc = 0
        correct = 0
        total = 0

        for i, data in enumerate(test_dataloader, 0):
            img0, label1 = data
            # print(f'label1: ', label1)

            # change the order of 12 leads
            # pick specific number of lead
            if order is not None:
                img0 = img0[:, order, :]

                # print(f'img0: ', img0)
                # print(f'img0.shape: ', img0[0][0].shape)
                # print(f'orde: ', order)

            img0, label1 = Variable(img0.cuda()), Variable(label1.cuda().type(torch.cuda.LongTensor))
            img0 = img0.unsqueeze(dim = 1).type(torch.cuda.FloatTensor)

            # 計算前向傳播，並且得到損失函數的值
            output1 = net(img0)
            loss = nn.CrossEntropyLoss()
            loss1 = loss(output1, label1)

            # 記錄誤差
            test_loss += loss1.item()
            print(f'test_loss: ', test_loss)

            # 計算分類的準確率
            prediction1 = output1.data.max(1)[1]
            accuracy1 = prediction1.eq(label1.data).cpu().sum().numpy()/img0.size(0)*100
            # print(f'accuracy1: ', accuracy1)
            test_acc += accuracy1
            # print(f'test_acc: ', test_acc)

            # test_losses.append(test_loss / len(test_dataloader))
            # test_acces.append(test_acc / len(test_dataloader))

    return (test_loss/len(test_dataloader))

############################################################################################
# plot activation map
# data_all : a list contains tuples including 12 leads, (lead data, age, agegp, gender)
# lead_name : the order of the lead
# locate : the index of lead you used to training the model  ECG 的第幾個 lead
# model : the model
# model_name : the model name
# row_num : the number of the observation  你要用第幾筆資料下去畫
# cut : the number of time steps you want to remove respectivly  您要分別移除的 the number of time steps
# demographic: the paramter of eval_model() from training.py
# multi: the paramter of eval_model() from training.py

def plot_am(data_all, lead_name, locate, model, model_name, row_num, cut, demographic=None, multi=None):

    # data = data_all[row_num]
    # data = data[0]
    # data = np.array(data)
    # data = np.reshape(data, (5000, 12))
    # img = pd.DataFrame(data)
    # img.columns = lead_name

    data = data_all[row_num]
    data = data[0]
    img = pd.DataFrame(data).T
    img.columns = lead_name

    # plot the single lead data
    dpi_value = 300
    plt.figure(figsize=(25, 3))
    signal = img[lead_name[locate]]
    plt.plot(signal, color='black', linewidth=3)
    plt.xlim((0, 5000))
    plt.ylim((-20, 20))
    plt.style.use('seaborn-white')

    # eliminate the margin
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())

    plt.savefig("/home/server_605_3090/huanci/ECG_NSAID/plot/one_lead_{}_data_{}.png".format(lead_name[locate], row_num), dpi=dpi_value, bbox_inches="tight")
    plt.close()

    # plot activation map
    data = torch.from_numpy(data[0, :])
    data = data.unsqueeze(dim=0).unsqueeze(dim=0).unsqueeze(dim=0)
    data = Variable(data.cuda())
    data = data.type(torch.cuda.FloatTensor)

    # load model and weight
    net = model().cuda()

    size = (2500, 300)
    layer = []
    for a in ['conv1', "layer1", "layer2", "layer3", "layer4"]:
        target = a
        # grad cam is here!!!!
        grad_cam = GradCam(model=net, target_layer_name=target, use_cuda=True)
        mask, pred = grad_cam(data, size)
        heatmap = cv2.applyColorMap(np.uint8(255*mask), cv2.COLORMAP_JET)
        heatmap = np.float32(heatmap)/255

        # read the single lead just plotted previously #變成multi-lead了
        # 1 specifies to load a color image
        img = cv2.imread("/home/server_605_3090/huanci/ECG_NSAID/plot/one_lead_{}_data_{}.png".format(lead_name[locate], row_num), 1)
        # resize the figure of single lead data
        img = np.float32(cv2.resize(img, size))/255
        # merge the figure with the heatmape produced by grad cam  將圖形與 grad cam 生成的 heatmape 合併
        img = cv2.addWeighted(img, 0.6, heatmap, 0.4, 0)
        layer.append(img)

    # plot the importance for each time section
    loss_list = []
    s = cut

    for z in range(int(5000/s)):  # ecah sample
        test = copy.deepcopy(data_all[row_num])
        test[0][:, (z*s):((z+1)*s)] = 0
        test = [test]
        # def eval_model_one(model, test_dataloader, order=None):
        test_loss = eval_model_one(model, test, [locate])
        loss_list = loss_list + [test_loss]*s

    lead_important = pd.DataFrame(np.array([loss_list]).T, columns=['test_loss'])
    # print(lead_important)

    y_name = 'test_loss'
    lead_list = list(range(1, 5001, 1))
    score_list = lead_important.loc[:, y_name]

    # re scale the importance
    score_list = score_list - np.min(score_list)
    scale = preprocessing.MinMaxScaler(feature_range=(0, 1))
    score_list = scale.fit_transform(np.array(score_list).reshape(-1, 1))  # Data

    plt.figure(figsize=(25, 3))
    plt.bar(lead_list, score_list.squeeze(), width=1, label='lead_list')
    plt.xlim((0, 5000))
    plt.ylim((0, 1))
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.savefig('/home/server_605_3090/huanci/ECG_NSAID/plot/lead{}_data{}_step{}.png'.format(lead_name[locate], row_num, s), dpi=dpi_value, bbox_inches="tight")
    plt.close()

    # read the single lead just plotted previously
    # 1 specifies to load a color image
    img = cv2.imread("/home/server_605_3090/huanci/ECG_NSAID/plot/one_lead_{}_data_{}.png".format(lead_name[locate], row_num), 1)
    # read the bar chart of time step importance just plotted
    # 1 specifies to load a color image
    heatmap = cv2.imread('/home/server_605_3090/huanci/ECG_NSAID/plot/lead{}_data{}_step{}.png'.format(lead_name[locate], row_num, s), 1)
    # resize the plots
    img = np.float32(cv2.resize(img, size))/255
    heatmap = np.float32(cv2.resize(heatmap, size))/255
    img = cv2.addWeighted(img, 0.6, heatmap, 0.4, 0)
    # the heatmaps of each layer
    img = np.concatenate((layer[0], layer[1], layer[2], layer[3], layer[4], img), axis=0)
    cv2.imwrite("/home/server_605_3090/huanci/ECG_NSAID/plot/{}_lead_{}_data_{}_gradcam.png".format("SCNet_testing", lead_name[locate], row_num), np.uint8(255*img))

# def plot_am(data_all, lead_name, locate, model, model_name, row_num, cut=None, demographic=None, multi=None):
plot_am(data_all=lead, lead_name=lead_name, locate=0, model=model, model_name=model_name, row_num=0, cut=20)

</code>```

About the code pasted above
Successfully calculated the loss value (about CrossEntropyLoss)

Body:
Why is there no way to calculate the loss value? (About CrossEntropyLoss)

My code is a binary classification problem. I try to calculate the loss value in the final test stage, and finally use the loss value to draw a histogram.
However, there will always be errors in the part of calculating the loss value, and there are several times when the data format is different.
Please help, thank you

# when batch size (BATCH) is 1
def eval_model_one(model, test_dataloader, order=None):
    # eval_model_one(model, test, [locate])

    test_dataloader = DataLoader(test_dataloader, shuffle=False, batch_size=1)

    # load well-trained model
    net = model().cuda()

    # evaluation mode
    net.eval()

    with torch.no_grad():
        test_loss = 0
        test_acc = 0
        correct = 0
        total = 0

        for i, data in enumerate(test_dataloader, 0):
            img0, label1 = data
            # print(f'label1: ', label1)

            # change the order of 12 leads
            # pick specific number of lead
            if order is not None:
                img0 = img0[:, order, :]

                # print(f'img0: ', img0)
                # print(f'img0.shape: ', img0[0][0].shape)
                # print(f'orde: ', order)

            img0, label1 = Variable(img0.cuda()), Variable(label1.cuda().type(torch.cuda.LongTensor))
            img0 = img0.unsqueeze(dim = 1).type(torch.cuda.FloatTensor)

            # 計算前向傳播，並且得到損失函數的值
            output1 = net(img0)
            loss = nn.CrossEntropyLoss()
            loss1 = loss(output1, label1)

            # 記錄誤差
            test_loss += loss1.item()
            print(f'test_loss: ', test_loss)

            # 計算分類的準確率
            prediction1 = output1.data.max(1)[1]
            accuracy1 = prediction1.eq(label1.data).cpu().sum().numpy()/img0.size(0)*100
            # print(f'accuracy1: ', accuracy1)
            test_acc += accuracy1
            # print(f'test_acc: ', test_acc)

            # test_losses.append(test_loss / len(test_dataloader))
            # test_acces.append(test_acc / len(test_dataloader))

    return (test_loss/len(test_dataloader))

############################################################################################
# plot activation map
# data_all : a list contains tuples including 12 leads, (lead data, age, agegp, gender)
# lead_name : the order of the lead
# locate : the index of lead you used to training the model  ECG 的第幾個 lead
# model : the model
# model_name : the model name
# row_num : the number of the observation  你要用第幾筆資料下去畫
# cut : the number of time steps you want to remove respectivly  您要分別移除的 the number of time steps
# demographic: the paramter of eval_model() from training.py
# multi: the paramter of eval_model() from training.py

def plot_am(data_all, lead_name, locate, model, model_name, row_num, cut, demographic=None, multi=None):

    # data = data_all[row_num]
    # data = data[0]
    # data = np.array(data)
    # data = np.reshape(data, (5000, 12))
    # img = pd.DataFrame(data)
    # img.columns = lead_name

    data = data_all[row_num]
    data = data[0]
    img = pd.DataFrame(data).T
    img.columns = lead_name

    # plot the single lead data
    dpi_value = 300
    plt.figure(figsize=(25, 3))
    signal = img[lead_name[locate]]
    plt.plot(signal, color='black', linewidth=3)
    plt.xlim((0, 5000))
    plt.ylim((-20, 20))
    plt.style.use('seaborn-white')

    # eliminate the margin
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())

    plt.savefig("/home/server_605_3090/huanci/ECG_NSAID/plot/one_lead_{}_data_{}.png".format(lead_name[locate], row_num), dpi=dpi_value, bbox_inches="tight")
    plt.close()

    # plot activation map
    data = torch.from_numpy(data[0, :])
    data = data.unsqueeze(dim=0).unsqueeze(dim=0).unsqueeze(dim=0)
    data = Variable(data.cuda())
    data = data.type(torch.cuda.FloatTensor)

    # load model and weight
    net = model().cuda()

    size = (2500, 300)
    layer = []
    for a in ['conv1', "layer1", "layer2", "layer3", "layer4"]:
        target = a
        # grad cam is here!!!!
        grad_cam = GradCam(model=net, target_layer_name=target, use_cuda=True)
        mask, pred = grad_cam(data, size)
        heatmap = cv2.applyColorMap(np.uint8(255*mask), cv2.COLORMAP_JET)
        heatmap = np.float32(heatmap)/255

        # read the single lead just plotted previously #變成multi-lead了
        # 1 specifies to load a color image
        img = cv2.imread("/home/server_605_3090/huanci/ECG_NSAID/plot/one_lead_{}_data_{}.png".format(lead_name[locate], row_num), 1)
        # resize the figure of single lead data
        img = np.float32(cv2.resize(img, size))/255
        # merge the figure with the heatmape produced by grad cam  將圖形與 grad cam 生成的 heatmape 合併
        img = cv2.addWeighted(img, 0.6, heatmap, 0.4, 0)
        layer.append(img)

    # plot the importance for each time section
    loss_list = []
    s = cut

    for z in range(int(5000/s)):  # ecah sample
        test = copy.deepcopy(data_all[row_num])
        test[0][:, (z*s):((z+1)*s)] = 0
        test = [test]
        # def eval_model_one(model, test_dataloader, order=None):
        test_loss = eval_model_one(model, test, [locate])
        loss_list = loss_list + [test_loss]*s

    lead_important = pd.DataFrame(np.array([loss_list]).T, columns=['test_loss'])
    # print(lead_important)

    y_name = 'test_loss'
    lead_list = list(range(1, 5001, 1))
    score_list = lead_important.loc[:, y_name]

    # re scale the importance
    score_list = score_list - np.min(score_list)
    scale = preprocessing.MinMaxScaler(feature_range=(0, 1))
    score_list = scale.fit_transform(np.array(score_list).reshape(-1, 1))  # Data

    plt.figure(figsize=(25, 3))
    plt.bar(lead_list, score_list.squeeze(), width=1, label='lead_list')
    plt.xlim((0, 5000))
    plt.ylim((0, 1))
    plt.gca().set_axis_off()
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.savefig('/home/server_605_3090/huanci/ECG_NSAID/plot/lead{}_data{}_step{}.png'.format(lead_name[locate], row_num, s), dpi=dpi_value, bbox_inches="tight")
    plt.close()

    # read the single lead just plotted previously
    # 1 specifies to load a color image
    img = cv2.imread("/home/server_605_3090/huanci/ECG_NSAID/plot/one_lead_{}_data_{}.png".format(lead_name[locate], row_num), 1)
    # read the bar chart of time step importance just plotted
    # 1 specifies to load a color image
    heatmap = cv2.imread('/home/server_605_3090/huanci/ECG_NSAID/plot/lead{}_data{}_step{}.png'.format(lead_name[locate], row_num, s), 1)
    # resize the plots
    img = np.float32(cv2.resize(img, size))/255
    heatmap = np.float32(cv2.resize(heatmap, size))/255
    img = cv2.addWeighted(img, 0.6, heatmap, 0.4, 0)
    # the heatmaps of each layer
    img = np.concatenate((layer[0], layer[1], layer[2], layer[3], layer[4], img), axis=0)
    cv2.imwrite("/home/server_605_3090/huanci/ECG_NSAID/plot/{}_lead_{}_data_{}_gradcam.png".format("SCNet_testing", lead_name[locate], row_num), np.uint8(255*img))

# def plot_am(data_all, lead_name, locate, model, model_name, row_num, cut=None, demographic=None, multi=None):
plot_am(data_all=lead, lead_name=lead_name, locate=0, model=model, model_name=model_name, row_num=0, cut=20)

About the code pasted above
Successfully calculated the loss value (about CrossEntropyLoss)


问:
how to configure Flink in AWS EC2 CLI to access the dashboard locally?
I have installed flink in my AWS EC2 ubuntu machine CLI. However, I am unable to connect to the dashboard locally.

All the required ports in security group are opened. What are the edits that I have to do it config files to access the dashboard locally ? I tried searching answers in various ways but still in vain. Please help. Thanks.


问:
iPad SplitView cannot resize its PrimaryView width correctly
Hi guys I encountered a weird problem with the horizontal size of the PrimaryView of SplitView. It seems that SplitView cannot auto resize its PrimaryView width properly during view initialization, and thus the TableView relies on it also has a wrong width.

Here is the screenshot of the simulator (iOS 14 - 16 all have this problem) and you could see the TableCell has a left part that is outside of the screen:

This is my MasterViewController:

import UIKit

class MasterViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.delegate = self
        tableView.dataSource = self
        setUpTableViewContraints()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        // Content configuration.
        var content = cell.defaultContentConfiguration()
        content.text = "Cell Item \(indexPath.row)"
        cell.contentConfiguration = content

        // Style and layout configuration.
        cell.layer.cornerRadius = 12
        cell.clipsToBounds = true

        return cell
    }

    private func setUpTableViewContraints() {
        let constraints = [
            tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor),
            tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor),
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ]
        NSLayoutConstraint.activate(constraints)
    }
}

```
<p>This is my <code>DetailViewController</code> (nothing inside):</p>
<pre class="lang-swift prettyprint-override"><code>import UIKit

class DetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

</code>```

I have tried modifying almost all the properties inside storyboard, setting up LayoutAnchors or frame during runtime, but nothing can solve the problem. The TableCell is always having incorrect width like the screenshot above.

I am expecting the PrimaryView of the SplitView has a correct width. I haven't seen anyone posting something similar in the forum so I am guessing I might have made a very funny mistake. But I just could not figure out where it is...

Body:
Hi guys I encountered a weird problem with the horizontal size of the PrimaryView of SplitView. It seems that SplitView cannot auto resize its PrimaryView width properly during view initialization, and thus the TableView relies on it also has a wrong width.

Here is the screenshot of the simulator (iOS 14 - 16 all have this problem) and you could see the TableCell has a left part that is outside of the screen:

This is my MasterViewController:

import UIKit

class MasterViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.delegate = self
        tableView.dataSource = self
        setUpTableViewContraints()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        // Content configuration.
        var content = cell.defaultContentConfiguration()
        content.text = "Cell Item \(indexPath.row)"
        cell.contentConfiguration = content

        // Style and layout configuration.
        cell.layer.cornerRadius = 12
        cell.clipsToBounds = true

        return cell
    }

    private func setUpTableViewContraints() {
        let constraints = [
            tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor),
            tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor),
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ]
        NSLayoutConstraint.activate(constraints)
    }
}

This is my DetailViewController (nothing inside):

import UIKit

class DetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

I have tried modifying almost all the properties inside storyboard, setting up LayoutAnchors or frame during runtime, but nothing can solve the problem. The TableCell is always having incorrect width like the screenshot above.

I am expecting the PrimaryView of the SplitView has a correct width. I haven't seen anyone posting something similar in the forum so I am guessing I might have made a very funny mistake. But I just could not figure out where it is...


问:
Patch imagemin library with patch-package
I want to apply a patch for the imagemin (https://www.npmjs.com/package/imagemin) library using patch-package (https://www.npmjs.com/package/patch-package). The patch includes also patches in some sub-libraries gifsicle, jpegtran-bin and optipng-bin. When I run yarn install, the installation of the gifsicle library still fails, as the installation compiles some C code (./configure, make). The problem seems to be that the patch is installed "postinstall", so at the time the gifsicle library is compiled, the patch is not applied.
Does anyone know how to patch libraries which compile c code in submodules during install?


问:
Family Tree Visualization
So my father came to me and asked me to create a program that displays my family tree. The names are preset but he wants a visualisation like the following: The root node would be the first ancestor and if you click on that name, the program should then dropdown the next generation originating from that node. He wants this done for each member of the tree to make it interactive. Now obviously computer scientists aren't well versed in such things but I was hoping if anyone could direct me to tools/ builders/ languages I could use to create such an animation no matter how many generations I enter in the tree.

Any tips would be much appreciated. I have never personally dabbled with such kind of animation and visualisations. Thank you!

I tried using services like Creately and LucidChart but they all provided static visualisations. I wasn't able to get each node to produce an animation. I tried to use Netbeans as I know you can create windows with animated buttons but this didn't quite fuflil my father's wish of an aesthetic tree where the arrows drop down nicely and one can simply scroll through it.

Title: Family Tree Visualization


问:
Invalid identifier in sql create table query
I understand from online articles that this issue is related to case-sensitivity with oracle sql. However, I cannot see the error in my query: For example:

```<code>ENGINE =  create_engine('credentials', pool_pre_ping = True)
connection = ENGINE.raw_connection()
cursor = connection.cursor()

cursor.execute("CREATE TABLE US (NAME VARCHAR2(255), ACTION_NAME VARCHAR2(255), CONNECTORNAME VARCHAR2(255), TRIGGER VARCHAR2(255), UPDATEDBY DATE, IDSET VARCHAR2(255), CONNECTORID VARCHAR2(255))")
</code>```

Will give the error:

cx_Oracle.DatabaseError: ORA-00904: : invalid identifier

Body:
I understand from online articles that this issue is related to case-sensitivity with oracle sql. However, I cannot see the error in my query: For example:

ENGINE =  create_engine('credentials', pool_pre_ping = True)
connection = ENGINE.raw_connection()
cursor = connection.cursor()

cursor.execute("CREATE TABLE US (NAME VARCHAR2(255), ACTION_NAME VARCHAR2(255), CONNECTORNAME VARCHAR2(255), TRIGGER VARCHAR2(255), UPDATEDBY DATE, IDSET VARCHAR2(255), CONNECTORID VARCHAR2(255))")

Will give the error:

cx_Oracle.DatabaseError: ORA-00904: : invalid identifier


问:
Tungstenite read_message stuck on receiving messages
I connect to a websocket using the tungstenite crate and it all works fine for a couple of hours. After that the websocket stop sending messages or something and the program gets stuck on read_message waiting for a message to arrive. Does anyone know what is happening or why it is?

I have tried changing the features of tungstenite from rust-tls and native-tls but both seem to produce the same problem after some time.

loop {
            println!("before read_message");
            let Ok(msg) = socket.read_message() else {println!("Could not read message"); break};
            println!("after read_message");
            let now = Local::now().timestamp_nanos();
}
```

I added the print statements to verify that the read_message is the problem of the program and it indeed keeps the program running, and does not get to the after read_message part.

Body:
I connect to a websocket using the tungstenite crate and it all works fine for a couple of hours. After that the websocket stop sending messages or something and the program gets stuck on read_message waiting for a message to arrive. Does anyone know what is happening or why it is?

I have tried changing the features of tungstenite from rust-tls and native-tls but both seem to produce the same problem after some time.

loop {
            println!("before read_message");
            let Ok(msg) = socket.read_message() else {println!("Could not read message"); break};
            println!("after read_message");
            let now = Local::now().timestamp_nanos();
}

I added the print statements to verify that the read_message is the problem of the program and it indeed keeps the program running, and does not get to the after read_message part.