问:
Why can't I reuse a driver in the newest version of selenium?
``

Hi, last time I used selenium was 2-3 years ago, now that I come back to it I realise a lot of things have changed, and one of them is that after running the code chromedriver automatically closes and aparently the only way to keep it open is using this command

```<code>options = Options()
options.add_experimental_option("detach", True)
</code>```

Using these lines of code keeps it open after the code stops but it makes the driver that already is opened  unable to be used again with the following commands on another script

```<code>driver = webdriver.Remote(command_executor=url, desired_capabilities={})

driver.session_id = session_id
</code>```

because I get the following error:

raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=57349): Max retries exceeded with url: /session (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000022FFDB034F0>: Failed to establish a new connection: [WinError 10061] No se puede establecer una conexión ya que el equipo de destino denegó expresamente dicha conexión'))

To summarize, I use two scripts, one only for opening chrome, then I manually do some things because is better not to automate them, and then when I´m ready I run another script that uses the previously opened chrome and starts where I left it. If I use an older version of selenium like 3.0, chrome do not close automatically and I can reuse the driver with its url and session ID that I store in an excel document to use them on the second script. The problem is, newer versions of selenium closes automatically chrome and to keep it alive I have to use detach option but I suspect this option is the one who causes the error above. Can someone explain this to me? is there a way to work around this?, I can just use the old version of selenium but I'm afraid it becomes no longer available and selenium forces me to use newer version or something like that, thanks.

FULL CODE THAT OPENS CHROME:

```<code>from selenium import webdriver
import openpyxl
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
s = Service(r'C:\Users\juanb\PycharmProjects\KT\chromedriver.exe')
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(executable_path=r'C:\Users\juanb\PycharmProjects\KT\chromedriver.exe',options=options)
url = driver.command_executor._url
session_id = driver.session_id
wb = openpyxl.load_workbook("DRIVER.xlsx")
sheet = wb.active
sheet.cell(1, 2).value = session_id
sheet.cell(2, 2).value = url
wb.save("DRIVER.xlsx")

driver.get("https://www.google.com/?hl=es")
print(url)
print(session_id)
</code>```

FULL CODE I USE TO DO WHAT I NEED:

```<code>from selenium import webdriver
import openpyxl

wb = openpyxl.load_workbook("DRIVER.xlsx")
sheet = wb.active
session_id = sheet.cell(1, 2).value
url = sheet.cell(2, 2).value
print(url)
driver = webdriver.Remote(command_executor=url, desired_capabilities={})  # ERROR OCCURS HERE
driver.session_id = session_id
.
.
.

</code>```

I tried installing an older version of selenium and it worked, but like I said, I would like to know if t here is a way to do this on newer versions. Also I could not find a single person having this problem or solution on the internet.

Body:
``

Hi, last time I used selenium was 2-3 years ago, now that I come back to it I realise a lot of things have changed, and one of them is that after running the code chromedriver automatically closes and aparently the only way to keep it open is using this command

options = Options()
options.add_experimental_option("detach", True)

Using these lines of code keeps it open after the code stops but it makes the driver that already is opened  unable to be used again with the following commands on another script

driver = webdriver.Remote(command_executor=url, desired_capabilities={})

driver.session_id = session_id

because I get the following error:

raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=57349): Max retries exceeded with url: /session (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000022FFDB034F0>: Failed to establish a new connection: [WinError 10061] No se puede establecer una conexión ya que el equipo de destino denegó expresamente dicha conexión'))

To summarize, I use two scripts, one only for opening chrome, then I manually do some things because is better not to automate them, and then when I´m ready I run another script that uses the previously opened chrome and starts where I left it. If I use an older version of selenium like 3.0, chrome do not close automatically and I can reuse the driver with its url and session ID that I store in an excel document to use them on the second script. The problem is, newer versions of selenium closes automatically chrome and to keep it alive I have to use detach option but I suspect this option is the one who causes the error above. Can someone explain this to me? is there a way to work around this?, I can just use the old version of selenium but I'm afraid it becomes no longer available and selenium forces me to use newer version or something like that, thanks.

FULL CODE THAT OPENS CHROME:

from selenium import webdriver
import openpyxl
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
s = Service(r'C:\Users\juanb\PycharmProjects\KT\chromedriver.exe')
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(executable_path=r'C:\Users\juanb\PycharmProjects\KT\chromedriver.exe',options=options)
url = driver.command_executor._url
session_id = driver.session_id
wb = openpyxl.load_workbook("DRIVER.xlsx")
sheet = wb.active
sheet.cell(1, 2).value = session_id
sheet.cell(2, 2).value = url
wb.save("DRIVER.xlsx")

driver.get("https://www.google.com/?hl=es")
print(url)
print(session_id)

FULL CODE I USE TO DO WHAT I NEED:

from selenium import webdriver
import openpyxl

wb = openpyxl.load_workbook("DRIVER.xlsx")
sheet = wb.active
session_id = sheet.cell(1, 2).value
url = sheet.cell(2, 2).value
print(url)
driver = webdriver.Remote(command_executor=url, desired_capabilities={})  # ERROR OCCURS HERE
driver.session_id = session_id
.
.
.

I tried installing an older version of selenium and it worked, but like I said, I would like to know if t here is a way to do this on newer versions. Also I could not find a single person having this problem or solution on the internet.


来源: stackexchange

问:
Take the content in the clipboard and store it in a string
This is my first time using VB in word. I entered the following code in the VB editor I loaded from Microsoft Word. I pasted the code from a website, assuming it would work. My understanding is that the code will take the content in the clipboard and store it in a string. But when I click run, I get the following error message

"Compile error: User-defined type not defined"

The code I have in my editor is as follows:

```<code>Sub ClipboardTest()
'
' ClipboardTest Macro
'
'
Dim MyData As DataObject
Dim strClip As String

Set MyData = New DataObject
MyData.GetFromClipboard
strClip = MyData.GetText
End Sub
</code>```

Thank you!

ContentLicense: CC BY-SA 4.0

Body:
This is my first time using VB in word. I entered the following code in the VB editor I loaded from Microsoft Word. I pasted the code from a website, assuming it would work. My understanding is that the code will take the content in the clipboard and store it in a string. But when I click run, I get the following error message

"Compile error: User-defined type not defined"

The code I have in my editor is as follows:

Sub ClipboardTest()
'
' ClipboardTest Macro
'
'
Dim MyData As DataObject
Dim strClip As String

Set MyData = New DataObject
MyData.GetFromClipboard
strClip = MyData.GetText
End Sub

Thank you!


问:
Why are flex items overflowing container when flex-shrink set to 0?
Flex container not growing to accommodate items when some items have a flex-shink:0 and container has flex-wrap:nowrap.

Case:

container (blue) does not have an specified width (it should grow to accommodate items).

items 1 & 3 (green) should be able to grow to certain size (10rem to 15rem) but not shrink.

items 2 & 4 (yellow) should be able to shrink to certain size but not grow.

Note: I know there are ways to work around the problem like setting a width to the container etc... but that is not the question, I would like to know if this is normal behavior and why is it happening.

HTML:

```<code><div class="static">
  <div class="contents">
    <div class="container">

      <span class="one">ITEM #1</span>

      <span class="two">ITEM #2</span>

      <span class="three">ITEM #3</span>

      <span class="four">ITEM #4</span>

    </div>
  </div>
</div>
</code>```

CSS:

```<code> * {
   box-sizing: border-box;
 }

 .static {
   display: flex;
   flex-direction: column;
   align-items: center;
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   overflow-y: scroll;
   padding: 0.5em 0;
 }

 .contents {
   display: flex;
   flex-direction: column;
   max-width: 90%;
 }

 .container {
   position: relative;
   text-align: center;
   display: flex;
   flex-wrap: nowrap;
   align-items: center;
   justify-content: space-between;
   padding: 1rem 1rem;
   background-color: blue;
 }

 .container>.one,
 .container>.three {
   flex: 1 0 10rem;
   max-width: 15rem;
   background-color: green;
 }

 .container>.two,
 .container>.four {
   flex: 0 1 5rem;
   min-width: 5rem;
   background-color: yellow;
 }
</code>```

RESULTS:

EXPECTED RESULT:

JSFIDDLE: https://jsfiddle.net/3b7vrjy1/3/

Body:
Flex container not growing to accommodate items when some items have a flex-shink:0 and container has flex-wrap:nowrap.

Case:

container (blue) does not have an specified width (it should grow to accommodate items).

items 1 & 3 (green) should be able to grow to certain size (10rem to 15rem) but not shrink.

items 2 & 4 (yellow) should be able to shrink to certain size but not grow.

Note: I know there are ways to work around the problem like setting a width to the container etc... but that is not the question, I would like to know if this is normal behavior and why is it happening.

HTML:

      ITEM #1

      ITEM #2

      ITEM #3

      ITEM #4

CSS:

 * {
   box-sizing: border-box;
 }

 .static {
   display: flex;
   flex-direction: column;
   align-items: center;
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   overflow-y: scroll;
   padding: 0.5em 0;
 }

 .contents {
   display: flex;
   flex-direction: column;
   max-width: 90%;
 }

 .container {
   position: relative;
   text-align: center;
   display: flex;
   flex-wrap: nowrap;
   align-items: center;
   justify-content: space-between;
   padding: 1rem 1rem;
   background-color: blue;
 }

 .container>.one,
 .container>.three {
   flex: 1 0 10rem;
   max-width: 15rem;
   background-color: green;
 }

 .container>.two,
 .container>.four {
   flex: 0 1 5rem;
   min-width: 5rem;
   background-color: yellow;
 }

RESULTS:

EXPECTED RESULT:

JSFIDDLE: https://jsfiddle.net/3b7vrjy1/3/


问:
Force class FIELD initialization via initializer then make it readonly in C#
Below С# class has not the properties and I don't want to add them until they actually required.

public class Person
{

  public required uint ID;
  public required string Name;
  public required string Email;
  public required string PhoneNumber;
  public byte? Age;

  public Person Clone()
  {
    return new Person
    {
      ID = ID,
      Name = Name,
      Email = Email,
      PhoneNumber = PhoneNumber,
      Age = Age
    };
  }

}
```
<p>Next, I want to make the ID <code>readonly</code>. However, if I'll add <code>readonly</code> keyword, it will be error</p>
<blockquote>
<p>Required member 'MyProject.Entities.Person.ID' must be settable</p>
</blockquote>
<p>Ideally, it should be <code>init</code> keyword for the class field, however, as far as I collected the information, this keyword is only for the properties...</p>
<h3>Why I don't like below solutions</h3>
<h4>Initialize the <code>ID</code> via constructor</h4>
<p>I will avoid the usage of the constructor until position parameters will not be discarded from the language.</p>
```// What is 45? The age?!
new Person(45);
```
<p>The programmers WILL avoid the named parameters while its usage is optional - it is the human nature.</p>
<h4>Replace the fields with properties</h4>
<p>I am admitting that I am wrong, but from the viewpoint of logic, the properties are useless while getters are only returns the value and setters are only sets it, herewith getters and setters are public.</p>
<pre class="lang-cs prettyprint-override"><code>public class Person
{

  public uint ID { get; init; }
  public required string Name;

  // ...

  public Person Clone()
  {
    return new Person
    {
      ID = ID,
      Name = Name,
      Email = Email,
      PhoneNumber = PhoneNumber,
      Age = Age
    };
  }

}
</code>```

looks more or less normal, but I am feeling uncomfortable about class has became a little bit complex.

Body:
Below С# class has not the properties and I don't want to add them until they actually required.

public class Person
{

  public required uint ID;
  public required string Name;
  public required string Email;
  public required string PhoneNumber;
  public byte? Age;

  public Person Clone()
  {
    return new Person
    {
      ID = ID,
      Name = Name,
      Email = Email,
      PhoneNumber = PhoneNumber,
      Age = Age
    };
  }

}

Next, I want to make the ID readonly. However, if I'll add readonly keyword, it will be error

Required member 'MyProject.Entities.Person.ID' must be settable

Ideally, it should be init keyword for the class field, however, as far as I collected the information, this keyword is only for the properties...

Why I don't like below solutions

Initialize the ID via constructor

I will avoid the usage of the constructor until position parameters will not be discarded from the language.

// What is 45? The age?!
new Person(45);

The programmers WILL avoid the named parameters while its usage is optional - it is the human nature.

Replace the fields with properties

I am admitting that I am wrong, but from the viewpoint of logic, the properties are useless while getters are only returns the value and setters are only sets it, herewith getters and setters are public.

public class Person
{

  public uint ID { get; init; }
  public required string Name;

  // ...

  public Person Clone()
  {
    return new Person
    {
      ID = ID,
      Name = Name,
      Email = Email,
      PhoneNumber = PhoneNumber,
      Age = Age
    };
  }

}

looks more or less normal, but I am feeling uncomfortable about class has became a little bit complex.


问:
ckeditor 4 Cannot load external plugings successfully
I have load ckeditor as follows;

```<code><!-- Scripts Admin -->
<script src="https://cdn.ckeditor.com/4.18.0/standard/ckeditor.js"></script>
<script src="'.base_url().'/admin/post/js/config.js"></script>
</code>```

My config.js is as follows;

```<code>CKEDITOR.plugins.addExternal('ckeditor_add_class', '/admin/post/js/plugins/ckeditor_add_class/plugin.js');
CKEDITOR.plugins.addExternal('youtube', '/admin/post/js/plugins/youtube/plugin.js');

CKEDITOR.replace( 'post_body' ,{
    filebrowserBrowseUrl : './filemanager/dialog.php?type=2&editor=ckeditor&fldr=',
    filebrowserImageBrowseUrl : '../../filemanager/dialog.php?type=2&editor=ckeditor&fldr=&akey='+fmKey ,
    extraPlugins: 'ckeditor_add_class,youtube',
});
</code>```

While my filemanager works as expected, I cannot see ckeditor_add_class nor youtube.  I do not see any errors on the console either.  Not sure how to trouble shoot.  Any ideas?

Body:
I have load ckeditor as follows;

My config.js is as follows;

CKEDITOR.plugins.addExternal('ckeditor_add_class', '/admin/post/js/plugins/ckeditor_add_class/plugin.js');
CKEDITOR.plugins.addExternal('youtube', '/admin/post/js/plugins/youtube/plugin.js');

CKEDITOR.replace( 'post_body' ,{
    filebrowserBrowseUrl : './filemanager/dialog.php?type=2&editor=ckeditor&fldr=',
    filebrowserImageBrowseUrl : '../../filemanager/dialog.php?type=2&editor=ckeditor&fldr=&akey='+fmKey ,
    extraPlugins: 'ckeditor_add_class,youtube',
});

While my filemanager works as expected, I cannot see ckeditor_add_class nor youtube.  I do not see any errors on the console either.  Not sure how to trouble shoot.  Any ideas?


问:
Module could not be found err or loading dependencies Pytorch Python
I'm trying to install PyTorch into my Conda environment using Anaconda Prompt(Miniconda3) but running into a similar issue seen here

First, I created my Conda environment:

```<code>conda create --name token python=3.
</code>```

Next, I activate my environment and download PyTorch without fail using the following:

```<code>activate token
conda install pytorch pytorch-cuda=11.6 -c pytorch -c nvidia
</code>```

Next, I go into my python console and try to import torch but find the following error:

```<code>python
>>>import torch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\.conda\envs\token\lib\site-packages\torch\__init__.py", line 139, in <module>
    raise err
OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\.conda\envs\token\lib\site-packages\torch\lib\shm.dll" or one of its dependencies.

</code>```

When running the list command:

```<code>(base) C:\Users>conda list -n token pytorch
# packages in environment at C:\Users\.conda\envs\token:
#
# Name                    Version                   Build  Channel
pytorch                   1.13.0          py3.10_cuda11.6_cudnn8_0    pytorch
pytorch-cuda              11.6                 h867d48c_0    pytorch
pytorch-mutex             1.0                        cuda    pytorch
</code>```

Is there a way to check which dependencies are missing or know why PyTorch is not being recognised?

Body:
I'm trying to install PyTorch into my Conda environment using Anaconda Prompt(Miniconda3) but running into a similar issue seen here

First, I created my Conda environment:

conda create --name token python=3.

Next, I activate my environment and download PyTorch without fail using the following:

activate token
conda install pytorch pytorch-cuda=11.6 -c pytorch -c nvidia

Next, I go into my python console and try to import torch but find the following error:

python
>>>import torch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\.conda\envs\token\lib\site-packages\torch\__init__.py", line 139, in <module>
    raise err
OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\.conda\envs\token\lib\site-packages\torch\lib\shm.dll" or one of its dependencies.

When running the list command:

(base) C:\Users>conda list -n token pytorch
# packages in environment at C:\Users\.conda\envs\token:
#
# Name                    Version                   Build  Channel
pytorch                   1.13.0          py3.10_cuda11.6_cudnn8_0    pytorch
pytorch-cuda              11.6                 h867d48c_0    pytorch
pytorch-mutex             1.0                        cuda    pytorch

Is there a way to check which dependencies are missing or know why PyTorch is not being recognised?


问:
How to sum values returned from web Api Query?
would it be possible to sum the following values using pure JavaScript/ (jQuery) :

```<code>$("#val_1").text();
$("#val_2").text();
$("#val_3").text();

// add the reduce or sum function here.

// place result into an element:

$("#result").val();

// append result into the html here:

$('[data-name="section"] tbody').find('td').first().append('<tr><td class="clearfix cell"><h4>'+ result +
'</h4></td></tr>');
}
</code>```

your help is much appreciated!

kind regards,
MRowan

I have tried without success reduce() and jquery sum.

Body:
would it be possible to sum the following values using pure JavaScript/ (jQuery) :

$("#val_1").text();
$("#val_2").text();
$("#val_3").text();

// add the reduce or sum function here.

// place result into an element:

$("#result").val();

// append result into the html here:

$('[data-name="section"] tbody').find('td').first().append('

'+ result +
'

');
}

your help is much appreciated!

kind regards,
MRowan

I have tried without success reduce() and jquery sum.


问:
Error: No module named 'airflow.www' when starting an airflow server
When I jumpstart an Airflow server in a virtual environment, the following error appears during the initialization:

```<code>Error: No module named 'airflow.www'
</code>```

I looked at a similar question as posed here: how to resolve "Error: No module named 'airflow.www'" while starting airflow websever

The highest-rated answer suggests that the gunicorn module should be located in the bin directory of the virtual environment. I've confirmed that gunicorn it is found in the bin folder of the virtual environment directory.

I've also tried pip uninstall and pip install gunicorn - to no avail.

I used the following command to create a virtual environment the with specified python and airflow versions:

```<code>pipenv install --python=3.9 apache-airflow=2.5
</code>```

Any suggestion would be greatly appreciated!

Body:
When I jumpstart an Airflow server in a virtual environment, the following error appears during the initialization:

Error: No module named 'airflow.www'

I looked at a similar question as posed here: how to resolve "Error: No module named 'airflow.www'" while starting airflow websever

The highest-rated answer suggests that the gunicorn module should be located in the bin directory of the virtual environment. I've confirmed that gunicorn it is found in the bin folder of the virtual environment directory.

I've also tried pip uninstall and pip install gunicorn - to no avail.

I used the following command to create a virtual environment the with specified python and airflow versions:

pipenv install --python=3.9 apache-airflow=2.5

Any suggestion would be greatly appreciated!


问:
Risc-V emulator U-Mode not running
I'm implementing a Risc-V emulator, and I'm not able to run U-Mode instructions.
It has MMU SV32, CSR, PLIC, CLINT and VirtIO (disk and console).

I'm studying a lot to do it working, but I'm alone and having the error...

```<code>[    1.943313] virtio_blk virtio1: 1/0/0 default/read/poll queues
[    1.973432] virtio_blk virtio1: [vda] 20480 512-byte logical blocks (10.5 MB/10.0 MiB)
[    2.030908] cpuidle-riscv-sbi: HSM suspend not available
[    2.115550] EXT4-fs (vda): mounting ext2 file system using the ext4 subsystem
[    2.204245] EXT4-fs (vda): mounted filesystem without journal. Quota mode: disabled.
[    2.207929] VFS: Mounted root (ext2 filesystem) readonly on device 254:0.
[    2.215999] devtmpfs: mounted
[    2.224530] Freeing unused kernel image (initmem) memory: 96K
[    2.226806] Kernel memory protection not selected by kernel config.
[    2.229195] Run /sbin/init as init process
[    2.230880]   with arguments:
[    2.232339]     /sbin/init
[    2.233718]   with environment:
[    2.235212]     HOME=/
[    2.236554]     TERM=linux
[    2.277966] Starting init: /sbin/init exists but couldn't execute it (error -13)
[    2.280540] Run /etc/init as init process
[    2.282216]   with arguments:
[    2.283675]     /etc/init
[    2.285044]   with environment:
[    2.286537]     HOME=/
[    2.287879]     TERM=linux
[    2.296848] Run /bin/init as init process
[    2.298523]   with arguments:
[    2.299983]     /bin/init
[    2.301351]   with environment:
[    2.302845]     HOME=/
[    2.304187]     TERM=linux
[    2.313239] Run /bin/sh as init process
[    2.314888]   with arguments:
[    2.316347]     /bin/sh
[    2.317690]   with environment:
[    2.319184]     HOME=/
[    2.320526]     TERM=linux
[    2.425304] sh[1]: unhandled signal 11 code 0x1 at 0x00000004 in ld-linux-riscv32-ilp32d.so.1[95b60000+21000]
[    2.430274] CPU: 0 PID: 1 Comm: sh Not tainted 5.19.9 #1
[    2.432913] Hardware name: ucbbar,riscvemu-bare (DT)
[    2.434846] epc : 95b615e8 ra : 95b608d8 sp : 9d86bea0
[    2.437381]  gp : c023cb00 tp : 00000000 t0 : 00000000
[    2.439729]  t1 : 00000000 t2 : 00000000 s0 : 9d86bef0
[    2.442077]  s1 : 00000000 a0 : 9d86bef0 a1 : 00000000
[    2.444424]  a2 : 00000000 a3 : 00000000 a4 : 00000000
[    2.446666]  a5 : 00000000 a6 : 00000000 a7 : 00000000
[    2.448909]  s2 : 00000000 s3 : 00000000 s4 : 00000000
[    2.451171]  s5 : 00000000 s6 : 00000000 s7 : 95b83040
[    2.453519]  s8 : 95b60000 s9 : 00000000 s10: 00000000
[    2.455844]  s11: 00000000 t3 : 00000000 t4 : 00000000
[    2.458086]  t5 : 00000000 t6 : 00000000
[    2.459911] status: 00004020 badaddr: 00000004 cause: 0000000d
[    2.463676] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b
[    2.466374] ---[ end Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b ]---
</code>```
```<code>
</code>```

void cpu_take_trap(const uint32_t cause, const uint32_t tval){

```<code>if(cpu.privilege <= SUPERVISOR
        && (((cause & (1 << 31)) && ((csr.mideleg >> (cause & 0x7FFFFFFF)) & 1)) || ((~cause & (1 << 31)) && ((csr.medeleg >> cause) & 1))) ) {
</code>```

//      printf("cpu_take_trap %d\n", cause & ~(1 << 31));

```<code>    csr.sepc= cpu.pc;

    if(cause & (1 << 31)){
        /*This bit is set when the exception was triggered by an interrupt.*/

        uint32_t vectored= csr.stvec & 3 ? (cause << 2) : 0;
        cpu.pc= (csr.stvec & ~3) + vectored;

    } else cpu.pc= csr.stvec & ~3;

    csr.stval= tval;
    csr.scause= cause;

    csr.sstatus &= ~(1 << 5 /*SPIE*/);                          // clear SPIE
    csr.sstatus |= ((csr.sstatus >> cpu.privilege) & 1) << 5;   // copies SIE into SPIE
    csr.sstatus &= ~(1 << cpu.privilege /*SIE*/);               // clear SIE

    csr.sstatus &= ~(1 << 8 /*SPP*/);                           // clear SPP
    csr.sstatus |= (cpu.privilege << 8 /*SPP*/);                // copies current privilege into SPP

    cpu.privilege= SUPERVISOR;

} else {

    csr.mepc= cpu.pc;

    if(cause & (1 << 31)){
        /*This bit is set when the exception was triggered by an interrupt.*/

        uint32_t vectored= csr.mtvec & 1 ? (cause << 2) : 0;
        cpu.pc= (csr.mtvec & ~3) + vectored;

    } else cpu.pc= csr.mtvec & ~3;

    csr.mtval= tval;
    csr.mcause= cause;

    csr.mstatus &= ~(1 << 7 /*MPIE*/);                          // clear MPIE
    csr.mstatus |= ((csr.mstatus >> cpu.privilege) & 1) << 7;   // copies MIE into MPIE
    csr.mstatus &= ~(1 << cpu.privilege /*MIE*/);               // clear MIE

    csr.mstatus &= ~(3 << 11 /*MPP*/);                          // clear MPP
    csr.mstatus |= (cpu.privilege << 11 /*MPP*/);               // copies current privilege into MPP

    cpu.privilege= MACHINE;
}
</code>```

}

```<code>
</code>```

Title: Risc-V emulator U-Mode not running

Body:
I'm implementing a Risc-V emulator, and I'm not able to run U-Mode instructions.
It has MMU SV32, CSR, PLIC, CLINT and VirtIO (disk and console).

I'm studying a lot to do it working, but I'm alone and having the error...

[    1.943313] virtio_blk virtio1: 1/0/0 default/read/poll queues
[    1.973432] virtio_blk virtio1: [vda] 20480 512-byte logical blocks (10.5 MB/10.0 MiB)
[    2.030908] cpuidle-riscv-sbi: HSM suspend not available
[    2.115550] EXT4-fs (vda): mounting ext2 file system using the ext4 subsystem
[    2.204245] EXT4-fs (vda): mounted filesystem without journal. Quota mode: disabled.
[    2.207929] VFS: Mounted root (ext2 filesystem) readonly on device 254:0.
[    2.215999] devtmpfs: mounted
[    2.224530] Freeing unused kernel image (initmem) memory: 96K
[    2.226806] Kernel memory protection not selected by kernel config.
[    2.229195] Run /sbin/init as init process
[    2.230880]   with arguments:
[    2.232339]     /sbin/init
[    2.233718]   with environment:
[    2.235212]     HOME=/
[    2.236554]     TERM=linux
[    2.277966] Starting init: /sbin/init exists but couldn't execute it (error -13)
[    2.280540] Run /etc/init as init process
[    2.282216]   with arguments:
[    2.283675]     /etc/init
[    2.285044]   with environment:
[    2.286537]     HOME=/
[    2.287879]     TERM=linux
[    2.296848] Run /bin/init as init process
[    2.298523]   with arguments:
[    2.299983]     /bin/init
[    2.301351]   with environment:
[    2.302845]     HOME=/
[    2.304187]     TERM=linux
[    2.313239] Run /bin/sh as init process
[    2.314888]   with arguments:
[    2.316347]     /bin/sh
[    2.317690]   with environment:
[    2.319184]     HOME=/
[    2.320526]     TERM=linux
[    2.425304] sh[1]: unhandled signal 11 code 0x1 at 0x00000004 in ld-linux-riscv32-ilp32d.so.1[95b60000+21000]
[    2.430274] CPU: 0 PID: 1 Comm: sh Not tainted 5.19.9 #1
[    2.432913] Hardware name: ucbbar,riscvemu-bare (DT)
[    2.434846] epc : 95b615e8 ra : 95b608d8 sp : 9d86bea0
[    2.437381]  gp : c023cb00 tp : 00000000 t0 : 00000000
[    2.439729]  t1 : 00000000 t2 : 00000000 s0 : 9d86bef0
[    2.442077]  s1 : 00000000 a0 : 9d86bef0 a1 : 00000000
[    2.444424]  a2 : 00000000 a3 : 00000000 a4 : 00000000
[    2.446666]  a5 : 00000000 a6 : 00000000 a7 : 00000000
[    2.448909]  s2 : 00000000 s3 : 00000000 s4 : 00000000
[    2.451171]  s5 : 00000000 s6 : 00000000 s7 : 95b83040
[    2.453519]  s8 : 95b60000 s9 : 00000000 s10: 00000000
[    2.455844]  s11: 00000000 t3 : 00000000 t4 : 00000000
[    2.458086]  t5 : 00000000 t6 : 00000000
[    2.459911] status: 00004020 badaddr: 00000004 cause: 0000000d
[    2.463676] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b
[    2.466374] ---[ end Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b ]---

void cpu_take_trap(const uint32_t cause, const uint32_t tval){

if(cpu.privilege <= SUPERVISOR
        && (((cause & (1 << 31)) && ((csr.mideleg >> (cause & 0x7FFFFFFF)) & 1)) || ((~cause & (1 << 31)) && ((csr.medeleg >> cause) & 1))) ) {

//      printf("cpu_take_trap %d\n", cause & ~(1 << 31));

    csr.sepc= cpu.pc;

    if(cause & (1 << 31)){
        /*This bit is set when the exception was triggered by an interrupt.*/

        uint32_t vectored= csr.stvec & 3 ? (cause << 2) : 0;
        cpu.pc= (csr.stvec & ~3) + vectored;

    } else cpu.pc= csr.stvec & ~3;

    csr.stval= tval;
    csr.scause= cause;

    csr.sstatus &= ~(1 << 5 /*SPIE*/);                          // clear SPIE
    csr.sstatus |= ((csr.sstatus >> cpu.privilege) & 1) << 5;   // copies SIE into SPIE
    csr.sstatus &= ~(1 << cpu.privilege /*SIE*/);               // clear SIE

    csr.sstatus &= ~(1 << 8 /*SPP*/);                           // clear SPP
    csr.sstatus |= (cpu.privilege << 8 /*SPP*/);                // copies current privilege into SPP

    cpu.privilege= SUPERVISOR;

} else {

    csr.mepc= cpu.pc;

    if(cause & (1 << 31)){
        /*This bit is set when the exception was triggered by an interrupt.*/

        uint32_t vectored= csr.mtvec & 1 ? (cause << 2) : 0;
        cpu.pc= (csr.mtvec & ~3) + vectored;

    } else cpu.pc= csr.mtvec & ~3;

    csr.mtval= tval;
    csr.mcause= cause;

    csr.mstatus &= ~(1 << 7 /*MPIE*/);                          // clear MPIE
    csr.mstatus |= ((csr.mstatus >> cpu.privilege) & 1) << 7;   // copies MIE into MPIE
    csr.mstatus &= ~(1 << cpu.privilege /*MIE*/);               // clear MIE

    csr.mstatus &= ~(3 << 11 /*MPP*/);                          // clear MPP
    csr.mstatus |= (cpu.privilege << 11 /*MPP*/);               // copies current privilege into MPP

    cpu.privilege= MACHINE;
}

}


问:
Creatin a new array with value count and populate google chart dynamically using that array in laravel
I'm trying to build a custom Shopify application with their REST API.

In my laravel application, controller, I'm accessing Shopify's orders endpoint as follows...

```<code>$url = "https://MY_API_KEY:MY_AUTH_TOKEN@MY_STORE.myshopify.com/admin/api/2022-10/orders.json?status=any";
            $curl = curl_init( $url );
            curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $json_response = curl_exec($curl);
            curl_close($curl);
            $result_3 = json_decode($json_response, TRUE);
</code>```

This curl request works fine and it gives me an array of all the properties.

Now, on my blade view, I'm trying to display a google donut chart to display the usage of each payment gateway by the customers.

I have to use following array key for that

I have this on my blade view so far..

```<code>`<script type="text/javascript">
                    google.charts.load("current", {packages:["corechart"]});
                    google.charts.setOnLoadCallback(drawChart);
                    function drawChart() {
                        var data = google.visualization.arrayToDataTable([
                        ['Payment Gateway', 'Number of Orders'],
                        ['Work',     11],
                        ['Eat',      2],
                        ['Commute',  2],
                        ['Watch TV', 2],
                        ['Sleep',    7]
                        ]);

                        var options = {
                        title: 'Payment Gateways',
                        pieHole: 0.4,
                        };

                        var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
                        chart.draw(data, options);
                    }
                </script>
                <div id="donutchart" style="width: 100%;"></div>`
</code>```

There, the following array,

```<code>`['Work',     11],
['Eat',      2],
['Commute',  2],
['Watch TV', 2],
['Sleep',    7]`
</code>```

has to be replaced dynamically with my controller.

But now I'm stuck at creating a new array with all the payment gateways and the total number for each usage and populate above array on my blade with that??

EG:

['stripe','2'], ['paypal', '4'], ['bogus', '1']

Body:
I'm trying to build a custom Shopify application with their REST API.

In my laravel application, controller, I'm accessing Shopify's orders endpoint as follows...

$url = "https://MY_API_KEY:MY_AUTH_TOKEN@MY_STORE.myshopify.com/admin/api/2022-10/orders.json?status=any";
            $curl = curl_init( $url );
            curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $json_response = curl_exec($curl);
            curl_close($curl);
            $result_3 = json_decode($json_response, TRUE);

This curl request works fine and it gives me an array of all the properties.

Now, on my blade view, I'm trying to display a google donut chart to display the usage of each payment gateway by the customers.

I have to use following array key for that

I have this on my blade view so far..

`

`

There, the following array,

`['Work',     11],
['Eat',      2],
['Commute',  2],
['Watch TV', 2],
['Sleep',    7]`

has to be replaced dynamically with my controller.

But now I'm stuck at creating a new array with all the payment gateways and the total number for each usage and populate above array on my blade with that??

EG:

['stripe','2'], ['paypal', '4'], ['bogus', '1']


问:
Calling class elements after AJAX rendering
Is it possible to run this piece of code:

```<code>$('.features').each(function () {
        var $features_p_tag = $(this).find('p');
        if ($features_p_tag.text().length > 110) {
            var unsatisfactory_features = $features_p_tag.text();
            unsatisfactory_features = unsatisfactory_features.substring(0, 100);
            unsatisfactory_features = unsatisfactory_features += "...";
            $features_p_tag.addClass('decent_features').hide();
            unsatisfactory_features += `<span class="decent_features_p_tag font-weight-bold"><br/><img src="images/soaked.png" alt="Wine cube" class="mr-1"/> Read more</span>`;
            $features_p_tag.append(`<span class="unsatisfactory_features_p_tag font-weight-bold"><br/><img src="images/half_soaked.png" alt="Half-soaked wine cube" class="mr-1"/> Read less</span>`);
            $(this).append(`<p class="unsatisfactory red_wine_color">` + unsatisfactory_features + `</p>`);
        }
    });
</code>```

after AJAX rewrites the whole div in which are .features classes? It doesn't work after rendering, but is there a way for me to make changes in call of this each function so it can look for features every time they're present on the page. (in the similar way like $(document).on(event,class... where class isn't necessary required to be present on the page all the time.
For understanding the issue sakes, the code is about cutting the description of a product.

Body:
Is it possible to run this piece of code:

$('.features').each(function () {
        var $features_p_tag = $(this).find('p');
        if ($features_p_tag.text().length > 110) {
            var unsatisfactory_features = $features_p_tag.text();
            unsatisfactory_features = unsatisfactory_features.substring(0, 100);
            unsatisfactory_features = unsatisfactory_features += "...";
            $features_p_tag.addClass('decent_features').hide();
            unsatisfactory_features += `<span class="decent_features_p_tag font-weight-bold"><br/><img src="images/soaked.png" alt="Wine cube" class="mr-1"/> Read more</span>`;
            $features_p_tag.append(`<span class="unsatisfactory_features_p_tag font-weight-bold"><br/><img src="images/half_soaked.png" alt="Half-soaked wine cube" class="mr-1"/> Read less</span>`);
            $(this).append(`<p class="unsatisfactory red_wine_color">` + unsatisfactory_features + `</p>`);
        }
    });

after AJAX rewrites the whole div in which are .features classes? It doesn't work after rendering, but is there a way for me to make changes in call of this each function so it can look for features every time they're present on the page. (in the similar way like $(document).on(event,class... where class isn't necessary required to be present on the page all the time.
For understanding the issue sakes, the code is about cutting the description of a product.


问:
How do you displayed output as currency in Python?( Using PySimpleGUI)?
New to python and have little to no experience in coding but learning. I am looking to display currency when a user fills out a field in a forum. Would like the field to be limited to numbers as well so the user does not mistakenly enters text. Where/how would I write those string? I am use PySimpleGUI. Also is PySimpleGUI the best for this? Would I need to use other scripts?</p>
```<code>This is what i am using to pratice:
</code>```
```<code>import PySimpleGUI as sg
sg.theme('DarkAmber')   # Add a little color to your windows
# All the stuff inside your window. This is the PSG magic code compactor...
layout = [  [sg.Text('Some text on Row 1')],
            [sg.Text('Enter something on Row 2'), sg.InputText()],*<----to display currency when user types in numerical characters examples: $1,000.00/$20.00 or $1,000/$20
            [sg.OK(), sg.Cancel()]]

# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events"
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Cancel'):
        break

window.close()
</code>```

Body:
New to python and have little to no experience in coding but learning. I am looking to display currency when a user fills out a field in a forum. Would like the field to be limited to numbers as well so the user does not mistakenly enters text. Where/how would I write those string? I am use PySimpleGUI. Also is PySimpleGUI the best for this? Would I need to use other scripts?

This is what i am using to pratice:

import PySimpleGUI as sg
sg.theme('DarkAmber')   # Add a little color to your windows
# All the stuff inside your window. This is the PSG magic code compactor...
layout = [  [sg.Text('Some text on Row 1')],
            [sg.Text('Enter something on Row 2'), sg.InputText()],*<----to display currency when user types in numerical characters examples: $1,000.00/$20.00 or $1,000/$20
            [sg.OK(), sg.Cancel()]]

# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events"
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Cancel'):
        break

window.close()


问:
Class weights not working with return_sequences Keras
''''

#x_train format = [samples, timesteps, features]
#y_train format = [samples, timesteps]

```<code>num_timesteps = len(x_train[0])
num_features = len(x_train[0, 0])
num_classes = 3

model = Sequential()
model.add(Dense(50, input_shape = (num_timesteps, num_features)))
model.add(Dense(50))
model.add(Dense(50))
model.add(LSTM(300, return_sequences=True))
model.add(Dense(50))
model.add(Dense(50))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'],
sample_weight_mode='temporal')
model.fit(x_train, y_train, epochs=1, batch_size=500, class_weight = class_weights)
</code>```

''''

I get an error that seems to indicate something is wrong with indices. The code works if I remove class_weights.

Does anyone know what I am doing wrong?

Error:

Traceback (most recent call last):
File "C:/Users/Documents/Neural Network for probabilities/keras_test_real_data_non_stateful_return_sequences_with_class_weights.py", line 129, in
model.fit(x_train, y_train, epochs=1, batch_size=500, class_weight = class_weights)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper
return method(self, *args, **kwargs)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 848, in fit
tmp_logs = train_function(iterator)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 580, in call
result = self._call(*args, **kwds)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 644, in _call
return self._stateless_fn(*args, **kwds)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 2420, in call
return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1665, in _filtered_call
self.captured_inputs)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1746, in _call_flat
ctx, args, cancellation_manager=cancellation_manager))
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 598, in call
ctx=ctx)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\execute.py", line 60, in quick_execute
inputs, attrs, num_outputs)
tensorflow.python.framework.errors_impl.InvalidArgumentError:  indices[1] = 4 is not in [0, 3)
[[{{node GatherV2}}]]
[[IteratorGetNext]] [Op:__inference_train_function_4037]

Function call stack:
train_function

Body:
''''

#x_train format = [samples, timesteps, features]
#y_train format = [samples, timesteps]

num_timesteps = len(x_train[0])
num_features = len(x_train[0, 0])
num_classes = 3

model = Sequential()
model.add(Dense(50, input_shape = (num_timesteps, num_features)))
model.add(Dense(50))
model.add(Dense(50))
model.add(LSTM(300, return_sequences=True))
model.add(Dense(50))
model.add(Dense(50))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'],
sample_weight_mode='temporal')
model.fit(x_train, y_train, epochs=1, batch_size=500, class_weight = class_weights)

''''

I get an error that seems to indicate something is wrong with indices. The code works if I remove class_weights.

Does anyone know what I am doing wrong?

Error:

Traceback (most recent call last):
File "C:/Users/Documents/Neural Network for probabilities/keras_test_real_data_non_stateful_return_sequences_with_class_weights.py", line 129, in
model.fit(x_train, y_train, epochs=1, batch_size=500, class_weight = class_weights)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper
return method(self, *args, **kwargs)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 848, in fit
tmp_logs = train_function(iterator)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 580, in call
result = self._call(*args, **kwds)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 644, in _call
return self._stateless_fn(*args, **kwds)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 2420, in call
return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1665, in _filtered_call
self.captured_inputs)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1746, in _call_flat
ctx, args, cancellation_manager=cancellation_manager))
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 598, in call
ctx=ctx)
File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\execute.py", line 60, in quick_execute
inputs, attrs, num_outputs)
tensorflow.python.framework.errors_impl.InvalidArgumentError:  indices[1] = 4 is not in [0, 3)
[[{{node GatherV2}}]]
[[IteratorGetNext]] [Op:__inference_train_function_4037]

Function call stack:
train_function


问:
Do Polars dataframes need to be formatted a certain way to be used with scikit-learn models?
I've been working through a notebook on Kaggle that used Pandas, and I wanted to refactor it to Polars.

The dataframes I'm working with look like this:

X_train

Pclass (i64)
Sex (i16)
Age (i32)
Fare (i16)
Embarked (i16)
title (i16)
family_size (i64)
is_alone (i64)
age*class (i64)

3
0
1
0
1
1
2
1
0

...
...
...
...
...
...
...
...
...

shape: (891,9)

y_train

Survived (i64)

0

1

...

shape: (891,1)

Kaggle has me creating a logistic regression with the following code:

```<code>logreg = LogisticRegression()
logreg.fit(X_train, Y_train)
</code>```

It's my understanding that Polars dataframes don't work with sklearn, so I modified X_train and y_train to be numpy ndarrays like so:

```<code>logreg.fit(X_train.to_numpy(),y_train.to_numpy())
</code>```

but then I get the following error:

```<code>>>> logreg.fit(X_train.to_numpy(),y_train.to_numpy())
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py:993: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
LogisticRegression()
</code>```

I was going to try saying y_train.transpose(), but there's no mention of needing to reshape the Pandas dataframe so I'm wondering if a transpose is really necessary, or if I'm doing something else wrong.

Edit:

I added the numpy.ravel() function like this logreg.fit(X_train.to_numpy(),y_train.to_numpy().ravel()) and it seems to have worked, but now when I say
y_pred = logreg.predict(X_test.to_numpy()) I get the following error

```<code>>>>y_pred= logreg.predict(X_test.to_numpy())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/linear_model/_base.py", line 425, in predict
    scores = self.decision_function(X)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/linear_model/_base.py", line 407, in decision_function
    X = self._validate_data(X, accept_sparse="csr", reset=False)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/base.py", line 566, in _validate_data
    X = check_array(X, **check_params)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 800, in check_array
    _assert_all_finite(array, allow_nan=force_all_finite == "allow-nan")
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 114, in _assert_all_finite
    raise ValueError(
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
</code>```

My X_test df is the same as X_train with the addition of a Survived feature.

Survived (i64)
Pclass (i64)
Sex (i16)
Age (i32)
Fare (i16)
Embarked (i16)
title (i16)
family_size (i64)
is_alone (i64)
age*class (i64)

null
3
0
1
0
1
1
2
1
0

...
...
...
...
...
...
...
...
...
...

shape (418,10)

Body:
I've been working through a notebook on Kaggle that used Pandas, and I wanted to refactor it to Polars.

The dataframes I'm working with look like this:

X_train

Pclass (i64)
Sex (i16)
Age (i32)
Fare (i16)
Embarked (i16)
title (i16)
family_size (i64)
is_alone (i64)
age*class (i64)

3
0
1
0
1
1
2
1
0

...
...
...
...
...
...
...
...
...

shape: (891,9)

y_train

Survived (i64)

0

1

...

shape: (891,1)

Kaggle has me creating a logistic regression with the following code:

logreg = LogisticRegression()
logreg.fit(X_train, Y_train)

It's my understanding that Polars dataframes don't work with sklearn, so I modified X_train and y_train to be numpy ndarrays like so:

logreg.fit(X_train.to_numpy(),y_train.to_numpy())

but then I get the following error:

>>> logreg.fit(X_train.to_numpy(),y_train.to_numpy())
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py:993: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
LogisticRegression()

I was going to try saying y_train.transpose(), but there's no mention of needing to reshape the Pandas dataframe so I'm wondering if a transpose is really necessary, or if I'm doing something else wrong.

Edit:

I added the numpy.ravel() function like this logreg.fit(X_train.to_numpy(),y_train.to_numpy().ravel()) and it seems to have worked, but now when I say
y_pred = logreg.predict(X_test.to_numpy()) I get the following error

>>>y_pred= logreg.predict(X_test.to_numpy())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/linear_model/_base.py", line 425, in predict
    scores = self.decision_function(X)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/linear_model/_base.py", line 407, in decision_function
    X = self._validate_data(X, accept_sparse="csr", reset=False)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/base.py", line 566, in _validate_data
    X = check_array(X, **check_params)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 800, in check_array
    _assert_all_finite(array, allow_nan=force_all_finite == "allow-nan")
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/sklearn/utils/validation.py", line 114, in _assert_all_finite
    raise ValueError(
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

My X_test df is the same as X_train with the addition of a Survived feature.

Survived (i64)
Pclass (i64)
Sex (i16)
Age (i32)
Fare (i16)
Embarked (i16)
title (i16)
family_size (i64)
is_alone (i64)
age*class (i64)

null
3
0
1
0
1
1
2
1
0

...
...
...
...
...
...
...
...
...
...

shape (418,10)


问:
Diverting the output of a c++ that calls python mangles it
I have a c++ (VS2019) app

```<code>#include <stdio.h>
#include <Python.h>

void main(int argc, char *argv[])
{
    printf( "- before\n" );

    FILE* file;
    Py_SetPath( L"c:\\Python37\\Lib" );
    Py_Initialize();
    file = fopen( "abc.py", "r" );
    PyRun_SimpleFile( file, "abc.py" );
    Py_Finalize();

    printf( "- after\n" );

    return;
}
</code>```

that calls a python (3.10) script abc.py

```<code>print( "hi" );
</code>```

When run (on Win11) from cmd (main.exe), the output is:

```<code>- before
hi
- after
</code>```

However, when diverted into a file (main.exe > out.txt, or used in a pipe to tee), I get:

```<code>hi
- before
- after
</code>```

In my real app, where I interleave python with c++, the python output is printed after the script terminates (again, only when diverting the app's output).

Adding

setbuf( stdout, NULL );

, like @retired-ninja suggested, resolves the simple example above. However, in my more complicated app, it doesn't. I need to find a new simple example.

I only needed to add auto-flush to my python script to resolve the issue:

```<code>sys.stdout.reconfigure(line_buffering=True)
</code>```

Body:
I have a c++ (VS2019) app

#include <stdio.h>
#include <Python.h>

void main(int argc, char *argv[])
{
    printf( "- before\n" );

    FILE* file;
    Py_SetPath( L"c:\\Python37\\Lib" );
    Py_Initialize();
    file = fopen( "abc.py", "r" );
    PyRun_SimpleFile( file, "abc.py" );
    Py_Finalize();

    printf( "- after\n" );

    return;
}

that calls a python (3.10) script abc.py

print( "hi" );

When run (on Win11) from cmd (main.exe), the output is:

- before
hi
- after

However, when diverted into a file (main.exe > out.txt, or used in a pipe to tee), I get:

hi
- before
- after

In my real app, where I interleave python with c++, the python output is printed after the script terminates (again, only when diverting the app's output).

Adding

setbuf( stdout, NULL );

, like @retired-ninja suggested, resolves the simple example above. However, in my more complicated app, it doesn't. I need to find a new simple example.

I only needed to add auto-flush to my python script to resolve the issue:

sys.stdout.reconfigure(line_buffering=True)


问:
Why does my call to my local server take so long to return a result?
For some reason it takes forever to get to this endpoint and then run the validate function.

Everything works correctly, it's just slow when I delete the token from my localstorage. Not sure why this is taking so long to complete.....

It takes probably 10 seconds to hit my log out console log.

Is it my verifyToken middleware that is messing everything up? Or am I laying this out weirdly?

```<code>app.get('/testAuth', verifyToken, (req, res) => {
  try{
    return res.sendStatus(200)
  }
  catch(err) {
    res.send(404)
  }
})

function verifyToken(req, res) {
  if(!req.headers.authorization) {
    console.log('log out')
    res.sendStatus(403)
  }
  else {
    const bearerToken = req.headers.authorization.split(' ')[1];
    requestVerified = jwt.verify(bearerToken, process.env.TOKEN_KEY);
    console.log('request verified.')
}
</code>```

I tried restarting visual studio code, tried rearranging the code, tried sending different statuses and returning the status instead.

Body:
For some reason it takes forever to get to this endpoint and then run the validate function.

Everything works correctly, it's just slow when I delete the token from my localstorage. Not sure why this is taking so long to complete.....

It takes probably 10 seconds to hit my log out console log.

Is it my verifyToken middleware that is messing everything up? Or am I laying this out weirdly?

app.get('/testAuth', verifyToken, (req, res) => {
  try{
    return res.sendStatus(200)
  }
  catch(err) {
    res.send(404)
  }
})

function verifyToken(req, res) {
  if(!req.headers.authorization) {
    console.log('log out')
    res.sendStatus(403)
  }
  else {
    const bearerToken = req.headers.authorization.split(' ')[1];
    requestVerified = jwt.verify(bearerToken, process.env.TOKEN_KEY);
    console.log('request verified.')
}

I tried restarting visual studio code, tried rearranging the code, tried sending different statuses and returning the status instead.


问:
How to mock permission guard in Jest for NestJS?
In a project using NestJS and GraphQL. For authentication, using guard of NestJS. Then do an Unit test for the resolver function with permission. It's using Inject. But how to mock it correctly is a problem.

The NestJS code:

src/lib/auth/permission.ts

    import { applyDecorators, Inject, Injectable, Scope, UseGuards } from '@nestjs/common';
    import { CanActivate, ExecutionContext } from '@nestjs/common';
    import { PermissionManager } from './permissionManager';
    import { PERMISSION_MANAGER } from './permissionManager.module';

    @Injectable({ scope: Scope.REQUEST })
    export class PermissionScopeGuard implements CanActivate {
      constructor(
        @Inject(PERMISSION_MANAGER) private manager: PermissionManager,
      ) {}

      async canActivate(_context: ExecutionContext) {

        ......
        return true;
      }
    }

    export const PermissionScope = () => applyDecorators(UseGuards(PermissionScopeGuard));
```
<p>GraphQL resolver</p>
<p>src/resolver/query/post.ts</p>
<pre class="lang-js prettyprint-override"><code>    import { Args, Query, Resolver } from '@nestjs/graphql';

    import { Authorized } from '@lib/auth/authorized';
    import { PermissionScope } from '@lib/auth/permissionScope';

    @Resolver()
    export class PostsResolver {
      @PermissionScope()
      @Authorized([
        PermissionEnum.READ_MANAGEMENT,
      ])
      @Query()
      async findPosts() {
         return .....
      }
    }
</code>```

When write an unit test for this resolver

    import { Test, TestingModule } from '@nestjs/testing';

    import { PERMISSION_MANAGER } from '@lib/auth/permissionManager.module';
    import { PostsResolver } from '@resolver/query/post';
    ........

    describe('PostsResolver', () => {
      let resolver: PostsResolver;

      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          providers: [
            {
              provide: PERMISSION_MANAGER,
              useValue: jest.fn(),
            },
            ......
          ],
        }).compile();

        resolver = module.get<PostsResolver>(PostsResolver);
      });

      describe('findPosts', () => {
        it('should return data', async () => {
          const posts = await resolver.findPosts({
            id: '11111111-1111-1111-1111-111111111111',
          });

          const expected = [
            .....
          ];

          expect(posts).toEqual(expected);
        });
      });
    });
```

Since using @PermissionScope() decorater in the resolver, it's necessary to mock the permission, but only set the mock provider in the test above doesn't work. Then how to mock?

Body:
In a project using NestJS and GraphQL. For authentication, using guard of NestJS. Then do an Unit test for the resolver function with permission. It's using Inject. But how to mock it correctly is a problem.

The NestJS code:

src/lib/auth/permission.ts

    import { applyDecorators, Inject, Injectable, Scope, UseGuards } from '@nestjs/common';
    import { CanActivate, ExecutionContext } from '@nestjs/common';
    import { PermissionManager } from './permissionManager';
    import { PERMISSION_MANAGER } from './permissionManager.module';

    @Injectable({ scope: Scope.REQUEST })
    export class PermissionScopeGuard implements CanActivate {
      constructor(
        @Inject(PERMISSION_MANAGER) private manager: PermissionManager,
      ) {}

      async canActivate(_context: ExecutionContext) {

        ......
        return true;
      }
    }

    export const PermissionScope = () => applyDecorators(UseGuards(PermissionScopeGuard));

GraphQL resolver

src/resolver/query/post.ts

    import { Args, Query, Resolver } from '@nestjs/graphql';

    import { Authorized } from '@lib/auth/authorized';
    import { PermissionScope } from '@lib/auth/permissionScope';

    @Resolver()
    export class PostsResolver {
      @PermissionScope()
      @Authorized([
        PermissionEnum.READ_MANAGEMENT,
      ])
      @Query()
      async findPosts() {
         return .....
      }
    }

When write an unit test for this resolver

    import { Test, TestingModule } from '@nestjs/testing';

    import { PERMISSION_MANAGER } from '@lib/auth/permissionManager.module';
    import { PostsResolver } from '@resolver/query/post';
    ........

    describe('PostsResolver', () => {
      let resolver: PostsResolver;

      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          providers: [
            {
              provide: PERMISSION_MANAGER,
              useValue: jest.fn(),
            },
            ......
          ],
        }).compile();

        resolver = module.get<PostsResolver>(PostsResolver);
      });

      describe('findPosts', () => {
        it('should return data', async () => {
          const posts = await resolver.findPosts({
            id: '11111111-1111-1111-1111-111111111111',
          });

          const expected = [
            .....
          ];

          expect(posts).toEqual(expected);
        });
      });
    });

Since using @PermissionScope() decorater in the resolver, it's necessary to mock the permission, but only set the mock provider in the test above doesn't work. Then how to mock?


问:
How to save custom type array using FileManager?
I have this custom type FileManager

```<code>class Article: Identifiable, Hashable, Codable {
    static func == (lhs: Article, rhs: Article) -> Bool {
        lhs.title == rhs.title
    }
    var hashValue: Int {
          return self.id.hashValue
        }

    var id: UUID
    var title: String
    var text: String

    init(id: UUID, title: String, text: String) {
        self.id = id
        self.title = title
        self.text = text
    }
}
</code>```

And have this custom type array:

```<code>@State var articles = [Article]()
</code>```

I tried to save and loading it back using following method, but it doesn't work.
Here's what I have tried:

saving:

```<code>let fileManager = FileManager.default

let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first

let arrayURL = documentsDirectory?.appendingPathComponent("articles")

let arrayData = NSArray(array: articles).data(from: 0, to: articles.count)
let success = arrayData.write(to: arrayURL, atomically: true)
</code>```

loading it back:

```<code>let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
let arrayURL = documentsDirectory.appendingPathComponent("articles")
let arrayData = fileManager.data(contentsOf: arrayURL)
let myArray = NSArray.array(from: arrayData, of: [Article].self)
</code>```

But both of them doesn't work, can anyone help me with this?

EDIT:
I tried this solution but it didn't work: Whats the best practice to save and load array of struct?

Size of array is big. so using UserDefaults seems not a good option.
Experienced data loss and takes too long time saving it.(I'm trying ti save data moment before if app gonna crash.)

Body:
I have this custom type FileManager

class Article: Identifiable, Hashable, Codable {
    static func == (lhs: Article, rhs: Article) -> Bool {
        lhs.title == rhs.title
    }
    var hashValue: Int {
          return self.id.hashValue
        }

    var id: UUID
    var title: String
    var text: String

    init(id: UUID, title: String, text: String) {
        self.id = id
        self.title = title
        self.text = text
    }
}

And have this custom type array:

@State var articles = [Article]()

I tried to save and loading it back using following method, but it doesn't work.
Here's what I have tried:

saving:

let fileManager = FileManager.default

let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first

let arrayURL = documentsDirectory?.appendingPathComponent("articles")

let arrayData = NSArray(array: articles).data(from: 0, to: articles.count)
let success = arrayData.write(to: arrayURL, atomically: true)

loading it back:

let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
let arrayURL = documentsDirectory.appendingPathComponent("articles")
let arrayData = fileManager.data(contentsOf: arrayURL)
let myArray = NSArray.array(from: arrayData, of: [Article].self)

But both of them doesn't work, can anyone help me with this?

EDIT:
I tried this solution but it didn't work: Whats the best practice to save and load array of struct?

Size of array is big. so using UserDefaults seems not a good option.
Experienced data loss and takes too long time saving it.(I'm trying ti save data moment before if app gonna crash.)


问:
Video Cues not playing on time in p5js WEBGL
Im curently working on a 3d project where at a certain point in the video the user can press a button for a caption and a cue'd caption will appear. the cue's and the texts are in a function that is called in draw when a button is pressed. When i press the button all the cues play, for instance the cue is set to 3.0 if I press a button at 1.0 it still appears.
`

```<code>
let stamps = [0.0,0.1,1.0,];
let ppress = true;
let isplaying=true;
function preload() {
  vid = createVideo('clouds.mp4');
   did = createAudio('clouds.mp4');
  vid.showControls();
  fonta = loadFont('Exo-Regular.otf');
}
function setup() {
  createCanvas(710, 400, WEBGL);

 frameRate(30);

  vid.loop();

  textFont(fonta);
  textSize(60)
  color('white');
  vid.play().time(0);
}

let cap = ['caption0','caption1','caption2'];

function draw() {

translate(0,0,-900);
  sequence();

   if (keyIsPressed === true) {

  }

  orbitControl(2,2,0);
 texture(vid);
 noStroke();
  sphere(outerWidth);

}
function sequence(){

 if (isplaying ===  false){

   translate(0,0,90);
   id0= vid.addCue(stamps(0),captions(0));
   id1= vid.addCue(stamps(1),captions(1));

  }
}
function captions(x){

    text(cap[x],0,0);
}

function keyPressed(){

    if (isplaying === true){

    vid.pause();
    isplaying=false;
    }else{
    vid.play();
    isplaying = true}

}

</code>```

`

I tried changing the cues around and even just putting them in draw or in set up but still no luck.

Body:
Im curently working on a 3d project where at a certain point in the video the user can press a button for a caption and a cue'd caption will appear. the cue's and the texts are in a function that is called in draw when a button is pressed. When i press the button all the cues play, for instance the cue is set to 3.0 if I press a button at 1.0 it still appears.
`

let stamps = [0.0,0.1,1.0,];
let ppress = true;
let isplaying=true;
function preload() {
  vid = createVideo('clouds.mp4');
   did = createAudio('clouds.mp4');
  vid.showControls();
  fonta = loadFont('Exo-Regular.otf');
}
function setup() {
  createCanvas(710, 400, WEBGL);

 frameRate(30);

  vid.loop();

  textFont(fonta);
  textSize(60)
  color('white');
  vid.play().time(0);
}

let cap = ['caption0','caption1','caption2'];

function draw() {

translate(0,0,-900);
  sequence();

   if (keyIsPressed === true) {

  }

  orbitControl(2,2,0);
 texture(vid);
 noStroke();
  sphere(outerWidth);

}
function sequence(){

 if (isplaying ===  false){

   translate(0,0,90);
   id0= vid.addCue(stamps(0),captions(0));
   id1= vid.addCue(stamps(1),captions(1));

  }
}
function captions(x){

    text(cap[x],0,0);
}

function keyPressed(){

    if (isplaying === true){

    vid.pause();
    isplaying=false;
    }else{
    vid.play();
    isplaying = true}

}

`

I tried changing the cues around and even just putting them in draw or in set up but still no luck.


问:
python-docx how to add space before/after a table
I have a table defined in python-docx. To add a bit of space before/after that table, I'm just using an empty paragraph. That's ok but I would like to add a half/line worth space instead of a full line's worth of space.

Found these:

http://www.datypic.com/sc/ooxml/a-w_topFromText-1.html

http://www.datypic.com/sc/ooxml/a-w_bottomFromText-1.html

Both are part of tblpPr:

http://www.datypic.com/sc/ooxml/e-w_tblpPr-1.html

These seem to do exactly what I want. But I haven't been able to figure out how to add those attributes.

I have tried:

tbl._tblPr.set(qn('w:bottomFromText'), '1440')
Note the tbl._tblPr is defined and accessible in Python but it does not generate any extra space. Note the units for 1440 are "twentieths of point".

What am I doing wrong?


问:
OpenCV: Segmentation Fault with destroyAllWindows()
I am writing a program which displays a video, and when the user presses the 'q' key on their keyboard it displays that frame and records 4 of the user's clicks on the image. However, when I have clicked the 4 points, it randomly throws a Segmentation Fault. I have narrowed the issue down to the cv2.destroyAllWindows line in calibrate.py. Any help/improvements would be really helpful!

Software details:

Python 3.9.2

Raspbian 64-bit OS

OpenCV version 4.6.0.66

test.py

```<code>import cv2
import calibrate

path = "crowd.mp4"

cap = cv2.VideoCapture(path)

while(cap.isOpened()):
    ret, frame = cap.read()
    if frame is None:
        continue

    frame = cv2.resize(frame, (640, 480), cv2.INTER_AREA)
    cv2.imshow("output", frame)

    if cv2.waitKey(1) & 0xFF == ord('q' or 'Q'):
        calibrate.main(frame)
        break
        cv2.destroyWindow("output")

cap.release()
</code>```

calibrate.py

```<code>import cv2

cnt = 0

def click_event(event, x, y, flags, params):
    global cnt

    if cnt == 4:
        cv2.destroyWindow("image")
        return None

    if event == cv2.EVENT_LBUTTONDOWN:
        cnt += 1
        #cv2.circle(img, (x,y), (0,0,255), 5, -1)
        print(x,y)

def main(img):

    cv2.imshow('image', img)
    cv2.setMouseCallback('image', click_event)
    cv2.waitKey(0)

if __name__=="__main__":
    main()
</code>```

Body:
I am writing a program which displays a video, and when the user presses the 'q' key on their keyboard it displays that frame and records 4 of the user's clicks on the image. However, when I have clicked the 4 points, it randomly throws a Segmentation Fault. I have narrowed the issue down to the cv2.destroyAllWindows line in calibrate.py. Any help/improvements would be really helpful!

Software details:

Python 3.9.2

Raspbian 64-bit OS

OpenCV version 4.6.0.66

test.py

import cv2
import calibrate

path = "crowd.mp4"

cap = cv2.VideoCapture(path)

while(cap.isOpened()):
    ret, frame = cap.read()
    if frame is None:
        continue

    frame = cv2.resize(frame, (640, 480), cv2.INTER_AREA)
    cv2.imshow("output", frame)

    if cv2.waitKey(1) & 0xFF == ord('q' or 'Q'):
        calibrate.main(frame)
        break
        cv2.destroyWindow("output")

cap.release()

calibrate.py

import cv2

cnt = 0

def click_event(event, x, y, flags, params):
    global cnt

    if cnt == 4:
        cv2.destroyWindow("image")
        return None

    if event == cv2.EVENT_LBUTTONDOWN:
        cnt += 1
        #cv2.circle(img, (x,y), (0,0,255), 5, -1)
        print(x,y)

def main(img):

    cv2.imshow('image', img)
    cv2.setMouseCallback('image', click_event)
    cv2.waitKey(0)

if __name__=="__main__":
    main()


问:
How to create a linked database via Notion API?
Manually, I can create a linked database (see the attached image) and then put it under a page, in notion. So far, so good. On the attached image, you can see the arrow on the left and it shows that this is a linked database.

When I fetch that block via Notion API, I see that this block type is called "child_database". My goal is to create that "child_database" via API.

Notion API tells me that I need to create a database and then update it to create a child database. But, when I do that, it does NOT create a linked database, it creates a NEW database.

So, my question is how to create a linked database via Notion API?


问:
Discord message not sending, but API is connecting. I am currently using the client send method and it will not send. Any help appreciated
```<code># Import the discord.py library
import discord

# Create a new Discord client
intents = discord.Intents()
intents.guilds = True
intents.guild_messages = True
client = discord.Client(intents=intents)

# Define the bot token
bot_token = "token"

# Define the channel ID
channel_id = "channelid"

# Run the client
@client.event
async def on_ready():
    # Print a message to indicate that the bot is ready
    print("Bot is ready.")

    # Get the channel object
    channel = client.get_channel(channel_id)

    # Check if the channel object is None
    if channel is None:
        return

    # Use the client.send() method to send a message to the channel
    await client.send(channel, "Hello, this is a test message")

# Authenticate the bot
client.run(bot_token)
</code>```

Any help appreciated

I was trying to send a standard message through discord bot, but it would not work and has left me stuck. It connects to the API, comes online, and then just runs until I kill the CMD line. Im unsure how to fix it and have searched on the internet with no luck. I assume its something that I havent added to do with my python scripting

Body:
# Import the discord.py library
import discord

# Create a new Discord client
intents = discord.Intents()
intents.guilds = True
intents.guild_messages = True
client = discord.Client(intents=intents)

# Define the bot token
bot_token = "token"

# Define the channel ID
channel_id = "channelid"

# Run the client
@client.event
async def on_ready():
    # Print a message to indicate that the bot is ready
    print("Bot is ready.")

    # Get the channel object
    channel = client.get_channel(channel_id)

    # Check if the channel object is None
    if channel is None:
        return

    # Use the client.send() method to send a message to the channel
    await client.send(channel, "Hello, this is a test message")

# Authenticate the bot
client.run(bot_token)

Any help appreciated

I was trying to send a standard message through discord bot, but it would not work and has left me stuck. It connects to the API, comes online, and then just runs until I kill the CMD line. Im unsure how to fix it and have searched on the internet with no luck. I assume its something that I havent added to do with my python scripting


问:
Is it possible to load a floating-point immediate value into a register using local variables?
I know that it isn't possible to load an immediate value directly into a register in x64 assembly. I do know, however, that we can declare a global variable in the .data segment of a program, then load that value into a register. What I'm curious about, on the other hand, is the possibility of storing these values as local variables to a function on the stack (just like we can for word-sized integers). I'm writing a small compiler with a desire to support floating-point values, and would rather not have to write all variables out to global static memory (but I suppose I can if that's the only way).


问:
What caused the list elements split into individual letters?
In the following code, by mistake, I used string concatenation on a variable defined as a list. Instead of giving an error, it split up the list elements into individual letters. What causes this? is it supposed to do this?

```<code>def strList(spam):

    #x = ''  <--- I meant say x is empty string but erroneously said a blank *list*
    x = []
    for i in range(len(spam)-1):
        x += (spam[i]+',')
    x += ('and '+spam[len(spam)-1])
    return x

spam = ['apples', 'bananas', 'tofu', 'cats', 'dogs', 'elephants']
print(strList(spam))
</code>```

The answer it gave was ['a', 'p', 'p', 'l', 'e', 's', ',', 'b', 'a', 'n', 'a', 'n', 'a', 's', ',', 't', 'o', 'f', 'u', ',', 'c', 'a', 't', 's', ',', 'd', 'o', 'g', 's', ',', 'a', 'n', 'd', ' ', 'e', 'l', 'e', 'p', 'h', 'a', 'n', 't', 's'] instead of an error.

Body:
In the following code, by mistake, I used string concatenation on a variable defined as a list. Instead of giving an error, it split up the list elements into individual letters. What causes this? is it supposed to do this?

def strList(spam):

    #x = ''  <--- I meant say x is empty string but erroneously said a blank *list*
    x = []
    for i in range(len(spam)-1):
        x += (spam[i]+',')
    x += ('and '+spam[len(spam)-1])
    return x

spam = ['apples', 'bananas', 'tofu', 'cats', 'dogs', 'elephants']
print(strList(spam))

The answer it gave was ['a', 'p', 'p', 'l', 'e', 's', ',', 'b', 'a', 'n', 'a', 'n', 'a', 's', ',', 't', 'o', 'f', 'u', ',', 'c', 'a', 't', 's', ',', 'd', 'o', 'g', 's', ',', 'a', 'n', 'd', ' ', 'e', 'l', 'e', 'p', 'h', 'a', 'n', 't', 's'] instead of an error.


问:
What is the difference between System Variables and Enviroment Variable?
it is challenging to find difference between system variable and Environment variable

I used environment variables in the past. Now I am unable to create them but system variables. Hence want to know the difference


问:
There are 50 courses and 500 students. Ecah student will register 5 course from it. How could I tell if there exsit a time table with no conflict?
I am doing a project that makes a course-table(location and time) for students that minimize their walking distance by using genetic algorithm.

There are 500 students and each of them will register for 3 mandatory courses out of 10 courses, and 2 elective courses out of 40 courses. So 50 courses in total and each student will have 5 classes to take.

For example:

student1 = [(math100,0), (phys100,1), (chem100,2), (art100,3), (hist100,4)].
This means for student1, his first class is math100, his second class is phys100 and etc.

And the course-table will looks like:

```<code>|        Course       |      Location    |  Time Section    |
|---------------------|------------------|------------------|
|       math 100      |     Building A   |        0         |
|       phys 100      |     Building B   |        1         |
|       chem 100      |     Building C   |        2         |
</code>```

The problem I am facing right now is, how I know if there exists a course-table such that there is no time conflict for every student. By time conflict, I mean if there exist a student such that:

student1 = [(math100,0), (phys100,0), (chem100,2), (art100,2), (hist100,4)], then there is a time conflict.

To clarify, my question is given students like below:

```<code>student_1 = [`(math100)`, `(phys100)`, `(chem100)`, `(art100)`, `(hist100)`]
student_2 = [`(math101)`, `(phys101)`, `(chem101)`, `(art101)`, `(hist101)`]
...
student_n = [`(math100)`, `(phys100)`, `(chem100)`, `(art100)`, `(hist100)`]
</code>```

How do I know if there exists a course-table that there is no time conflict?

Hoping for your ideas/helps!

Body:
I am doing a project that makes a course-table(location and time) for students that minimize their walking distance by using genetic algorithm.

There are 500 students and each of them will register for 3 mandatory courses out of 10 courses, and 2 elective courses out of 40 courses. So 50 courses in total and each student will have 5 classes to take.

For example:

student1 = [(math100,0), (phys100,1), (chem100,2), (art100,3), (hist100,4)].
This means for student1, his first class is math100, his second class is phys100 and etc.

And the course-table will looks like:

|        Course       |      Location    |  Time Section    |
|---------------------|------------------|------------------|
|       math 100      |     Building A   |        0         |
|       phys 100      |     Building B   |        1         |
|       chem 100      |     Building C   |        2         |

The problem I am facing right now is, how I know if there exists a course-table such that there is no time conflict for every student. By time conflict, I mean if there exist a student such that:

student1 = [(math100,0), (phys100,0), (chem100,2), (art100,2), (hist100,4)], then there is a time conflict.

To clarify, my question is given students like below:

student_1 = [`(math100)`, `(phys100)`, `(chem100)`, `(art100)`, `(hist100)`]
student_2 = [`(math101)`, `(phys101)`, `(chem101)`, `(art101)`, `(hist101)`]
...
student_n = [`(math100)`, `(phys100)`, `(chem100)`, `(art100)`, `(hist100)`]

How do I know if there exists a course-table that there is no time conflict?

Hoping for your ideas/helps!


问:
Why Err is greater than Ok whilst Some is greater than None in Rust?
In Rust, the following is satisfied (as far as inner type(s) can be comparable):

Option::None < Option::Some(x) for any x

Result::Ok(x) < Result::Err(y) for any (x, y)

As both Option and Result just #[derive(PartialOrd, Ord, PartialEq, Eq)] (source1, source2), the relationship above comes purely from the declaration order:

pub enum Result<T, E> {
    Ok(T),  //1st
    Err(E), //2nd
}
```
<pre class="lang-rust prettyprint-override"><code>pub enum Option<T> {
    None,    //1st
    Some(T), //2nd
}
</code>```

I personally feel some sort of inconsistency. In other words, to me, None < Some is very intuitive while Ok < Err is not.

Is there any advantage to make Err greater than Ok?

Body:
In Rust, the following is satisfied (as far as inner type(s) can be comparable):

Option::None < Option::Some(x) for any x

Result::Ok(x) < Result::Err(y) for any (x, y)

As both Option and Result just #[derive(PartialOrd, Ord, PartialEq, Eq)] (source1, source2), the relationship above comes purely from the declaration order:

pub enum Result<T, E> {
    Ok(T),  //1st
    Err(E), //2nd
}

pub enum Option<T> {
    None,    //1st
    Some(T), //2nd
}

I personally feel some sort of inconsistency. In other words, to me, None < Some is very intuitive while Ok < Err is not.

Is there any advantage to make Err greater than Ok?


问:
Windowing functions perform poorly after upgrade from SQL Server 2012 to SQL Server 2016
I am currently involved in the upgrade of a server from Microsoft SQL Server 2012 to 2016. Following the upgrade, we are finding that objects with windowing functions are behaving very poorly.

By "windowing functions," I mean statements like ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) or LAG(...) OVER (PARTITION BY ... ORDER BY ...).

We can fix the performance issues by replacing these functions with MIN/MAX and extra joins.

For example, something like this behaves poorly:

```<code>FROM
    table1 AS t1
LEFT JOIN
    (SELECT
         t2.ID,
         ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t2.ROW_ID DESC) AS RowNum
     FROM
         table2 AS t2
     WHERE
         t2.flag = -1) AS t2Rollup ON t2Rollup.RowNum = 1
                                   AND t2Rollup.ID = t1.ID
WHERE
    t1.ID LIKE '%042'
</code>```

Changing it to this dramatically improves performance:

```<code>FROM
    table1 AS t1
LEFT JOIN
    (SELECT
         t2.ID,
         MAX(t2.ROW_ID) AS MaxRowID
     FROM
         table2 AS t2
     WHERE
         t2.flag = -1
     GROUP BY
         t2.ID) AS MaxRow ON MaxRow.ID = t1.ID
LEFT JOIN
    table2 AS t2Rollup ON t2Rollup.ID = MaxRow.ID
                       AND t2Rollup.ROW_ID = MaxRow.MaxRowID
WHERE
    t1.ID LIKE '%042'
</code>```

In these examples, table1 has 1 row per ID, and table2 has multiple rows per ID but unique ROW_IDs. I include the WHERE to insinuate that there are many more IDs in the tables than ultimately need to be considered for the output.

Inspecting the execution plan suggests that in the first case, SQL Server is sorting many more rows than actually need to be considered for the final query. I.e., it is sorting rows where t1.ID does not end in '042'. Even if I'm wrong about that, it is definitely spending a lot of time sorting.

One final clue, I think (but am not 100% sure) that we did not have this problem immediately following the upgrade. However, we were having other problems, notably with queries involving table variables, so we tried first turning Legacy Cardinality Estimation on, then turning that off and changing the compatibility level to SQL Server 2012 (110). After changing that setting, this problem appeared across many procedures.

My question is this: is anyone aware of database-wide configuration issue or settings that could explain this problem? I do not think it's an issue with the specific procedures, as they worked fine on our SQL Server 2012 instances. I do think there's a more than decent chance of something being wrong with configuration settings on the server or databases.

I have so far simply been replacing window functions with schemes based on MIN/MAX and multiple subqueries. I have inspected database configuration settings but was not able to come up with ideas.

Body:
I am currently involved in the upgrade of a server from Microsoft SQL Server 2012 to 2016. Following the upgrade, we are finding that objects with windowing functions are behaving very poorly.

By "windowing functions," I mean statements like ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) or LAG(...) OVER (PARTITION BY ... ORDER BY ...).

We can fix the performance issues by replacing these functions with MIN/MAX and extra joins.

For example, something like this behaves poorly:

FROM
    table1 AS t1
LEFT JOIN
    (SELECT
         t2.ID,
         ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t2.ROW_ID DESC) AS RowNum
     FROM
         table2 AS t2
     WHERE
         t2.flag = -1) AS t2Rollup ON t2Rollup.RowNum = 1
                                   AND t2Rollup.ID = t1.ID
WHERE
    t1.ID LIKE '%042'

Changing it to this dramatically improves performance:

FROM
    table1 AS t1
LEFT JOIN
    (SELECT
         t2.ID,
         MAX(t2.ROW_ID) AS MaxRowID
     FROM
         table2 AS t2
     WHERE
         t2.flag = -1
     GROUP BY
         t2.ID) AS MaxRow ON MaxRow.ID = t1.ID
LEFT JOIN
    table2 AS t2Rollup ON t2Rollup.ID = MaxRow.ID
                       AND t2Rollup.ROW_ID = MaxRow.MaxRowID
WHERE
    t1.ID LIKE '%042'

In these examples, table1 has 1 row per ID, and table2 has multiple rows per ID but unique ROW_IDs. I include the WHERE to insinuate that there are many more IDs in the tables than ultimately need to be considered for the output.

Inspecting the execution plan suggests that in the first case, SQL Server is sorting many more rows than actually need to be considered for the final query. I.e., it is sorting rows where t1.ID does not end in '042'. Even if I'm wrong about that, it is definitely spending a lot of time sorting.

One final clue, I think (but am not 100% sure) that we did not have this problem immediately following the upgrade. However, we were having other problems, notably with queries involving table variables, so we tried first turning Legacy Cardinality Estimation on, then turning that off and changing the compatibility level to SQL Server 2012 (110). After changing that setting, this problem appeared across many procedures.

My question is this: is anyone aware of database-wide configuration issue or settings that could explain this problem? I do not think it's an issue with the specific procedures, as they worked fine on our SQL Server 2012 instances. I do think there's a more than decent chance of something being wrong with configuration settings on the server or databases.

I have so far simply been replacing window functions with schemes based on MIN/MAX and multiple subqueries. I have inspected database configuration settings but was not able to come up with ideas.


问:
Why is there no duplication when using offset limit in querydsl fetchjoin statement?
Classes

```<code>@Getter
@NoArgsConstructor
@Entity
@Table
public class Classes {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String className;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "classes", orphanRemoval = true)
    private List<Teacher> teachers;

    @Builder
    public Classes(String className, List<Teacher> teachers) {
        this.className = className;
        this.teachers = teachers;
    }

    public void updateTeachers(List<Teacher> teachers) {
        teachers.forEach(teacher -> teacher.updateClasses(this));
        this.teachers = teachers;
    }
}

</code>```

Teacher

```<code>@Getter
@NoArgsConstructor
@Entity
@Table
public class Teacher {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "classes_id", referencedColumnName = "id")
    private Classes classes;

    @Builder
    public Teacher(String name, Integer age, Classes classes) {
        this.name = name;
        this.age = age;
        this.classes = classes;
    }

    public void updateClasses(Classes classes) {
        this.classes = classes;
    }
}
</code>```

ClassesQueryDsl

```<code>public class ClassesCustomRepositoryImpl extends QuerydslRepositorySupport implements ClassesCustomRepository  {

    @Override
    public List<Classes> findAllNoPageFetchJoin() {
        return from(classes)
                .leftJoin(classes.teachers).fetchJoin()
                .fetch();
    }

}

</code>```

Test Code

```<code>@Test
void findAllNoPageFetchJoin() {
    // given
    List<InputRequest.TeacherRequest> teacherRequests = List.of(InputRequest.TeacherRequest.builder()
                    .age(12)
                    .name("name")
                    .build(), InputRequest.TeacherRequest.builder()
                    .age(23)
                    .name("name2")
                    .build(),
            InputRequest.TeacherRequest.builder()
                    .age(41)
                    .name("wedul")
                    .build()
    );

    List<InputRequest.TeacherRequest> teacherRequests2 = List.of(InputRequest.TeacherRequest.builder()
                    .age(22)
                    .name("name4")
                    .build(), InputRequest.TeacherRequest.builder()
                    .age(33)
                    .name("name5")
                    .build(),
            InputRequest.TeacherRequest.builder()
                    .age(44)
                    .name("name6")
                    .build()
    );

    // when
    sut.insert(InputRequest.builder()
            .className("1")
            .teacherRequestList(teacherRequests)
            .build());
    sut.insert(InputRequest.builder()
            .className("2")
            .teacherRequestList(teacherRequests2)
            .build());

    // then
    List<Classes> savedData = classesRepository.findAllNoPageFetchJoin();

    assertThat(savedData).hasSize(6);
}
</code>```

result count image

An entity has a oneToMany relationship between classes and teachers.

When bringing classes using querydsl, duplicate classes are brought as many as the number of teachers.

[result]

class id : 1,  List<> teach id : 1,2,3

class id : 1,  List<> teach id : 1,2,3

class id : 1,  List<> teach id : 1,2,3

class id : 2,  List<> teach id : 4,5,6

class id : 2,  List<> teach id : 4,5,6

class id : 2,  List<> teach id : 4,5,6

However, if only the offset limit is attached to the same querydsl statement, the value is not duplicated.

Rows with the same class id are not paginated as much as the number of teach, but classes with duplicates removed are paginated and exposed.

QueryDsl

```<code>@Override
public List<Classes> findAllPageFetchJoin(int offset, int limit) {
    return from(classes)
            .leftJoin(classes.teachers).fetchJoin()
            .offset(offset)
            .limit(limit)
            .fetch();
}
</code>```

result count image

[result]

class id : 1, List<> : teach id : 1,2,3

class id : 2, List<> : teach id : 4,5,6

I know that the application handles paging when I do offset limit in fetch join, but I don't know why duplicates became distinct.

Thanks in advance.

Body:
Classes

@Getter
@NoArgsConstructor
@Entity
@Table
public class Classes {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String className;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "classes", orphanRemoval = true)
    private List<Teacher> teachers;

    @Builder
    public Classes(String className, List<Teacher> teachers) {
        this.className = className;
        this.teachers = teachers;
    }

    public void updateTeachers(List<Teacher> teachers) {
        teachers.forEach(teacher -> teacher.updateClasses(this));
        this.teachers = teachers;
    }
}

Teacher

@Getter
@NoArgsConstructor
@Entity
@Table
public class Teacher {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "classes_id", referencedColumnName = "id")
    private Classes classes;

    @Builder
    public Teacher(String name, Integer age, Classes classes) {
        this.name = name;
        this.age = age;
        this.classes = classes;
    }

    public void updateClasses(Classes classes) {
        this.classes = classes;
    }
}

ClassesQueryDsl

public class ClassesCustomRepositoryImpl extends QuerydslRepositorySupport implements ClassesCustomRepository  {

    @Override
    public List<Classes> findAllNoPageFetchJoin() {
        return from(classes)
                .leftJoin(classes.teachers).fetchJoin()
                .fetch();
    }

}

Test Code

@Test
void findAllNoPageFetchJoin() {
    // given
    List<InputRequest.TeacherRequest> teacherRequests = List.of(InputRequest.TeacherRequest.builder()
                    .age(12)
                    .name("name")
                    .build(), InputRequest.TeacherRequest.builder()
                    .age(23)
                    .name("name2")
                    .build(),
            InputRequest.TeacherRequest.builder()
                    .age(41)
                    .name("wedul")
                    .build()
    );

    List<InputRequest.TeacherRequest> teacherRequests2 = List.of(InputRequest.TeacherRequest.builder()
                    .age(22)
                    .name("name4")
                    .build(), InputRequest.TeacherRequest.builder()
                    .age(33)
                    .name("name5")
                    .build(),
            InputRequest.TeacherRequest.builder()
                    .age(44)
                    .name("name6")
                    .build()
    );

    // when
    sut.insert(InputRequest.builder()
            .className("1")
            .teacherRequestList(teacherRequests)
            .build());
    sut.insert(InputRequest.builder()
            .className("2")
            .teacherRequestList(teacherRequests2)
            .build());

    // then
    List<Classes> savedData = classesRepository.findAllNoPageFetchJoin();

    assertThat(savedData).hasSize(6);
}

result count image

An entity has a oneToMany relationship between classes and teachers.

When bringing classes using querydsl, duplicate classes are brought as many as the number of teachers.

[result]

class id : 1,  List<> teach id : 1,2,3

class id : 1,  List<> teach id : 1,2,3

class id : 1,  List<> teach id : 1,2,3

class id : 2,  List<> teach id : 4,5,6

class id : 2,  List<> teach id : 4,5,6

class id : 2,  List<> teach id : 4,5,6

However, if only the offset limit is attached to the same querydsl statement, the value is not duplicated.

Rows with the same class id are not paginated as much as the number of teach, but classes with duplicates removed are paginated and exposed.

QueryDsl

@Override
public List<Classes> findAllPageFetchJoin(int offset, int limit) {
    return from(classes)
            .leftJoin(classes.teachers).fetchJoin()
            .offset(offset)
            .limit(limit)
            .fetch();
}

result count image

[result]

class id : 1, List<> : teach id : 1,2,3

class id : 2, List<> : teach id : 4,5,6

I know that the application handles paging when I do offset limit in fetch join, but I don't know why duplicates became distinct.

Thanks in advance.