问:
why can't draw_bbox library run?
This code does not open the webcam i guess because of the draw_bbox, but i wanna know why?, and also i'm using MAC OS

```<code>import cvlib as cv
from cvlib.object_detection import draw_bbox
import cv2
import pyttsx3
engine = pyttsx3.init()
def speak(audio):
    engine.say (audio)
    engine.runAndWait()
webcam = cv2.VideoCapture(0)
if not webcam.isOpened():
    speak("Could not open webcam")
    exit()
while webcam.isOpened():
    status, frame = webcam.read()
    if not status:
        speak("Could not read frame")
        exit()
    bbox, label, conf = cv.detect_common_objects(frame)
    print(bbox, label, conf)
    out = draw_bbox(frame, bbox, label, conf)
    cv2.imshow("Real-time object detection", out)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
webcam.release()
cv2.destroyAllWindows()
</code>```

i want to detect object from the webcam

Title: why can't draw_bbox library run?

Body:
This code does not open the webcam i guess because of the draw_bbox, but i wanna know why?, and also i'm using MAC OS

import cvlib as cv
from cvlib.object_detection import draw_bbox
import cv2
import pyttsx3
engine = pyttsx3.init()
def speak(audio):
    engine.say (audio)
    engine.runAndWait()
webcam = cv2.VideoCapture(0)
if not webcam.isOpened():
    speak("Could not open webcam")
    exit()
while webcam.isOpened():
    status, frame = webcam.read()
    if not status:
        speak("Could not read frame")
        exit()
    bbox, label, conf = cv.detect_common_objects(frame)
    print(bbox, label, conf)
    out = draw_bbox(frame, bbox, label, conf)
    cv2.imshow("Real-time object detection", out)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
webcam.release()
cv2.destroyAllWindows()

i want to detect object from the webcam


来源: stackexchange

问:
I am trying to display data trough Array but is shows error : Attempt to read property " " on string here are my approaches in Codeigniter
here is all MVC code below error to fetch data

controller

```<code>public function bid_data()
       {
            $user   = $this->session->userdata('user');
            $id     = $user['id'];
            $this->load->model('GetModel');
            $data['admin'] = $this->GetModel->auction_data($id);

            if(!empty($data['admin'])){
           $this->load->view('user/bidData',$data);
            }else{
               $this->session->set_flashdata('no_record','<b>Sorry</b> No record found !!');
              redirect(base_url().'user/UserSubmit');
            }
         }
</code>```

im expecting to print data trough row in Array in my views but show error

view

```<code> <?php  foreach($admin as $row): ?>
          <tr style="text-align:center">
         <td class="list"><?php echo $row->sno; ?></td>
         <td class="list"><a href="<?php echo base_url().'user/bid_result/remove/'.$id ;?>">remove</a></td>
         <td class="list"><a href="">win</a></td>
             </tr>
            <?php endforeach; ?>
</code>```

model

```<code>public function auction_data($id)
        {
              $query = $this->db->get_where('user_bid',['id'=> $id]);
              return $query->row();

        }

</code>```

ContentLicense: CC BY-SA 4.0

Body:
here is all MVC code below error to fetch data

controller

public function bid_data()
       {
            $user   = $this->session->userdata('user');
            $id     = $user['id'];
            $this->load->model('GetModel');
            $data['admin'] = $this->GetModel->auction_data($id);

            if(!empty($data['admin'])){
           $this->load->view('user/bidData',$data);
            }else{
               $this->session->set_flashdata('no_record','Sorry No record found !!');
              redirect(base_url().'user/UserSubmit');
            }
         }

im expecting to print data trough row in Array in my views but show error

view

 <?php  foreach($admin as $row): ?>

         <?php echo $row->sno; ?>
         <a href="<?php echo base_url().'user/bid_result/remove/'.$id ;?>">remove
         win

            <?php endforeach; ?>

model

public function auction_data($id)
        {
              $query = $this->db->get_where('user_bid',['id'=> $id]);
              return $query->row();

        }


问:
How to manage multiple rsocket clients in SpringBoot
I need some some help creating a mechanism where I can send requests to multiple clients from Spring server and fetch response. I went through few examples and rsocket reference documentation, but I couldn't understand how to work with multiple clients. I think, I need to create and store RSocketRequester for each client(in a Map). I may be wrong. Kindly help.</p>


问:
MongoDB: How to sort providing 2 filters?
I am trying to make a program in which i can get a leaderboard of people with highest levels(descending order) and i am getting it. But the case is that they are not arranged by another factor which is xp( every 100 xp == +1 level)

I tried searching for solutions but sadly couldn't find it, maybe if i could get a head-up through? Any tips would be appreciated!


问:
How to implement maximum mean discrepancy in CNN architecture for domain adaptation?
I want to know with code,  How to implement maximum mean discrepancy in CNN architecture for domain adaptation?

I would like to implement domain adaptation for 1D CNN audio files as shown in the link
https://machinelearningmastery.com/cnn-models-for-human-activity-recognition-time-series-classification/.

The above link shows only 1D CNN but I need to implement and practice the domain adaptation using only MMD, not through adversarial methods. I could see a lot of examples for every method other than MMD for CNN.


问:
Weird react-js bug, JSON Images not showing if window width exceeds 580px
This is the weird bug I am facing with my nextjs code:

When the browser window size exceeds 580px, some of the images (images on the top) stop showing, if I resize the browser window to less than 580px, all the images show correctly.

Here is the link to the code sandbox:
https://codesandbox.io/s/cocky-borg-dgexfx?file=/data/data.json

This is the link for testing the bug with the browser:
https://dgexfx.sse.codesandbox.io/


问:
CKEditor dataProcessor filter changed entities
I have CKEditor plugin with this code:

```<code>editor.dataProcessor.dataFilter.addRules( {
                elements: {
                    li: function( el ) {
                        if ( !el.children[0].name || (el.children[0].name && el.children[0].name !== 'i') ) {
                            el.children[0].value = '<i class="li-icon"></i><span>'+el.children[0].value+'</span>';
                        }
                    }
                }
            });

            editor.dataProcessor.htmlFilter.addRules( {
                elements: {
                    li: function( el ) {
                        if ( !el.children[0].name || (el.children[0].name && el.children[0].name !== 'i') ) {
                            el.children[0].value = '<i class="li-icon"></i><span>'+el.children[0].value+'</span>';
                        }
                    }
                }
            });
</code>```

When I see source code in browser i see no changes like this:

```<code><ul>
    <li>A</li>
    <li>B</li>
</ul>
</code>```

When I swith in CKEditor into source code view I see this:

```<code><ul>
    <li><i class="li-icon"></i><span>A</span></li>
    <li><i class="li-icon"></i><span>B</span></li>
</ul>
</code>```

I expect no changed entities like this:

```<code><ul>
    <li><i class="li-icon"></i><span>A</span></li>
    <li><i class="li-icon"></i><span>B</span></li>
</ul>
</code>```

And what do change to see changes immediately?

Body:
I have CKEditor plugin with this code:

editor.dataProcessor.dataFilter.addRules( {
                elements: {
                    li: function( el ) {
                        if ( !el.children[0].name || (el.children[0].name && el.children[0].name !== 'i') ) {
                            el.children[0].value = ''+el.children[0].value+'';
                        }
                    }
                }
            });

            editor.dataProcessor.htmlFilter.addRules( {
                elements: {
                    li: function( el ) {
                        if ( !el.children[0].name || (el.children[0].name && el.children[0].name !== 'i') ) {
                            el.children[0].value = ''+el.children[0].value+'';
                        }
                    }
                }
            });

When I see source code in browser i see no changes like this:

A

B

When I swith in CKEditor into source code view I see this:

A

B

I expect no changed entities like this:

A

B

And what do change to see changes immediately?


问:
use gujarati fonts shruti with tcpdf
I want to use gujarati fonts in pdf. I used TCPDF V6.4.4. I am using google indic for input gujarati text. My php version is 8.0. I put shruti fonts into fonts folder. I wrote these code.

```<code>require_once('TCPDF/tcpdf.php');
$patient1 = "ચિરાગ";
    $patient2 = "પરમાર";
    $patient3 = "મારું";
    $patient4 = "નામ";
    $patient5 = "કલીનીક";

    $doctorname="doctorname";
    $filename="filename1.pdf";
    $billreport = "Billreport";
    $pdf_clinicname="pdf clicnicname"; $pdf_address="pdf address";

    $html = '';
    $pdfheader='';
    $html .= '<style>
              body {
        font-size: 13px;
        color: #000;
        overflow-x: hidden;
        font: inherit;
        }
        .pdfprint{width: 100%; clear: both; float: left; margin: 10px; padding: 10px; color: #000; border: 1px solid #121010; }
        .pdfheader{}
        .leftheader{}
        .red{color: red;}
        .clinicname{font-size: 24px; font-weight: 800;}
        .doctorname{font-size: 20px; font-weight: 800;}
        .doctordegree{font-weight: 600; color: #000; font-size: 12px;}
        .dtagline{}
        .hrtag{clear:both; width: 100%; border: 1px solid #d9d6d6; height: 1px;}
        .namebox{float: left; background-color: #eee;border: 1px solid #e5e6e7;border-radius: 1px; color: inherit; display: block; padding: 6px 6px; margin-right: 10px;}
        .pipesymbol{padding-left: 15px; padding-right: 15px;}
        .rx{font-size: x-large;width: 49%; float: left;}
        .rx2{font-size: x-large; }
        .doclasssection{padding-left: 15px;}
        .patientsection{width: 100%;clear: both; float: left; padding-top: 5px; padding-bottom: 10px;}
        .prescription{width: 49%; float: left;}
        .doclasssection{width: 49%; float: left;}
        .comeafter{width: 100%; float: left; clear: both;}
        .medicinetimetable{float: left; padding-left:50px;}
        </style>';
        $html .= '<body>
                <div id="wrapper">
                    <div id="page-wrapper" class="gray-bg1 dashbard-1">
                        <div id="pdfprint" class="pdfprint chirag1">';

                        $html.='<div class="patientsection" >
                    <div class="patientname">
                        <span class="namebox">'.utf8_encode($patient1).'</span>
                        <span class="namebox">Age : '.utf8_encode($patient2).'</span> <span class="namebox">'.utf8_encode($patient2).'</span>
                        <span class="namebox">ID : '.utf8_encode($patient3).'</span>
                        <span class="namebox">Case No : '.utf8_encode($patient4).'</span>
                        <span class="namebox">Date : '.utf8_encode($patient5).'</span>
                    </div>
                </div> <div class="hrtag"></div>';
         $html.='</div> </div>
        </div>'; // end wrapper id
        $html.='</body>';

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // convert TTF font to TCPDF format and store it on the fonts folder
        $fontname = TCPDF_FONTS::addTTFfont('/TCPDF/fonts/shruti.ttf', 'TrueTypeUnicode', '', 96);

        // use the font
        $pdf->SetFont($fontname, '', 14, '', false);

         // set document information
    $pdf->SetCreator(PDF_CREATOR);
    //$pdf->SetAuthor('Nicola Asuni');
    $pdf->SetAuthor($doctorname);
    //$pdf->SetTitle('TCPDF Example 021');
    $pdf->SetTitle($filename);
    //$pdf->SetSubject('TCPDF Tutorial');
    $pdf->SetSubject($billreport);
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, utf8_encode($pdf_clinicname), utf8_encode($pdf_address));

 // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // set image scale factor
    //$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        //$pdf->setLanguageArray($l);
    }

    // set font
    $pdf->SetFont('shruti', '', 6);

   $pdf->setFontSubsetting(true);
    // add a page
    $pdf->AddPage();

    // output the HTML content
    $pdf->writeHTML(utf8_encode($html), true, 0, true, 0);

    // reset pointer to the last page
    $pdf->lastPage();

    //Close and output PDF document
    //$pdf->Output('example_021.pdf', 'I');
    $pdf->Output($filename, 'D');
</code>```

When I run this code, I got this output.

Gujrati fonts are not displayed. Please help me to display gujrati fonts into pdf. Thank you in advance.

Title: use gujarati fonts shruti with tcpdf

Body:
I want to use gujarati fonts in pdf. I used TCPDF V6.4.4. I am using google indic for input gujarati text. My php version is 8.0. I put shruti fonts into fonts folder. I wrote these code.

require_once('TCPDF/tcpdf.php');
$patient1 = "ચિરાગ";
    $patient2 = "પરમાર";
    $patient3 = "મારું";
    $patient4 = "નામ";
    $patient5 = "કલીનીક";

    $doctorname="doctorname";
    $filename="filename1.pdf";
    $billreport = "Billreport";
    $pdf_clinicname="pdf clicnicname"; $pdf_address="pdf address";

    $html = '';
    $pdfheader='';
    $html .= '';
        $html .= '

';

                        $html.='

                        '.utf8_encode($patient1).'
                        Age : '.utf8_encode($patient2).' '.utf8_encode($patient2).'
                        ID : '.utf8_encode($patient3).'
                        Case No : '.utf8_encode($patient4).'
                        Date : '.utf8_encode($patient5).'

';
         $html.='

'; // end wrapper id
        $html.='';

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // convert TTF font to TCPDF format and store it on the fonts folder
        $fontname = TCPDF_FONTS::addTTFfont('/TCPDF/fonts/shruti.ttf', 'TrueTypeUnicode', '', 96);

        // use the font
        $pdf->SetFont($fontname, '', 14, '', false);

         // set document information
    $pdf->SetCreator(PDF_CREATOR);
    //$pdf->SetAuthor('Nicola Asuni');
    $pdf->SetAuthor($doctorname);
    //$pdf->SetTitle('TCPDF Example 021');
    $pdf->SetTitle($filename);
    //$pdf->SetSubject('TCPDF Tutorial');
    $pdf->SetSubject($billreport);
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, utf8_encode($pdf_clinicname), utf8_encode($pdf_address));

 // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // set image scale factor
    //$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        //$pdf->setLanguageArray($l);
    }

    // set font
    $pdf->SetFont('shruti', '', 6);

   $pdf->setFontSubsetting(true);
    // add a page
    $pdf->AddPage();

    // output the HTML content
    $pdf->writeHTML(utf8_encode($html), true, 0, true, 0);

    // reset pointer to the last page
    $pdf->lastPage();

    //Close and output PDF document
    //$pdf->Output('example_021.pdf', 'I');
    $pdf->Output($filename, 'D');

When I run this code, I got this output.

Gujrati fonts are not displayed. Please help me to display gujrati fonts into pdf. Thank you in advance.


问:
How to retrieve the data after post api call using Vuex vuejs
How to show data after getting it from getters ?

get the list from this.$store.dispatch('list') and put it into the computed function it loads the data after refresh when we do add it should reflect on an immediate base. How to fix it please guide ?

export default {
  data(){
    return {
      isLoading: false,
    }
  },
  async created(){
    await this.profile()
  },
  methods: {
    async profile(){
      this.isLoading = true;
      return await Promise.all([
        this.$store.dispatch('class'),
        this.$store.dispatch('list')
      ]).finally(() => {
           this.isLoading = false;
      })
    },
    async addprofile(payload){
      const profile = await this.$store.dispatch('addProfile', payload)
        this.getItem();
        console.log("Call the getItem", getItem)
    }
 },
 computed: {
   getItem() {
     return => this.$store.getters.listItem;
   }
 }
}
```


问:
Problem with authentication in ASP.NET Core on mac
I have an ASP.NET Core 6.0 web application that uses Microsoft.AspNetCore.Identity in order to authenticate users.

Everything is ok when I run application on Windows and IIS and SigIn section works properly, but when I run on Mac with Kestrel, it returns to the login page without authentication.

Is the problem related to Microsoft.AspNetCore.Identity package that just works on Windows?


问:
How to I recompile an extracted pyinstaller file back to exe?
I've decompiled a pyinstaller exe using pyinstrxtctor and i have no clue how to recompile it back to an exe.

I've tried using the .spec file but no luck with that.


问:
Pip installation of PyInstaller failing on Windows
I'm trying to turn a Python file into an executable file with pyinstaller but I can't install pyinstall with pip install pyinstaller from cmd.
I get this error when I am trying to install pyinstaller:

ERROR: Could not install packages due to an OSError: [Errno 22] Invalid argument: 'C:\Users\Olgun\AppData\Local\Temp\pip-unpack-bdh65vkf\pyinstaller-5.7.0-py3-none-win_amd64.whl'.

I don't know if there is something wrong with my Python directory.

I tried to change the Windows file directory length limit but it was already at max limit. I tried using py2exe but it doesn't support the current Python version.


问:
dynamically created JS class property appears null - JSON fetched with Fetch API
I created a method to fetch a copy of my backend locale strings that are stored under my server document root as a JSON file.

I have a Form class that handles submitting a form and deals with showing error messages and so on.

When I use fetch to get my JSON and store in the the object as a property named locale, this referencing the class shows my class with a locale property being set correctly with all my translation keys and values but the next line, this.local is undefined.

There are 2 errors in the console:

Uncaught (in promise) TypeError: this.locales is undefined
Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

The class:

class Form
{
    constructor(form)
    {
        this.form = form
    }

    getLocales()
    {
        if (!this.locales)
        {

            fetch("/locales.json")
                .then(response => { response.json().then(locales => { this.locales = locales })})

        }

        console.log(this) // here the class is shown and the locale appears as an object
        console.log(this.locales) // here this.locale is undefined

        return this.locales
    }
}
```

I was expecting to set the locales on the object and then return it.

I am absolutely certain the JSON format is correct. The browser displays it correctly.

Body:
I created a method to fetch a copy of my backend locale strings that are stored under my server document root as a JSON file.

I have a Form class that handles submitting a form and deals with showing error messages and so on.

When I use fetch to get my JSON and store in the the object as a property named locale, this referencing the class shows my class with a locale property being set correctly with all my translation keys and values but the next line, this.local is undefined.

There are 2 errors in the console:

Uncaught (in promise) TypeError: this.locales is undefined
Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

The class:

class Form
{
    constructor(form)
    {
        this.form = form
    }

    getLocales()
    {
        if (!this.locales)
        {

            fetch("/locales.json")
                .then(response => { response.json().then(locales => { this.locales = locales })})

        }

        console.log(this) // here the class is shown and the locale appears as an object
        console.log(this.locales) // here this.locale is undefined

        return this.locales
    }
}

I was expecting to set the locales on the object and then return it.

I am absolutely certain the JSON format is correct. The browser displays it correctly.


问:
ENOENT: no such file or directory
I have a nodejs application and I want to deploy it using docker.
I have the following structure for folders and files

```<code>/src
   /config
       status.js
       role.js
       index.js
   /routes
       user.routes.js
       product.routes.js
       index.js
   index.js
   Dockerfile
   package.json
   ... other files and folders
</code>```

the content of src/config/index.js is:

```<code>module.exports = {
  ...require("./status"),
  ...require("./role"),
};
</code>```

The content of Dockerfile

```<code>FROM node:19-alpine3.16

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm i

COPY . .

CMD ["node", "src/index.js"]
</code>```

when I do docker image build I got the following error

```<code> ---> Running in 2f2e6c84845b
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /usr/src/app/src/config/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/usr/src/app/src/config/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-26T09_17_19_235Z-debug-0.log
The command '/bin/sh -c npm i' returned a non-zero code: 254
</code>```

I tried to add package.json with empty json to every folder has index.js file and that worked fine. but does that make sense to add package.json to every folder.

Title: ENOENT: no such file or directory

Body:
I have a nodejs application and I want to deploy it using docker.
I have the following structure for folders and files

/src
   /config
       status.js
       role.js
       index.js
   /routes
       user.routes.js
       product.routes.js
       index.js
   index.js
   Dockerfile
   package.json
   ... other files and folders

the content of src/config/index.js is:

module.exports = {
  ...require("./status"),
  ...require("./role"),
};

The content of Dockerfile

FROM node:19-alpine3.16

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm i

COPY . .

CMD ["node", "src/index.js"]

when I do docker image build I got the following error

 ---> Running in 2f2e6c84845b
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /usr/src/app/src/config/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/usr/src/app/src/config/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-26T09_17_19_235Z-debug-0.log
The command '/bin/sh -c npm i' returned a non-zero code: 254

I tried to add package.json with empty json to every folder has index.js file and that worked fine. but does that make sense to add package.json to every folder.


问:
Python Subprocess.Popen stdout and stderr problems
I have created a script (x) that can start and stop some other scripts (y). The "y" scripts redirect sys.stdout = SomeClass() and sys.stderr = SomeClass().

SomeClass() simply sends a pyside6 signal with the stdout/stderr written text and places that into a text area. The problem is, however, that the starter script (x), outputs EVERYTHING into the console that pops up when I start the "y" script (i.e. the redirect part in the "y" script doesn't work).

To clarify, I want stdout to ONLY go to the text area, and stderr to ONLY go to the console.

What could be causing this? I suppose it could be something with subprocess.Popen redirecting stdout and stderr to the console that is opened when I run the command that starts the "y" scripts.

I have tried adding: stdout=subprocess.PIPE to the "x" script as an argument in subprocess.Popen and I've also tried stdout=subprocess.DEVNULL to the "x" script as an argument in subprocess.Popen, but this removes the output completely.

The class that I redirect it to is located inside the "y" script (the script that gets started by the "x" script using Popen.) and is called SomeClass(). It looks like this:

```<code>class SomeClass(QObject):
    textWritten = Signal(str)

    def write(self, text):
        self.textWritten.emit(str(text))

    def flush(self):
        pass
</code>```

And this is the code where I redirect the signal and stdout (Also located inside the "y" script):

```<code>sys.stdout = SomeClass()
sys.stderr = SomeClass()
sys.stdout.textWritten.connect(self.handle_text_changed)
sys.stderr.textWritten.connect(self.handle_text_changed)
</code>```

And the handle_text_changedfunction looks like this:

```<code>def handle_text_changed(self, text):
    self.textEdit.moveCursor(QTextCursor.End)
    self.textEdit.insertPlainText(text)
    self.textEdit.moveCursor(QTextCursor.End)
</code>```

The part of the "x" script where I start the "y" script looks like this:

```<code>proc = subprocess.Popen(["deactivate.bat", "&&", "cd", path, "&&", "SET", "PYTHONPATH=pathtothescript".format(path), "&&", r".\venv\Scripts\python", "main.py"], creationflags=subprocess.CREATE_NEW_CONSOLE)
proc.poll()
</code>```

Body:
I have created a script (x) that can start and stop some other scripts (y). The "y" scripts redirect sys.stdout = SomeClass() and sys.stderr = SomeClass().

SomeClass() simply sends a pyside6 signal with the stdout/stderr written text and places that into a text area. The problem is, however, that the starter script (x), outputs EVERYTHING into the console that pops up when I start the "y" script (i.e. the redirect part in the "y" script doesn't work).

To clarify, I want stdout to ONLY go to the text area, and stderr to ONLY go to the console.

What could be causing this? I suppose it could be something with subprocess.Popen redirecting stdout and stderr to the console that is opened when I run the command that starts the "y" scripts.

I have tried adding: stdout=subprocess.PIPE to the "x" script as an argument in subprocess.Popen and I've also tried stdout=subprocess.DEVNULL to the "x" script as an argument in subprocess.Popen, but this removes the output completely.

The class that I redirect it to is located inside the "y" script (the script that gets started by the "x" script using Popen.) and is called SomeClass(). It looks like this:

class SomeClass(QObject):
    textWritten = Signal(str)

    def write(self, text):
        self.textWritten.emit(str(text))

    def flush(self):
        pass

And this is the code where I redirect the signal and stdout (Also located inside the "y" script):

sys.stdout = SomeClass()
sys.stderr = SomeClass()
sys.stdout.textWritten.connect(self.handle_text_changed)
sys.stderr.textWritten.connect(self.handle_text_changed)

And the handle_text_changedfunction looks like this:

def handle_text_changed(self, text):
    self.textEdit.moveCursor(QTextCursor.End)
    self.textEdit.insertPlainText(text)
    self.textEdit.moveCursor(QTextCursor.End)

The part of the "x" script where I start the "y" script looks like this:

proc = subprocess.Popen(["deactivate.bat", "&&", "cd", path, "&&", "SET", "PYTHONPATH=pathtothescript".format(path), "&&", r".\venv\Scripts\python", "main.py"], creationflags=subprocess.CREATE_NEW_CONSOLE)
proc.poll()


问:
How can I satisfy the At-Most constraint in a workflow satisfiability problem with Google OR-Tools?
For a given set of steps T, I have to ensure that at most k users are assigned to steps T. For example, at most 2 users can be assigned to steps 1, 2, and 3.  Each task is only assigned to one user and a user can have multiple tasks.
I have already made boolvar assignments for every pair of users and steps, such that assignments[user_x, step_y] is true if user_x is assigned to step_y. I get data from an input file in the form of a list of lists, e.g. [[2,1,2,3], [3,1,2,3,4,5]] means 2 At-Most constraints, the first list meaning 2 maximum users for the group of steps 1, 2, and 3, and the second list meaning 3 maximum users for the group of steps 1, 2, 3, 4, and 5.

```<code>for list in range(len(at_most_k)):
    # get max number of users
    k = at_most_k[list][0]
    # get the group of steps
    group_of_steps = at_most_k[list][1:]
    user_group = []
    for steps in group_of_steps:
        for users in range(num_users):
            user_group.append(assignments[users, steps-1])
    model.Add(sum(user_group) <= k)
</code>```

Actually, I've taken a look at the documentation provided by google OR-Tools at https://developers.google.com/optimization/assignment/assignment_teams
and modified it accordingly. I can confirm that editing the code provided by the above website to work on lists of lists, as I'm using, does work. However, the above code, which is supposed to be satisfiable, doesn't work.

Any explanation or help would be much appreciated.

Body:
For a given set of steps T, I have to ensure that at most k users are assigned to steps T. For example, at most 2 users can be assigned to steps 1, 2, and 3.  Each task is only assigned to one user and a user can have multiple tasks.
I have already made boolvar assignments for every pair of users and steps, such that assignments[user_x, step_y] is true if user_x is assigned to step_y. I get data from an input file in the form of a list of lists, e.g. [[2,1,2,3], [3,1,2,3,4,5]] means 2 At-Most constraints, the first list meaning 2 maximum users for the group of steps 1, 2, and 3, and the second list meaning 3 maximum users for the group of steps 1, 2, 3, 4, and 5.

for list in range(len(at_most_k)):
    # get max number of users
    k = at_most_k[list][0]
    # get the group of steps
    group_of_steps = at_most_k[list][1:]
    user_group = []
    for steps in group_of_steps:
        for users in range(num_users):
            user_group.append(assignments[users, steps-1])
    model.Add(sum(user_group) <= k)

Actually, I've taken a look at the documentation provided by google OR-Tools at https://developers.google.com/optimization/assignment/assignment_teams
and modified it accordingly. I can confirm that editing the code provided by the above website to work on lists of lists, as I'm using, does work. However, the above code, which is supposed to be satisfiable, doesn't work.

Any explanation or help would be much appreciated.


问:
Download button is not working for every images on website
I have one Website where i am loading multiple images from source and after every image i have shown one button.when i am clicking on download button only first image is downloading with many time.I want to download every images which is available on website.Can Any one please help.

this is code where i am loading images and rendering to website.but after one image next download button is not working for next image.it is only working for first one.

```<code>const btn = document.getElementById('downloadImage');
const imgurl = url;

        let new_html ='';
        new_html += '<tr>';
        new_html +='<td>';
        new_html +='<img  src="'+url+'" class="center">';
        new_html += '<a href="'+url+'" download>download</a>';
        new_html +='</td>';
        new_html +='</tr>';
        $('#List').find('tbody').append(new_html);

btn.addEventListener('click', (event) => {
  event.preventDefault();
  console.log('ABC')
  downloadImage(imgurl);
})

function downloadImage(url) {
  fetch(url, {
    mode : 'no-cors',
  })
    .then(response => response.blob())
    .then(blob => {
    let blobUrl = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.download = url.replace(/^.*[\\\/]/, '');
    a.href = blobUrl;
    document.body.appendChild(a);
    a.click();
    a.remove();
  })
}
})}}
</code>```

Any one can help so that every download button can work for every specific image which is loading from source.

Body:
I have one Website where i am loading multiple images from source and after every image i have shown one button.when i am clicking on download button only first image is downloading with many time.I want to download every images which is available on website.Can Any one please help.

this is code where i am loading images and rendering to website.but after one image next download button is not working for next image.it is only working for first one.

const btn = document.getElementById('downloadImage');
const imgurl = url;

        let new_html ='';
        new_html += '
';
        new_html +='';
        new_html +='';
        new_html += 'download';
        new_html +='	';
        new_html +='
';
        $('#List').find('tbody').append(new_html);

btn.addEventListener('click', (event) => {
  event.preventDefault();
  console.log('ABC')
  downloadImage(imgurl);
})

function downloadImage(url) {
  fetch(url, {
    mode : 'no-cors',
  })
    .then(response => response.blob())
    .then(blob => {
    let blobUrl = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.download = url.replace(/^.*[\\\/]/, '');
    a.href = blobUrl;
    document.body.appendChild(a);
    a.click();
    a.remove();
  })
}
})}}

Any one can help so that every download button can work for every specific image which is loading from source.


问:
how to use call function in Javascript?
undefined is printed instead of "Tester"

```<code>var sayName = () => {
    console.log('My name is ' + this.name);
};

const person = {
    'name': 'Tester',
    'age': 34
};

sayName.call(person)
</code>```

Expected to print "

```<code>My name is Tester
</code>```

"
but got

```<code>My name is undefined
</code>```

Title: how to use call function in Javascript?

Body:
undefined is printed instead of "Tester"

var sayName = () => {
    console.log('My name is ' + this.name);
};

const person = {
    'name': 'Tester',
    'age': 34
};

sayName.call(person)

Expected to print "

My name is Tester

"
but got

My name is undefined


问:
StorPortGetDeviceInformation yields error and thus cannot use it
I am trying to get my harddisk serial ID by using StorPortGetDeviceInformation, but it gives me an error: identifier StorPortGetDeviceInformation is undefined. I am also seeing an error such as "Error (active)    E0020   identifier "PRTL_RUN_ONCE_INIT_FN" is undefined mutante C:\Program Files (x86)\Windows Kits\10\Include\10.0.22621.0\km\ntddk.h  2225    "

I would be happy if someone could take a look at see why this does not work. Below is the code I am using (from an empty Driver Project created in Visual Studio 2022):

#include <Windows.h>
#include <storport.h>
#include <stdio.h>
#include <ntddk.h>

int main()
{
    // Enumerate the physical drives on the system
    for (int i = 0; i < 256; i++)
    {
        // Open a handle to the storage device
        WCHAR deviceName[32];
        swprintf_s(deviceName, L"\\\\.\\PhysicalDrive%d", i);
        HANDLE hDevice = CreateFile(deviceName,
            GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
        if (hDevice == INVALID_HANDLE_VALUE)
        {
            continue;
        }

        // Allocate a buffer to hold the serial ID
        ULONG serialIdSize = sizeof(STORAGE_DEVICE_ID_DESCRIPTOR);
        PSTORAGE_DEVICE_ID_DESCRIPTOR pSerialId =
            (PSTORAGE_DEVICE_ID_DESCRIPTOR)malloc(serialIdSize);
        if (pSerialId == NULL)
        {
            printf("Failed to allocate buffer.\n");
            CloseHandle(hDevice);
            return 1;
        }

        // Retrieve the serial ID
        ULONG bytesReturned;
        if (!StorPortGetDeviceInformation(hDevice,
            StorageDeviceIdDescriptor, pSerialId, serialIdSize, &bytesReturned))
        {
            printf("Failed to get device information.\n");
            free(pSerialId);
            CloseHandle(hDevice);
            return 1;
        }

        // Print the serial ID
        printf("Serial ID of disk %d: %S\n", i, pSerialId->Identifiers[0].Identifier);

        // Clean up
        free(pSerialId);
        CloseHandle(hDevice);
    }

    return 0;
}

```

What I done so far:

Created an empty driver project

Installed WDK and can be found in C:\Program Files (x86)\Windows Kits\10

Tried to link against the storport.lib library at C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0\km\x64\storport.lib

What I expected:

I can call StorPortGetDeviceInformation from my driver.

Body:
I am trying to get my harddisk serial ID by using StorPortGetDeviceInformation, but it gives me an error: identifier StorPortGetDeviceInformation is undefined. I am also seeing an error such as "Error (active)    E0020   identifier "PRTL_RUN_ONCE_INIT_FN" is undefined mutante C:\Program Files (x86)\Windows Kits\10\Include\10.0.22621.0\km\ntddk.h  2225    "

I would be happy if someone could take a look at see why this does not work. Below is the code I am using (from an empty Driver Project created in Visual Studio 2022):

#include <Windows.h>
#include <storport.h>
#include <stdio.h>
#include <ntddk.h>

int main()
{
    // Enumerate the physical drives on the system
    for (int i = 0; i < 256; i++)
    {
        // Open a handle to the storage device
        WCHAR deviceName[32];
        swprintf_s(deviceName, L"\\\\.\\PhysicalDrive%d", i);
        HANDLE hDevice = CreateFile(deviceName,
            GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
        if (hDevice == INVALID_HANDLE_VALUE)
        {
            continue;
        }

        // Allocate a buffer to hold the serial ID
        ULONG serialIdSize = sizeof(STORAGE_DEVICE_ID_DESCRIPTOR);
        PSTORAGE_DEVICE_ID_DESCRIPTOR pSerialId =
            (PSTORAGE_DEVICE_ID_DESCRIPTOR)malloc(serialIdSize);
        if (pSerialId == NULL)
        {
            printf("Failed to allocate buffer.\n");
            CloseHandle(hDevice);
            return 1;
        }

        // Retrieve the serial ID
        ULONG bytesReturned;
        if (!StorPortGetDeviceInformation(hDevice,
            StorageDeviceIdDescriptor, pSerialId, serialIdSize, &bytesReturned))
        {
            printf("Failed to get device information.\n");
            free(pSerialId);
            CloseHandle(hDevice);
            return 1;
        }

        // Print the serial ID
        printf("Serial ID of disk %d: %S\n", i, pSerialId->Identifiers[0].Identifier);

        // Clean up
        free(pSerialId);
        CloseHandle(hDevice);
    }

    return 0;
}

What I done so far:

Created an empty driver project

Installed WDK and can be found in C:\Program Files (x86)\Windows Kits\10

Tried to link against the storport.lib library at C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0\km\x64\storport.lib

What I expected:

I can call StorPortGetDeviceInformation from my driver.


问:
NodeJS Route not working. "Assignment to constant variable." Error
I am trying to set up a Shop page for my website. I have a navigation bar with 7 items. Each item works. They all work via a RestFUL API (Node server, routes, and controllers...). So I have it set up exactly the same for all pages. But for the shop page it won't work, not sure why. Thanks for all input.

Route
`

```<code>router.post('/addshopitem', encodedParser, function(req, res) {
  console.log("okay step 2");
  const name = req.body.name;
  const desc = req.body.desc;
  const price = req.body.price;
  const stock = req.body.stock;
  const createdby = req.body.createdby;

  console.log("okay step 2 almost");

  ShopController.add_item(req,res,name,desc,price,stock,createdby);

  console.log("okay step 2 done");
});
</code>```

Controller

```<code>exports.add_item = (req, res, name, desc, price, stock, createdby) => {
  const Item = require('../models/item');
  const item = new Item(1, name, desc, price, stock, createdby);

  const response = item.save();

  if (response) {
    res.render('shopitemadded');
  } else {
    res.render('error');
  }
}
</code>```

NAV-Item

```<code><div class='dropdown'>
        <button class='dropbtn' id='shop' onclick="window.location.href='/shop';">Shop</button>
        <div class='dropdown-content'></div>
    </div>
</code>```

`

Shop.ejs (View)
`

```<code><body>
  <div class='nav-div'>
    <%- include('./partials/nav.ejs') %>
  </div>

  <div class='content' id='content-one'>
    <div class="grid">
      <%- include('./partials/item.ejs') %>
    </div>
  </div>

  <div class='content' id='content-two'>
  </div>

  <div class='content' id='content-three'>
  </div>
</body>
</code>```

`

Item.ejs (Partial View Element)
`

```<code><% items.forEach(function(item) { %>
<div class="card"><img class="card__img" src="" alt="Canyons" />
  <div class="card__content">
    <h1 class="card__header"><%=item.name%></h1>
    <p class="card__text"><%=item.desc%></p>
    <form action="/shop/addtobasket" method="post">
      <input type="text" name="iditem" value="2" style="display: none;">
      <label for="amount">2
        <input type="text" name="amount" value="3">
      </label>
      <p>Anzahl an Lager: <%=item.stock%></p>
      <p>Stückpreis: <%=item.price%></p>
      <input class="card__btn" type="submit" name="submit" value="Dem Warenkorb hinzufügen">
    </form>
  </div>
</div>
<% })%>
</code>```

`

I am trying to set up a shop page. I did it the exact same way as all the other views (with a route and a controller). Only thing different: The ejs View has a partial (item.ejs) with a for each inside. Maybe I messed something up in there. Not sure.

Body:
I am trying to set up a Shop page for my website. I have a navigation bar with 7 items. Each item works. They all work via a RestFUL API (Node server, routes, and controllers...). So I have it set up exactly the same for all pages. But for the shop page it won't work, not sure why. Thanks for all input.

Route
`

router.post('/addshopitem', encodedParser, function(req, res) {
  console.log("okay step 2");
  const name = req.body.name;
  const desc = req.body.desc;
  const price = req.body.price;
  const stock = req.body.stock;
  const createdby = req.body.createdby;

  console.log("okay step 2 almost");

  ShopController.add_item(req,res,name,desc,price,stock,createdby);

  console.log("okay step 2 done");
});

Controller

exports.add_item = (req, res, name, desc, price, stock, createdby) => {
  const Item = require('../models/item');
  const item = new Item(1, name, desc, price, stock, createdby);

  const response = item.save();

  if (response) {
    res.render('shopitemadded');
  } else {
    res.render('error');
  }
}

NAV-Item

        <button class='dropbtn' id='shop' onclick="window.location.href='/shop';">Shop</button>

`

Shop.ejs (View)
`

    <%- include('./partials/nav.ejs') %>

      <%- include('./partials/item.ejs') %>

`

Item.ejs (Partial View Element)
`

<% items.forEach(function(item) { %>

<%=item.name%>

<%=item.desc%>

    <form action="/shop/addtobasket" method="post">
      <input type="text" name="iditem" value="2" style="display: none;">
      2
        <input type="text" name="amount" value="3">

Anzahl an Lager: <%=item.stock%>

Stückpreis: <%=item.price%>

      <input class="card__btn" type="submit" name="submit" value="Dem Warenkorb hinzufügen">
    </form>

<% })%>

`

I am trying to set up a shop page. I did it the exact same way as all the other views (with a route and a controller). Only thing different: The ejs View has a partial (item.ejs) with a for each inside. Maybe I messed something up in there. Not sure.


问:
Unable to achieve good accuracy in dog breed classifier using Keras CNN
I am (very) new to deep learning and I am trying to train a dog breed classifier using Tensorflow/Keras. I have selected a subset of 10 breeds to speed up calculations, and I am using all the images available in the Stanford dataset for those breeds, which I have placed in train/test/val directories. I have 1338 images for training, 379 images for validation and 200 images for test.

I have first tried building a simple CNN from scratch without data augmentation, and I quickly reached 99% accuracy for the training set and got stuck at 30% for the val set (which I assume is quite normal without augmentation ?)

Then I applied data augmentation and tried two approaches, building a CNN from scratch and using transfer learning. With the "home-made" CNN I can't reach more than around 30 % accuracy even for the training set, and I can't figure out what the problem is. And I am stuck around 80 % with transfer learning, which I guess is not that good either ?

Here is the code for data augmentation:

`

```<code># Creating image generator steps
train_datagen = ImageDataGenerator(rescale=1.0/255.0,
                                   rotation_range=60,
                                   width_shift_range=0.3,
                                   height_shift_range=0.3,
                                   shear_range=0.2,
                                   zoom_range=[0.5, 1.5],
                                   brightness_range=[0.5, 1.5],
                                   horizontal_flip=True
                                   )

val_datagen = ImageDataGenerator(rescale=1.0/255.0)

test_datagen = ImageDataGenerator(rescale=1.0/255.0)

train_generator = train_datagen.flow_from_directory(
    directory="split_output/train",
    target_size=(224,224),
    color_mode="rgb",
    batch_size=8,
    class_mode='sparse',
    shuffle='True',
    seed=42
    )

val_generator = val_datagen.flow_from_directory(
    directory="split_output/val",
    target_size=(224,224),
    color_mode="rgb",
    batch_size=8,
    class_mode='sparse',
    shuffle='True',
    seed=42
    )

test_generator = test_datagen.flow_from_directory(
    directory="split_output/test",
    target_size=(224,224),
    color_mode="rgb",
    batch_size=8,
    class_mode='sparse',
    shuffle='False',
    seed=42
    )

</code>```

`

Here is the first CNN I tried (for which accuracies are both stuck around 25 %):

`

```<code># The CNN architecture
model = Sequential()
model.add(Conv2D(32,(3,3), padding="same", activation='relu',input_shape = (224,224,3)))
model.add(MaxPooling2D((2,2)))
# 32 = number of filters
# (3, 3) = kernel size

model.add(Conv2D(64,(3,3), padding="same", activation='relu'))
model.add(MaxPooling2D((2,2)))

model.add(Conv2D(64,(3,3), padding="same", activation='relu'))
model.add(MaxPooling2D((2,2)))

model.add(Flatten())
model.add(Dense(64,activation='relu'))
model.add(Dense(10,activation='softmax'))

# Fitting the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']
              )

history = model.fit_generator(train_generator,
                #    steps_per_epoch=1000,
                    epochs=50,
                    validation_data=val_generator,
                #    validation_steps=250,
                    verbose=1
                    )

</code>```

`

And the second one, a bit deeper and including BatchNorm and Dropout (accuracies are stuck around 35%):

`

```<code># The CNN architecture
model = Sequential()
model.add(Conv2D(32,(3,3), padding="same", activation='relu',input_shape = (224,224,3)))
model.add(MaxPooling2D((2,2)))
# 32 = number of filters
# (3, 3) = kernel size

model.add(Conv2D(32,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D((2,2)))

model.add(Conv2D(64,(3,3), padding="same", activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D((2,2)))

model.add(Conv2D(128,(3,3), padding="same", activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D((2,2)))

model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(512,activation='relu'))
model.add(Dense(10,activation='softmax'))

model.summary()

opt = Adam(lr=0.0001)

# Fitting the model
model.compile(optimizer=opt,
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']
              )

history = model.fit(train_generator,
                #    steps_per_epoch=1000,
                    epochs=50,
                    validation_data=val_generator,
                #    validation_steps=250,
                    verbose=1
                    )

</code>```

`

Here is the history for that second CNN:
accuracies for 2nd CNN

And finally I tried with a resnet, which gets stuck around 90% for train and 80% for val:

`

```<code>model = Sequential()

model.add(ResNet50(include_top=False, pooling='avg', weights="imagenet"))
model.add(Flatten())
model.add(BatchNormalization())
model.add(Dense(2048, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(1024, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(10, activation='softmax'))

opt = Adam(lr=0.0001)

model.compile(optimizer=opt, loss='sparse_categorical_crossentropy', metrics=['accuracy'])

history = model.fit(train_generator,
                #    steps_per_epoch=1000,
                    epochs=150,
                    validation_data=val_generator,
                #    validation_steps=250,
                    verbose=1
                    )

</code>```

`

And the history for this last one:
resnet history

I'm a bit surprised at how the accuracies (especially val) get stuck so fast at a nearly constant value...

Again I'm very new at this so there could be very basic mistakes!

Body:
I am (very) new to deep learning and I am trying to train a dog breed classifier using Tensorflow/Keras. I have selected a subset of 10 breeds to speed up calculations, and I am using all the images available in the Stanford dataset for those breeds, which I have placed in train/test/val directories. I have 1338 images for training, 379 images for validation and 200 images for test.

I have first tried building a simple CNN from scratch without data augmentation, and I quickly reached 99% accuracy for the training set and got stuck at 30% for the val set (which I assume is quite normal without augmentation ?)

Then I applied data augmentation and tried two approaches, building a CNN from scratch and using transfer learning. With the "home-made" CNN I can't reach more than around 30 % accuracy even for the training set, and I can't figure out what the problem is. And I am stuck around 80 % with transfer learning, which I guess is not that good either ?

Here is the code for data augmentation:

`

# Creating image generator steps
train_datagen = ImageDataGenerator(rescale=1.0/255.0,
                                   rotation_range=60,
                                   width_shift_range=0.3,
                                   height_shift_range=0.3,
                                   shear_range=0.2,
                                   zoom_range=[0.5, 1.5],
                                   brightness_range=[0.5, 1.5],
                                   horizontal_flip=True
                                   )

val_datagen = ImageDataGenerator(rescale=1.0/255.0)

test_datagen = ImageDataGenerator(rescale=1.0/255.0)

train_generator = train_datagen.flow_from_directory(
    directory="split_output/train",
    target_size=(224,224),
    color_mode="rgb",
    batch_size=8,
    class_mode='sparse',
    shuffle='True',
    seed=42
    )

val_generator = val_datagen.flow_from_directory(
    directory="split_output/val",
    target_size=(224,224),
    color_mode="rgb",
    batch_size=8,
    class_mode='sparse',
    shuffle='True',
    seed=42
    )

test_generator = test_datagen.flow_from_directory(
    directory="split_output/test",
    target_size=(224,224),
    color_mode="rgb",
    batch_size=8,
    class_mode='sparse',
    shuffle='False',
    seed=42
    )

`

Here is the first CNN I tried (for which accuracies are both stuck around 25 %):

`

# The CNN architecture
model = Sequential()
model.add(Conv2D(32,(3,3), padding="same", activation='relu',input_shape = (224,224,3)))
model.add(MaxPooling2D((2,2)))
# 32 = number of filters
# (3, 3) = kernel size

model.add(Conv2D(64,(3,3), padding="same", activation='relu'))
model.add(MaxPooling2D((2,2)))

model.add(Conv2D(64,(3,3), padding="same", activation='relu'))
model.add(MaxPooling2D((2,2)))

model.add(Flatten())
model.add(Dense(64,activation='relu'))
model.add(Dense(10,activation='softmax'))

# Fitting the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']
              )

history = model.fit_generator(train_generator,
                #    steps_per_epoch=1000,
                    epochs=50,
                    validation_data=val_generator,
                #    validation_steps=250,
                    verbose=1
                    )

`

And the second one, a bit deeper and including BatchNorm and Dropout (accuracies are stuck around 35%):

`

# The CNN architecture
model = Sequential()
model.add(Conv2D(32,(3,3), padding="same", activation='relu',input_shape = (224,224,3)))
model.add(MaxPooling2D((2,2)))
# 32 = number of filters
# (3, 3) = kernel size

model.add(Conv2D(32,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D((2,2)))

model.add(Conv2D(64,(3,3), padding="same", activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D((2,2)))

model.add(Conv2D(128,(3,3), padding="same", activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D((2,2)))

model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(512,activation='relu'))
model.add(Dense(10,activation='softmax'))

model.summary()

opt = Adam(lr=0.0001)

# Fitting the model
model.compile(optimizer=opt,
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']
              )

history = model.fit(train_generator,
                #    steps_per_epoch=1000,
                    epochs=50,
                    validation_data=val_generator,
                #    validation_steps=250,
                    verbose=1
                    )

`

Here is the history for that second CNN:
accuracies for 2nd CNN

And finally I tried with a resnet, which gets stuck around 90% for train and 80% for val:

`

model = Sequential()

model.add(ResNet50(include_top=False, pooling='avg', weights="imagenet"))
model.add(Flatten())
model.add(BatchNormalization())
model.add(Dense(2048, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(1024, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(10, activation='softmax'))

opt = Adam(lr=0.0001)

model.compile(optimizer=opt, loss='sparse_categorical_crossentropy', metrics=['accuracy'])

history = model.fit(train_generator,
                #    steps_per_epoch=1000,
                    epochs=150,
                    validation_data=val_generator,
                #    validation_steps=250,
                    verbose=1
                    )

`

And the history for this last one:
resnet history

I'm a bit surprised at how the accuracies (especially val) get stuck so fast at a nearly constant value...

Again I'm very new at this so there could be very basic mistakes!


问:
How to implement database to BroadcastReceiver (Alarm)
I'm making a app, that will notificate when time of task expiring. For creating notifications I'm using BroadcastReceiver.
There is my code of class AlarmReceiver

```<code>class AlarmReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("yeah", "yeah")

        val dao = TasksDatabase.getInstance(context = context!!.applicationContext).dao
        //val repository = TasksRepositoryImpl(dao)
        var list: List<Task> = listOf()
        runBlocking {
            launch {
                Log.e("sad", "dsa")
                list = dao.getTasks().flattenToList()
                Log.e("list", list.toString())
            }
        }

        val builder = NotificationCompat.Builder(context, "DoneApp")
            .setSmallIcon(R.drawable.icon)
            .setContentTitle("Done App")
            .setContentText("")
            .setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
        val notificationManager = NotificationManagerCompat.from(context)

        if(list.isNotEmpty()){
            for(i in list){
                Log.e("string", i.toString())
            }
        } else {
            Log.e("log---", "---------------------------------")
        }

        notificationManager.notify(123, builder.build())
    }
    suspend fun <T> Flow<List<T>>.flattenToList() = flatMapConcat { it.asFlow() }.toList()
}
</code>```

But it stops on list = dao.getTasks().flattenToList()

There is TasksDao

```<code>@Dao
interface TasksDAO {
    @Insert
    suspend fun insertTask(task: Task)

    @Query("UPDATE task_table SET checked = :checked WHERE id = :id")
    suspend fun checkTask(id: Int, checked: Boolean)

    @Query("UPDATE task_table SET text = :text WHERE id = :id")
    suspend fun textTask(id: Int, text: String)

    @Query("DELETE FROM task_table WHERE id = :id")
    suspend fun deleteTask(id: Int)

    @Query("SELECT * FROM task_table")
    fun getTasks(): Flow<List<Task>>
}
</code>```

Body:
I'm making a app, that will notificate when time of task expiring. For creating notifications I'm using BroadcastReceiver.
There is my code of class AlarmReceiver

class AlarmReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e("yeah", "yeah")

        val dao = TasksDatabase.getInstance(context = context!!.applicationContext).dao
        //val repository = TasksRepositoryImpl(dao)
        var list: List<Task> = listOf()
        runBlocking {
            launch {
                Log.e("sad", "dsa")
                list = dao.getTasks().flattenToList()
                Log.e("list", list.toString())
            }
        }

        val builder = NotificationCompat.Builder(context, "DoneApp")
            .setSmallIcon(R.drawable.icon)
            .setContentTitle("Done App")
            .setContentText("")
            .setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
        val notificationManager = NotificationManagerCompat.from(context)

        if(list.isNotEmpty()){
            for(i in list){
                Log.e("string", i.toString())
            }
        } else {
            Log.e("log---", "---------------------------------")
        }

        notificationManager.notify(123, builder.build())
    }
    suspend fun <T> Flow<List<T>>.flattenToList() = flatMapConcat { it.asFlow() }.toList()
}

But it stops on list = dao.getTasks().flattenToList()

There is TasksDao

@Dao
interface TasksDAO {
    @Insert
    suspend fun insertTask(task: Task)

    @Query("UPDATE task_table SET checked = :checked WHERE id = :id")
    suspend fun checkTask(id: Int, checked: Boolean)

    @Query("UPDATE task_table SET text = :text WHERE id = :id")
    suspend fun textTask(id: Int, text: String)

    @Query("DELETE FROM task_table WHERE id = :id")
    suspend fun deleteTask(id: Int)

    @Query("SELECT * FROM task_table")
    fun getTasks(): Flow<List<Task>>
}


问:
I receive a WinError2 whenever I try to download a playlist using pytube
I'm trying to create a mp3 playlist downloader using python and the module 'pytube' Though whenever I run the code I get '[WinError 2] The system cannot find the file specified'. Here's the code I'm working on:

```<code>from pytube import Playlist
import os

yt = Playlist((input("Enter the URL of the video you want to download: \n>> ")))

for video in yt.videos:
    print('videos to be downloaded:')
    print(video.title)

print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'

out_file = video.streams.filter(only_audio=True).first().download(destination)

for len in out_file:
    base, ext = os.path.splitext(out_file)
    new_file = base + '.mp3'
    os.rename(out_file, new_file)
    print(video.title + " has been successfully downloaded.")
</code>```

It could only download one video and result in this error. If I remove it from the 'for' loop, it downloads all the song but only the last downloaded video gets converted into an mp3 while the rest is an .mp4 file type. I was expecting it to download all the song while updating the user of what song has finished downloading.

Body:
I'm trying to create a mp3 playlist downloader using python and the module 'pytube' Though whenever I run the code I get '[WinError 2] The system cannot find the file specified'. Here's the code I'm working on:

from pytube import Playlist
import os

yt = Playlist((input("Enter the URL of the video you want to download: \n>> ")))

for video in yt.videos:
    print('videos to be downloaded:')
    print(video.title)

print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'

out_file = video.streams.filter(only_audio=True).first().download(destination)

for len in out_file:
    base, ext = os.path.splitext(out_file)
    new_file = base + '.mp3'
    os.rename(out_file, new_file)
    print(video.title + " has been successfully downloaded.")

It could only download one video and result in this error. If I remove it from the 'for' loop, it downloads all the song but only the last downloaded video gets converted into an mp3 while the rest is an .mp4 file type. I was expecting it to download all the song while updating the user of what song has finished downloading.


问:
Measuring L1-Instruction cache associativity with a benchmark
How to practically test associativity degree of L1-Instruction cache?
As far as I get it, I need cpu to execute same command from different addresses wth offset = (Bank size) * N, but how can I do it using code on c++?

Fore example, I have i5 11300h with L1-I cache 8-way, 32KB/core

I tested associativity degree of L1-D and L2 caches but don't have an idea about instruction cache.


问:
open form to a specific record through listbox filter issue
I have a transactions form opening through select case open arguments.

Receipt, Transfer and Adjustment.

I have made 2 list boxes.

1st to filter the records and 2nd is to show records as per the 1st one filter

on double click in list box 2, i want to open specific record of receipt or transfer or adjustment.

for receipt records, it's opening the correct record whereas for transfer it's opening on 1st record of transfer. It's not filtering the records in transfer case.

I have tried different ways, most probably i doubt on case defining issue in transfer case or record source issue.

Kindly suggest how to resolve.

the code used in main form and list boxes are as under

```<code>Private Sub Form_Open(Cancel As Integer)

Select Case Me.OpenArgs

Case "Transfer" 'Transfer

lblForm.Caption = "Transfer"
lblTranDate.Caption = "Date"
lblDocumentNumber.Caption = "Transfer Number"
lblMainWarehouseFK.Caption = "Transfer From"
lblEntityFK.Caption = "Transfer To"
EntityFK.Visible = True
lblEntityFK.Visible = True
VendorsFK.Visible = False
TranTypeFK.RowSource = "SELECT TranTypePK, TranType from tblTranTypes WHERE TranTypePK>=3 And TranTypePK<=5"
TranTypeFK.DefaultValue = 3
RecordSource = "SELECT * from tblTransactions WHERE TranTypeFK>=3 And TranTypeFK<=5"
frmTransactionsSub!NewQuantity.ColumnHidden = True
Frame1.DefaultValue = 3

End Select
End Sub

Private Sub DynamicList_Click()

If Me.DynamicList.RowSource = "SELECT * from tblMasterTables WHERE MasterTablesPK>3;" Then

  If Me.DynamicList.ListIndex = 2 Then 'Transferred
    Me.DynamicList1.RowSource = "SELECT TransactionsPK, TranTypePK, TranDate, DocumentNumber, ItemsListName, PackingSize, TranType, Stock_In_Out, EntityName from qryTransactionsExtended WHERE TranTypePK=3;"
    Me.DynamicList1.ColumnCount = 9
    Me.DynamicList1.ColumnHeads = True
    Me.DynamicList1.ColumnWidths = "0;0;3cm;3.5cm,6cm;3cm;3cm;3cm;5cm"
    End If

End If

End Sub

Private Sub DynamicList1_DblClick(Cancel As Integer)
If Me.DynamicList.ListIndex = 2 Then
    DoCmd.OpenForm "frmTransactionsMain", , , "TransactionsPK=" & Me.DynamicList1, , , "Transfer"
End If

End Sub
</code>```

Body:
I have a transactions form opening through select case open arguments.

Receipt, Transfer and Adjustment.

I have made 2 list boxes.

1st to filter the records and 2nd is to show records as per the 1st one filter

on double click in list box 2, i want to open specific record of receipt or transfer or adjustment.

for receipt records, it's opening the correct record whereas for transfer it's opening on 1st record of transfer. It's not filtering the records in transfer case.

I have tried different ways, most probably i doubt on case defining issue in transfer case or record source issue.

Kindly suggest how to resolve.

the code used in main form and list boxes are as under

Private Sub Form_Open(Cancel As Integer)

Select Case Me.OpenArgs

Case "Transfer" 'Transfer

lblForm.Caption = "Transfer"
lblTranDate.Caption = "Date"
lblDocumentNumber.Caption = "Transfer Number"
lblMainWarehouseFK.Caption = "Transfer From"
lblEntityFK.Caption = "Transfer To"
EntityFK.Visible = True
lblEntityFK.Visible = True
VendorsFK.Visible = False
TranTypeFK.RowSource = "SELECT TranTypePK, TranType from tblTranTypes WHERE TranTypePK>=3 And TranTypePK<=5"
TranTypeFK.DefaultValue = 3
RecordSource = "SELECT * from tblTransactions WHERE TranTypeFK>=3 And TranTypeFK<=5"
frmTransactionsSub!NewQuantity.ColumnHidden = True
Frame1.DefaultValue = 3

End Select
End Sub

Private Sub DynamicList_Click()

If Me.DynamicList.RowSource = "SELECT * from tblMasterTables WHERE MasterTablesPK>3;" Then

  If Me.DynamicList.ListIndex = 2 Then 'Transferred
    Me.DynamicList1.RowSource = "SELECT TransactionsPK, TranTypePK, TranDate, DocumentNumber, ItemsListName, PackingSize, TranType, Stock_In_Out, EntityName from qryTransactionsExtended WHERE TranTypePK=3;"
    Me.DynamicList1.ColumnCount = 9
    Me.DynamicList1.ColumnHeads = True
    Me.DynamicList1.ColumnWidths = "0;0;3cm;3.5cm,6cm;3cm;3cm;3cm;5cm"
    End If

End If

End Sub

Private Sub DynamicList1_DblClick(Cancel As Integer)
If Me.DynamicList.ListIndex = 2 Then
    DoCmd.OpenForm "frmTransactionsMain", , , "TransactionsPK=" & Me.DynamicList1, , , "Transfer"
End If

End Sub


问:
How to get URL query on user redirect in Next.js?
On the main page user can provide email address and click go, then, he will be redirected to registration page, where I want to get this email address from URL and paste it in field.

```<code>// index.ts

const router = useRouter()

const handleRedirect = async (path: string) => {
    await router.push(path)
}

<StartButton onClick={() => handleRedirect(`/signup?email=${email}`)}>
  <ButtonText>
    HERE WE GO
  </ButtonText>
</StartButton>
</code>```
```<code>// signup.ts

React.useEffect(() => {
  if (router.isReady) {
    setEmail({...email, email: router.query.email as string})
  }
}, [router.query, router.isReady]);
</code>```

For now it works only when user reloads the page already with email in URL query, but when they click on HERE WE GO button and got redirected to sign up page, it doesn't work.

I also tried to use <Link> tag from next/link, but it didn't help.

How can I fix that?

Body:
On the main page user can provide email address and click go, then, he will be redirected to registration page, where I want to get this email address from URL and paste it in field.

// index.ts

const router = useRouter()

const handleRedirect = async (path: string) => {
    await router.push(path)
}

<StartButton onClick={() => handleRedirect(`/signup?email=${email}`)}>
  <ButtonText>
    HERE WE GO
  </ButtonText>
</StartButton>

// signup.ts

React.useEffect(() => {
  if (router.isReady) {
    setEmail({...email, email: router.query.email as string})
  }
}, [router.query, router.isReady]);

For now it works only when user reloads the page already with email in URL query, but when they click on HERE WE GO button and got redirected to sign up page, it doesn't work.

I also tried to use <Link> tag from next/link, but it didn't help.

How can I fix that?


问:
Add leading zero to months
This is a sample of my OrderDate column, and I am trying to convert it from "text" type to "date" type.
I believe first I need to add the missing leading zeros to some months (first row, for example).

OrderDate

29-8-2016

25-12-2018

22-11-2015

--------

How can I add the leading zero missing in some months ?

Title: Add leading zero to months


问:
Capturing a specific window using BitBlt return the black or transparent border which represent the classic gui layer
I tried to capture a screenshot of specific window using BitBlt and save it to clipboard, but it returns the screenshot with the content inside window border only while the window border itself is remain transparent or blacked out with many weird behaviors.

The expected result should be the full window border with the full content:

This is the actual result:

This is what I tried:

Comment the SetLayeredWindowAttributes function before performing BitBlt but the result is the entire black screenshot.

Tried to set the delay after UpdateWindow function but the weird border remains the same.

Disabling some coded option but it didn't help...

Use PrintWindow but the result is the classic gui border, which is not the intended goal (and many article indicate about the problem with this function).

I don't have any idea why this happened nor able to find out due to lack of information of this command when searching Internet.

Is there anything wrong with my code?

void QuickScreenshot()
{
    HWND    windowHandle(::FindWindowW(0, L"Internet Download Manager 6.41"));
    ANIMATIONINFO AnimationInfo{};
    SystemParametersInfoW(SPI_GETANIMATION, sizeof(ANIMATIONINFO), &AnimationInfo, NULL);

    auto DefaultAnimationInfo(AnimationInfo);
    AnimationInfo.iMinAnimate = 0;
    DefaultAnimationInfo.cbSize = sizeof(ANIMATIONINFO);

    SystemParametersInfoW(SPI_SETANIMATION, sizeof(ANIMATIONINFO), &AnimationInfo, WM_SETTINGCHANGE);

    auto originalExstyle(GetWindowLongW(windowHandle, GWL_EXSTYLE));
    SetWindowLongW(windowHandle, GWL_EXSTYLE, WS_EX_LAYERED);

    COLORREF        windowColor;
    BYTE            windowAlpha, customAlpha(1);
    DWORD           flag;
    WINDOWPLACEMENT windowState{};
    windowState.length = sizeof(WINDOWPLACEMENT);

    GetLayeredWindowAttributes(windowHandle, &windowColor, &windowAlpha, &flag);
    SetLayeredWindowAttributes(windowHandle, windowColor, customAlpha, flag);
    GetWindowPlacement(windowHandle, &windowState);

    if (windowState.showCmd == SW_SHOWMINIMIZED)
    {
        if ((windowState.flags & WPF_RESTORETOMAXIMIZED) == WPF_RESTORETOMAXIMIZED)
        {
            ShowWindow(windowHandle, SW_MAXIMIZE);
        }
        else
        {
            ShowWindow(windowHandle, SW_SHOWNORMAL);
        }
    }
    else
    {
        ShowWindow(windowHandle, windowState.showCmd);
    }

    RECT    windowRectangleCoordinates;
    GetWindowRect(windowHandle, &windowRectangleCoordinates);
    InvalidateRect(windowHandle, &windowRectangleCoordinates, TRUE);
    UpdateWindow(windowHandle);
    Sleep(100);

    HDC     ScreenContentHandle(GetWindowDC(windowHandle));
    HDC     DestinationContentHandle(CreateCompatibleDC(ScreenContentHandle));

    auto cx(windowRectangleCoordinates.right - windowRectangleCoordinates.left);
    auto cy(windowRectangleCoordinates.bottom - windowRectangleCoordinates.top);

    HBITMAP BitmapHandle(CreateCompatibleBitmap(ScreenContentHandle, cx, cy));
    HGDIOBJ oldObject(SelectObject(DestinationContentHandle, BitmapHandle));

    //PrintWindow(windowHandle, ScreenContentHandle, NULL);

    BitBlt
    (
        DestinationContentHandle,
        0, 0, cx, cy,
        ScreenContentHandle,
        0, 0,
        SRCCOPY | CAPTUREBLT
    );

    SaveToClipboard(BitmapHandle);

    SelectObject(DestinationContentHandle, oldObject);
    DeleteDC(DestinationContentHandle));
    ReleaseDC(NULL, ScreenContentHandle));
    DeleteObject(BitmapHandle));

    ShowWindow(windowHandle, SW_MINIMIZE);
    SetLayeredWindowAttributes(windowHandle, windowColor, windowAlpha, flag);
    SetWindowLongW(windowHandle, GWL_EXSTYLE, originalExstyle);
    SystemParametersInfoW(SPI_SETANIMATION, sizeof(ANIMATIONINFO), &DefaultAnimationInfo, WM_SETTINGCHANGE);
}
```


问:
Networkx: how to determine isomorphism regardless of edge directedness
What is the best way to determine if two graphs are isomorphic when one of them is directed and the other undirected?

The networkx is_isomorphic(G,H) function complains if G and H are not of the same type.

```<code>import networkx as nx
import networkx.algorithms.isomorphism as isomorph

G = nx.gn_graph(25)  # directed 25 node graph

if nx.is_directed(G):
    print("Graph G is directed")
else:
    print("Graph G is undirected")

H = G.to_undirected()

if nx.is_directed(H):
    print("Graph H is directed")
else:
    print("Graph H is undirected")

if G.nodes.data() == H.nodes.data():
    print("G and H graphs data are the same")

if isomorph.is_isomorphic(G, H):
    print("G and H are isomorphic")
</code>```

yields the following output:

```<code>Graph G is directed
Graph H is undirected
G and H graphs data are the same
Traceback (most recent call last):
  File "/Users/bob/Documents/work/stanza2netgraph/test/path_test.py", line 28, in <module>
    if isomorph.is_isomorphic(G, H):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/bob/opt/miniconda3/envs/stanza2netgraph/lib/python3.11/site-packages/networkx/algorithms/isomorphism/isomorph.py", line 229, in is_isomorphic
    raise NetworkXError("Graphs G1 and G2 are not of the same type.")
networkx.exception.NetworkXError: Graphs G1 and G2 are not of the same type.
</code>```

Would applying to_undirected to both graphs introduce any side-effects?

Thank you

Body:
What is the best way to determine if two graphs are isomorphic when one of them is directed and the other undirected?

The networkx is_isomorphic(G,H) function complains if G and H are not of the same type.

import networkx as nx
import networkx.algorithms.isomorphism as isomorph

G = nx.gn_graph(25)  # directed 25 node graph

if nx.is_directed(G):
    print("Graph G is directed")
else:
    print("Graph G is undirected")

H = G.to_undirected()

if nx.is_directed(H):
    print("Graph H is directed")
else:
    print("Graph H is undirected")

if G.nodes.data() == H.nodes.data():
    print("G and H graphs data are the same")

if isomorph.is_isomorphic(G, H):
    print("G and H are isomorphic")

yields the following output:

Graph G is directed
Graph H is undirected
G and H graphs data are the same
Traceback (most recent call last):
  File "/Users/bob/Documents/work/stanza2netgraph/test/path_test.py", line 28, in <module>
    if isomorph.is_isomorphic(G, H):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/bob/opt/miniconda3/envs/stanza2netgraph/lib/python3.11/site-packages/networkx/algorithms/isomorphism/isomorph.py", line 229, in is_isomorphic
    raise NetworkXError("Graphs G1 and G2 are not of the same type.")
networkx.exception.NetworkXError: Graphs G1 and G2 are not of the same type.

Would applying to_undirected to both graphs introduce any side-effects?

Thank you