问:
why perf record --count option doesn't work properly?
I've the following program

```<code>int main(){

    int a = 0;
    a += 1;

    return 0;
}
</code>```
```<code>main:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], 0
        add     DWORD PTR [rbp-4], 1
        mov     eax, 0
        pop     rbp
        ret
</code>```

I want to count instructions by using perf tool

when i set -c  --count with 2 I understand that perf collects a sample for every 2 instructions.

When i execute the following

```<code>
 gcc -O0 simple_main.cc
 sudo su
 perf stat ./a.out

 Performance counter stats for './a.out':

              0,46 msec task-clock                #    0,488 CPUs utilized
                 0      context-switches          #    0,000 /sec
                 0      cpu-migrations            #    0,000 /sec
                50      page-faults               #  108,640 K/sec
           722.745      cycles                    #    1,570 GHz
           696.848      instructions              #    0,96  insn per cycle
           135.823      branches                  #  295,117 M/sec
             4.688      branch-misses             #    3,45% of all branches
         3.613.725      slots                     #    7,852 G/sec
           779.430      topdown-retiring          #     21,6% retiring
           439.315      topdown-bad-spec          #     12,2% bad speculation
         1.417.147      topdown-fe-bound          #     39,2% frontend bound
           977.831      topdown-be-bound          #     27,1% backend bound

       0,000942582 seconds time elapsed

       0,001022000 seconds user
       0,000000000 seconds sys

</code>```

It says I've 696k instructions total (my program + kernel instructions)

```<code>perf record -e instructions -c 2 ./a.out
</code>```
```<code>perf report --stdio
# To display the perf.data header info, please use --header/--header-only options.
#
#
# Total Lost Samples: 0
#
# Samples: 1  of event 'instructions'
# Event count (approx.): 2
#
# Overhead  Command  Shared Object      Symbol
# ........  .......  .................  ..................
#
   100.00%  perf-ex  [kernel.kallsyms]  [k] x86_pmu_enable

#
# (Cannot load tips.txt file, please install perf!)
#

</code>```

I get 2 or sometimes nothing
but when i say --count=12000

```<code>root@rt7-laptop-vivo:/home/rt7/Desktop/omp_perf_example# perf record -e instructions -c 12000 ./a.out
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0,026 MB perf.data (52 samples) ]
root@rt7-laptop-vivo:/home/rt7/Desktop/omp_perf_example# perf report --stdio
# To display the perf.data header info, please use --header/--header-only options.
#
#
# Total Lost Samples: 0
#
# Samples: 52  of event 'instructions'
# Event count (approx.): 624000
#
# Overhead  Command  Shared Object         Symbol
# ........  .......  ....................  .......................................
#
     7.69%  a.out    [kernel.kallsyms]     [k] __handle_mm_fault
     5.77%  a.out    [kernel.kallsyms]     [k] filemap_map_pages
     5.77%  a.out    [kernel.kallsyms]     [k] page_add_file_rmap
     5.77%  a.out    ld-linux-x86-64.so.2  [.] add_to_global_resize
     3.85%  a.out    [kernel.kallsyms]     [k] next_uptodate_page
     3.85%  a.out    ld-linux-x86-64.so.2  [.] _dl_profile_fixup
     1.92%  a.out    [kernel.kallsyms]     [k] __cgroup_throttle_swaprate
     1.92%  a.out    [kernel.kallsyms]     [k] __kmalloc
     1.92%  a.out    [kernel.kallsyms]     [k] clear_page_erms
     1.92%  a.out    [kernel.kallsyms]     [k] crng_make_state
     1.92%  a.out    [kernel.kallsyms]     [k] do_mmap
     1.92%  a.out    [kernel.kallsyms]     [k] do_open
     1.92%  a.out    [kernel.kallsyms]     [k] find_vma
     1.92%  a.out    [kernel.kallsyms]     [k] free_pipe_info
     1.92%  a.out    [kernel.kallsyms]     [k] free_swap_cache
     1.92%  a.out    [kernel.kallsyms]     [k] handle_mm_fault
     1.92%  a.out    [kernel.kallsyms]     [k] ksys_mmap_pgoff
     1.92%  a.out    [kernel.kallsyms]     [k] lock_page_memcg
     1.92%  a.out    [kernel.kallsyms]     [k] memcg_slab_post_alloc_hook
:

</code>```

I get similar results to perf stat. It counted 624k instructions. why and how?

doesn't perf record -c N ./a.out mean collect a single sample after every N operations? in this case it should collect single sample after each 12000 instructions. Am i mistaken??

Body:
I've the following program

int main(){

    int a = 0;
    a += 1;

    return 0;
}

main:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], 0
        add     DWORD PTR [rbp-4], 1
        mov     eax, 0
        pop     rbp
        ret

I want to count instructions by using perf tool

when i set -c  --count with 2 I understand that perf collects a sample for every 2 instructions.

When i execute the following

 gcc -O0 simple_main.cc
 sudo su
 perf stat ./a.out

 Performance counter stats for './a.out':

              0,46 msec task-clock                #    0,488 CPUs utilized
                 0      context-switches          #    0,000 /sec
                 0      cpu-migrations            #    0,000 /sec
                50      page-faults               #  108,640 K/sec
           722.745      cycles                    #    1,570 GHz
           696.848      instructions              #    0,96  insn per cycle
           135.823      branches                  #  295,117 M/sec
             4.688      branch-misses             #    3,45% of all branches
         3.613.725      slots                     #    7,852 G/sec
           779.430      topdown-retiring          #     21,6% retiring
           439.315      topdown-bad-spec          #     12,2% bad speculation
         1.417.147      topdown-fe-bound          #     39,2% frontend bound
           977.831      topdown-be-bound          #     27,1% backend bound

       0,000942582 seconds time elapsed

       0,001022000 seconds user
       0,000000000 seconds sys

It says I've 696k instructions total (my program + kernel instructions)

perf record -e instructions -c 2 ./a.out

perf report --stdio
# To display the perf.data header info, please use --header/--header-only options.
#
#
# Total Lost Samples: 0
#
# Samples: 1  of event 'instructions'
# Event count (approx.): 2
#
# Overhead  Command  Shared Object      Symbol
# ........  .......  .................  ..................
#
   100.00%  perf-ex  [kernel.kallsyms]  [k] x86_pmu_enable

#
# (Cannot load tips.txt file, please install perf!)
#

I get 2 or sometimes nothing
but when i say --count=12000

root@rt7-laptop-vivo:/home/rt7/Desktop/omp_perf_example# perf record -e instructions -c 12000 ./a.out
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0,026 MB perf.data (52 samples) ]
root@rt7-laptop-vivo:/home/rt7/Desktop/omp_perf_example# perf report --stdio
# To display the perf.data header info, please use --header/--header-only options.
#
#
# Total Lost Samples: 0
#
# Samples: 52  of event 'instructions'
# Event count (approx.): 624000
#
# Overhead  Command  Shared Object         Symbol
# ........  .......  ....................  .......................................
#
     7.69%  a.out    [kernel.kallsyms]     [k] __handle_mm_fault
     5.77%  a.out    [kernel.kallsyms]     [k] filemap_map_pages
     5.77%  a.out    [kernel.kallsyms]     [k] page_add_file_rmap
     5.77%  a.out    ld-linux-x86-64.so.2  [.] add_to_global_resize
     3.85%  a.out    [kernel.kallsyms]     [k] next_uptodate_page
     3.85%  a.out    ld-linux-x86-64.so.2  [.] _dl_profile_fixup
     1.92%  a.out    [kernel.kallsyms]     [k] __cgroup_throttle_swaprate
     1.92%  a.out    [kernel.kallsyms]     [k] __kmalloc
     1.92%  a.out    [kernel.kallsyms]     [k] clear_page_erms
     1.92%  a.out    [kernel.kallsyms]     [k] crng_make_state
     1.92%  a.out    [kernel.kallsyms]     [k] do_mmap
     1.92%  a.out    [kernel.kallsyms]     [k] do_open
     1.92%  a.out    [kernel.kallsyms]     [k] find_vma
     1.92%  a.out    [kernel.kallsyms]     [k] free_pipe_info
     1.92%  a.out    [kernel.kallsyms]     [k] free_swap_cache
     1.92%  a.out    [kernel.kallsyms]     [k] handle_mm_fault
     1.92%  a.out    [kernel.kallsyms]     [k] ksys_mmap_pgoff
     1.92%  a.out    [kernel.kallsyms]     [k] lock_page_memcg
     1.92%  a.out    [kernel.kallsyms]     [k] memcg_slab_post_alloc_hook
:

I get similar results to perf stat. It counted 624k instructions. why and how?

doesn't perf record -c N ./a.out mean collect a single sample after every N operations? in this case it should collect single sample after each 12000 instructions. Am i mistaken??


来源: stackexchange

问:
Drupal does not work in Azure App Service
When I upload the source code of Drupal 9 with php 8.1 in Azure App Service, and then I run the installation, all goes well, but when the installation process finishes, it suddenly gives me 404 error, index.php not found. I've tried with the template of the default file of nginx for Drupal (https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/), but it still does not work. I've tried to do the same with Drupal 10 also, but I get the same error.</p>

ContentLicense: CC BY-SA 4.0


问:
Is is possible to get additional information about the appstate?
I would like to know if there is a way to get additional information about the appstate? I'm using React Native and I looked at the documentation for AppState (https://reactnative.dev/docs/appstate) but I need more information than just 'active', 'inactive' or 'background'.

For example if the user would lock the phone I would need to get something like 'locked' or when the user gets a call when using the app I get back 'call'. Is something like this possible in React Native (or other programming languages)?


问:
Thickness animation changes brush color Textbox | WPF .NET Framework 8
I'm working on a style library for my own on a MVVM WPF App.
When i use a custom style in XAML on my textbox which contains a Trigger.EnterActions with a ThicknessAnimation on my border, my animation will append but it changes the initial BorderBrush of my textbox by the default blue color.

Here is my XAML Dictionnary

```<code><Style x:Key="TEST1"
           TargetType="TextBox">
        <!--SETTERS-->
        <Style.Setters>
            <Setter Property="VerticalContentAlignment"
                    Value="Center" />
        </Style.Setters>
        <!--TRIGGERS-->
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocused"
                     Value="True">
                <Trigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <ThicknessAnimation Duration="0:0:0.100" Storyboard.TargetProperty="BorderThickness" To="1 1 1 3" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
                <Trigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <ThicknessAnimation Duration="0:0:0.300" To="1" Storyboard.TargetProperty="BorderThickness" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.ExitActions>
            </Trigger>
        </Style.Triggers>
    </Style>

</code>```

Here is my textbox on my window :

```<code><Window x:Class="Design.View.Textboxes"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:Design.View"
      mc:Ignorable="d"
      d:DesignHeight="450" d:DesignWidth="800"
      Title="Textboxes"
      WindowStyle="SingleBorderWindow">

    <Border Width="500"
            Height="Auto">
        <StackPanel Orientation="Horizontal">

            <TextBox Width="100"
                     Height="30"
                     Margin="4"/>

            <TextBox Width="100"
                     Height="30"
                     Margin="4"
                     BorderBrush="{StaticResource Primary}"
                     Style="{StaticResource TEST1}" />

        </StackPanel>
    </Border>
</Window>

</code>```

I was expecting the border to fit the color already set in the BorderBrush field of the Textbox Template during the animation but it doesn't.

I tried to use ColorAnimation and didn't know how to make it functional and i do believe that it is a weird way to solve this problem and not clean at all.
I thought about creating a custom textbox inherating of TextBox class with a new dependency containing the color and set it in every Storyboard...

But i want to know if there is a better way to make it work easily and let the code as clean as possible in pure XAML without any code behind.

Body:
I'm working on a style library for my own on a MVVM WPF App.
When i use a custom style in XAML on my textbox which contains a Trigger.EnterActions with a ThicknessAnimation on my border, my animation will append but it changes the initial BorderBrush of my textbox by the default blue color.

Here is my XAML Dictionnary

    </Style>

Here is my textbox on my window :

<Window x:Class="Design.View.Textboxes"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:Design.View"
      mc:Ignorable="d"
      d:DesignHeight="450" d:DesignWidth="800"
      Title="Textboxes"
      WindowStyle="SingleBorderWindow">

    <Border Width="500"
            Height="Auto">
        <StackPanel Orientation="Horizontal">

            <TextBox Width="100"
                     Height="30"
                     Margin="4"/>

            <TextBox Width="100"
                     Height="30"
                     Margin="4"
                     BorderBrush="{StaticResource Primary}"
                     Style="{StaticResource TEST1}" />

        </StackPanel>
    </Border>
</Window>

I was expecting the border to fit the color already set in the BorderBrush field of the Textbox Template during the animation but it doesn't.

I tried to use ColorAnimation and didn't know how to make it functional and i do believe that it is a weird way to solve this problem and not clean at all.
I thought about creating a custom textbox inherating of TextBox class with a new dependency containing the color and set it in every Storyboard...

But i want to know if there is a better way to make it work easily and let the code as clean as possible in pure XAML without any code behind.


问:
Get keyframe rotation and position in python blender
Here is what I'm trying to do: I want to get each and every keyframe's rotation and position in blender to then export it into beamng drive. Well at least this is the first step. What I'm already strugling with is how do I get the keyframe data. I have a few years of programming experience, but not in python and blender, and I've only seen solutions to getting amrmature keyframes data, but not simply keyframe data.</p>


问:
(Solved) Android Studio. TextView can't be found using FindViewByID of the specific textView
I'm attempting to implement a RecyclerView in my app that consists of multiple items, each have a button which transitions to another activity and a TextView which says where the button will go to. Here is the XML file for the design and code:
Design
XML Code

This is my RecyclerView adapter.
Adapter

When line 39 is called, I get a nullPointerException.
Full Error Message

The AndroidManifest file if it helps.
(https://i.stack.imgur.com/1dbtW.png)

This happens when I open the activity that the RecyclerView is in. I have two System.out.println in my adapter to attempt to debug at the bottom of the adapter. The first one returned an integer for what I assume is the TextView ID, but the second one returns null. Why would it return null if the ID is an ID of something defined in R.id?

If it helps, I'm using this tutorial to learn about RecyclerView. If it's outdated that might explain it.
https://www.youtube.com/watch?v=Mc0XT58A1Z4&t=1195s

I've searched the XML file of the layout for the item to make sure it exists, I've renamed the TextView to something completely random to make sure there were no duplicate naming issues. I've hardcoded the ID to the ID of the specific element of the RecyclerView row item. Each time, there's been no change. When I open the new activity I just want a single row to appear for the one element I've defined so far.


问:
Windows Forms C# Buttons in TableLayoutPanel Margins being overwritten
Buttons very close to each other.

Component Code:

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing;

namespace CustomExplorer.Components
{
    public partial class RunningApps : TableLayoutPanel
    {
        public RunningApps()
        {
            InitializeComponent();
        }

        public RunningApps(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
            this.ColumnStyles.Clear();
            this.RowStyles.Clear();
            this.RowStyles.Add(new RowStyle(SizeType.Percent, 100));

            this.HandleCreated += new EventHandler(this.Form_Load);
        }

        private void Form_Load(object sender, EventArgs e)
        {
            // Process list and spawn buttons
            List<WindowData> ar = WindowsTasks.GetActiveTasks();
            this.ColumnCount = ar.Count;
            this.MinimumSize = new Size(50 * ar.Count, 54);
            this.Size = new Size(50 * ar.Count, 54);
            for (int i = 0; i < ar.Count; i++)
            {
                this.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100 / this.ColumnCount));
                Button button = new Button();

                WindowData w = ar[i];

                // Setup Button Style
                button.Name = string.Format("Button_{0:D}", i);
                button.Text = string.Format("Button_{0:D}", i);
                button.BackColor = Color.Transparent;
                button.FlatStyle = FlatStyle.Flat;
                button.FlatAppearance.BorderSize = 0;

                // Icon
                button.Image = w.icon.ToBitmap();
                button.ImageAlign = ContentAlignment.MiddleCenter;

                // Sizes
                button.MinimumSize = new Size(50, 54);
                button.Margin = new Padding(5);
                button.Size = new Size(50, 54);

                // Utils
                this.Controls.Add(button, i, 0);
            }
        }
    }
}
</code>```

The way buttons are exposed:

The function gives the running process that have "Graphics", add them all to Array ar. Then the for loop adds columns for each of the buttons and them other for loop add the buttons with the image

Tried all that I could found. Margins, Paddings and stuff seems to be only applied at the first Button.

The component is imported to a tablelayout at main Component

Body:
Buttons very close to each other.

Component Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing;

namespace CustomExplorer.Components
{
    public partial class RunningApps : TableLayoutPanel
    {
        public RunningApps()
        {
            InitializeComponent();
        }

        public RunningApps(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
            this.ColumnStyles.Clear();
            this.RowStyles.Clear();
            this.RowStyles.Add(new RowStyle(SizeType.Percent, 100));

            this.HandleCreated += new EventHandler(this.Form_Load);
        }

        private void Form_Load(object sender, EventArgs e)
        {
            // Process list and spawn buttons
            List<WindowData> ar = WindowsTasks.GetActiveTasks();
            this.ColumnCount = ar.Count;
            this.MinimumSize = new Size(50 * ar.Count, 54);
            this.Size = new Size(50 * ar.Count, 54);
            for (int i = 0; i < ar.Count; i++)
            {
                this.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100 / this.ColumnCount));
                Button button = new Button();

                WindowData w = ar[i];

                // Setup Button Style
                button.Name = string.Format("Button_{0:D}", i);
                button.Text = string.Format("Button_{0:D}", i);
                button.BackColor = Color.Transparent;
                button.FlatStyle = FlatStyle.Flat;
                button.FlatAppearance.BorderSize = 0;

                // Icon
                button.Image = w.icon.ToBitmap();
                button.ImageAlign = ContentAlignment.MiddleCenter;

                // Sizes
                button.MinimumSize = new Size(50, 54);
                button.Margin = new Padding(5);
                button.Size = new Size(50, 54);

                // Utils
                this.Controls.Add(button, i, 0);
            }
        }
    }
}

The way buttons are exposed:

The function gives the running process that have "Graphics", add them all to Array ar. Then the for loop adds columns for each of the buttons and them other for loop add the buttons with the image

Tried all that I could found. Margins, Paddings and stuff seems to be only applied at the first Button.

The component is imported to a tablelayout at main Component


问:
Running into grid item text overflow vertically on my sidebar
Running into an issue: I have a total of five grid items, but the problem lies within two items: leftbar & rightbar - the text overflows vertically when I scale the page down. Instead, I would like for the text to remain wthin the two grid items and mold around the brand shown in the middle. I understand that I can use overflow:scroll and it would solve my issue, but that's not a solution I'm looking for. Ideally, I want the the left/rightbars to adjust around the other grid items.

HTML:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>
<body>
    <header>
        <div class = "header">
        <a href="#"target="_blank"> Hello, World. </a>
        </div>
    </header>
    <div class = "container flex">
        <nav class="nav">
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">Gallery</a></li>
                <li><a href="#">Options</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
        <main class="logo-center">
            <div class= "logo-center-grid-items">
                <h1></h1>
                <h1></h1>
                <h1></h1>
                <h1></h1>
            </div>
        </main>
        <div class="leftbar">
            <h3>the art.</h3><br>
            <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima nostrum facere eum laborum blanditiis exercitationem doloremque. Veritatis suscipit sunt a earum error illum quam, adipisci, fuga corporis in distinctio molestias!
            </p> <br>
            <div class = "creations-btn">
                 <a href= "#">creations</a>
            </div><br>
        </div>
        <div class="rightbar">
            <h3>the craft.</h3><br>
            <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima nostrum facere eum laborum blanditiis exercitationem doloremque. Veritatis suscipit sunt a earum error illum quam, adipisci, fuga corporis in distinctio molestias!
            </p><br>
            <div class = "order-btn">
                 <a href= "#">order</a>
            </div><br>
        </div>
        <footer>
            <div class="social-media">
                <a href="#"> <i class="fab fa-facebook"></i></a>
                <a href="#"> <i class="fab fa-instagram"></i></a>
                <a href="#"> <i class="fab fa-discord"></i></a>
                <a href="#"> <i class="fab fa-youtube"></i></a>
            </div>
        </footer>
    </div>
</body>
</html>

</code>```

My CSS:

```<code>:root{
    --main-radius: 25px;
    --main-padding: 40px;
    box-sizing: border-box;
}

.container{
    display: grid;
    height: 100vh;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: auto 35% 35% auto;
    grid-template-areas:
    "nav nav nav nav"
    "leftbar main main rightbar"
    "leftbar main main rightbar"
    "footer footer footer footer";
    grid-gap: 1.5rem;
    text-align: center;
    margin: 15px;
    margin-bottom: 45px;
}

/* grid items (5) */
/* nav (deleted for the sake of unimportance) */

/* logo center */
 .logo-center {
    grid-area: main;
    display: grid;
 }

 .logo-center > div {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
 }

 .logo-center h1 {
     background-attachment: fixed;
 }

/* left sidebar */
.leftbar{
    grid-area: leftbar;
}

/* right sidebar*/
.rightbar{
    grid-area: rightbar;
}

.rightbar > p{
    margin: 20px;
}

/* footer (deleted for the sake of unimportance)  */

</code>```

I did find one solution that allowed the items to form around the grid like I want, adding inline-table to the parents...

```<code>display:inline-table;
width: 100%;
</code>```

but ultimately this solution comes with the price of the sidebars digging into the footer.

Body:
Running into an issue: I have a total of five grid items, but the problem lies within two items: leftbar & rightbar - the text overflows vertically when I scale the page down. Instead, I would like for the text to remain wthin the two grid items and mold around the brand shown in the middle. I understand that I can use overflow:scroll and it would solve my issue, but that's not a solution I'm looking for. Ideally, I want the the left/rightbars to adjust around the other grid items.

HTML:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

         Hello, World.

Home

Gallery

Options

Contact

the art.

 Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima nostrum facere eum laborum blanditiis exercitationem doloremque. Veritatis suscipit sunt a earum error illum quam, adipisci, fuga corporis in distinctio molestias!

                 creations

the craft.

 Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima nostrum facere eum laborum blanditiis exercitationem doloremque. Veritatis suscipit sunt a earum error illum quam, adipisci, fuga corporis in distinctio molestias!

                 order

My CSS:

:root{
    --main-radius: 25px;
    --main-padding: 40px;
    box-sizing: border-box;
}

.container{
    display: grid;
    height: 100vh;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: auto 35% 35% auto;
    grid-template-areas:
    "nav nav nav nav"
    "leftbar main main rightbar"
    "leftbar main main rightbar"
    "footer footer footer footer";
    grid-gap: 1.5rem;
    text-align: center;
    margin: 15px;
    margin-bottom: 45px;
}

/* grid items (5) */
/* nav (deleted for the sake of unimportance) */

/* logo center */
 .logo-center {
    grid-area: main;
    display: grid;
 }

 .logo-center > div {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
 }

 .logo-center h1 {
     background-attachment: fixed;
 }

/* left sidebar */
.leftbar{
    grid-area: leftbar;
}

/* right sidebar*/
.rightbar{
    grid-area: rightbar;
}

.rightbar > p{
    margin: 20px;
}

/* footer (deleted for the sake of unimportance)  */

I did find one solution that allowed the items to form around the grid like I want, adding inline-table to the parents...

display:inline-table;
width: 100%;

but ultimately this solution comes with the price of the sidebars digging into the footer.


问:
can console.log content of signedCookie but can not access content
Have an express backend that sent signedCookies. the content of the signedCookie is a key and an object with 2 JWT as value

```<code>   "tokens":  "{
          "accessToken":"klkmlk",
          "refreshToken":"kjlkjkle"
      }"
</code>```

When client is sending back the cookie, I can console log the "tokens", that shows the object, but for example tokens.accessToken returns undefined...
What's wrong ?

```<code>// parser with the secret jey to sign the cookie
app.use(cookieParser("secretKeyForCookie"));

// signed cookie options
res.cookie("tokens", checkLogin.data, {
        httpOnly: true,
        secure: true,
        signed: true,
        maxAge: 100000,
        sameSite: true,
        path: "/",
      });

//, Object.keys lists keys but undefined when access one of the key
console.log(
      Object.keys(req.signedCookies.tokens), // returns ['accessToken', 'refreshToken']
      req.cookies.tokens["accessToken"] // undefined
    );
</code>```

Body:
Have an express backend that sent signedCookies. the content of the signedCookie is a key and an object with 2 JWT as value

   "tokens":  "{
          "accessToken":"klkmlk",
          "refreshToken":"kjlkjkle"
      }"

When client is sending back the cookie, I can console log the "tokens", that shows the object, but for example tokens.accessToken returns undefined...
What's wrong ?

// parser with the secret jey to sign the cookie
app.use(cookieParser("secretKeyForCookie"));

// signed cookie options
res.cookie("tokens", checkLogin.data, {
        httpOnly: true,
        secure: true,
        signed: true,
        maxAge: 100000,
        sameSite: true,
        path: "/",
      });

//, Object.keys lists keys but undefined when access one of the key
console.log(
      Object.keys(req.signedCookies.tokens), // returns ['accessToken', 'refreshToken']
      req.cookies.tokens["accessToken"] // undefined
    );


问:
Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array
this is a custom hook that allows the user to log in dashboard page if he loggedin

```<code>import { getAuth, onAuthStateChanged } from 'firebase/auth'
import { useState, useEffect } from 'react'

export function useAuthStatus() {
    const [loggedIn, setLoggedIn] = useState(false)
    const [checkingStatus, setCheckingStatus] = useState(true)

    useEffect(()=>{
        const auth = getAuth()
        onAuthStateChanged(auth , (user)=>{
            if(user){
                setLoggedIn(true)
            }
            setCheckingStatus(false)
        })
        console.log("hello")

    }, [])
  return {loggedIn, checkingStatus}
}
</code>```

and here where im use it as a private route

```<code>import {useAuthStatus} from '../hooks/useAuthStatus'
import { Outlet , Navigate} from 'react-router-dom'

function PrivateRoute() {
    const {loggedIn, checkingStatus} = useAuthStatus();
    if(checkingStatus){
        return <div>looding...</div>
    }
  return loggedIn ? <Outlet/> : <Navigate to="/auth/sign-in"/>
}

export default PrivateRoute
</code>```

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array

Body:
this is a custom hook that allows the user to log in dashboard page if he loggedin

import { getAuth, onAuthStateChanged } from 'firebase/auth'
import { useState, useEffect } from 'react'

export function useAuthStatus() {
    const [loggedIn, setLoggedIn] = useState(false)
    const [checkingStatus, setCheckingStatus] = useState(true)

    useEffect(()=>{
        const auth = getAuth()
        onAuthStateChanged(auth , (user)=>{
            if(user){
                setLoggedIn(true)
            }
            setCheckingStatus(false)
        })
        console.log("hello")

    }, [])
  return {loggedIn, checkingStatus}
}

and here where im use it as a private route

import {useAuthStatus} from '../hooks/useAuthStatus'
import { Outlet , Navigate} from 'react-router-dom'

function PrivateRoute() {
    const {loggedIn, checkingStatus} = useAuthStatus();
    if(checkingStatus){
        return
looding...

    }
  return loggedIn ? <Outlet/> : <Navigate to="/auth/sign-in"/>
}

export default PrivateRoute

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array


问:
The action 'NAVIGATE' with payload {"name":"AddTask"} was not handled by any navigator. Do you have a screen named 'AddTask'?
App.js

```<code>import React from'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, Header } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Todo from './Todo';
import Done from './Done';
import Entrypage from './Entrypage';
import Addtask from './Addtask';
import Fontawesome5 from 'react-native-vector-icons/FontAwesome5';
import { StatusBar } from 'react-native';

const Tab = createBottomTabNavigator();

const Hometabs = () => {
return(
    <NavigationContainer
    independent={true}
    >
    <Tab.Navigator
    screenOptions={({route})=>({
    tabBarActiveTintColor:('#4682b4'),
    tabBarLabelStyle:{fontSize:13,fontWeight:'bold'},
    tabBarIcon:({focused,size,color,}) =>{
    let iconname;
    if(route.name==='To-do'){
    iconname='clipboard-list';
    color=focused? '#383':'#555';
    size=focused? 26 : 25;

    }else if(route.name==='Done'){
    iconname='clipboard-check';
    color=focused? '#383':'#555';
    size=focused? 26 : 25;

    }
    return(
        <Fontawesome5
        name={iconname}
        color={color}
        size={size}
        />
    )
    }
    })}
    >
    <Tab.Screen
    name="To-do"
    component={Todo}
    options={{header:() => null}}
    />
    <Tab.Screen
    name="Done"
    component={Done}
    options={{header:() => null}}

    />
    </Tab.Navigator>
    </NavigationContainer>
)
}

const RootStack = createStackNavigator();

    const App = () =>{
        return(

            <NavigationContainer>
                <RootStack.Navigator
                initialRouteName="Entry"
                >
                    <RootStack.Screen
                    name="Entry"
                    component={Entrypage}
                    options={{
                        header:() => null
                    }}
                    />

                    <RootStack.Screen
                    name="Tasks"
                    component={Hometabs}
                    options={{headerStyle:{backgroundColor:'#4682b4'},
                    headerTintColor:'#fff',
                    headerTitleAlign:'center',
                    }}
                    />

                    <RootStack.Screen
                    name="AddTask"
                    component={Addtask}
                    />
                    </RootStack.Navigator>
            </NavigationContainer>
        )
    }

export default App;
</code>```

Entrypage:

```<code>import React, { useEffect } from 'react';
import{
View,
Text,
Image,
StyleSheet,
StatusBar,
 }from 'react-native';

export default function Enrtypage({navigation}) {

    useEffect(()=>{
        setTimeout(()=>{
            navigation.replace('Tasks');
        },2000);
    },[]);

    return(
        <View style={styles.body}>
            <StatusBar
            backgroundColor={'#4682b4'}
            />
            <Image
            style={styles.logo}
            source={require('../assests/write.png')}
            />
            <Text style={styles.Text}>
                To-Do List
            </Text>
        </View>
    )
}

const styles = StyleSheet.create({

body:{
flex:1,
backgroundColor:'#4682b4',
alignItems:'center',
justifyContent:'center',
},

Text:{
fontSize: 35,
fontWeight:'900',
margin:15,
color:'#fff'

},

logo:{
height:150,
width: 150,
},

})
</code>```

Todo:

```<code>import React from 'react';
import{
View,
Text,
StyleSheet,
TouchableOpacity,
Button,
}from 'react-native';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';

export default function Todo ({navigation}) {
    return(
        <View style={styles.body}>
        <TouchableOpacity style={styles.button}
        onPress={()=>{
            navigation.navigate('AddTask');
        }}
        >
            <FontAwesome5
            name='pen'
            color='#fff'
            size={23}
            />
        </TouchableOpacity>
        </View>
    )
}

const styles = StyleSheet.create({
    body:{
    flex:1,
    },

    text:{
    color:'#000',
    },

    button:{
    width:60,
    height:60,
    backgroundColor:'#4682b4',
    borderRadius: 50,
    borderColor:'#000',
    justifyContent:'center',
    alignItems:'center',
    position:'absolute',
    bottom:20,
    right: 20,
    },
})

</code>```

Done:

```<code>import React from 'react';
import{
View,
Text,
StyleSheet,
}from 'react-native';

export default function Done () {
    return(
        <View style={styles.body}>
        <Text style={styles.text}>
            Done
        </Text>
    </View>
    )
}

const styles = StyleSheet.create({
    body:{
        flex:1,
        },

        text:{
        color:'#000',
        }
})
</code>```

Addtask:

```<code>import React from 'react';
import{
View,
StyleSheet,
} from 'react-native';
import { TextInput } from 'react-native-gesture-handler';

export default function Addtask () {
    return(
    <View>
        <TextInput/>
    </View>
    )
}

const style=StyleSheet.create({
body:{
flex:1,
},

})
</code>```

The Button in Todo is not navigating to Addtask page.

Body:
App.js

import React from'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, Header } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Todo from './Todo';
import Done from './Done';
import Entrypage from './Entrypage';
import Addtask from './Addtask';
import Fontawesome5 from 'react-native-vector-icons/FontAwesome5';
import { StatusBar } from 'react-native';

const Tab = createBottomTabNavigator();

const Hometabs = () => {
return(
    <NavigationContainer
    independent={true}
    >
    <Tab.Navigator
    screenOptions={({route})=>({
    tabBarActiveTintColor:('#4682b4'),
    tabBarLabelStyle:{fontSize:13,fontWeight:'bold'},
    tabBarIcon:({focused,size,color,}) =>{
    let iconname;
    if(route.name==='To-do'){
    iconname='clipboard-list';
    color=focused? '#383':'#555';
    size=focused? 26 : 25;

    }else if(route.name==='Done'){
    iconname='clipboard-check';
    color=focused? '#383':'#555';
    size=focused? 26 : 25;

    }
    return(
        <Fontawesome5
        name={iconname}
        color={color}
        size={size}
        />
    )
    }
    })}
    >
    <Tab.Screen
    name="To-do"
    component={Todo}
    options={{header:() => null}}
    />
    <Tab.Screen
    name="Done"
    component={Done}
    options={{header:() => null}}

    />
    </Tab.Navigator>
    </NavigationContainer>
)
}

const RootStack = createStackNavigator();

    const App = () =>{
        return(

            <NavigationContainer>
                <RootStack.Navigator
                initialRouteName="Entry"
                >
                    <RootStack.Screen
                    name="Entry"
                    component={Entrypage}
                    options={{
                        header:() => null
                    }}
                    />

                    <RootStack.Screen
                    name="Tasks"
                    component={Hometabs}
                    options={{headerStyle:{backgroundColor:'#4682b4'},
                    headerTintColor:'#fff',
                    headerTitleAlign:'center',
                    }}
                    />

                    <RootStack.Screen
                    name="AddTask"
                    component={Addtask}
                    />
                    </RootStack.Navigator>
            </NavigationContainer>
        )
    }

export default App;

Entrypage:

import React, { useEffect } from 'react';
import{
View,
Text,
Image,
StyleSheet,
StatusBar,
 }from 'react-native';

export default function Enrtypage({navigation}) {

    useEffect(()=>{
        setTimeout(()=>{
            navigation.replace('Tasks');
        },2000);
    },[]);

    return(
        <View style={styles.body}>
            <StatusBar
            backgroundColor={'#4682b4'}
            />
            <Image
            style={styles.logo}
            source={require('../assests/write.png')}
            />
            <Text style={styles.Text}>
                To-Do List
            </Text>
        </View>
    )
}

const styles = StyleSheet.create({

body:{
flex:1,
backgroundColor:'#4682b4',
alignItems:'center',
justifyContent:'center',
},

Text:{
fontSize: 35,
fontWeight:'900',
margin:15,
color:'#fff'

},

logo:{
height:150,
width: 150,
},

})

Todo:

import React from 'react';
import{
View,
Text,
StyleSheet,
TouchableOpacity,
Button,
}from 'react-native';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';

export default function Todo ({navigation}) {
    return(
        <View style={styles.body}>
        <TouchableOpacity style={styles.button}
        onPress={()=>{
            navigation.navigate('AddTask');
        }}
        >
            <FontAwesome5
            name='pen'
            color='#fff'
            size={23}
            />
        </TouchableOpacity>
        </View>
    )
}

const styles = StyleSheet.create({
    body:{
    flex:1,
    },

    text:{
    color:'#000',
    },

    button:{
    width:60,
    height:60,
    backgroundColor:'#4682b4',
    borderRadius: 50,
    borderColor:'#000',
    justifyContent:'center',
    alignItems:'center',
    position:'absolute',
    bottom:20,
    right: 20,
    },
})

Done:

import React from 'react';
import{
View,
Text,
StyleSheet,
}from 'react-native';

export default function Done () {
    return(
        <View style={styles.body}>
        <Text style={styles.text}>
            Done
        </Text>
    </View>
    )
}

const styles = StyleSheet.create({
    body:{
        flex:1,
        },

        text:{
        color:'#000',
        }
})

Addtask:

import React from 'react';
import{
View,
StyleSheet,
} from 'react-native';
import { TextInput } from 'react-native-gesture-handler';

export default function Addtask () {
    return(
    <View>
        <TextInput/>
    </View>
    )
}

const style=StyleSheet.create({
body:{
flex:1,
},

})

The Button in Todo is not navigating to Addtask page.


问:
React Native render error with _default method
My App is crashing due to the following error but i don´t have enough information for my self to solve the problem.

Render Error, Element type is invalid: expected a string (for built-in components) or a class/function (for composite components but got undefined)

Check the render method of _default

I assume it has something to do with some export or import in my code but i am not sure what is that is causing this issue.

createDataContext.js:

```<code>import React, { useReducer } from 'react';

export default (reducer, actions, initialState) => {
  const Context = React.createContext();

  const Provider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    const boundActions = {};
    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {children}
      </Context.Provider>
    );
  };

  return { Context, Provider };
};
</code>```

BlogContext.js:

```<code>import createDataContext from './createDataContext';

const blogReducer = (state, action) => {
  switch (action.type) {
    case 'add_blogpost':
      return [...state, { title: `Blog Post #${state.length + 1}` }];
    default:
      return state;
  }
};

const addBlogPost = dispatch => {
  return () => {
    dispatch({ type: 'add_blogpost' });
  };
};

export const { Context, Provider } = createDataContext(
  blogReducer,
  { addBlogPost },
  []
);
</code>```

IndexScreen.js:

```<code>import React, { useContext } from 'react';
import { View, Text, StyleSheet, FlatList, Button } from 'react-native';
import { Context } from '../context/BlogContext';

const IndexScreen = () => {
  const { state, addBlogPost } = useContext(Context);

  return (
    <View>
      <Text>Index Screen</Text>
      <Button title="Add Post" onPress={addBlogPost} />
      <FlatList
        data={state}
        keyExtractor={blogPost => blogPost.title}
        renderItem={({ item }) => {
          return <Text>{item.title}</Text>;
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({});

export default IndexScreen;
</code>```

Body:
My App is crashing due to the following error but i don´t have enough information for my self to solve the problem.

Render Error, Element type is invalid: expected a string (for built-in components) or a class/function (for composite components but got undefined)

Check the render method of _default

I assume it has something to do with some export or import in my code but i am not sure what is that is causing this issue.

createDataContext.js:

import React, { useReducer } from 'react';

export default (reducer, actions, initialState) => {
  const Context = React.createContext();

  const Provider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    const boundActions = {};
    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {children}
      </Context.Provider>
    );
  };

  return { Context, Provider };
};

BlogContext.js:

import createDataContext from './createDataContext';

const blogReducer = (state, action) => {
  switch (action.type) {
    case 'add_blogpost':
      return [...state, { title: `Blog Post #${state.length + 1}` }];
    default:
      return state;
  }
};

const addBlogPost = dispatch => {
  return () => {
    dispatch({ type: 'add_blogpost' });
  };
};

export const { Context, Provider } = createDataContext(
  blogReducer,
  { addBlogPost },
  []
);

IndexScreen.js:

import React, { useContext } from 'react';
import { View, Text, StyleSheet, FlatList, Button } from 'react-native';
import { Context } from '../context/BlogContext';

const IndexScreen = () => {
  const { state, addBlogPost } = useContext(Context);

  return (
    <View>
      <Text>Index Screen</Text>
      <Button title="Add Post" onPress={addBlogPost} />
      <FlatList
        data={state}
        keyExtractor={blogPost => blogPost.title}
        renderItem={({ item }) => {
          return <Text>{item.title}</Text>;
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({});

export default IndexScreen;


问:
How to make a newline between the options of a JOptionPane.showOptionDialog? Java
I show a menu with many options and I have to move the page to see all the options.

I would like to make a line break so that all the options are visible without having to move the window.


问:
Button is showing without form in template
I have a template in flask,and I want that a button will be showed inside a form element.
Basically what I'm trying to do is to show comment one after another with edit button between comments (according to the user that is login now).
This is the relevant part of the template:

```<code><div id='containerComment'>
            {% for comment in comments_post %}
                <div class='show_comment'>
                    <p>{{ comment['body'] }}</p>
                    <p class="about">by {{ comment_publishers[loop.index0] }} on {{ comment_times[loop.index0]}}</p>
                </div>
                {% if comment_publishers[loop.index0]==g.user['username'] %}
                    <form action="{{ url_for('blog.update_comment', id=comment['id'] )}}" method="get" id='Edit'>
                        <button name="edit" value='edit' id='toEdit' class='bo' type="submit" style='background-image: linear-gradient(#37ADB2, #329CA0)'>Edit</button>
                    </form>
                {% endif %}
            {% endfor %}
</div>
</code>```

All comments are showing with form element containing the edit button after them,except first comment, which is only button alone without form containing him.How to solve this?

All comments have after them (except first comment):

```<code><form>
     <button></button>
</form>
</code>```

First comment has after it:

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

Edit:
If I do this:

```<code>{% if comment_publishers[loop.index0]==g.user['username'] %}
                    {% if loop.index0==0 %}
                    <form>

                    </form>
                    {% endif %}
                    <form action="{{ url_for('blog.update_comment', id=comment['id'] )}}" method="get" id='Edit'>
                        <button name="edit" value='edit' id='toEdit' class='bo' type="submit" style='background-image: linear-gradient(#37ADB2, #329CA0)'>Edit</button>
                    </form>
{% endif %}
</code>```

Then it showing the form containing the edit button after the first comment,but somehow it don't show the empty form element when I check in developer tools.When I enter text in this empty form,it showing only this text without form.Very strange.Need explanation for why it always erasing the first form of my loop.

Body:
I have a template in flask,and I want that a button will be showed inside a form element.
Basically what I'm trying to do is to show comment one after another with edit button between comments (according to the user that is login now).
This is the relevant part of the template:

            {% for comment in comments_post %}

{{ comment['body'] }}

by {{ comment_publishers[loop.index0] }} on {{ comment_times[loop.index0]}}

                {% if comment_publishers[loop.index0]==g.user['username'] %}
                    <form action="{{ url_for('blog.update_comment', id=comment['id'] )}}" method="get" id='Edit'>
                        <button name="edit" value='edit' id='toEdit' class='bo' type="submit" style='background-image: linear-gradient(#37ADB2, #329CA0)'>Edit</button>
                    </form>
                {% endif %}
            {% endfor %}

All comments are showing with form element containing the edit button after them,except first comment, which is only button alone without form containing him.How to solve this?

All comments have after them (except first comment):

<form>
     <button></button>
</form>

First comment has after it:

<button></button>

Edit:
If I do this:

{% if comment_publishers[loop.index0]==g.user['username'] %}
                    {% if loop.index0==0 %}
                    <form>

                    </form>
                    {% endif %}
                    <form action="{{ url_for('blog.update_comment', id=comment['id'] )}}" method="get" id='Edit'>
                        <button name="edit" value='edit' id='toEdit' class='bo' type="submit" style='background-image: linear-gradient(#37ADB2, #329CA0)'>Edit</button>
                    </form>
{% endif %}

Then it showing the form containing the edit button after the first comment,but somehow it don't show the empty form element when I check in developer tools.When I enter text in this empty form,it showing only this text without form.Very strange.Need explanation for why it always erasing the first form of my loop.


问:
Passing generic function instance without explicitly enumerating template arguments
I have the following code:

#include <functional>

using FooFn = void(int, int, int);

template<class... Args>
void foo(Args&&... args) {
  // Do something
}

void bar(std::function<FooFn> fooFn) {
  fooFn(1, 2, 3);
}
```
<p>I am able to pass <code>foo</code> with explicit template arguments:</p>
<pre class="lang-cpp prettyprint-override"><code>bar(&foo<int, int, int>);
</code>```

I also can wrap foo in a generic lambda and pass it to a modified version of bar:

template<class F>
void bar(F fooFn) {
  fooFn(1, 2, 3);
}
```
<pre class="lang-cpp prettyprint-override"><code>bar([](auto... args){ foo(args...); });
</code>```

But it decreases code readability.

Since the number of arguments to FooFn can be quite large, I want to avoid enumerating arguments (possibly using FooFn alias). How do I do that?

Body:
I have the following code:

#include <functional>

using FooFn = void(int, int, int);

template<class... Args>
void foo(Args&&... args) {
  // Do something
}

void bar(std::function<FooFn> fooFn) {
  fooFn(1, 2, 3);
}

I am able to pass foo with explicit template arguments:

bar(&foo<int, int, int>);

I also can wrap foo in a generic lambda and pass it to a modified version of bar:

template<class F>
void bar(F fooFn) {
  fooFn(1, 2, 3);
}

bar([](auto... args){ foo(args...); });

But it decreases code readability.

Since the number of arguments to FooFn can be quite large, I want to avoid enumerating arguments (possibly using FooFn alias). How do I do that?


问:
My LogIn page has 2 different types of users , each in a separated collection in the firebase
am using a userId , that must exist in one of these 2 collections "Users" OR "StoreOwners"

one of them has a document inside the collection , and the other will cause an error since the document doesn't exists in the collection ... how to fix this problem ?

```<code>  CheckInWhichDocument() {
    String userId = _auth.currentUser!.uid;

    FirebaseFirestore.instance.
        .collection('Users')
        .doc(userId)
        .get()
        .then((value) {
    print("you entered users collection");
    }).catchError((e) {
      print(e);
    });

    FirebaseFirestore.instance
        .collection('StoreOwners')
        .doc(userId)
        .get()
        .then((value) {
    print("you entered storeOwners collection");
    });
  }
</code>```

the error "Null check operator used on a null value"
this error is caused by one of the collections because the document doesn't exist

(the userId exists in one of the collections)

Body:
am using a userId , that must exist in one of these 2 collections "Users" OR "StoreOwners"

one of them has a document inside the collection , and the other will cause an error since the document doesn't exists in the collection ... how to fix this problem ?

  CheckInWhichDocument() {
    String userId = _auth.currentUser!.uid;

    FirebaseFirestore.instance.
        .collection('Users')
        .doc(userId)
        .get()
        .then((value) {
    print("you entered users collection");
    }).catchError((e) {
      print(e);
    });

    FirebaseFirestore.instance
        .collection('StoreOwners')
        .doc(userId)
        .get()
        .then((value) {
    print("you entered storeOwners collection");
    });
  }

the error "Null check operator used on a null value"
this error is caused by one of the collections because the document doesn't exist

(the userId exists in one of the collections)


问:
while web scraping want to locate an element, which might be on two different places. How to extract only one of them?

I am scraping a website, in which an info might be on any of the two places.
So, I have to find if it exists in first place, if not then look for second place, and finally store it in variable.
Which block of code will work here?

if (driver.find_element(xxx))=True:
  ele= driver.find_element(xxx)
  list1.append(ele.text)
else:
  ele= driver.find_ele(yyy)
  list1.append(ele.text)
```


问:
Difficulty defining new custom provider in angularJS script?
I have a webapp that I would like to have some consistent themes across pages. To do so, I have attempted to modify the routeProvider provider to allow for utilization of such a template. As far as I can tell, the ways to do this are to define the provider, configure it, include it in the controller scope, and then inject it into the controller. I believe I have done this. Here are the relevant code blocks:

```<code>var webApp = angular.module('myApp.module', ['ngRoute','ngCookies','angular-jwt']);

webApp.provider('extendedRouteProvider', function($routeProvider) {
  this.$get = function() {
    return {
      when: function(path,route) {
        if (route.layOutTemplateUrl) {
          route.resolve = route.resolve || {};
          route.resolve.layOutTemplateUrl = function (){
            return route.layOutTemplateUrl;
          };
        }
        $routeProvider.when(path,route);
      }
    }
  }
});

webApp.config(function(extendedRouteProvider) {
  extendedRouteProvider
  .when('/', {
    templateUrl: 'webapp_loginScreen_UIDesign.html',
    controller: 'loginScreenController'
  })
  //Could add the following to after the .html bellow in the file if we want screen to load at anchor point specified in the HTML file: #!/mainPage...
  //This would also require adding it into the $location.path within the screenController function if so
  .when('/mainPage', {
    templateUrl: '/UI Design/Main Page/HTML/webapp_mainPageScreen_UIDesign.html',
    controller: 'mainPageScreenController',
    layOutTemplateUrl: '/UI Design/webapp_mainLayoutTemplate.html'
  })
  .otherwise({
    redirectTo: '/'
  });
});
function loginScreenController($http, $cookies, $location, $route,extendedRouteProvider) {
  var vm = this;

  var layOutTemplateUrl = $route.current.layOutTemplateUrl;
  // do stuff
  const serverURL = "URL";
  $location.path('/mainPage');
}

webApp.controller('loginScreenController',loginScreenController);

loginScreenController.$inject = ['$http','$cookies','$location','$route','extendedRouteProvider'];
</code>```

However, this code, when running via VSCode's live server, gives me an $injector:unpr error. I don't understand why this is happening. Note that I 'enter' the webapp through an HTML page which does not itself utilize the layout template, but $location.path('/main') should be sending the user to the mainpage, which does utilize the layout template.

Body:
I have a webapp that I would like to have some consistent themes across pages. To do so, I have attempted to modify the routeProvider provider to allow for utilization of such a template. As far as I can tell, the ways to do this are to define the provider, configure it, include it in the controller scope, and then inject it into the controller. I believe I have done this. Here are the relevant code blocks:

var webApp = angular.module('myApp.module', ['ngRoute','ngCookies','angular-jwt']);

webApp.provider('extendedRouteProvider', function($routeProvider) {
  this.$get = function() {
    return {
      when: function(path,route) {
        if (route.layOutTemplateUrl) {
          route.resolve = route.resolve || {};
          route.resolve.layOutTemplateUrl = function (){
            return route.layOutTemplateUrl;
          };
        }
        $routeProvider.when(path,route);
      }
    }
  }
});

webApp.config(function(extendedRouteProvider) {
  extendedRouteProvider
  .when('/', {
    templateUrl: 'webapp_loginScreen_UIDesign.html',
    controller: 'loginScreenController'
  })
  //Could add the following to after the .html bellow in the file if we want screen to load at anchor point specified in the HTML file: #!/mainPage...
  //This would also require adding it into the $location.path within the screenController function if so
  .when('/mainPage', {
    templateUrl: '/UI Design/Main Page/HTML/webapp_mainPageScreen_UIDesign.html',
    controller: 'mainPageScreenController',
    layOutTemplateUrl: '/UI Design/webapp_mainLayoutTemplate.html'
  })
  .otherwise({
    redirectTo: '/'
  });
});
function loginScreenController($http, $cookies, $location, $route,extendedRouteProvider) {
  var vm = this;

  var layOutTemplateUrl = $route.current.layOutTemplateUrl;
  // do stuff
  const serverURL = "URL";
  $location.path('/mainPage');
}

webApp.controller('loginScreenController',loginScreenController);

loginScreenController.$inject = ['$http','$cookies','$location','$route','extendedRouteProvider'];

However, this code, when running via VSCode's live server, gives me an $injector:unpr error. I don't understand why this is happening. Note that I 'enter' the webapp through an HTML page which does not itself utilize the layout template, but $location.path('/main') should be sending the user to the mainpage, which does utilize the layout template.


问:
Is it possible to invoke pstops manually from command line?
I am trying to learn how CUPS is implemented.
I see that the first step in the chain is to submit a PS to the pstops filter, which takes the PPD and shall return another PS for pstoraster.

I have read the source code for pstops but it is not very commented and I am struggling to:

understand if launching pstops from command line specifying a PS file is possible at all.

understand which shall be used for the rest of parameters:

job-id

user

title

copies

options

understand specifically where shall I include the path to the PPD file of the printer that is intended to be used later.


问:
How can I loop through an array using a promise?
My use-case: using each SKU in my SQL database, I will compare its respective price with the current, realtime price retrieved using API. Later on, I will compare these prices and overwrite the price in my DB with the realtime price.

TL;DR:

Query: run loop to pass each SKU from getAllBridalDB as {{dynamicSKU}} in getProducts API call.

comparePrices: assign price from JSON retrieved in {{dynamicSKU}} API call as a dynamic variable

(Later use case): compare price from getAllBridalDB to price from comparePrices.

3a. Update DB price as needed.

Query

Goal: retrieve the first SKU from table getAllBridalDB and store it in dynamicSKU, pass it into getProducts (see below), and store the price retrieved from getProducts as a new variable (see comparePrices below). I will then compare the price from the SKU in the table with the price from getProducts. If there's a change (+/-) from the price in my database, I will overwrite the price in my database (I haven't made it this far yet - I'm still trying to get to the point of comparing prices).

This query hasn't really been working. In fact, it crashes my app every time I run it. Everything else seems to be working so far. Question #1: how can I amend this loop to meet the above need?

```<code>const bridalArray = await getAllBridalDB.trigger({});
//console.log(bridalArray)
const bridalArraySKUs = bridalArray.Sku

const query = getProducts

const promises = bridalArraySKUs.map((Sku) => {
  return query.trigger({
    additionalScope: {
      dynamicSKU: Sku
    }
  });
});

return Promise.all(promises);
</code>```

getAllBridalDB

Simply imports SQL database into table. Each row has a unique SKU (not pictured)

Example of SQL data in table:

https://ibb.co/BngDXzd

getProducts

https://ibb.co/HXKBqTn

comparePrices

I'm working with an array of nested objects. This script logs the price as a decimal. It should work for every SKU as the JSON structure doesn't change.

If I simply type in a SKU in the value of getProducts, compareProducts logs the price successfully. I will need this to be dynamic in production (hence {{dynamicSKU}}).

Question #2: how can I dynamically store this decimal to later compare with my DB price? I'd probably run the comparison in real-time in this script.

```<code>//Passes thru every object thru price
let values = Object.values(getProducts.data.Products[0].Price)
//use values[0] because values [1] is the currency denomination as a string (which is not needed)
let currentPrice = values[0] //current price of given SKU as a decimal
console.log(currentPrice) //result: 1610.93
</code>```

Body:
My use-case: using each SKU in my SQL database, I will compare its respective price with the current, realtime price retrieved using API. Later on, I will compare these prices and overwrite the price in my DB with the realtime price.

TL;DR:

Query: run loop to pass each SKU from getAllBridalDB as {{dynamicSKU}} in getProducts API call.

comparePrices: assign price from JSON retrieved in {{dynamicSKU}} API call as a dynamic variable

(Later use case): compare price from getAllBridalDB to price from comparePrices.

3a. Update DB price as needed.

Query

Goal: retrieve the first SKU from table getAllBridalDB and store it in dynamicSKU, pass it into getProducts (see below), and store the price retrieved from getProducts as a new variable (see comparePrices below). I will then compare the price from the SKU in the table with the price from getProducts. If there's a change (+/-) from the price in my database, I will overwrite the price in my database (I haven't made it this far yet - I'm still trying to get to the point of comparing prices).

This query hasn't really been working. In fact, it crashes my app every time I run it. Everything else seems to be working so far. Question #1: how can I amend this loop to meet the above need?

const bridalArray = await getAllBridalDB.trigger({});
//console.log(bridalArray)
const bridalArraySKUs = bridalArray.Sku

const query = getProducts

const promises = bridalArraySKUs.map((Sku) => {
  return query.trigger({
    additionalScope: {
      dynamicSKU: Sku
    }
  });
});

return Promise.all(promises);

getAllBridalDB

Simply imports SQL database into table. Each row has a unique SKU (not pictured)

Example of SQL data in table:

https://ibb.co/BngDXzd

getProducts

https://ibb.co/HXKBqTn

comparePrices

I'm working with an array of nested objects. This script logs the price as a decimal. It should work for every SKU as the JSON structure doesn't change.

If I simply type in a SKU in the value of getProducts, compareProducts logs the price successfully. I will need this to be dynamic in production (hence {{dynamicSKU}}).

Question #2: how can I dynamically store this decimal to later compare with my DB price? I'd probably run the comparison in real-time in this script.

//Passes thru every object thru price
let values = Object.values(getProducts.data.Products[0].Price)
//use values[0] because values [1] is the currency denomination as a string (which is not needed)
let currentPrice = values[0] //current price of given SKU as a decimal
console.log(currentPrice) //result: 1610.93


问:
php websocket fallback to ajax best practices
Everything is working perfectly with this set:
I'm using docker-compose running some containers: nginx:1.22.0-alpine, php:8.1-cli, php:8.1.10-fpm, redis:7.0.5, [...].
My folders within the server are like:

```<code>-var/www/web
 -var/www/web/sharedPHPScript.php
 -var/www/web/public
  -var/www/web/public/index.php
 -var/www/web/core/ajax
  -var/www/web/core/ajax/ajax.parser.php
 -var/www/web/core/websocket
  -var/www/web/core/websocket/websocket.php
  -var/www/web/core/websocket/websocket.parser.php
[...]
</code>```

I just mounted the same host /var/www/web into both containers: php:8.1-cli, php:8.1.10-fpm.
This way I need just to code from my host and the code state are replicated in both containers.
I just picked php:8.1-cli to run my websocket-server because I was benchmarking for performance but I do not know if would be better to use php-fpm to it.
on docker-composer.yml:

```<code>version: '3.7'
services:
[...]
 fpm:
 [...]
  volumes:
   - ./web:/web:delegated
 swoole:
 [...]
  volumes:
   - ./web:/web:delegated
</code>```

index.php includes a controller that manage to call ajax.php when ever I send a fetch request from the client:

```<code>index.php>controller.php>include('/web/sharedPHPScript.php')
</code>```

websocket.php keeps running like a thread listening for connections to spaw filedescriptors to the server:

```<code>use Swoole\WebSocket\Server;
// Init redis
$redis = new Redis();
$redis->connect(REDIS['host'], REDIS['port']);
// Create websocket instance
$server = new Server("0.0.0.0", 8443);
[...]
// Register the "onOpen" event handler
$server->on("open", function (Server $server, $request) use(&$redis) {
 [...]
 include('/web/sharedPHPScript.php')
}
[...]
</code>```

My client (using javascript) onload event, creates a websocket connection with the server: server-ip/websocket>nginx:1.22.0-alpine>php:8.1-cli.
If the websocket connection status is not working, it just start using an ajax fetch.

```<code>function sendJSON(obj){
  // check if ws is active
  console.log('socket.readyState',socket.readyState);
  // use Websocket
  if(socket.readyState === 1){
    wsSend(obj); // some wrapper for socket.send();
    return;
  }
  // use AJAX
  ajaxSend(obj); // some wrapper for ajax fetch().then()
}
</code>```

My doubt is:
As I want to use this /web/sharedPHPScript.php to handle the fetches comming from php-fpm and the socket comming from php-cli, for better debugging as no need to write for two diferent data flows and database connections, I'm creating some wrap functions to decide which action to take depending on the origin (from websocket.parser.php or ajax.parser.php). inside /web/sharedPHPScript.php:

```<code>if($continue){ sendGlobal($req,$server,$request); $continue = dieGlobal($req); }
if($continue){
  sendGlobal($object,$server,$request);
  $continue = dieGlobal($req);
}
if(!$continue){return;}
</code>```

from vendor/autoload.php from each container:

```<code>composer.json:
[...]
"autoload":{
 "psr-4":{
 "Classes\\":"../web/core/!classes/"
 }
}

/web/core/!classes/sharedFunctions.php:
// Requests
// used for ajax
function sendAJAX($obj){
  header("Content-type: application/json");
  echo json_encode($obj);
}
// used for ws
function sendWS($obj,$server,$request){
  if($server && $request){$server->push($request->fd, json_encode($obj));}
}
// used for both ajax and ws (Global)
function sendGlobal($obj,$server=0,$request=0){
  if(isset($obj->ajax)){ sendAJAX($obj); }
  if(isset($obj->ws)){ sendWS($obj,$server,$request); }
}
function dieGlobal($obj){
  if(isset($obj->ajax)){ die; }
  if(isset($obj->ws)){ return false; }
}
</code>```

from ajax.parser.php:

```<code>$ajax = true;
$req = (object)$_POST;
$continue = true;
$server=null;
$request=null;
include('/web/sharedPHPScript.php');
</code>```

from websocket.parser.php:

```<code>$ws=true;
include('/web/sharedPHPScript.php');
</code>```

The problem is that php-cli as running a loop, I cannot use php commands like die;,setheader();,echo(); to send the http response back to the client. And from php-fpm, I do not have a $server or $request object, etc... Not even mentioning the wrapper for the $_SESSION...
So I'm woundering if there is a better/cleaner/simpler (in terms of best practice) way to do this websocket fallback to ajax because it is working like a charm and performing very nice but the sharedPHPScript.php is looking ugly...

I tryed separated flows for each websocket and ajax connections but this way i realised, as the project grows, I would need to create two slightly different codes for each container to do the same task...

Body:
Everything is working perfectly with this set:
I'm using docker-compose running some containers: nginx:1.22.0-alpine, php:8.1-cli, php:8.1.10-fpm, redis:7.0.5, [...].
My folders within the server are like:

-var/www/web
 -var/www/web/sharedPHPScript.php
 -var/www/web/public
  -var/www/web/public/index.php
 -var/www/web/core/ajax
  -var/www/web/core/ajax/ajax.parser.php
 -var/www/web/core/websocket
  -var/www/web/core/websocket/websocket.php
  -var/www/web/core/websocket/websocket.parser.php
[...]

I just mounted the same host /var/www/web into both containers: php:8.1-cli, php:8.1.10-fpm.
This way I need just to code from my host and the code state are replicated in both containers.
I just picked php:8.1-cli to run my websocket-server because I was benchmarking for performance but I do not know if would be better to use php-fpm to it.
on docker-composer.yml:

version: '3.7'
services:
[...]
 fpm:
 [...]
  volumes:
   - ./web:/web:delegated
 swoole:
 [...]
  volumes:
   - ./web:/web:delegated

index.php includes a controller that manage to call ajax.php when ever I send a fetch request from the client:

index.php>controller.php>include('/web/sharedPHPScript.php')

websocket.php keeps running like a thread listening for connections to spaw filedescriptors to the server:

use Swoole\WebSocket\Server;
// Init redis
$redis = new Redis();
$redis->connect(REDIS['host'], REDIS['port']);
// Create websocket instance
$server = new Server("0.0.0.0", 8443);
[...]
// Register the "onOpen" event handler
$server->on("open", function (Server $server, $request) use(&$redis) {
 [...]
 include('/web/sharedPHPScript.php')
}
[...]

My client (using javascript) onload event, creates a websocket connection with the server: server-ip/websocket>nginx:1.22.0-alpine>php:8.1-cli.
If the websocket connection status is not working, it just start using an ajax fetch.

function sendJSON(obj){
  // check if ws is active
  console.log('socket.readyState',socket.readyState);
  // use Websocket
  if(socket.readyState === 1){
    wsSend(obj); // some wrapper for socket.send();
    return;
  }
  // use AJAX
  ajaxSend(obj); // some wrapper for ajax fetch().then()
}

My doubt is:
As I want to use this /web/sharedPHPScript.php to handle the fetches comming from php-fpm and the socket comming from php-cli, for better debugging as no need to write for two diferent data flows and database connections, I'm creating some wrap functions to decide which action to take depending on the origin (from websocket.parser.php or ajax.parser.php). inside /web/sharedPHPScript.php:

if($continue){ sendGlobal($req,$server,$request); $continue = dieGlobal($req); }
if($continue){
  sendGlobal($object,$server,$request);
  $continue = dieGlobal($req);
}
if(!$continue){return;}

from vendor/autoload.php from each container:

composer.json:
[...]
"autoload":{
 "psr-4":{
 "Classes\\":"../web/core/!classes/"
 }
}

/web/core/!classes/sharedFunctions.php:
// Requests
// used for ajax
function sendAJAX($obj){
  header("Content-type: application/json");
  echo json_encode($obj);
}
// used for ws
function sendWS($obj,$server,$request){
  if($server && $request){$server->push($request->fd, json_encode($obj));}
}
// used for both ajax and ws (Global)
function sendGlobal($obj,$server=0,$request=0){
  if(isset($obj->ajax)){ sendAJAX($obj); }
  if(isset($obj->ws)){ sendWS($obj,$server,$request); }
}
function dieGlobal($obj){
  if(isset($obj->ajax)){ die; }
  if(isset($obj->ws)){ return false; }
}

from ajax.parser.php:

$ajax = true;
$req = (object)$_POST;
$continue = true;
$server=null;
$request=null;
include('/web/sharedPHPScript.php');

from websocket.parser.php:

$ws=true;
include('/web/sharedPHPScript.php');

The problem is that php-cli as running a loop, I cannot use php commands like die;,setheader();,echo(); to send the http response back to the client. And from php-fpm, I do not have a $server or $request object, etc... Not even mentioning the wrapper for the $_SESSION...
So I'm woundering if there is a better/cleaner/simpler (in terms of best practice) way to do this websocket fallback to ajax because it is working like a charm and performing very nice but the sharedPHPScript.php is looking ugly...

I tryed separated flows for each websocket and ajax connections but this way i realised, as the project grows, I would need to create two slightly different codes for each container to do the same task...


问:
Importing Keras modules : Facing issues with an ML image classifier app - "Keeps on loading but no prediction output"
I am building a Machine Learning application using CNN resnet50 architecture for image classification. This simple web app will take an image as input from the user and will predict the picture in the image followed by the developed model.

Issue statement:
The web-app keeps on loading when I click 'predict image' after attaching an input image.

Tools:
Python 3.9,
Tensorflow,
Resnet50 architecture

My code scenario:

I had imported the following modules from tensorflow: showing errors for all three!

```<code>from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
</code>```

Tried to fix the error using as follows: Are these right? (I simply used pip to install packages)

```<code>from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.models import load_model
from keras.preprocessing import image
</code>```

Additional Question:
3. The same ML model (in .h5 extension) provides different output (prediction) in a different machine. What may be the reason for it?

Why are the installed packages stored in default site-packages instead of the created project environment?

Thank you.

Body:
I am building a Machine Learning application using CNN resnet50 architecture for image classification. This simple web app will take an image as input from the user and will predict the picture in the image followed by the developed model.

Issue statement:
The web-app keeps on loading when I click 'predict image' after attaching an input image.

Tools:
Python 3.9,
Tensorflow,
Resnet50 architecture

My code scenario:

I had imported the following modules from tensorflow: showing errors for all three!

from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image

Tried to fix the error using as follows: Are these right? (I simply used pip to install packages)

from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.models import load_model
from keras.preprocessing import image

Additional Question:
3. The same ML model (in .h5 extension) provides different output (prediction) in a different machine. What may be the reason for it?

Why are the installed packages stored in default site-packages instead of the created project environment?

Thank you.


问:
GraddleError on load tasks
Could not create task ':generateDevelopmentBundle'
Extension of type 'RelocationExtension' does not exist. Currently registered extension types: [ExtraPropertiesExtension, BasePluginExtension, DefaultArtifactPublicationSet, SourceSetContainer, ReportingExtension, JavaPluginExtension, JavaToolchainService, TestingExtension, PublishingExtension, ShadowExtension, IdeaModel]

The truth is I've had this problem with gradle and I still don't know how to solve it, I can't think of anything at all

Title: GraddleError on load tasks


问:
Do Webhooks really avoid polling?
A server pushes an event to a webhook URL for my server to be notified.What do you do in order to monitor the webhook URL from my server's side for any state change?
Do you do a classic poll at that url?

In general, even if the system is pub/sub, do you still have to poll at one point or the other?

Title: Do Webhooks really avoid polling?


问:
React : Canvas doen't get returned as NULL in draw function
I am currenty reading code of Excalidraw and trying to understand how app works. I started from first commit and see that code

```<code>const rootElement = document.getElementById("root");

function drawScene() {
  ReactDOM.render(<App />, rootElement);
  const canvas = document.getElementById("canvas");

  const context = canvas.getContext("2d");
  }
drawScene();
</code>```

Everything works fine ,but when I do my version

```<code>const root = ReactDOM.createRoot(document.getElementById("root"));

    const drawScene = () => {

    root.render(<App />);

    const canvas = document.getElementById("canvas");

    const context = canvas.getContext("2d");
 };

 drawScene();
</code>```

Canvas is NULL, but it renders. I understand that I use different version of React,but can you tell me and give me the link why in the first case canvas is normal value , in mine is Null.

the project was initially created 3 years ago and that version of react was used, now I use the last version of it. I understand that to write code the way is quite messy, but I follow commits and want to go step by step.

Body:
I am currenty reading code of Excalidraw and trying to understand how app works. I started from first commit and see that code

const rootElement = document.getElementById("root");

function drawScene() {
  ReactDOM.render(<App />, rootElement);
  const canvas = document.getElementById("canvas");

  const context = canvas.getContext("2d");
  }
drawScene();

Everything works fine ,but when I do my version

const root = ReactDOM.createRoot(document.getElementById("root"));

    const drawScene = () => {

    root.render(<App />);

    const canvas = document.getElementById("canvas");

    const context = canvas.getContext("2d");
 };

 drawScene();

Canvas is NULL, but it renders. I understand that I use different version of React,but can you tell me and give me the link why in the first case canvas is normal value , in mine is Null.

the project was initially created 3 years ago and that version of react was used, now I use the last version of it. I understand that to write code the way is quite messy, but I follow commits and want to go step by step.


问:
Image urls import from csv file gives error in Python
Need some help from this forum.

I am new to python. I want to import some images(kept in the local drive) from CSV file(contains all Image URLs) to blender.

I try the below code but it gives an error: No such file or directory.

When I used for testing path = r"C:\pic\temp\test1.png" then it's working fine.

But the requirement is to import all image URLs from a CSV file for that I can not configure "path"(for looping so I can import all images).
Tried path = 'r'm   but got an error.

Any solution will be highly appreciated.

`

```<code>with open(csvFilename, 'r') as csvFile:
    csvreader = csv.reader(csvFile)
    # extracting field names through first row
    fields = next(csvreader)  # skip the header
    for row in csvreader:
        j += 1
        y,z,m = [str(value)for value in row] #store each row value of excel sheet
        txt=bpy.data.objects['Text_country'+str(j)]
        txt.data.body=y
        txt=bpy.data.objects['Text_capital'+str(j)]
        txt.data.body=z
        path = m   # image URL      # can not configure
        obj = bpy.data.objects['img'+str(j)]
        mat = obj.active_material
        texImage = mat.node_tree.nodes["Image Texture"]
        texImage.image = bpy.data.images.load(path)        # path = r"C:\pic\temp\test1.png" ------Working fine
    if j== 5:
</code>```

`

Body:
Need some help from this forum.

I am new to python. I want to import some images(kept in the local drive) from CSV file(contains all Image URLs) to blender.

I try the below code but it gives an error: No such file or directory.

When I used for testing path = r"C:\pic\temp\test1.png" then it's working fine.

But the requirement is to import all image URLs from a CSV file for that I can not configure "path"(for looping so I can import all images).
Tried path = 'r'm   but got an error.

Any solution will be highly appreciated.

`

with open(csvFilename, 'r') as csvFile:
    csvreader = csv.reader(csvFile)
    # extracting field names through first row
    fields = next(csvreader)  # skip the header
    for row in csvreader:
        j += 1
        y,z,m = [str(value)for value in row] #store each row value of excel sheet
        txt=bpy.data.objects['Text_country'+str(j)]
        txt.data.body=y
        txt=bpy.data.objects['Text_capital'+str(j)]
        txt.data.body=z
        path = m   # image URL      # can not configure
        obj = bpy.data.objects['img'+str(j)]
        mat = obj.active_material
        texImage = mat.node_tree.nodes["Image Texture"]
        texImage.image = bpy.data.images.load(path)        # path = r"C:\pic\temp\test1.png" ------Working fine
    if j== 5:

`


问:
How do I prevent my string in my picker from wrapping and display on only one line?
I have a picker where the user can pick values and the one that is picked is displayed. How do I get the selected value to stay on one line instead of displaying on two lines like:

conce

rt

```<code>VStack{

            HStack{

                Text("Type ")
                    .padding(.horizontal, 15)

                // picker for type of event
                Picker(selection: $eventType, label: Text("Type")) {
                    Text("All     ").tag("1")
                    Text("Friends ").tag("2")
                    Text("Concert ").tag("3")
                    Text("Festival").tag("4")
                    Text("Food    ").tag("5")

                }

                Text("Time")
                    .padding(.horizontal, 15)

                // picker for time of event
                Picker(selection: $timeRange, label: Text("Type")) {
                    Text("Today").tag("1")
                    Text("Week ").tag("2")
                    Text("Month").tag("3")

                }
            }

</code>```

Body:
I have a picker where the user can pick values and the one that is picked is displayed. How do I get the selected value to stay on one line instead of displaying on two lines like:

conce

rt

VStack{

            HStack{

                Text("Type ")
                    .padding(.horizontal, 15)

                // picker for type of event
                Picker(selection: $eventType, label: Text("Type")) {
                    Text("All     ").tag("1")
                    Text("Friends ").tag("2")
                    Text("Concert ").tag("3")
                    Text("Festival").tag("4")
                    Text("Food    ").tag("5")

                }

                Text("Time")
                    .padding(.horizontal, 15)

                // picker for time of event
                Picker(selection: $timeRange, label: Text("Type")) {
                    Text("Today").tag("1")
                    Text("Week ").tag("2")
                    Text("Month").tag("3")

                }
            }


问:
Does anyone know how to display a location in google map without using the latitude and longitude?
I need to display a list of locations on google map.

I have used google autocomplete to store the places name in the database, and now I need to display those same places in google map.

I know how to do it using the latitude and longitude, but not with places 'name


问:
stable_baselines3 best observation space for custom environment
I'm newbie in RL and I'm learning stable_baselines3. I've create simple 2d game, where we want't to catch as many as possible falling apples. If we don't catch apple, apple disappears and we loose a point, else we gain 1 point. We can move only left or right.
I thought that AI will learn faster when I give him raw data without CNN with PPO and MlpPolicy.

The problem is that I don't know how many apples will be in the game in every moment, only that there will max 10 of them.
So I thought that I will create observation_space like this:

```<code>self.observation_space = Box(0, 1, (11, 2))
</code>```

Where first element would be position of player, and rest positions of apples. If apple doesn't exists I would push value (0, 0).
I trained it for 100000 steps, but it seems very stupid, and goes to left edge of screen.
How can I improve it?

Body:
I'm newbie in RL and I'm learning stable_baselines3. I've create simple 2d game, where we want't to catch as many as possible falling apples. If we don't catch apple, apple disappears and we loose a point, else we gain 1 point. We can move only left or right.
I thought that AI will learn faster when I give him raw data without CNN with PPO and MlpPolicy.

The problem is that I don't know how many apples will be in the game in every moment, only that there will max 10 of them.
So I thought that I will create observation_space like this:

self.observation_space = Box(0, 1, (11, 2))

Where first element would be position of player, and rest positions of apples. If apple doesn't exists I would push value (0, 0).
I trained it for 100000 steps, but it seems very stupid, and goes to left edge of screen.
How can I improve it?


问:
How to load .env vars when running node.js command line application?
I created a small application using node.js and express but wanted to convert part of it's functionality into a command line tool.

When I run the application from the command line the .env file doesn't seem to be loading with the variables, and instead return undefined e.g. const token = process.env.TOKEN;

However if I run the application by starting up the server it will inject those variables as normal.

I don't want to pass them along in the command line as args

Is there any way to ensure environment variables are injected?

I've used npm install -g . to install the application and ran it from the command line. The values are defined when I start up the application using ts-node. I feel like this is something to do with the order of executions when loading the app.

my package json looks like this:

```<code>{
  "name": "spotifybpmsort",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "env-cmd ts-node ./src/index.ts",
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "npx tsc"
  },
  "bin": "./src/index.ts",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/yargs": "^17.0.17",
    "axios": "^1.1.3",
    "dotenv": "^16.0.3",
    "env-cmd": "^10.1.0",
    "express": "^4.18.2",
    "nodemon": "^2.0.20",
    "ts-node": "^10.9.1",
    "yargs": "^17.6.2"
  },
  "devDependencies": {
    "@types/express": "^4.17.14",
    "ts-node-dev": "^2.0.0"
  }
}
</code>```

Body:
I created a small application using node.js and express but wanted to convert part of it's functionality into a command line tool.

When I run the application from the command line the .env file doesn't seem to be loading with the variables, and instead return undefined e.g. const token = process.env.TOKEN;

However if I run the application by starting up the server it will inject those variables as normal.

I don't want to pass them along in the command line as args

Is there any way to ensure environment variables are injected?

I've used npm install -g . to install the application and ran it from the command line. The values are defined when I start up the application using ts-node. I feel like this is something to do with the order of executions when loading the app.

my package json looks like this:

{
  "name": "spotifybpmsort",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "env-cmd ts-node ./src/index.ts",
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "npx tsc"
  },
  "bin": "./src/index.ts",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/yargs": "^17.0.17",
    "axios": "^1.1.3",
    "dotenv": "^16.0.3",
    "env-cmd": "^10.1.0",
    "express": "^4.18.2",
    "nodemon": "^2.0.20",
    "ts-node": "^10.9.1",
    "yargs": "^17.6.2"
  },
  "devDependencies": {
    "@types/express": "^4.17.14",
    "ts-node-dev": "^2.0.0"
  }
}


问:
MySQL Shutdown Unexpectedly and Fixed by Repairing mysql DB
I have a very wierd issue after installing new OS and new XAMPP,
After restoring my old htdocs and mysql's DBs including the ibdata1, The mysql service always stopped with the known message MySQL shutdown unexpectedly when I'm trying to access any Database rather than the mysql DB,

BUT...

Once I open mysql DB and select all tables and Repair Tables, it worked perfectly and all Databases opened, and no more stops.

But after stopping mysql's service manually and restart it, I MUST open mysql's DB and repair all tables to be able to access DBs.

I've tried to Empty session data but nothing work except repairing mysql's DB tables.


问:
Using loadpng to convert between BMP and PNG formats in C
I am using Visual Studio 2022 on a Windows 10 platform, and wish to convert between BMP and PNG image formats in C. This is because I have some applications that manipulate pixels in BMP images, and wish to convert the final images to PNG format, and likewise input PNG images and convert them to BMP format. This is specifically for 24-bit RGB images without the alpha channel. There are online image converters, Adobe software can do this, and I believe there are Windows utilities that can also do this. However, I wish to incorporate such conversion software in my projects without external dependencies or using a specific operating system.

LoadPng appears to fit the bill, and from the link https://lodev.org/lodepng/ I downloaded the files loadpng.c and loadpng.h and put them into a Visual Studio project. I also copied the code from example_decode.c and example_encode.c into the main function in the project, and used conditional compilation to select either encoding or decoding, for now as a test I have selected encoding and use the encodeOneStep() function for testing. There are encodeTwoSteps() and encodeWithState() functions that are not invoked.

Anyway, when compiling with the x64 option in Debug mode I get a whole list of warning messages. The first two are

```<code>lodepng.c(712,54): warning C4334: '<<': result of 32-bit     shift implicitly converted to 64 bits (was 64-bit shift intended?)
lodepng.c(730,28): warning C4267: '=': conversion from 'size_t' to 'unsigned short', possible loss of data
</code>```

and there are many other warnings like these two. It should be relatively easy to fix warnings like the second one, but how do I fix warnings like the first one? Incidentally, the line numbers in the file loadpng.c are the same as downloaded, as that file has not been edited.

When I run the program, it does indeed work and produces a test output image. Be that as it may, I want to get rid of these warning messages.

When I compile the project with the x86 option in Debug mode, all warning messages of the first type, i.e. "'<<': result of 32-bit" disappear, and most of the warnings of the second type also disappear, but a few still appear as "conversion from 'size_t' to 'unsigned short'". Again, the application runs correctly. However, this is an aside, as I wish to stick to 64-bit (x64) compilation.

Finally, although the examples in LoadPng are set up for RGBA images, there is code for RGB images which I plan to use, assuming the above issues can be resolved. Could someone kindly give me advice on how to fix the code so that the warning messages for x64 compilation do not appear - many thanks.

Body:
I am using Visual Studio 2022 on a Windows 10 platform, and wish to convert between BMP and PNG image formats in C. This is because I have some applications that manipulate pixels in BMP images, and wish to convert the final images to PNG format, and likewise input PNG images and convert them to BMP format. This is specifically for 24-bit RGB images without the alpha channel. There are online image converters, Adobe software can do this, and I believe there are Windows utilities that can also do this. However, I wish to incorporate such conversion software in my projects without external dependencies or using a specific operating system.

LoadPng appears to fit the bill, and from the link https://lodev.org/lodepng/ I downloaded the files loadpng.c and loadpng.h and put them into a Visual Studio project. I also copied the code from example_decode.c and example_encode.c into the main function in the project, and used conditional compilation to select either encoding or decoding, for now as a test I have selected encoding and use the encodeOneStep() function for testing. There are encodeTwoSteps() and encodeWithState() functions that are not invoked.

Anyway, when compiling with the x64 option in Debug mode I get a whole list of warning messages. The first two are

lodepng.c(712,54): warning C4334: '<<': result of 32-bit     shift implicitly converted to 64 bits (was 64-bit shift intended?)
lodepng.c(730,28): warning C4267: '=': conversion from 'size_t' to 'unsigned short', possible loss of data

and there are many other warnings like these two. It should be relatively easy to fix warnings like the second one, but how do I fix warnings like the first one? Incidentally, the line numbers in the file loadpng.c are the same as downloaded, as that file has not been edited.

When I run the program, it does indeed work and produces a test output image. Be that as it may, I want to get rid of these warning messages.

When I compile the project with the x86 option in Debug mode, all warning messages of the first type, i.e. "'<<': result of 32-bit" disappear, and most of the warnings of the second type also disappear, but a few still appear as "conversion from 'size_t' to 'unsigned short'". Again, the application runs correctly. However, this is an aside, as I wish to stick to 64-bit (x64) compilation.

Finally, although the examples in LoadPng are set up for RGBA images, there is code for RGB images which I plan to use, assuming the above issues can be resolved. Could someone kindly give me advice on how to fix the code so that the warning messages for x64 compilation do not appear - many thanks.


问:
Creating a Pathfinder for a simple game in VB.Net?
I have a simple coin collector game which is passed an array and must go from players x and y position in the array to a coin x and y position in the array without going on array values "w" and chrw(9068). "w" represent the blue water and chrw(9068) is the grey walls (this will make more sense when you look at the image.

I am doing this because i kepp ending up in situations like this where it is impossible to reach the coin or the player is spawned ina boxed in area.

I have browsed online but can't seem to find much explaining them and pretty much nothing in vb.net that isn't outdated.