问:
Track particle status, brownian walkers
I am simulating 1D heat conduction using brownian motion in python. The question here is to track if the particle pass the inerface of the left or right cell. I have to count it somehow, could you please purpose solution or I should update code concept(rethink model).

Short desciption: Medium is consist of cell, in each cell it has own quantity of particles. The particles are moving from one cell to another. First and last cell has constant quantity of particle (in this case 500 and 0). Result gives the tempertaure profile along x. If we know the number of particles that are pass the interface of the cell (left or right) we might find Heat flux.
Edit: I've made counting of particle pass throught interface (from right or left). But in "theory" the value of Heat Flux should me constant. So, I gues there is the problem with my code(specified code excerpt). Could you please review it. Am I counting right?

Edit code:

```<code>import numpy as np
import matplotlib.pyplot as plt

def Cell_dist(a, dx):

    res = [[] for i in range(N)]

    for i in range(N):
        for value in a:
            if dx*i < value < dx*i+dx:
                res[i].append(value)

    return res

L = 0.2 # length of the medium
N = 10 # number of cells
dx = L/N # cell dimension

dt = 1 # time step

dur = 60 # duration

M = 20  # number of particles

ro =  8930 # density
k = 391 # thermal conductivity
C_p = 380 # specific heat capacity

T_0 = 100  # maintained temperature
T_r = 0 # reference temperature
DT = T_0 - T_r # characteristic temperature

a = k / ro / C_p # thermal diffusivity of the copper
dh_r = ro * C_p * dx * DT / M # refernce elementary enthalpy

c = (2*a*dt)**(1/2) # diffusion length

pos = [[] for i in range(N)] # creating cells

for time_step in range(dur):

    M_plus = [[] for i in range(N-1)]
    M_minus = [[] for i in range(N-1)]
    flux = [0] * (N-1)

    unirnd = np.random.uniform(0,dx, M).tolist() # uniform random distribution
    pos[0] = unirnd # 1st cell BC

    pos[-1] = []    # last cell BC at T_r = 0

    curr_pos = sorted([x for sublist in pos for x in sublist]) # flatten list of particles (concatenation)

    M_t = len(curr_pos)  # number of particles at instant time step

    pos_tmp = []

    # Move each particle
    for i in range(M_t):

        normal_distr = np.random.default_rng().normal(0,1)

        displacement = c*normal_distr

        final_pos = curr_pos[i] + displacement

        pos_tmp.append(final_pos)

        #HERE is the question________________________
        if normal_distr > 0:
            for i in range(1,len(M_plus)-1):
                if i*dx < final_pos < (i+1)*dx:
                    M_plus[i-1].append(1)
        else:
            for i in range(len(M_minus)):
                if i*dx < final_pos < (i+1)*dx:
                    M_minus[i].append(1)
        #END of the question________________________
        for i in range(N-1):
            flux[i] = (len(M_plus[i])-len(M_minus[i]))*dh_r/dt/1000

    pos_new = Cell_dist(pos_tmp,dx)
    pos_new[0] = unirnd

    pos = pos_new

    walker_number_in_cell = []
    for i in range(N):
        walker_number_in_cell.append(len(pos[i]))

    T_n = []
    for num in  walker_number_in_cell:
        T_n.append(T_r + num*dh_r/ro/C_p/dx)

# __________Plotting FLUX profile__________

x_a = [0]*(N-1)
for i in range(0, N-1):
    x_a[i] = "{}".format(i+1)+"_{}".format(i+2)

plt.plot(x_a,flux[0:N-1],'-')
plt.xlabel('Interface')
plt.ylabel('Flux')

plt.show()
</code>```

Title: Track particle status, brownian walkers

Body:
I am simulating 1D heat conduction using brownian motion in python. The question here is to track if the particle pass the inerface of the left or right cell. I have to count it somehow, could you please purpose solution or I should update code concept(rethink model).

Short desciption: Medium is consist of cell, in each cell it has own quantity of particles. The particles are moving from one cell to another. First and last cell has constant quantity of particle (in this case 500 and 0). Result gives the tempertaure profile along x. If we know the number of particles that are pass the interface of the cell (left or right) we might find Heat flux.
Edit: I've made counting of particle pass throught interface (from right or left). But in "theory" the value of Heat Flux should me constant. So, I gues there is the problem with my code(specified code excerpt). Could you please review it. Am I counting right?

Edit code:

import numpy as np
import matplotlib.pyplot as plt

def Cell_dist(a, dx):

    res = [[] for i in range(N)]

    for i in range(N):
        for value in a:
            if dx*i < value < dx*i+dx:
                res[i].append(value)

    return res

L = 0.2 # length of the medium
N = 10 # number of cells
dx = L/N # cell dimension

dt = 1 # time step

dur = 60 # duration

M = 20  # number of particles

ro =  8930 # density
k = 391 # thermal conductivity
C_p = 380 # specific heat capacity

T_0 = 100  # maintained temperature
T_r = 0 # reference temperature
DT = T_0 - T_r # characteristic temperature

a = k / ro / C_p # thermal diffusivity of the copper
dh_r = ro * C_p * dx * DT / M # refernce elementary enthalpy

c = (2*a*dt)**(1/2) # diffusion length

pos = [[] for i in range(N)] # creating cells

for time_step in range(dur):

    M_plus = [[] for i in range(N-1)]
    M_minus = [[] for i in range(N-1)]
    flux = [0] * (N-1)

    unirnd = np.random.uniform(0,dx, M).tolist() # uniform random distribution
    pos[0] = unirnd # 1st cell BC

    pos[-1] = []    # last cell BC at T_r = 0

    curr_pos = sorted([x for sublist in pos for x in sublist]) # flatten list of particles (concatenation)

    M_t = len(curr_pos)  # number of particles at instant time step

    pos_tmp = []

    # Move each particle
    for i in range(M_t):

        normal_distr = np.random.default_rng().normal(0,1)

        displacement = c*normal_distr

        final_pos = curr_pos[i] + displacement

        pos_tmp.append(final_pos)

        #HERE is the question________________________
        if normal_distr > 0:
            for i in range(1,len(M_plus)-1):
                if i*dx < final_pos < (i+1)*dx:
                    M_plus[i-1].append(1)
        else:
            for i in range(len(M_minus)):
                if i*dx < final_pos < (i+1)*dx:
                    M_minus[i].append(1)
        #END of the question________________________
        for i in range(N-1):
            flux[i] = (len(M_plus[i])-len(M_minus[i]))*dh_r/dt/1000

    pos_new = Cell_dist(pos_tmp,dx)
    pos_new[0] = unirnd

    pos = pos_new

    walker_number_in_cell = []
    for i in range(N):
        walker_number_in_cell.append(len(pos[i]))

    T_n = []
    for num in  walker_number_in_cell:
        T_n.append(T_r + num*dh_r/ro/C_p/dx)

# __________Plotting FLUX profile__________

x_a = [0]*(N-1)
for i in range(0, N-1):
    x_a[i] = "{}".format(i+1)+"_{}".format(i+2)

plt.plot(x_a,flux[0:N-1],'-')
plt.xlabel('Interface')
plt.ylabel('Flux')

plt.show()


来源: stackexchange

问:
How to scroll smoothly to a specific section and not JUMP using JAVASCRIPT?
I want to make my navbar so when one of the option in the navbar is clicked the page would scroll smoothly and NOT JUMP IMMEDIATELY to that specific section in the page, for example when i click contact on my navbar the page would scroll down to the contact section in the same page.

How to make something like that USING JAVASCRIPT and not CSS, can anyone help me ?

Here's my HTML code for the nav bar:

```<code><ul id="navbar__list">
    <li><a class="menu__link" href="#section1">Section 1</a></li>
    <li><a class="menu__link" href="#section2">Section 2</a></li>
    <li><a class="menu__link" href="#section3">Section 3</a></li>
    <li><a class="menu__link" href="#section4">Section 4</a></li>

  </ul>
</nav>
</code>```

and here's my incomplete Javascript code that i can't figure out. Confused what to use:

```<code>document.querySelectorAll("li").addEventListener("click", scrollTo());
</code>```

and here is one of the sections in HTML:

```<code><section id="section1" data-nav="Section 1" class="your-active-class">
      <div class="landing__container">
        <h2>Section 1</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. </p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. </p>
      </div>
    </section>
</code>```

can anyone help?

ContentLicense: CC BY-SA 4.0

Body:
I want to make my navbar so when one of the option in the navbar is clicked the page would scroll smoothly and NOT JUMP IMMEDIATELY to that specific section in the page, for example when i click contact on my navbar the page would scroll down to the contact section in the same page.

How to make something like that USING JAVASCRIPT and not CSS, can anyone help me ?

Here's my HTML code for the nav bar:

Section 1

Section 2

Section 3

Section 4

and here's my incomplete Javascript code that i can't figure out. Confused what to use:

document.querySelectorAll("li").addEventListener("click", scrollTo());

and here is one of the sections in HTML:

Section 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue.

Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam.

can anyone help?


问:
How can I convert a Path2D object into an SVG String in JavaScript?
Is there a way to take a Javascript Path2D object and convert it to its corresponding SVG String? According to the docs, it's pretty easy to convert string to Path using the constructor, but I can't seem to find a way to do the inverse.

The context (if relevant) is that I have a Path2D object that I want to use as a clip-path style on an element. So, if there is a way to set the style property using a Path2D object, that would be good enough for me!


问:
Should i close each substreams of filestream or closing filestream will be enought?
I readed a lot of topics about C# streams, but did not find my situation.
For learing purpose i did list-file json-bd like:

```<code>public sealed class JSONBD<T> : IDisposable {
    private FileStream fileStream;
    private TextWriter textWriter; // textWriter = new StreamWriter(fileStream)
    private TextReader textReader; // textReader = new StreamReader(fileStream)
    public List<T> Bd { get; set; } // null is not awailable here
    public string FilePath { get; }
    public void Open();
    public void Commit();
    public void Close();
}
</code>```

I tryed to use System.IO streams because they are garantee the only user of it file will be a current instance.
Much time in living time object i need to commit, so i cant using using construction because StreamWriter instance closes my FileStream when commiting like StreamReader after deserealization the file. Well, i need to close both of them?

So i decided to use one FileStream, StreamWriter and StreamReader objects at the same time.
The problem is: is it correct to do that way, having 2 streams from FileStream?
The second problem is: how should i close these streams? Will be FileStream.Close() enough or not? At the topics i didnt find any exact solution about that instead closing lower stream. But i have 2 lower streams actually! Well, should i close both of them? But one of them already closes FileStream.

I am really sorry for english mistakes i did. Im still in progress.

Body:
I readed a lot of topics about C# streams, but did not find my situation.
For learing purpose i did list-file json-bd like:

public sealed class JSONBD<T> : IDisposable {
    private FileStream fileStream;
    private TextWriter textWriter; // textWriter = new StreamWriter(fileStream)
    private TextReader textReader; // textReader = new StreamReader(fileStream)
    public List<T> Bd { get; set; } // null is not awailable here
    public string FilePath { get; }
    public void Open();
    public void Commit();
    public void Close();
}

I tryed to use System.IO streams because they are garantee the only user of it file will be a current instance.
Much time in living time object i need to commit, so i cant using using construction because StreamWriter instance closes my FileStream when commiting like StreamReader after deserealization the file. Well, i need to close both of them?

So i decided to use one FileStream, StreamWriter and StreamReader objects at the same time.
The problem is: is it correct to do that way, having 2 streams from FileStream?
The second problem is: how should i close these streams? Will be FileStream.Close() enough or not? At the topics i didnt find any exact solution about that instead closing lower stream. But i have 2 lower streams actually! Well, should i close both of them? But one of them already closes FileStream.

I am really sorry for english mistakes i did. Im still in progress.


问:
VSCode Activity Bar - styling in an extension
I have these settings applied in the theme file for an extension I use:

  "font-family": "Arial",
  "colors": {
    "activityBar.background": "#ffffff",
    "activityBar.foreground": "#000000",
    "activityBar.activeBorder": "#615386",
    "activityBar.activeBackground": "#ff00ff",
    "activityBar.activeForeground": "#ffffff",
    "activityBarBadge.background": "#615386"
  }
```
<p>Everything is working fine apart from three values for <code>active</code> element of the ActivityBar. I don't understand what's wrong.. I am able to change the values for my own theme I use on a daily basis (it's based on Egoist One) using the same settings:</p>
<pre class="lang-json prettyprint-override"><code>"workbench.colorCustomizations": {
    "activityBar.activeBorder": "#ffc600",
    "activityBar.activeBackground":"#3a414f",
}
</code>```

I did not find any documentation that would say that these settings can't be modified in the theme file of an extension. Does anybody know why it's not working?

Body:
I have these settings applied in the theme file for an extension I use:

  "font-family": "Arial",
  "colors": {
    "activityBar.background": "#ffffff",
    "activityBar.foreground": "#000000",
    "activityBar.activeBorder": "#615386",
    "activityBar.activeBackground": "#ff00ff",
    "activityBar.activeForeground": "#ffffff",
    "activityBarBadge.background": "#615386"
  }

Everything is working fine apart from three values for active element of the ActivityBar. I don't understand what's wrong.. I am able to change the values for my own theme I use on a daily basis (it's based on Egoist One) using the same settings:

"workbench.colorCustomizations": {
    "activityBar.activeBorder": "#ffc600",
    "activityBar.activeBackground":"#3a414f",
}

I did not find any documentation that would say that these settings can't be modified in the theme file of an extension. Does anybody know why it's not working?


问:
C# implementation Button Animation shows weird behaviour
I made a button animation by a c#(code) approach with a MouseEnter event to make the button bigger and with a MouseLeave event to make the button smaller again. It works if I hover on a button and wait till its done resizing and then hover off the button. But if I quickly hover over the same button twice or over a different button it shows weird behaviour. It think it is a multithreading issue and that the MouseEnter and MouseLeave methods are executed multiple times at the same time but I don't know how to solve it.

```<code><Button Name="Redo" Click="ButtonPressed" Canvas.Left="148" VerticalAlignment="Center" MouseEnter="MouseEnter" MouseLeave="MouseLeave">Redo</Button>
</code>```

DispatcherTimer timer;
int elapsedTime = 0;
int interval = 1;
int totalTime = 5;
string name = null;

public void MouseEnter(object sender, MouseEventArgs e)
{

    if (e.OriginalSource is not Button)
    {
        return;
    }
    //if (name != null)
    //    return;

    Button hoveredButton = e.OriginalSource as Button;
    name = hoveredButton.Name;
    elapsedTime = 0;
    timer = new DispatcherTimer();

    timer.IsEnabled = true;
    timer.Interval = TimeSpan.FromMilliseconds(interval);

    timer.Tick += delegate { MouseAnimation(1, hoveredButton); };
}
public void MouseAnimation(int resize, Button button)
{
    timer.Stop();
    if (elapsedTime > totalTime)
    {
        elapsedTime = 0;
        return;
    }

    timer.IsEnabled = true;
    button.Height = button.ActualHeight + resize;
    button.Width = button.ActualWidth + resize;

    elapsedTime += interval;
}
public void MouseLeave(object sender, MouseEventArgs e)
{
    //if (elapsedTime > 0)
    //    return;

    if (e.OriginalSource is not Button)
    {
        return;
    }

    Button hoveredButton = e.OriginalSource as Button;
    //if (hoveredButton.Name != name)
    //    return;
    //if (name == null)
    //    return;

    Button tempButton = (Button)e.OriginalSource;

    //if(e.OriginalSource != hoveredButton)
    //{
    //    return;
    //}

    elapsedTime = 0;
    timer = new DispatcherTimer();
    timer.IsEnabled = true;
    timer.Interval = TimeSpan.FromMilliseconds(interval);
    timer.Tick += delegate { MouseAnimation(-1, hoveredButton); };
    timer.IsEnabled = true;
    name = null;

}

```

I tried to store the name of a button in variable and look if the same button is hovered over twice but that didn't work.

Body:
I made a button animation by a c#(code) approach with a MouseEnter event to make the button bigger and with a MouseLeave event to make the button smaller again. It works if I hover on a button and wait till its done resizing and then hover off the button. But if I quickly hover over the same button twice or over a different button it shows weird behaviour. It think it is a multithreading issue and that the MouseEnter and MouseLeave methods are executed multiple times at the same time but I don't know how to solve it.

<Button Name="Redo" Click="ButtonPressed" Canvas.Left="148" VerticalAlignment="Center" MouseEnter="MouseEnter" MouseLeave="MouseLeave">Redo</Button>

DispatcherTimer timer;
int elapsedTime = 0;
int interval = 1;
int totalTime = 5;
string name = null;

public void MouseEnter(object sender, MouseEventArgs e)
{

    if (e.OriginalSource is not Button)
    {
        return;
    }
    //if (name != null)
    //    return;

    Button hoveredButton = e.OriginalSource as Button;
    name = hoveredButton.Name;
    elapsedTime = 0;
    timer = new DispatcherTimer();

    timer.IsEnabled = true;
    timer.Interval = TimeSpan.FromMilliseconds(interval);

    timer.Tick += delegate { MouseAnimation(1, hoveredButton); };
}
public void MouseAnimation(int resize, Button button)
{
    timer.Stop();
    if (elapsedTime > totalTime)
    {
        elapsedTime = 0;
        return;
    }

    timer.IsEnabled = true;
    button.Height = button.ActualHeight + resize;
    button.Width = button.ActualWidth + resize;

    elapsedTime += interval;
}
public void MouseLeave(object sender, MouseEventArgs e)
{
    //if (elapsedTime > 0)
    //    return;

    if (e.OriginalSource is not Button)
    {
        return;
    }

    Button hoveredButton = e.OriginalSource as Button;
    //if (hoveredButton.Name != name)
    //    return;
    //if (name == null)
    //    return;

    Button tempButton = (Button)e.OriginalSource;

    //if(e.OriginalSource != hoveredButton)
    //{
    //    return;
    //}

    elapsedTime = 0;
    timer = new DispatcherTimer();
    timer.IsEnabled = true;
    timer.Interval = TimeSpan.FromMilliseconds(interval);
    timer.Tick += delegate { MouseAnimation(-1, hoveredButton); };
    timer.IsEnabled = true;
    name = null;

}

I tried to store the name of a button in variable and look if the same button is hovered over twice but that didn't work.


问:
How to display content from cdkVirtualFor and cdk-virtual-scroll-viewport
I'm trying to make a virtual scroll in Angular 14, but I haven't been capable of.

This is my code

```<code>  <mat-drawer-container class="rounded" [hasBackdrop]="false">
    <mat-drawer
      class="box-border h-auto w-72"
      #drawer
      [mode]="'over'"
      position="end"
    >
      <div class="flex text-medium text-secondary font-bold p-2 border rounded">
        <span class=""> Notificaciones </span>
        <button class="w-full text-right" (click)="drawer.toggle()">
          <mat-icon> close </mat-icon>
        </button>
      </div>
      <cdk-virtual-scroll-viewport
        [itemSize]="50"
      >
      <div
        *cdkVirtualFor="let inbox of aplicationsDataUser; let i = index"
        class="p-1 px-3 border w-70 grid gap-3"
      >
        <div>
          <p class="text-xs text-left">
            {{ inbox.createAt | date : "shortDate" }}
          </p>
        </div>
        <div>
          <button class="" (click)="linkRedirection(i)">
            <span class="text-base text-[#071330] text-justify font-bold">{{
              inbox.message
            }}</span>
          </button>
        </div>
        <div class="grid sm:grid-cols-2">
          <div>
            <!-- {{ inbox.usersRead.length > 0 ? true : false }} -->
            <button>
              <mat-icon
                [ngStyle]="{
                  color: inbox.usersRead.length > 0 ? '#2ECC71' : 'grey'
                }"
                (click)="messageView(i)"
                class="text-lg"
              >
                check_circle
              </mat-icon>
            </button>
          </div>
          <div>
            <p class="text-xs text-right">
              {{ inbox.createAt | date : "shortTime" }}
            </p>
          </div>
        </div>
      </div>
    </cdk-virtual-scroll-viewport>
    <button class="w-full bg-[#071330] text-white p-4">
      <div>"Mostras mas notificaciones"</div>
    </button>
    </mat-drawer>
</code>```

As I am working with Tailwind I tried to make the container again but in SCSS and add those attributes to the cdk-virtual-scroll-viewport, as I have seen in other solutions, but it hasn't work

Body:
I'm trying to make a virtual scroll in Angular 14, but I haven't been capable of.

This is my code

  <mat-drawer-container class="rounded" [hasBackdrop]="false">
    <mat-drawer
      class="box-border h-auto w-72"
      #drawer
      [mode]="'over'"
      position="end"
    >

         Notificaciones
        <button class="w-full text-right" (click)="drawer.toggle()">
          <mat-icon> close </mat-icon>
        </button>

      <cdk-virtual-scroll-viewport
        [itemSize]="50"
      >

            {{ inbox.createAt | date : "shortDate" }}

          <button class="" (click)="linkRedirection(i)">
            {{
              inbox.message
            }}
          </button>

            <button>
              <mat-icon
                [ngStyle]="{
                  color: inbox.usersRead.length > 0 ? '#2ECC71' : 'grey'
                }"
                (click)="messageView(i)"
                class="text-lg"
              >
                check_circle
              </mat-icon>
            </button>

              {{ inbox.createAt | date : "shortTime" }}

    </cdk-virtual-scroll-viewport>
    <button class="w-full bg-[#071330] text-white p-4">

"Mostras mas notificaciones"

    </button>
    </mat-drawer>

As I am working with Tailwind I tried to make the container again but in SCSS and add those attributes to the cdk-virtual-scroll-viewport, as I have seen in other solutions, but it hasn't work


问:
how to install requirement with pip
I have a problem with pip. I have created my enviroment by miniconda. I have run this command

```<code>conda env create --file enviroment.yml
</code>```

enviroment.yml

```<code>name: data-science-handbook
channels:
  - conda-forge
dependencies:
  - python=3.10

</code>```

requirements.txt

```<code>numpy==1.11.1
pandas==0.18.1
scipy==0.17.1
scikit-learn==0.17.1
scikit-image==0.12.3
pillow==3.4.2
matplotlib==1.5.1
seaborn==0.7.0
jupyter
notebook
line_profiler
memory_profiler
numexpr
pandas-datareader
netcdf4

</code>```

I have searched google for a couple of hours, but I have not solved.

After run pip install -r requirements.txt

```<code>Collecting numpy==1.11.1
  Downloading numpy-1.11.1.zip (4.7 MB)
     ---------------------------------------- 4.7/4.7 MB 6.3 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting pandas==0.18.1
  Downloading pandas-0.18.1.zip (8.5 MB)
     ---------------------------------------- 8.5/8.5 MB 9.2 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting scipy==0.17.1
  Downloading scipy-0.17.1.zip (13.8 MB)
     ---------------------------------------- 13.8/13.8 MB 9.8 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting scikit-learn==0.17.1
  Downloading scikit-learn-0.17.1.tar.gz (7.9 MB)
     ---------------------------------------- 7.9/7.9 MB 10.1 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting scikit-image==0.12.3
  Downloading scikit-image-0.12.3.tar.gz (20.7 MB)
     ---------------------------------------- 20.7/20.7 MB 8.2 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [5 lines of output]
      To install scikit-image from source, you will need numpy.
      Install numpy with pip:
      pip install numpy
      Or use your operating system package manager. For more
      details, see http://scikit-image.org/docs/stable/install.html
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

</code>```

I tried install with conda. conda install --file requirements.txt and still error

```<code>Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - matplotlib==1.5.1
  - scikit-image==0.12.3
  - pandas==0.18.1
  - scikit-learn==0.17.1
  - numpy==1.11.1
  - pillow==3.4.2
  - scipy==0.17.1
  - seaborn==0.7.0

Current channels:

  - https://repo.anaconda.com/pkgs/main/win-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/win-64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://repo.anaconda.com/pkgs/msys2/win-64
  - https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

</code>```

How can i fix it? please help me. Thanks

Title: how to install requirement with pip

Body:
I have a problem with pip. I have created my enviroment by miniconda. I have run this command

conda env create --file enviroment.yml

enviroment.yml

name: data-science-handbook
channels:
  - conda-forge
dependencies:
  - python=3.10

requirements.txt

numpy==1.11.1
pandas==0.18.1
scipy==0.17.1
scikit-learn==0.17.1
scikit-image==0.12.3
pillow==3.4.2
matplotlib==1.5.1
seaborn==0.7.0
jupyter
notebook
line_profiler
memory_profiler
numexpr
pandas-datareader
netcdf4

I have searched google for a couple of hours, but I have not solved.

After run pip install -r requirements.txt

Collecting numpy==1.11.1
  Downloading numpy-1.11.1.zip (4.7 MB)
     ---------------------------------------- 4.7/4.7 MB 6.3 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting pandas==0.18.1
  Downloading pandas-0.18.1.zip (8.5 MB)
     ---------------------------------------- 8.5/8.5 MB 9.2 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting scipy==0.17.1
  Downloading scipy-0.17.1.zip (13.8 MB)
     ---------------------------------------- 13.8/13.8 MB 9.8 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting scikit-learn==0.17.1
  Downloading scikit-learn-0.17.1.tar.gz (7.9 MB)
     ---------------------------------------- 7.9/7.9 MB 10.1 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Collecting scikit-image==0.12.3
  Downloading scikit-image-0.12.3.tar.gz (20.7 MB)
     ---------------------------------------- 20.7/20.7 MB 8.2 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [5 lines of output]
      To install scikit-image from source, you will need numpy.
      Install numpy with pip:
      pip install numpy
      Or use your operating system package manager. For more
      details, see http://scikit-image.org/docs/stable/install.html
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I tried install with conda. conda install --file requirements.txt and still error

Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - matplotlib==1.5.1
  - scikit-image==0.12.3
  - pandas==0.18.1
  - scikit-learn==0.17.1
  - numpy==1.11.1
  - pillow==3.4.2
  - scipy==0.17.1
  - seaborn==0.7.0

Current channels:

  - https://repo.anaconda.com/pkgs/main/win-64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/win-64
  - https://repo.anaconda.com/pkgs/r/noarch
  - https://repo.anaconda.com/pkgs/msys2/win-64
  - https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

How can i fix it? please help me. Thanks


问:
Flyweight Pattern implementation in python
I'm trying to implement flyweight pattern in python3 for a word processor, that has a character class which stores the unicode of a character, and a flyweight factory class that returns the flyweight object for the character. Is there a way to find the memory saved by the flyweight pattern in python just like in Java?

Need help with the flyweight implementation in python3 for creating a Word processor.


问:
React Native - "FAILURE: Build completed with 2 failures" (Android)
When I run npx react-native run-android in my React Native project I receive the following error in my local terminal:

```<code>info Installing the app...

Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details
5 actionable tasks: 5 up-to-date

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Build file '/Users/jacksaunders/gymzoo/android/app/build.gradle' line: 85

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not open cp_dsl generic class cache for script '/Users/jacksaunders/gymzoo/node_modules/react-native/react.gradle' (/Users/jacksaunders/.gradle/caches/7.5.1/scripts/iw3zdgivw8z53seb2tteei08).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 14s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Build file '/Users/jacksaunders/gymzoo/android/app/build.gradle' line: 85

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not open cp_dsl generic class cache for script '/Users/jacksaunders/gymzoo/node_modules/react-native/react.gradle' (/Users/jacksaunders/.gradle/caches/7.5.1/scripts/iw3zdgivw8z53seb2tteei08).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 14s

    at makeError (/Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:174:9)
    at /Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (/Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:109:5)
    at async Command.handleAction (/Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli/build/index.js:142:9)
info Run CLI with --verbose flag for more details.
</code>```

I can see from this error, that it is saying that there is an error on line 85 of my build.gradle

```<code>apply from: "../../node_modules/react-native/react.gradle"
</code>```

Also, I can see that the second task says that the compileSdk is not specified. However, when I search for this throughout my project I can see that in my 'android/build.gradle' I have:

```<code>buildscript {
    ext {
        buildToolsVersion = "31.0.0"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
</code>```

and in my app/build.gradle I have:

```<code>android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.gymzoo"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
</code>```

I am unsure consequently what this means (or what I am doing wrong/missing). I have tried to ./gradlew clean in the android folder. But it actually just repeats the same error.

edit: after looking at this even more... I feel like it could be something to do with jdk. Tried switching to jdk 8 with export JAVA_HOME=/usr/libexec/java_home -v 1.8 but I don't think that worked because I get

Execution failed for task ':react-native-gradle-plugin:compileKotlin'.

Failed to query the value of task ':react-native-gradle-plugin:compileKotlin' property
'compilerRunner$kotlin_gradle_plugin'.
Kotlin could not find the required JDK tools in the Java installation. Make sure Kotlin compilation is running on a JDK, not
JRE.

Body:
When I run npx react-native run-android in my React Native project I receive the following error in my local terminal:

info Installing the app...

Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details
5 actionable tasks: 5 up-to-date

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Build file '/Users/jacksaunders/gymzoo/android/app/build.gradle' line: 85

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not open cp_dsl generic class cache for script '/Users/jacksaunders/gymzoo/node_modules/react-native/react.gradle' (/Users/jacksaunders/.gradle/caches/7.5.1/scripts/iw3zdgivw8z53seb2tteei08).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 14s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Build file '/Users/jacksaunders/gymzoo/android/app/build.gradle' line: 85

* What went wrong:
A problem occurred evaluating project ':app'.
> Could not open cp_dsl generic class cache for script '/Users/jacksaunders/gymzoo/node_modules/react-native/react.gradle' (/Users/jacksaunders/.gradle/caches/7.5.1/scripts/iw3zdgivw8z53seb2tteei08).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 63

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 14s

    at makeError (/Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:174:9)
    at /Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (/Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:109:5)
    at async Command.handleAction (/Users/jacksaunders/gymzoo/node_modules/@react-native-community/cli/build/index.js:142:9)
info Run CLI with --verbose flag for more details.

I can see from this error, that it is saying that there is an error on line 85 of my build.gradle

apply from: "../../node_modules/react-native/react.gradle"

Also, I can see that the second task says that the compileSdk is not specified. However, when I search for this throughout my project I can see that in my 'android/build.gradle' I have:

buildscript {
    ext {
        buildToolsVersion = "31.0.0"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31

and in my app/build.gradle I have:

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.gymzoo"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

I am unsure consequently what this means (or what I am doing wrong/missing). I have tried to ./gradlew clean in the android folder. But it actually just repeats the same error.

edit: after looking at this even more... I feel like it could be something to do with jdk. Tried switching to jdk 8 with export JAVA_HOME=/usr/libexec/java_home -v 1.8 but I don't think that worked because I get

Execution failed for task ':react-native-gradle-plugin:compileKotlin'.

Failed to query the value of task ':react-native-gradle-plugin:compileKotlin' property
'compilerRunner$kotlin_gradle_plugin'.
Kotlin could not find the required JDK tools in the Java installation. Make sure Kotlin compilation is running on a JDK, not
JRE.


问:
using sockets in Python to get information from a url fragment
I am writing a Python script that interacts with the Spotify API. To authenticate, I generate a url that looks something like this: https://accounts.spotify.com/authorize?response_type=token&client_id=<client_id_here>&redirect_uri=http%3A%2F%2F127.0.0.1%3A8083. Spotify then redirects me to my redirect uri, which is currently localhost (127.0.0.1:8083). Spotify attaches the access token as a fragment to the redirect uri. I need to access the uri fragment from Python.

Currently I am using the following code (the function generate_login_url() generates the accounts.spotify.com url I need)

webbrowser.open(generate_login_url())

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind(('127.0.0.1', 8083))
    sock.listen()
    conn, _ = sock.accept()
    with conn:
        data = conn.recv(1024)
        conn.sendall(data)
```

When I run this, I can see in the web browser that I have been redirected to the correct url (http://127.0.0.1:8083/#access_token=<access_token_here>&token_type=Bearer&expires_in=3600) but I cannot find a way to access the fragment from python. Calling conn.recv(1024) again causes a timeout, and the information I need is not found anywhere in data, which seems to just hold the user-agent string and the headers.

Body:
I am writing a Python script that interacts with the Spotify API. To authenticate, I generate a url that looks something like this: https://accounts.spotify.com/authorize?response_type=token&client_id=<client_id_here>&redirect_uri=http%3A%2F%2F127.0.0.1%3A8083. Spotify then redirects me to my redirect uri, which is currently localhost (127.0.0.1:8083). Spotify attaches the access token as a fragment to the redirect uri. I need to access the uri fragment from Python.

Currently I am using the following code (the function generate_login_url() generates the accounts.spotify.com url I need)

webbrowser.open(generate_login_url())

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind(('127.0.0.1', 8083))
    sock.listen()
    conn, _ = sock.accept()
    with conn:
        data = conn.recv(1024)
        conn.sendall(data)

When I run this, I can see in the web browser that I have been redirected to the correct url (http://127.0.0.1:8083/#access_token=<access_token_here>&token_type=Bearer&expires_in=3600) but I cannot find a way to access the fragment from python. Calling conn.recv(1024) again causes a timeout, and the information I need is not found anywhere in data, which seems to just hold the user-agent string and the headers.


问:
How to make Rmarkdown website using one .rmd file as template for multiple pages instead of one .rmd for each page?
I find rmarkdown sites interesting, but I would like to change from most example I have seen and I haven't found something yet.

I try to make a repoducible example:

folder struture:

```<code>project_folder
\_ _site.yml
\_ index.rmd
\_ script.R
\_ templates
   \_pages.rmd
</code>```

I yml file alows to make the structure: I would like to have a website with the following categories (this an example of my _site.yml):

```<code>name: "website"
navbar:
  title: "website"
  left:
  - text: "global info"
    href: index.html
  - text: "species"
    menu:
        - text: "all species result"
          href: all.html
        - text: "---------"
        - text: "versicolor"
          href: versicolor_1.html
        - text: "setosa"
          href: setosa.html
</code>```

then an index.rmd (here just a title in order to keep the example simple).

```<code>---
title: Some stuff
---
</code>```

a template page like page.rmd in a template folder (very simple as well but it uses a parameter.

```<code>---
params:
  data_set:
title: "Region results"
---

hist(param$dataset$Sepal.Length)
</code>```

and a "script" like, to render the site and then all pages except index.

```<code>markdown::render_site()

# import data
species = c("versicolor", "setosa")

# filter data and render page
for (i in 1:nrow(species)){
data_filtered <- dplyr::filter(iris, species == species[i])
rmarkdown::render("templates/page.rmd.Rmd", params = list(
  data_set = data_filtered,
output_file = paste0("../_site/", pages$species[i], ".html"))
}
</code>```

Right now, I don't get the header on top of my html as I am not using the common structure....

I could also use another option (R based) if you have ideas. shiny isn't the best option.

Thank you!

Body:
I find rmarkdown sites interesting, but I would like to change from most example I have seen and I haven't found something yet.

I try to make a repoducible example:

folder struture:

project_folder
\_ _site.yml
\_ index.rmd
\_ script.R
\_ templates
   \_pages.rmd

I yml file alows to make the structure: I would like to have a website with the following categories (this an example of my _site.yml):

name: "website"
navbar:
  title: "website"
  left:
  - text: "global info"
    href: index.html
  - text: "species"
    menu:
        - text: "all species result"
          href: all.html
        - text: "---------"
        - text: "versicolor"
          href: versicolor_1.html
        - text: "setosa"
          href: setosa.html

then an index.rmd (here just a title in order to keep the example simple).

---
title: Some stuff
---

a template page like page.rmd in a template folder (very simple as well but it uses a parameter.

---
params:
  data_set:
title: "Region results"
---

hist(param$dataset$Sepal.Length)

and a "script" like, to render the site and then all pages except index.

markdown::render_site()

# import data
species = c("versicolor", "setosa")

# filter data and render page
for (i in 1:nrow(species)){
data_filtered <- dplyr::filter(iris, species == species[i])
rmarkdown::render("templates/page.rmd.Rmd", params = list(
  data_set = data_filtered,
output_file = paste0("../_site/", pages$species[i], ".html"))
}

Right now, I don't get the header on top of my html as I am not using the common structure....

I could also use another option (R based) if you have ideas. shiny isn't the best option.

Thank you!


问:
Expose c-function for testing
I have a c-function within a class:

```<code>@interface MyClass: NSObject
@end

@implementation MyClass
static void MyFunction(void) {
// Do some stuff.
}
@end
</code>```

And I'd like to expose my function for testing:

```<code>@interface MyClass (testing)
static void MyFunction(void);
@end
</code>```

But this leads to error:

Function 'MyFunction' has internal linkage but is not
definedclang(-Wundefined-internal)

Is there some way to expose this method?

Title: Expose c-function for testing

Body:
I have a c-function within a class:

@interface MyClass: NSObject
@end

@implementation MyClass
static void MyFunction(void) {
// Do some stuff.
}
@end

And I'd like to expose my function for testing:

@interface MyClass (testing)
static void MyFunction(void);
@end

But this leads to error:

Function 'MyFunction' has internal linkage but is not
definedclang(-Wundefined-internal)

Is there some way to expose this method?


问:
I am trying to get Matlab Minibatchqueue to spit out 500 rows per column, from a 16 columns (variable ds) at a time
I have an EEG with 16 chanel. It is organized in a table using TabularTextDatastore. 16 columns, one per chanel. I want to organize the data in minibatchs 500x16 datapoints. Each datapoint count for a signal mesuments at 1 sec interval.

ds[100000 X 16] -> minibatchqueue -> [80000] -> model
||
[ch1ch2ch3...n]
||
[500 500 500 500 ...]

model has 500x16=80000 inputs in the feature layer

this is m minibacthqueue code:

```<code>mbq = minibatchqueue(ds, ...
                     MiniBatchSize=miniBatchSize, ...
                     PartialMiniBatch="discard", ...
                     MiniBatchFcn=@preprocessMiniBatch, ...
                     MiniBatchFormat="SSCB");
</code>```

the preprocessMiniBatch function I can't figure out. How do I manipulate the date so it spits out 500 seconds of each channel to my model. The alternative is to to create 16 identical models that can process 1 chanel at a time.

I tried:

```<code>function X = preprocessMiniBatch(data)
    % Concatenate mini-batch
    X = data{1,1:500};

    for idx = 2:16
        X = cat(1,X,data{idx,1:500});
    end

end

</code>```

the ouput is this:

Error using minibatchqueue>iValidateMiniBatchFcn (line 778)
Number of mini-batch variables (16) must be less than or equal to the number of outputs (1) of function specified by
'MiniBatchFcn'. Set number of mini-batch variables or modify the number of outputs of the function.

Error in minibatchqueue>iParseInputs (line 656)
iValidateMiniBatchFcn(options.MiniBatchFcn, numVariables, options.NumOutputs);

Error in minibatchqueue (line 294)
options = iParseInputs(numVariables, varargin{:});

Error in eegbtexp (line 66)
mbq = minibatchqueue(ds, ...

Body:
I have an EEG with 16 chanel. It is organized in a table using TabularTextDatastore. 16 columns, one per chanel. I want to organize the data in minibatchs 500x16 datapoints. Each datapoint count for a signal mesuments at 1 sec interval.

ds[100000 X 16] -> minibatchqueue -> [80000] -> model
||
[ch1ch2ch3...n]
||
[500 500 500 500 ...]

model has 500x16=80000 inputs in the feature layer

this is m minibacthqueue code:

mbq = minibatchqueue(ds, ...
                     MiniBatchSize=miniBatchSize, ...
                     PartialMiniBatch="discard", ...
                     MiniBatchFcn=@preprocessMiniBatch, ...
                     MiniBatchFormat="SSCB");

the preprocessMiniBatch function I can't figure out. How do I manipulate the date so it spits out 500 seconds of each channel to my model. The alternative is to to create 16 identical models that can process 1 chanel at a time.

I tried:

function X = preprocessMiniBatch(data)
    % Concatenate mini-batch
    X = data{1,1:500};

    for idx = 2:16
        X = cat(1,X,data{idx,1:500});
    end

end

the ouput is this:

Error using minibatchqueue>iValidateMiniBatchFcn (line 778)
Number of mini-batch variables (16) must be less than or equal to the number of outputs (1) of function specified by
'MiniBatchFcn'. Set number of mini-batch variables or modify the number of outputs of the function.

Error in minibatchqueue>iParseInputs (line 656)
iValidateMiniBatchFcn(options.MiniBatchFcn, numVariables, options.NumOutputs);

Error in minibatchqueue (line 294)
options = iParseInputs(numVariables, varargin{:});

Error in eegbtexp (line 66)
mbq = minibatchqueue(ds, ...


问:
How does sklearn deal with singular matrices when performing Linear Regression
I was trying to implement my own function of linear regression by using this formula to calculate the regression coefficients:

However if given a dataset where a string value was encoded, it might be that during the split we may have a row of 0s in our data which will give us a singular matrix, thus making it non invertible.

One solution to this would be to use np.linalg.pinv instad of np.linalg.inv however it greatly reduces the model's accuracy, compared to the sklearn's implementation.

How does sklearn deal with this issue?


问:
Google OAuth2 Demo fails with 403 ["message": "Cannot determine user location for geographically restricted operation."]
While I was checking out some of the Google public APIs for OAuth2, encountered above error  message.

I basically didn't change a lot, tried not to add anything invalid as well

but when it goes to Step 3. Configure request to API; it's failing.

When I clicked on the link from the first screenshot, it takes me to the website where I get the second screenshot.

Has anyone worked on this resolved, or anyone who's knowledgeable in this area can help with this?

Source: https://developers.google.com/oauthplayground/

Thank you in advance!!


问:
Preview Word & Excel in a PDF control connector/API
I have a custom entity where I am using the file type column in dataverse and I have a workflow that stores every file that is being uploaded to Azure blob, delete it from Dataverse and fill up the URL of the file in another column.

The user should be able to preview any document type that is being stored in Azure blob based on the file path of the form. Previewing the file should be in the canvas app and not inside model-driven.
In Azure Blob, we can only preview PDF and image files, and the canvas app only supports seeing those files.

However, when it comes to Word and Excel documents, users will not be able to preview the file and the only option will be to download the file to their local desktop since there is no API for Azure Blob that supports those formats.

In SharePoint we do have API's to preview documents such as word/excel/PPT etc.. (we can't use SharePoint in our requirements)

I am trying to find a way to allow the user to preview the above-mentioned document types within the canvas app.

Is there any 3rd party API we can extend in the canvas app that converts other doc types to PDF? I thought of creating a flow that calls an API and responds to power apps to preview the file.

Some helpful content that I found are based on SharePoint/Dataverse but my scenario is totally different where I am using Azure Blob that is:

https://www.youtube.com/watch?v=vqK29FWbLxU&t=221s

https://www.youtube.com/watch?v=GFfAkk3g1y8&t=3s

https://pcf.gallery/notes-attachment-file-preview/

Any help is highly appreciated.


问:
Why does my prompt-toolkit Dialog flicker on terminal output with asyncio and patch_stout?
When running a prompt-toolkit Dialog it will flicker if there is terminal output from a different asyncio task.

I am using the context with patch_stdout() within a task as mentioned in the doc, at least as far as I understand it. I read somewhere that starting with prompt-toolkit 3.0 it uses the default asyncio event loop and does not create one itself.

And since asyncio.run always creates a new event loop and closes it at the end and the context manager is within that, I have no clue what could be the reason for the flickering.

(Python 3.9, prompt-toolkit 3.0.36)

This is a MCVE:

```<code>import asyncio
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.shortcuts.dialogs import _create_app, _return_none
from prompt_toolkit.widgets import Button, Dialog, Label

dialog_align = Dialog(
    title='Please align',
    body=Label(text="init", dont_extend_height=True),
    buttons=[Button(text='Start measurement', width=21, handler=_return_none)],
    with_background=True,
)

async def prompt_align():

    return await _create_app(dialog_align, style=None).run_async()

async def main_datasource():

    while True:
        await asyncio.sleep(0.5)
        print("test")

async def main():

    with patch_stdout():

        task1 = asyncio.create_task(prompt_align())
        task2 = asyncio.create_task(main_datasource())

        await asyncio.gather(task1, task2)

if __name__ == "__main__":

    try:
        from asyncio import run
    except ImportError:
        asyncio.run_until_complete(main())
    else:

        asyncio.run(main())
</code>```

Body:
When running a prompt-toolkit Dialog it will flicker if there is terminal output from a different asyncio task.

I am using the context with patch_stdout() within a task as mentioned in the doc, at least as far as I understand it. I read somewhere that starting with prompt-toolkit 3.0 it uses the default asyncio event loop and does not create one itself.

And since asyncio.run always creates a new event loop and closes it at the end and the context manager is within that, I have no clue what could be the reason for the flickering.

(Python 3.9, prompt-toolkit 3.0.36)

This is a MCVE:

import asyncio
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.shortcuts.dialogs import _create_app, _return_none
from prompt_toolkit.widgets import Button, Dialog, Label

dialog_align = Dialog(
    title='Please align',
    body=Label(text="init", dont_extend_height=True),
    buttons=[Button(text='Start measurement', width=21, handler=_return_none)],
    with_background=True,
)

async def prompt_align():

    return await _create_app(dialog_align, style=None).run_async()

async def main_datasource():

    while True:
        await asyncio.sleep(0.5)
        print("test")

async def main():

    with patch_stdout():

        task1 = asyncio.create_task(prompt_align())
        task2 = asyncio.create_task(main_datasource())

        await asyncio.gather(task1, task2)

if __name__ == "__main__":

    try:
        from asyncio import run
    except ImportError:
        asyncio.run_until_complete(main())
    else:

        asyncio.run(main())


问:
Sorting a finite number of elements where each element takes 1 bit of memory in c
I'm trying to create a type set, that holds like so

typedef struct set
{
    char *blocks;
    char *numbers;
    char blockNum;
};
```
<p>then in order to create it I do</p>
<pre class="lang-c prettyprint-override"><code>void createSet(set *newSet)
{
    newSet->blockNum = 1;
    newSet->blocks = calloc(newSet->blockNum, BYTE_SIZE);
}
</code>```

I can initially get numbers from [0,127], with no duplicates
so in order to do that, I want to change the nth bit into 1, and then when I want to read the set, I look at the memory that set.blocks take, and check the position of each bit inside it, if a bit is equal to 1, then the number that is equal to the position of that bit is in the set.
here's the code for adding an item

void addItem(set *set, unsigned int item)
{
    int blocksToAdd = 0;
    int i = 0;
    int r = (item / BYTE_SIZE);
    int rem=item % BYTE_SIZE;
    if (r > set->blockNum)
    {
        if(r!=0) {
            blocksToAdd = r - (set->blockNum);
        }
        set->blocks = realloc(set->blocks, (set->blockNum + blocksToAdd)*BYTE_SIZE);
    }
    *(set->blocks+r)  = (1 << rem);
}
```
<p>also, I increase the memory of blocks, by adding the amount of bytes needed to get the nth amount of bits,
so far it kinda works, but when the selected number to add is 7, I get that <code>*blocks: -128</code> when it supposed to be 128, I guess it happen cause the then <code>*blocks = 1000 0000</code>.</p>
<p>So, I tried working around it but I couldn't get it to work, and I'm pretty sure I'm doing something wrong.</p>
<p>the goal was to store numbers from [0,127] with no duplicates, in a way that each element(number) takes 1 bit of memory.</p>
<pre class="lang-c prettyprint-override"><code>    int num =*(set->blocks+r);
    if(num<0) {
        set->blocks = (char *)realloc(set->blocks, (set->blockNum + 1)*BYTE_SIZE);
        num*=-1;
        *(set->blocks+r)  = num;
    }
</code>```

Tried doing this to get around it, but it wouldn't work

edit

I managed to fix the issue, by changing blocks from char* to unsigned char*, also allocated 16 bytes from the start since calling relloc to increase the size every time isn't efficient, so I would instead check if I can decrease the memory allocated for set after adding all the items

Body:
I'm trying to create a type set, that holds like so

typedef struct set
{
    char *blocks;
    char *numbers;
    char blockNum;
};

then in order to create it I do

void createSet(set *newSet)
{
    newSet->blockNum = 1;
    newSet->blocks = calloc(newSet->blockNum, BYTE_SIZE);
}

I can initially get numbers from [0,127], with no duplicates
so in order to do that, I want to change the nth bit into 1, and then when I want to read the set, I look at the memory that set.blocks take, and check the position of each bit inside it, if a bit is equal to 1, then the number that is equal to the position of that bit is in the set.
here's the code for adding an item

void addItem(set *set, unsigned int item)
{
    int blocksToAdd = 0;
    int i = 0;
    int r = (item / BYTE_SIZE);
    int rem=item % BYTE_SIZE;
    if (r > set->blockNum)
    {
        if(r!=0) {
            blocksToAdd = r - (set->blockNum);
        }
        set->blocks = realloc(set->blocks, (set->blockNum + blocksToAdd)*BYTE_SIZE);
    }
    *(set->blocks+r)  = (1 << rem);
}

also, I increase the memory of blocks, by adding the amount of bytes needed to get the nth amount of bits,
so far it kinda works, but when the selected number to add is 7, I get that *blocks: -128 when it supposed to be 128, I guess it happen cause the then *blocks = 1000 0000.

So, I tried working around it but I couldn't get it to work, and I'm pretty sure I'm doing something wrong.

the goal was to store numbers from [0,127] with no duplicates, in a way that each element(number) takes 1 bit of memory.

    int num =*(set->blocks+r);
    if(num<0) {
        set->blocks = (char *)realloc(set->blocks, (set->blockNum + 1)*BYTE_SIZE);
        num*=-1;
        *(set->blocks+r)  = num;
    }

Tried doing this to get around it, but it wouldn't work

edit

I managed to fix the issue, by changing blocks from char* to unsigned char*, also allocated 16 bytes from the start since calling relloc to increase the size every time isn't efficient, so I would instead check if I can decrease the memory allocated for set after adding all the items


问:
Define local dns for a headless service in minikube
I have a headless service (type:ClusterIP) in my local minikube cluster which I want to access using a dns address.

I was exploring the ingress controller of minikube but both the solutions described here :
https://www.zhaowenyu.com/minikube-doc/addons/ingress-dns.html

require a manual step of manipulating with some host level network files.

I am looking for a fully automated solution to be able to define dns and access the service.

I have tried the solution described here : https://www.zhaowenyu.com/minikube-doc/addons/ingress-dns.html but it requires manual step.

I have explored solution here : https://tanzu.vmware.com/developer/blog/securely-connect-with-your-local-kubernetes-environment/ as well but it has the minikube ip fragmented with in dns address.


问:
Redirection Host
I own an app in the Google Playstore.

This is accessible under the following url:

https://play.google.com/store/apps/details?id=#APPID#

#APPID# was used as a cover code.

Now I wanted to redirect the default url to the playstore URL with my Nginx proxy manager.
Means: example.org => https://play.google.com/store/apps/details?id=#APPID#

I have now tried many settings.
Correct me if I am wrong but I have applied the following configuration:

Domain Names: (example.org)

Scheme: auto

Forward Domain: https://play.google.com/store/apps/details?id=#APPID#

HTTP Code: 308

Perserve Path: Yes

Block COmmon Exploits: Yes.

And I add a SSL Certificate to my example.org

Force SSL: Yes

Everything else: No

it once (almost) worked and redirected me to https://play.google.com/store/apps/details?id=#APPID# /
(notice the / ) which is not recognized as url

Thanks in advance

Title: Redirection Host


问:
I have a NavigationDrawer activity which is using fragments. In one of my fragments I want to load data from the Firebase Google Login
[I want to show the data of google login in the dashboardfragment ](https://i.stack.imgur.com/ZOvqQ.p

I want to show the data of google login in the dashboard fragments , tell me how to show the data from.


问:
Fix for first borrow used after second mutable borrow in rust
I have a toy problem where I am trying to push a mutable reference onto a stack. The mutable reference being pushed is obtained from a vector held in the top most element of the stack.

```<code>struct Node {
    name: String,
    children: Vec<Node>,
}

fn main() {
    let mut root = Node {
        name: String::from("/"),
        children: Vec::new(),
    };

    let mut stack: Vec<&mut Node> = Vec::new();
    stack.push(&mut root);

    // first mutable borrow occurs here
    let top = stack.last_mut().unwrap();
    let children = &mut top.children;
    for node in children.iter_mut() {
        if node.name == "asdf" {
            // second mutable borrow occurs here
            // FIXME: first borrow later used here
            stack.push(node);
            break;
        }
    }
}
</code>```

I sorta get that the second mutable borrow should only occur after all code referenced in the block by the first mutable borrow is no longer in use. Though I am not certain whether the pattern I am trying to implement is impossible to achieve in Rust, or if there is an alternative that could help here.

Body:
I have a toy problem where I am trying to push a mutable reference onto a stack. The mutable reference being pushed is obtained from a vector held in the top most element of the stack.

struct Node {
    name: String,
    children: Vec<Node>,
}

fn main() {
    let mut root = Node {
        name: String::from("/"),
        children: Vec::new(),
    };

    let mut stack: Vec<&mut Node> = Vec::new();
    stack.push(&mut root);

    // first mutable borrow occurs here
    let top = stack.last_mut().unwrap();
    let children = &mut top.children;
    for node in children.iter_mut() {
        if node.name == "asdf" {
            // second mutable borrow occurs here
            // FIXME: first borrow later used here
            stack.push(node);
            break;
        }
    }
}

I sorta get that the second mutable borrow should only occur after all code referenced in the block by the first mutable borrow is no longer in use. Though I am not certain whether the pattern I am trying to implement is impossible to achieve in Rust, or if there is an alternative that could help here.


问:
TextMate rules - ContentName and inclusion of rules
I have this rule that is nested in earlier rules that work fine.

```<code>"sql_function": {
    "name": "source.custom.sql.function",
    "begin": "(\\w+)(\\()",
    "end": "(\\))",
    "contentName": "source.custom.sql.function.value",
    "beginCaptures": {
        "0": {
            "name": "source.custom.sql.function.name"
        },
        "1": {
            "name": "source.custom.sql.function.scope.start"
        }
    },
    "endCaptures": {
        "0": {
            "name": "source.custom.sql.function.scope.end"
        }
    },
    "patterns": [
        {"include": "#variable"},
        {"include": "#string"},
        {"include": "#number"},
        {"include": "#sql_constant"},
        {"include": "#sql_keyword"},
        {"include": "#sql_keyword_main"},
        {"include": "#sql_keyword_type"},
        {"include": "#operator"},
        {"include": "#sql_function"}
    ]
},
</code>```

and I'm testing it on the following line:

```<code>sql: CAST(IF(${TABLE}.attempted_at IS NULL, 0, 1) AS BOOL) ;;
</code>```

The functions are correctly recognised even when nested

Only the #variable patterns works fine "match": "\\${[^\\}]+}" but the rest is not recognised.

For example I have the sql_keyword_type that is defined like this:

```<code>"match": "(?<!\\w)(BOOL|BOOLEAN|VARCHAR|NUMERIC|DECIMAL|INTEGER|)(?!\\w)"
</code>```

but it's not recognised inside the source.lookml.sql.function.value and I'm not sure why. There's nothing different between #variable and #sql_keyword_type`, is there?

Body:
I have this rule that is nested in earlier rules that work fine.

"sql_function": {
    "name": "source.custom.sql.function",
    "begin": "(\\w+)(\\()",
    "end": "(\\))",
    "contentName": "source.custom.sql.function.value",
    "beginCaptures": {
        "0": {
            "name": "source.custom.sql.function.name"
        },
        "1": {
            "name": "source.custom.sql.function.scope.start"
        }
    },
    "endCaptures": {
        "0": {
            "name": "source.custom.sql.function.scope.end"
        }
    },
    "patterns": [
        {"include": "#variable"},
        {"include": "#string"},
        {"include": "#number"},
        {"include": "#sql_constant"},
        {"include": "#sql_keyword"},
        {"include": "#sql_keyword_main"},
        {"include": "#sql_keyword_type"},
        {"include": "#operator"},
        {"include": "#sql_function"}
    ]
},

and I'm testing it on the following line:

sql: CAST(IF(${TABLE}.attempted_at IS NULL, 0, 1) AS BOOL) ;;

The functions are correctly recognised even when nested

Only the #variable patterns works fine "match": "\\${[^\\}]+}" but the rest is not recognised.

For example I have the sql_keyword_type that is defined like this:

"match": "(?<!\\w)(BOOL|BOOLEAN|VARCHAR|NUMERIC|DECIMAL|INTEGER|)(?!\\w)"

but it's not recognised inside the source.lookml.sql.function.value and I'm not sure why. There's nothing different between #variable and #sql_keyword_type`, is there?


问:
Running a tornado deamon in an interactive python interpreter
I'm trying to establish a websocket connection between to python processes using tornado. On client side, I'm restricted to using python 2.7 which means that I cannot make use of some sophisticated asynchronous execution features. However, the websocket listener on client side needs to be non-blocking, i.e. it should run in the background and only get active if it receives a message from the server by the websocket. The really important requirement is that the client needs to be run from an interactive python interpreter. While the client is running in the background, the user should be able to input python commands into the interactive shell as if the client didn't exist.

So far I have put this together based on what was published here: https://www.georgeho.org/tornado-websockets/

tornado_server.py:

```<code>""" Every 100ms, sample from a Bernoulli and write the value to a WebSocket. """

import random
import tornado.ioloop
import tornado.web
import tornado.websocket

class WebSocketServer(tornado.websocket.WebSocketHandler):
    """Simple WebSocket handler to serve clients."""

    # Note that `clients` is a class variable and `send_message` is a
    # classmethod.
    clients = set()

    def open(self):
        WebSocketServer.clients.add(self)

    def on_close(self):
        WebSocketServer.clients.remove(self)

    @classmethod
    def send_message(cls, message: str):
        print(f"Sending message {message} to {len(cls.clients)} client(s).")
        for client in cls.clients:
            client.write_message(message)

class RandomBernoulli:
    def __init__(self):
        self.p = 0.72
        print(f"True p = {self.p}")

    def sample(self):
        return int(random.uniform(0, 1) <= self.p)

def main():
    # Create a web app whose only endpoint is a WebSocket, and start the web
    # app on port 8888.
    app = tornado.web.Application(
        [(r"/websocket/", WebSocketServer)],
        websocket_ping_interval=10,
        websocket_ping_timeout=30,
    )
    app.listen(8888)

    # Create an event loop (what Tornado calls an IOLoop).
    io_loop = tornado.ioloop.IOLoop.current()

    # Before starting the event loop, instantiate a RandomBernoulli and
    # register a periodic callback to write a sampled value to the WebSocket
    # every 100ms.
    random_bernoulli = RandomBernoulli()
    periodic_callback = tornado.ioloop.PeriodicCallback(
        lambda: WebSocketServer.send_message(str(random_bernoulli.sample())), 100
    )
    periodic_callback.start()

    # Start the event loop.
    io_loop.start()

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

tornado_client.py:

```<code>""" Stream data from the WebSocket and update the Beta posterior parameters online. """

import tornado.ioloop
import tornado.websocket
import subprocess, threading, time

class WebSocketClient:
    def __init__(self, io_loop):
        self.connection = None
        self.io_loop = io_loop
        self.num_successes = 0
        self.num_trials = 0

    def start(self):
        self.connect_and_read()

    def stop(self):
        self.io_loop.stop()

    def connect_and_read(self):
        print("Reading...")
        tornado.websocket.websocket_connect(
            url="ws://localhost:8888/websocket/",
            callback=self.maybe_retry_connection,
            on_message_callback=self.on_message,
            ping_interval=10,
            ping_timeout=30,
        )

    def maybe_retry_connection(self, future):
        try:
            self.connection = future.result()
        except:
            print("Could not reconnect, retrying in 3 seconds...")
            self.io_loop.call_later(3, self.connect_and_read)

    def on_message(self, message):
        if message is None:
            print("Disconnected, reconnecting...")
            self.connect_and_read()

        message = int(message)
        self.num_successes += message
        self.num_trials += 1

        alpha = 2 + self.num_successes
        beta = 2 + self.num_trials - self.num_successes
        mean = self.num_successes / self.num_trials
        print("alpha = " + str(alpha) + "; beta = " + str(beta) + "; mean = " +str(mean))

def run_background_listener():
    # Create an event loop (what Tornado calls an IOLoop).
    io_loop = tornado.ioloop.IOLoop.current()

    # Before starting the event loop, instantiate a WebSocketClient and add a
    # callback to the event loop to start it. This way the first thing the
    # event loop does is to start the client.
    client = WebSocketClient(io_loop)
    io_loop.add_callback(client.start)

    # Start the event loop -> works but will block main thread/interactive shell
    # io_loop.start()

    # Start the event loop in a separate thread -> will not block main thread
    eventLoopThread = threading.Thread(target=io_loop.start)
    eventLoopThread.daemon = True
    eventLoopThread.start()

if __name__ == "__main__":
    run_background_listener()

    while True:
        print('Main thread...')
        time.sleep(1)
</code>```

When I'm running both from command line by invoking

```<code>python tornado_server.py
</code>```

and

```<code>python tornado_client.py
</code>```

everything works as expected. But when I'm executing the client script in an interactive python interpreter (without the last if clause), calling run_background_listener() does not start the deamon process and the server will not find any clients to send messages to. Unfortunately, I do not get any output or error messages when calling run_background_listener() the first time. However, when calling it multiple times, an error is thrown indicating that the IOloop is already running. The server still reports zero connected clients, though.

Searching the internet didn't help much besides the fact that an interactive python interpreter might not be thread safe or similar (didn't understand it to be honest).

I would be glad if someone can give me a hint on how to solve this. Thanks in advance!

Body:
I'm trying to establish a websocket connection between to python processes using tornado. On client side, I'm restricted to using python 2.7 which means that I cannot make use of some sophisticated asynchronous execution features. However, the websocket listener on client side needs to be non-blocking, i.e. it should run in the background and only get active if it receives a message from the server by the websocket. The really important requirement is that the client needs to be run from an interactive python interpreter. While the client is running in the background, the user should be able to input python commands into the interactive shell as if the client didn't exist.

So far I have put this together based on what was published here: https://www.georgeho.org/tornado-websockets/

tornado_server.py:

""" Every 100ms, sample from a Bernoulli and write the value to a WebSocket. """

import random
import tornado.ioloop
import tornado.web
import tornado.websocket

class WebSocketServer(tornado.websocket.WebSocketHandler):
    """Simple WebSocket handler to serve clients."""

    # Note that `clients` is a class variable and `send_message` is a
    # classmethod.
    clients = set()

    def open(self):
        WebSocketServer.clients.add(self)

    def on_close(self):
        WebSocketServer.clients.remove(self)

    @classmethod
    def send_message(cls, message: str):
        print(f"Sending message {message} to {len(cls.clients)} client(s).")
        for client in cls.clients:
            client.write_message(message)

class RandomBernoulli:
    def __init__(self):
        self.p = 0.72
        print(f"True p = {self.p}")

    def sample(self):
        return int(random.uniform(0, 1) <= self.p)

def main():
    # Create a web app whose only endpoint is a WebSocket, and start the web
    # app on port 8888.
    app = tornado.web.Application(
        [(r"/websocket/", WebSocketServer)],
        websocket_ping_interval=10,
        websocket_ping_timeout=30,
    )
    app.listen(8888)

    # Create an event loop (what Tornado calls an IOLoop).
    io_loop = tornado.ioloop.IOLoop.current()

    # Before starting the event loop, instantiate a RandomBernoulli and
    # register a periodic callback to write a sampled value to the WebSocket
    # every 100ms.
    random_bernoulli = RandomBernoulli()
    periodic_callback = tornado.ioloop.PeriodicCallback(
        lambda: WebSocketServer.send_message(str(random_bernoulli.sample())), 100
    )
    periodic_callback.start()

    # Start the event loop.
    io_loop.start()

if __name__ == "__main__":
    main()

tornado_client.py:

""" Stream data from the WebSocket and update the Beta posterior parameters online. """

import tornado.ioloop
import tornado.websocket
import subprocess, threading, time

class WebSocketClient:
    def __init__(self, io_loop):
        self.connection = None
        self.io_loop = io_loop
        self.num_successes = 0
        self.num_trials = 0

    def start(self):
        self.connect_and_read()

    def stop(self):
        self.io_loop.stop()

    def connect_and_read(self):
        print("Reading...")
        tornado.websocket.websocket_connect(
            url="ws://localhost:8888/websocket/",
            callback=self.maybe_retry_connection,
            on_message_callback=self.on_message,
            ping_interval=10,
            ping_timeout=30,
        )

    def maybe_retry_connection(self, future):
        try:
            self.connection = future.result()
        except:
            print("Could not reconnect, retrying in 3 seconds...")
            self.io_loop.call_later(3, self.connect_and_read)

    def on_message(self, message):
        if message is None:
            print("Disconnected, reconnecting...")
            self.connect_and_read()

        message = int(message)
        self.num_successes += message
        self.num_trials += 1

        alpha = 2 + self.num_successes
        beta = 2 + self.num_trials - self.num_successes
        mean = self.num_successes / self.num_trials
        print("alpha = " + str(alpha) + "; beta = " + str(beta) + "; mean = " +str(mean))

def run_background_listener():
    # Create an event loop (what Tornado calls an IOLoop).
    io_loop = tornado.ioloop.IOLoop.current()

    # Before starting the event loop, instantiate a WebSocketClient and add a
    # callback to the event loop to start it. This way the first thing the
    # event loop does is to start the client.
    client = WebSocketClient(io_loop)
    io_loop.add_callback(client.start)

    # Start the event loop -> works but will block main thread/interactive shell
    # io_loop.start()

    # Start the event loop in a separate thread -> will not block main thread
    eventLoopThread = threading.Thread(target=io_loop.start)
    eventLoopThread.daemon = True
    eventLoopThread.start()

if __name__ == "__main__":
    run_background_listener()

    while True:
        print('Main thread...')
        time.sleep(1)

When I'm running both from command line by invoking

python tornado_server.py

and

python tornado_client.py

everything works as expected. But when I'm executing the client script in an interactive python interpreter (without the last if clause), calling run_background_listener() does not start the deamon process and the server will not find any clients to send messages to. Unfortunately, I do not get any output or error messages when calling run_background_listener() the first time. However, when calling it multiple times, an error is thrown indicating that the IOloop is already running. The server still reports zero connected clients, though.

Searching the internet didn't help much besides the fact that an interactive python interpreter might not be thread safe or similar (didn't understand it to be honest).

I would be glad if someone can give me a hint on how to solve this. Thanks in advance!


问:
YOLOv5 classification of images of different magnifications & sizes
I was wondering how well YOLOv5 performs when images are of different sizes and magnifications (e.g. 540x310 vs. 270x155). If it doesn't perform well, what could be some potential methods to mitigate these issues? I am aware that you can resize/crop to guarantee constant dimensions, but how would you guarantee a similar size for labeled objects if they are taken at different magnifications?</p>


问:
How to manage voice messages?
I have messages in my app. Each voice message have it's own state:

```<code>final _audioPlayer = AudioPlayer();
bool _isPlaying = false;

Stream<PositionData> get _seekBarPosition =>
      Rx.combineLatest3<Duration, Duration, Duration?, PositionData>(
          _audioPlayer.positionStream,
          _audioPlayer.bufferedPositionStream,
          _audioPlayer.durationStream,
          (position, bufferedPosition, duration) => PositionData(
              position, bufferedPosition, duration ?? Duration.zero));
</code>```

It's used to play or pause the message. Well it's working. But with this code I can play more than one message at the time and I don't need that. I want the messages to play only one at the moment. How can I do it?

AudioPlayer _audioPlayer - used to play, pause etc. the voice message.

bool _isPlaying - used to toggle play/pause button.

Stream _seekBarPosition - used to watch played time

Title: How to manage voice messages?

Body:
I have messages in my app. Each voice message have it's own state:

final _audioPlayer = AudioPlayer();
bool _isPlaying = false;

Stream<PositionData> get _seekBarPosition =>
      Rx.combineLatest3<Duration, Duration, Duration?, PositionData>(
          _audioPlayer.positionStream,
          _audioPlayer.bufferedPositionStream,
          _audioPlayer.durationStream,
          (position, bufferedPosition, duration) => PositionData(
              position, bufferedPosition, duration ?? Duration.zero));

It's used to play or pause the message. Well it's working. But with this code I can play more than one message at the time and I don't need that. I want the messages to play only one at the moment. How can I do it?

AudioPlayer _audioPlayer - used to play, pause etc. the voice message.

bool _isPlaying - used to toggle play/pause button.

Stream _seekBarPosition - used to watch played time


问:
Inserting in a doubly linked list in a sorted way
have been trying to insert in a doubly ll in sorted manner but it's just not working

here's what i have been doing so far

```<code>void insert(struct node **root, int val)
{
    struct node *temp, *p;
    temp=(struct node*)malloc(sizeof(struct node));
    temp->data=val;
    temp->back=NULL;temp->next=NULL;

    if(*root==NULL  || (*root)->data>=temp->data)
    {
        temp->next=*root;
        temp->next->back=temp;
        *root=temp;
    }
    else
    {

        p=*root;
        while(p->next!=NULL && p->next->data<temp->data)
        {
            p=p->next;
        }
        temp->back=p;
        temp->next=p->next;
        p->next=temp;

    }

}
</code>```

but when i do it like this

```<code>void insert(struct node **root, int val)
{
    struct node *temp, *p;
    temp=(struct node*)malloc(sizeof(struct node));
    temp->data=val;
    temp->back=NULL;temp->next=NULL;

    if(*root==NULL)
    {
        *root=temp;
    }
    else if( (*root)->data>=temp->data )
    {
        temp->next=*root;
        temp->next->back=temp;
        *root=temp;
    }
    else
    {

        p=*root;
        while(p->next!=NULL && p->next->data<temp->data)
        {
            p=p->next;
        }
        if(p->next)
        {
            p->next->back=temp;
        }
        temp->back=p;
        temp->next=p->next;
        p->next=temp;

    }

}

</code>```

it works fine so now i am confused as of why wasn't it working for the first time but works fine when i write the condition in a different else if statement

will be really helpful if someone can explain

tried inserting in a doubly linked list in a sorted manner but ran into (0xC0000005)

Body:
have been trying to insert in a doubly ll in sorted manner but it's just not working

here's what i have been doing so far

void insert(struct node **root, int val)
{
    struct node *temp, *p;
    temp=(struct node*)malloc(sizeof(struct node));
    temp->data=val;
    temp->back=NULL;temp->next=NULL;

    if(*root==NULL  || (*root)->data>=temp->data)
    {
        temp->next=*root;
        temp->next->back=temp;
        *root=temp;
    }
    else
    {

        p=*root;
        while(p->next!=NULL && p->next->data<temp->data)
        {
            p=p->next;
        }
        temp->back=p;
        temp->next=p->next;
        p->next=temp;

    }

}

but when i do it like this

void insert(struct node **root, int val)
{
    struct node *temp, *p;
    temp=(struct node*)malloc(sizeof(struct node));
    temp->data=val;
    temp->back=NULL;temp->next=NULL;

    if(*root==NULL)
    {
        *root=temp;
    }
    else if( (*root)->data>=temp->data )
    {
        temp->next=*root;
        temp->next->back=temp;
        *root=temp;
    }
    else
    {

        p=*root;
        while(p->next!=NULL && p->next->data<temp->data)
        {
            p=p->next;
        }
        if(p->next)
        {
            p->next->back=temp;
        }
        temp->back=p;
        temp->next=p->next;
        p->next=temp;

    }

}

it works fine so now i am confused as of why wasn't it working for the first time but works fine when i write the condition in a different else if statement

will be really helpful if someone can explain

tried inserting in a doubly linked list in a sorted manner but ran into (0xC0000005)


问:
Vite server encoding chartset problems (iso-8859-15)
When running a Vite server in vanilla js for development or build, charset encoding changes at index.html. For specific reasons, I need the encoding to be iso-8859-15 (I know utf-8 is a more standard one, but I must use iso-8859-15) for write simple html, css and js pages (I use Vite bec workflow in the future). I declared charset encoding in index.html as follow:

```<code><!DOCTYPE html>
<html lang="es">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>ÁÉÍÓÚ áéíóú ñ ¿?</h1>
    <script type="module" src="/js/main.js"></script>
  </body>
</html>
</code>```

Here is the result when running in dev mode (same on build: encoding changes):
html charset render wrong on Vite dev server

This is the result of changing the encoding also in Vs Code to iso-8859-15. Browsers return that the encoding is right (iso-8859-15), but it renders as the above image.

I'm kind of new using bundlers like Vite and it's my first time asking at Stack overflow because I couldn't find answers related to fix this problem. I suppose there is a way to change encoding at the vite.config.js or that the problem is related on how node.js runs a local server, but I can't figure it out a solution.

Any ideas of why this happens and how to solve it if it's possible? Thank you very much!

Body:
When running a Vite server in vanilla js for development or build, charset encoding changes at index.html. For specific reasons, I need the encoding to be iso-8859-15 (I know utf-8 is a more standard one, but I must use iso-8859-15) for write simple html, css and js pages (I use Vite bec workflow in the future). I declared charset encoding in index.html as follow:

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

ÁÉÍÓÚ áéíóú ñ ¿?

Here is the result when running in dev mode (same on build: encoding changes):
html charset render wrong on Vite dev server

This is the result of changing the encoding also in Vs Code to iso-8859-15. Browsers return that the encoding is right (iso-8859-15), but it renders as the above image.

I'm kind of new using bundlers like Vite and it's my first time asking at Stack overflow because I couldn't find answers related to fix this problem. I suppose there is a way to change encoding at the vite.config.js or that the problem is related on how node.js runs a local server, but I can't figure it out a solution.

Any ideas of why this happens and how to solve it if it's possible? Thank you very much!


问:
Connect file with json-animation to script in YII
Good afternoon.
Tell me, please, how can I connect a file with animation in json format to a file with an initialization script bodymovin.
The problem is that all this is spinning inside the YII, and configured so that relative paths do not work (don't ask :))
Is there a way to connect this somewhere in the controller, like registerCSS/registerJS ?
Thank you

Relative paths don't work (is it possible to determine the base path dynamically in YII)


问:
running mongoimport (mongodb tools) inside a docker container
I would like to be able to execute a mongoimport command within a container that runs nodejs as well.
should I specify a specific image in the FORM instruction in addition to nodejs image? OR:
should I put in the docker file an instruction to install the mongodb tools for the tar file?
how would you implement such requirement?

I tried to find a proper image but it doesn't seem to exist.


问:
How to decrease the opacity of only background in HTML, CSS?
`

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<style>
    #h1{
        background-color: rgb(81, 5, 151);
        opacity: 0.8;
    }
</style>
</head>
<body>
    <h1 id="h1">Change only background opacity not text. When I am run this code it has shown  me both opacity decrease background and text.<y /h1>
        <br>
        Here I have taken h1 and give id
</body>
</html>
</code>```

`

I want to decraese opacity only upper side of image but i am not getting solution.

Body:
`

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Change only background opacity not text. When I am run this code it has shown  me both opacity decrease background and text.<y /h1>

        Here I have taken h1 and give id

`

I want to decraese opacity only upper side of image but i am not getting solution.


问:
javascript . copying an image from one canvas to another and saving the image from the new one works unreliably
I have a canvas with an image.
I want to download its image when a link is clicked, but at a different size.

My solution works only when I press the link every other time. so I press the link the first time and it doesn't work (web browser's image saver fails to open), second time it does work, third time it does save but if the canvas image has been modified since the first successful save (second attempt), this attempt saves the original unmodified version, forth time it does work (modifications to canvas image is included in the saved image). This pattern is consistent and I don't believe I am mismanaging my files.

```<code>link.addEventListener('click', function() {
    var canvasN = document.createElement('canvas');
    var ctxN = canvasN.getContext("2d");

    canvasN.width = canvasX.value; // canvasX/Y global variables
    canvasN.height = canvasY.value;

    var imgo = new Image();
    imgo.src = canvas.toDataURL(); // data from original canvas global variable
            imgo.onload = function() {
        ctxN.drawImage(imgo,0,0, canvasN.width,canvasN.height);
        link.href = canvasN.toDataURL("image/png");
    };
        link.download = "image.png";

    });
</code>```

upon a link being clicked, my code creates a new canvas, with my desired size.
it then loads the data from the original canvas into an image, which is then drawn onto the new canvas, and its image is then finally downloaded (not reliably however).

How do I fix this to make it work consistently?

Body:
I have a canvas with an image.
I want to download its image when a link is clicked, but at a different size.

My solution works only when I press the link every other time. so I press the link the first time and it doesn't work (web browser's image saver fails to open), second time it does work, third time it does save but if the canvas image has been modified since the first successful save (second attempt), this attempt saves the original unmodified version, forth time it does work (modifications to canvas image is included in the saved image). This pattern is consistent and I don't believe I am mismanaging my files.

link.addEventListener('click', function() {
    var canvasN = document.createElement('canvas');
    var ctxN = canvasN.getContext("2d");

    canvasN.width = canvasX.value; // canvasX/Y global variables
    canvasN.height = canvasY.value;

    var imgo = new Image();
    imgo.src = canvas.toDataURL(); // data from original canvas global variable
            imgo.onload = function() {
        ctxN.drawImage(imgo,0,0, canvasN.width,canvasN.height);
        link.href = canvasN.toDataURL("image/png");
    };
        link.download = "image.png";

    });

upon a link being clicked, my code creates a new canvas, with my desired size.
it then loads the data from the original canvas into an image, which is then drawn onto the new canvas, and its image is then finally downloaded (not reliably however).

How do I fix this to make it work consistently?


问:
Getting only Bot as member when I try to get members of the channel in discord.js. How do I get all members present in the channel?
```<code>const client = new Client({intents: [GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMembers,
    Partials.GuildMember
], partials: ['MESSAGE', 'CHANNEL', 'REACTION', 'GUILD_MEMBER', 'USER'],});

const channel = client.channels.cache.get('#channel_id');
console.log(channel.members);

</code>```

The channel is not populated with members that are present in the channel before bot was created... Even though the required partials are given. Am I missing something ?

I expect to get all the users present in the channel and mention the user in the chat who has a particular role...

I am using discord version 14

Body:
const client = new Client({intents: [GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMembers,
    Partials.GuildMember
], partials: ['MESSAGE', 'CHANNEL', 'REACTION', 'GUILD_MEMBER', 'USER'],});

const channel = client.channels.cache.get('#channel_id');
console.log(channel.members);

The channel is not populated with members that are present in the channel before bot was created... Even though the required partials are given. Am I missing something ?

I expect to get all the users present in the channel and mention the user in the chat who has a particular role...

I am using discord version 14