问:
Background importing of slow python module
I have a python module (odoo.py) that creates a connection with an Odoo instance.

import odoorpc
from .env import ENV

ODOO = odoorpc.ODOO(ENV["ODOO_HOST"], port=ENV["ODOO_PORT"])
ODOO.login(db=ENV["ODOO_DB"], login=ENV["ODOO_USR"], password=ENV["ODOO_PWD"])
```
<p><code>ODOO</code> constant is imported by several modules containing Mongoengine classes to perform operations on the Odoo server. Here is an example:</p>
<pre class="lang-py prettyprint-override"><code>from mongoengine import *
from .odoo import ODOO

class Category(DynamicDocument):
    name = StringField(required=True)
    odoo_id = StringField()

    def publish(self):
        _model = ODOO.env["product.category"]
        self.odoo_id = _model.create({"name": self.name})
        self.save()
</code>```

Problem is that importing odoo.py takes about 10 seconds during application startup and it's REALLY annoying in development.

Let's consider this pseudo main.py:

import sys
from .category import Category

cat = Category(name=sys.argv[1])
if not 'test' in cat.name:
    cat.publish()
```

In this example if sys.argv[1] contains the string 'test' then ODOO constant will never be used and waiting for its import would be totally useless.

Is there a way to "background" importing of odoo.py and wait for it only when ODOO constant is actually needed?

Body:
I have a python module (odoo.py) that creates a connection with an Odoo instance.

import odoorpc
from .env import ENV

ODOO = odoorpc.ODOO(ENV["ODOO_HOST"], port=ENV["ODOO_PORT"])
ODOO.login(db=ENV["ODOO_DB"], login=ENV["ODOO_USR"], password=ENV["ODOO_PWD"])

ODOO constant is imported by several modules containing Mongoengine classes to perform operations on the Odoo server. Here is an example:

from mongoengine import *
from .odoo import ODOO

class Category(DynamicDocument):
    name = StringField(required=True)
    odoo_id = StringField()

    def publish(self):
        _model = ODOO.env["product.category"]
        self.odoo_id = _model.create({"name": self.name})
        self.save()

Problem is that importing odoo.py takes about 10 seconds during application startup and it's REALLY annoying in development.

Let's consider this pseudo main.py:

import sys
from .category import Category

cat = Category(name=sys.argv[1])
if not 'test' in cat.name:
    cat.publish()

In this example if sys.argv[1] contains the string 'test' then ODOO constant will never be used and waiting for its import would be totally useless.

Is there a way to "background" importing of odoo.py and wait for it only when ODOO constant is actually needed?


来源: stackexchange

问:
I/Ads: Ad failed to load : 3 on demo ad unit android libGDX
I have an error code while trying to load ad:

```<code>I/Ads: Ad failed to load : 3
</code>```

I use Demo ad unit from google: ca-app-pub-3940256099942544/5224354917.
It used to work before releasing my app for open tests in play console, after open test release it just stopped working with error code above. I read that It's just google error because they do not have ads to send me, but It's test add ID, so I'm not sure how It's possible.
I'm actually waiting for google to approve my admob account, but I'm not using ad id from my admob account anyway. And I already have ads enabled in play console.
It was working when I published app for internal tests

ContentLicense: CC BY-SA 4.0

Body:
I have an error code while trying to load ad:

I/Ads: Ad failed to load : 3

I use Demo ad unit from google: ca-app-pub-3940256099942544/5224354917.
It used to work before releasing my app for open tests in play console, after open test release it just stopped working with error code above. I read that It's just google error because they do not have ads to send me, but It's test add ID, so I'm not sure how It's possible.
I'm actually waiting for google to approve my admob account, but I'm not using ad id from my admob account anyway. And I already have ads enabled in play console.
It was working when I published app for internal tests


问:
How can I make my Windows Form to do and display my database query?
I have 3 Tables:

Titles:

TitleId (int 6, primary key)

TitleName (varchar 50)

Authors:

AuthorId (int 6, primary key)

AuthorName (varchar 50)

AuthorsTitles  (this is a junction table for Titles and Authors)

TitleId (int 6)

AuthorId (int 6)

There's a "many to many" relation: A Title may have many Authors, and an Author may have many Titles. This is why I need the junction table.

All I want is to get a Windows form with a ComboBox with Titles. The user selects a Title, and the Author or Authors of the selected Title will be listed in a ListBox.

I'm using Microsoft Visual C# Express Edition 2008 and SQL Server Express Edition 2008.

OwnerDisplayName: jordi

ContentLicense: CC BY-SA 3.0


问:
Learn about laravel component and I got Undefined variable $navbar

Error

ErrorException
Undefined variable $navbar (View: /home/wardi/Documents/myproject/resources/views/components/navbar.blade.php)
http://127.0.0.1:8000/

I tried these steps but can not figure out what is going wrong

app/View/Components/navbar.php

```<code><?php

namespace App\View\Components;

use Illuminate\View\Component;

class navbar extends Component
{
    public $navbar;
    public function __construct()
    {

    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        $navbar =[
            'Home' => '/',
            'persediaan' => '/persediaan',
            'pembelian' => '/pembelian',
            'penjualan' => '/penjualan'
        ];

        return view('components.navbar',compact('navbar'));
    }
}
</code>```

view/components/navbar.blade.php

```<code><ul class="navbar-nav me-auto mb-2 mb-lg-0">
    @foreach ($navbar as $name => $url )
        <li><a href="{{ $url }}">{{ $name }}</a></li>
    @endforeach
</u>
</code>```

view/home.blade.php

```<code><body>
   <x-navbar>
   </x-navbar>
   @yield('content')
</body>
</code>```

Body:
Error

ErrorException
Undefined variable $navbar (View: /home/wardi/Documents/myproject/resources/views/components/navbar.blade.php)
http://127.0.0.1:8000/

I tried these steps but can not figure out what is going wrong

app/View/Components/navbar.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class navbar extends Component
{
    public $navbar;
    public function __construct()
    {

    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        $navbar =[
            'Home' => '/',
            'persediaan' => '/persediaan',
            'pembelian' => '/pembelian',
            'penjualan' => '/penjualan'
        ];

        return view('components.navbar',compact('navbar'));
    }
}

view/components/navbar.blade.php

    @foreach ($navbar as $name => $url )

{{ $name }}

    @endforeach

view/home.blade.php

   <x-navbar>
   </x-navbar>
   @yield('content')


问:
Prevent race condition when bulk update job is running and transactional activity comes in
In our application two activites are running concurrent-

Bulk updates activity

Transactional activity

When both these activites are perfomed on same record cocurrently we see invalid values.

To prevent this I am thinking of using pessimistic locking(Postgres row level lock). But the issue here is I may have to lock all records for bulk updates.


问:
Dynamically allocating memory in C++
I am trying to store image frames in memory in a libcamera app on a Raspberry Pi 4b.  I created a container class 'ImageData' containing image metadata and a new buffer for the frame data.

```<code>class ImageData
{
public:
    ImageData(std::vector<libcamera::Span<uint8_t>> m, StreamInfo i, libcamera::ControlList met, std::string fil, std::string cam) :

    mem (m),
    info (i),
    metadata (met),
    filename (fil),
    cam_name (cam),
    buffer(new uint8_t[mem[0].size_bytes()]) {}

    ~ImageData() {delete[] buffer;}

    std::vector<libcamera::Span<uint8_t>> mem;
    StreamInfo info;
    libcamera::ControlList metadata;
    std::string filename;
    std::string cam_name;
    uint8_t* buffer;
};
</code>```

I create a buffer object

```<code>std::vector<ImageData> imageBuffer;
</code>```

and store the information in a new ImageData instance

```<code>const std::vector<libcamera::Span<uint8_t>> mem = app.Mmap(completed_request->buffers[stream]);
                    ImageData d = ImageData(mem, info, completed_request->metadata, new_name, app.CameraId());
                    memcpy(d.buffer, mem[0].data(), mem[0].size_bytes() );
                    imageBuffer.push_back(std::move(d));
</code>```

This works for a single frame but crashes with multiple frames.

I have no clue why.

Title: Dynamically allocating memory in C++

Body:
I am trying to store image frames in memory in a libcamera app on a Raspberry Pi 4b.  I created a container class 'ImageData' containing image metadata and a new buffer for the frame data.

class ImageData
{
public:
    ImageData(std::vector<libcamera::Span<uint8_t>> m, StreamInfo i, libcamera::ControlList met, std::string fil, std::string cam) :

    mem (m),
    info (i),
    metadata (met),
    filename (fil),
    cam_name (cam),
    buffer(new uint8_t[mem[0].size_bytes()]) {}

    ~ImageData() {delete[] buffer;}

    std::vector<libcamera::Span<uint8_t>> mem;
    StreamInfo info;
    libcamera::ControlList metadata;
    std::string filename;
    std::string cam_name;
    uint8_t* buffer;
};

I create a buffer object

std::vector<ImageData> imageBuffer;

and store the information in a new ImageData instance

const std::vector<libcamera::Span<uint8_t>> mem = app.Mmap(completed_request->buffers[stream]);
                    ImageData d = ImageData(mem, info, completed_request->metadata, new_name, app.CameraId());
                    memcpy(d.buffer, mem[0].data(), mem[0].size_bytes() );
                    imageBuffer.push_back(std::move(d));

This works for a single frame but crashes with multiple frames.

I have no clue why.


问:
opencv remove weakly connected small object from contour
small objects like displayed in attached image "polute" the skeleton I create from Image and make further tasks difficult.

I tried

```<code>_, labels = cv2.connectedComponents(myImage)
for label in np.unique(labels):
  if label == 0:
     continue
  area = (labels ==label).sum()
  if area < 20:
     myImage[labels==label]=0
</code>```

This code removed unconnected small objects of about the same size but had no effect on the object in question. Chance of connectivity didn't have an effect.

Body:
small objects like displayed in attached image "polute" the skeleton I create from Image and make further tasks difficult.

I tried

_, labels = cv2.connectedComponents(myImage)
for label in np.unique(labels):
  if label == 0:
     continue
  area = (labels ==label).sum()
  if area < 20:
     myImage[labels==label]=0

This code removed unconnected small objects of about the same size but had no effect on the object in question. Chance of connectivity didn't have an effect.


问:
How to solve 1.0000 not equal to 1 in MATLAB?
I have a matrix V.
I want to test if the matrix equal to one or not.

Sometimes the sum(V(:))==1.0000
but when I test if sum(V(:))== 1 the results always FALSE.

How to solve that problem.


问:
How to make matplotlib subplots same size as cartopy map with colourbar
I am trying to add a lineplot to the x and y axis of a cartopy map.
After a bit of trial and error I started to use gridspec in order to add the lineplots as subplots to the figure.

I use two predefined functions to create the map and the aligned colourbar:

```<code>def create_map(fig = None, sp_x = 1, sp_y = 1, sp_n = 1,
               figsize = (12,10)):

    # use UTM projection 32 for the plot
    global utm_crs
    utm_crs = ccrs.UTM(zone = 32)

    # If the figure already exists, add a suplot
    if fig:
        ax = fig.add_subplot(sp_x,sp_y,sp_n, projection=utm_crs)
        fig.subplots_adjust(hspace=-0.1)
    else:
        # otherwise create the figure first
        fig = plt.figure(figsize=(12,10))
        global gs
        gs = gridspec.GridSpec(2, 2,figure = fig, height_ratios=[3, 1],width_ratios=[1, 6] )
        ax = fig.add_subplot(gs[0,1], projection=utm_crs)

    # set the extent to the study region
    ax.set_extent([525000, 850000, 5940000, 6086000],
                  crs=utm_crs)

    # add land as background in gray
    gdf = gpd.read_file(dirpath+"/data/bbox/EU_Boarders_NUTS_0.geojson")
    gdf = gdf[gdf["CNTR_CODE"].isin(["DE", "DK", "PL"])]

    for geom in gdf["geometry"]:
        shape_feature = cfeature.ShapelyFeature([geom],
                                                ccrs.PlateCarree(),
                                                facecolor="gray",
                                                alpha = 0.5,
                                                edgecolor='black',
                                                lw=1,
                                                zorder = -50)

        ax.add_feature(shape_feature)

    # add grid lines
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=1, color='gray', alpha=0.5)
    gl.top_labels = False
    gl.right_labels = False
    gl.ylocator = mticker.FixedLocator([54, 54.5])
    gl.xlocator = mticker.FixedLocator([10, 12, 14])

    return fig, ax

def add_aligned_colorbar(fig, ax, pc, label = None,
                         ticks = None, ticklabels = None,
                         size = "3%", pad = 0.1):
    divider = make_axes_locatable(ax)
    ax_cb = divider.new_horizontal(size="3%", pad=0.1, axes_class=plt.Axes)

    fig.add_axes(ax_cb)
    cbar = plt.colorbar(pc, cax=ax_cb, label = label, ticks = ticks)

    if type(ticklabels) == list:
        cbar.ax.set_yticklabels(ticklabels)

    return cbar, ax_cb

</code>```

But the problem comes up when I try to add the subplots to the figure:

```<code>
xds_fpath = dirpath+"/data/GETM/WB200m.suf.2008-2021.nc"
xds = xr.open_dataset(xds_fpath)
xds.rio.write_crs(ccrs.UTM(zone = 32), inplace=True)

range_t= pd.date_range("2021-01-01","2021-12-31", freq="D")
mean_xds= xds.sel(time = range_t,
         method = "nearest").mean(dim = "time")

#create figure aswell as the map
fig, ax = create_map(sp_y = 2,
                     sp_x = 1,
                     sp_n = 1,
                     figsize = (12,8))

mc = mean_xds["salt"].plot(ax=ax,
                    transform=ccrs.PlateCarree(),
                    vmin = mean_xds["salt"].min(),
                    vmax = mean_xds["salt"].max(),
                    cmap = cm.thermal,
                    add_colorbar = False,
                    label='_nolegend_',
                    zorder = -25)

plt.title("Saltgradient")

#make colourbar same size as map
cbar1, ax_cb1 = add_aligned_colorbar(fig = fig, ax = ax, pc = mc,
                                    label = "Salinity [PPU]" ,
                                    size = "3%",
                                    pad = 8)

# X axis lineplot
fig.add_subplot(gs[1,1])
mean_lon = mean_xds.mean(dim = "lat")
lp = plt.plot(mean_lon["lon"],mean_lon["salt"])
plt.xlim([mean_lon["lon"].min(),mean_lon["lon"].max()])

# Y axis lineplot
fig.add_subplot(gs[0,0])
mean_lat= mean_xds.mean(dim = "lon")
plt.plot(mean_lat["salt"],mean_lat["lat"])
plt.ylim([mean_lat["lat"].min(),mean_lat["lat"].max()])

plt.tight_layout()

</code>```

Because the figure looks like this: Ideally the y and the x axis lineplots would have the same size as the cartopy map

I have tried to set the overall figure height and width at the end (similar to this solution: Tight layout using Cartopy without passing w_pad argument?) but I could only get one subplot to match.

```<code>xds_fpath = dirpath+"/data/GETM/WB200m.suf.2008-2021.nc"
xds = xr.open_dataset(xds_fpath)
xds.rio.write_crs(ccrs.UTM(zone = 32), inplace=True)

range_t= pd.date_range("2021-01-01","2021-12-31", freq="D")
mean_xds= xds.sel(time = range_t,
         method = "nearest").mean(dim = "time")

#create figure aswell as the map
fig, ax = create_map(sp_y = 2,
                     sp_x = 1,
                     sp_n = 1,
                     figsize = (12,8))

mc = mean_xds["salt"].plot(ax=ax,
                    transform=ccrs.PlateCarree(),
                    vmin = mean_xds["salt"].min(),
                    vmax = mean_xds["salt"].max(),
                    cmap = cm.thermal,
                    add_colorbar = False,
                    label='_nolegend_',
                    zorder = -25)

plt.title("Saltgradient")

#make colourbar same size as map
cbar1, ax_cb1 = add_aligned_colorbar(fig = fig, ax = ax, pc = mc,
                                    label = "Salinity [PPU]" ,
                                    size = "3%",
                                    pad = 8)

# X axis lineplot
fig.add_subplot(gs[1,1])
mean_lon = mean_xds.mean(dim = "lat")
lp = plt.plot(mean_lon["lon"],mean_lon["salt"])
plt.xlim([mean_lon["lon"].min(),mean_lon["lon"].max()])

# Y axis lineplot
fig.add_subplot(gs[0,0])
mean_lat= mean_xds.mean(dim = "lon")
plt.plot(mean_lat["salt"],mean_lat["lat"])
plt.ylim([mean_lat["lat"].min(),mean_lat["lat"].max()])

xmin, xmax = ax.get_xbound()
ymin, ymax = ax.get_ybound()
y2x_ratio = (ymax-ymin)/(xmax-xmin)

fig.set_figheight(12 * y2x_ratio)

plt.tight_layout()

</code>```

Here the y axis lineplot matches the height of the cartopy map

Body:
I am trying to add a lineplot to the x and y axis of a cartopy map.
After a bit of trial and error I started to use gridspec in order to add the lineplots as subplots to the figure.

I use two predefined functions to create the map and the aligned colourbar:

def create_map(fig = None, sp_x = 1, sp_y = 1, sp_n = 1,
               figsize = (12,10)):

    # use UTM projection 32 for the plot
    global utm_crs
    utm_crs = ccrs.UTM(zone = 32)

    # If the figure already exists, add a suplot
    if fig:
        ax = fig.add_subplot(sp_x,sp_y,sp_n, projection=utm_crs)
        fig.subplots_adjust(hspace=-0.1)
    else:
        # otherwise create the figure first
        fig = plt.figure(figsize=(12,10))
        global gs
        gs = gridspec.GridSpec(2, 2,figure = fig, height_ratios=[3, 1],width_ratios=[1, 6] )
        ax = fig.add_subplot(gs[0,1], projection=utm_crs)

    # set the extent to the study region
    ax.set_extent([525000, 850000, 5940000, 6086000],
                  crs=utm_crs)

    # add land as background in gray
    gdf = gpd.read_file(dirpath+"/data/bbox/EU_Boarders_NUTS_0.geojson")
    gdf = gdf[gdf["CNTR_CODE"].isin(["DE", "DK", "PL"])]

    for geom in gdf["geometry"]:
        shape_feature = cfeature.ShapelyFeature([geom],
                                                ccrs.PlateCarree(),
                                                facecolor="gray",
                                                alpha = 0.5,
                                                edgecolor='black',
                                                lw=1,
                                                zorder = -50)

        ax.add_feature(shape_feature)

    # add grid lines
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=1, color='gray', alpha=0.5)
    gl.top_labels = False
    gl.right_labels = False
    gl.ylocator = mticker.FixedLocator([54, 54.5])
    gl.xlocator = mticker.FixedLocator([10, 12, 14])

    return fig, ax

def add_aligned_colorbar(fig, ax, pc, label = None,
                         ticks = None, ticklabels = None,
                         size = "3%", pad = 0.1):
    divider = make_axes_locatable(ax)
    ax_cb = divider.new_horizontal(size="3%", pad=0.1, axes_class=plt.Axes)

    fig.add_axes(ax_cb)
    cbar = plt.colorbar(pc, cax=ax_cb, label = label, ticks = ticks)

    if type(ticklabels) == list:
        cbar.ax.set_yticklabels(ticklabels)

    return cbar, ax_cb

But the problem comes up when I try to add the subplots to the figure:

xds_fpath = dirpath+"/data/GETM/WB200m.suf.2008-2021.nc"
xds = xr.open_dataset(xds_fpath)
xds.rio.write_crs(ccrs.UTM(zone = 32), inplace=True)

range_t= pd.date_range("2021-01-01","2021-12-31", freq="D")
mean_xds= xds.sel(time = range_t,
         method = "nearest").mean(dim = "time")

#create figure aswell as the map
fig, ax = create_map(sp_y = 2,
                     sp_x = 1,
                     sp_n = 1,
                     figsize = (12,8))

mc = mean_xds["salt"].plot(ax=ax,
                    transform=ccrs.PlateCarree(),
                    vmin = mean_xds["salt"].min(),
                    vmax = mean_xds["salt"].max(),
                    cmap = cm.thermal,
                    add_colorbar = False,
                    label='_nolegend_',
                    zorder = -25)

plt.title("Saltgradient")

#make colourbar same size as map
cbar1, ax_cb1 = add_aligned_colorbar(fig = fig, ax = ax, pc = mc,
                                    label = "Salinity [PPU]" ,
                                    size = "3%",
                                    pad = 8)

# X axis lineplot
fig.add_subplot(gs[1,1])
mean_lon = mean_xds.mean(dim = "lat")
lp = plt.plot(mean_lon["lon"],mean_lon["salt"])
plt.xlim([mean_lon["lon"].min(),mean_lon["lon"].max()])

# Y axis lineplot
fig.add_subplot(gs[0,0])
mean_lat= mean_xds.mean(dim = "lon")
plt.plot(mean_lat["salt"],mean_lat["lat"])
plt.ylim([mean_lat["lat"].min(),mean_lat["lat"].max()])

plt.tight_layout()

Because the figure looks like this: Ideally the y and the x axis lineplots would have the same size as the cartopy map

I have tried to set the overall figure height and width at the end (similar to this solution: Tight layout using Cartopy without passing w_pad argument?) but I could only get one subplot to match.

xds_fpath = dirpath+"/data/GETM/WB200m.suf.2008-2021.nc"
xds = xr.open_dataset(xds_fpath)
xds.rio.write_crs(ccrs.UTM(zone = 32), inplace=True)

range_t= pd.date_range("2021-01-01","2021-12-31", freq="D")
mean_xds= xds.sel(time = range_t,
         method = "nearest").mean(dim = "time")

#create figure aswell as the map
fig, ax = create_map(sp_y = 2,
                     sp_x = 1,
                     sp_n = 1,
                     figsize = (12,8))

mc = mean_xds["salt"].plot(ax=ax,
                    transform=ccrs.PlateCarree(),
                    vmin = mean_xds["salt"].min(),
                    vmax = mean_xds["salt"].max(),
                    cmap = cm.thermal,
                    add_colorbar = False,
                    label='_nolegend_',
                    zorder = -25)

plt.title("Saltgradient")

#make colourbar same size as map
cbar1, ax_cb1 = add_aligned_colorbar(fig = fig, ax = ax, pc = mc,
                                    label = "Salinity [PPU]" ,
                                    size = "3%",
                                    pad = 8)

# X axis lineplot
fig.add_subplot(gs[1,1])
mean_lon = mean_xds.mean(dim = "lat")
lp = plt.plot(mean_lon["lon"],mean_lon["salt"])
plt.xlim([mean_lon["lon"].min(),mean_lon["lon"].max()])

# Y axis lineplot
fig.add_subplot(gs[0,0])
mean_lat= mean_xds.mean(dim = "lon")
plt.plot(mean_lat["salt"],mean_lat["lat"])
plt.ylim([mean_lat["lat"].min(),mean_lat["lat"].max()])

xmin, xmax = ax.get_xbound()
ymin, ymax = ax.get_ybound()
y2x_ratio = (ymax-ymin)/(xmax-xmin)

fig.set_figheight(12 * y2x_ratio)

plt.tight_layout()

Here the y axis lineplot matches the height of the cartopy map


问:
JS Drag&Drop on Firefox / Android not working
I am working on a drag & drop quiz where i can sort items into two areas.

Sadly it is not working in Firefox Mobile on Android. If i touch the items nothing happens. But i wonder why...

HTML:

```<code><!doctype html>

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<div class="step">

    <div class="handles">

        <div class="handle" id="handle4" data-target="omnivor" draggable="true">Meat</div>
        <div class="handle" id="handle1" data-target="vegan" draggable="true">Cocoa</div>
        <div class="handle" id="handle2" data-target="vegan" draggable="true">Banana</div>
        <div class="handle" id="handle3" data-target="omnivor" draggable="true">butter</div>

    </div>

    <div class="targets">
        <div id="target1" class="target">vegan</div>
        <div id="target2" class="target">omnivor</div>
    </div>

</div>

</body>
</html>
</code>```

Javascript:

```<code>window.addEventListener("load", function() {

    // handles-container auf feste hoehe setzen, damit er fix bleibt
    let handlesContainer = document.querySelector(".handles");
    handlesContainer.style.height = handlesContainer.offsetHeight+"px";

    // Handles draggable machen...
    let handles = document.querySelectorAll(".handles .handle");

    handles.forEach(function(e) {

        e.addEventListener("dragstart", function(e) {

            e.stopPropagation();
            e.dataTransfer.setData('text/plain', this.id);
            this.classList.add("drag-start");

        });

        e.addEventListener("dragend", function(e) {

            e.stopPropagation();
            this.classList.remove("drag-start");

        });

    });

    // Targets empfaenglich machen...

    let targets = document.querySelectorAll(".targets .target");

    targets.forEach(function(e) {

        e.addEventListener("dragenter", function(e) {

            e.preventDefault();
            this.classList.add("drag-enter");

        });

        e.addEventListener("dragleave", function() {

            this.classList.remove("drag-enter");

        });

        e.addEventListener("dragover", function(e) {
          e.preventDefault();
        });

        e.addEventListener("drop", function(e) {

            e.stopPropagation();
            this.classList.remove("drag-enter");

            let elmnt = document.getElementById(e.dataTransfer.getData("text/plain"));

                if(elmnt.dataset.target == this.innerText) {
                    console.log("korrekte zuordnung");
                }
                else {
                    console.log("Zuordnung falsch");
                }

            elmnt.remove();
        });

    });

});
</code>```

Here is my codepen:

https://codepen.io/kili123/pen/MWByGVE

I want to make the itams draggable and droppable on all modern browsers..

Body:
I am working on a drag & drop quiz where i can sort items into two areas.

Sadly it is not working in Firefox Mobile on Android. If i touch the items nothing happens. But i wonder why...

HTML:

<!doctype html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Meat

Cocoa

Banana

butter

vegan

omnivor

Javascript:

window.addEventListener("load", function() {

    // handles-container auf feste hoehe setzen, damit er fix bleibt
    let handlesContainer = document.querySelector(".handles");
    handlesContainer.style.height = handlesContainer.offsetHeight+"px";

    // Handles draggable machen...
    let handles = document.querySelectorAll(".handles .handle");

    handles.forEach(function(e) {

        e.addEventListener("dragstart", function(e) {

            e.stopPropagation();
            e.dataTransfer.setData('text/plain', this.id);
            this.classList.add("drag-start");

        });

        e.addEventListener("dragend", function(e) {

            e.stopPropagation();
            this.classList.remove("drag-start");

        });

    });

    // Targets empfaenglich machen...

    let targets = document.querySelectorAll(".targets .target");

    targets.forEach(function(e) {

        e.addEventListener("dragenter", function(e) {

            e.preventDefault();
            this.classList.add("drag-enter");

        });

        e.addEventListener("dragleave", function() {

            this.classList.remove("drag-enter");

        });

        e.addEventListener("dragover", function(e) {
          e.preventDefault();
        });

        e.addEventListener("drop", function(e) {

            e.stopPropagation();
            this.classList.remove("drag-enter");

            let elmnt = document.getElementById(e.dataTransfer.getData("text/plain"));

                if(elmnt.dataset.target == this.innerText) {
                    console.log("korrekte zuordnung");
                }
                else {
                    console.log("Zuordnung falsch");
                }

            elmnt.remove();
        });

    });

});

Here is my codepen:

https://codepen.io/kili123/pen/MWByGVE

I want to make the itams draggable and droppable on all modern browsers..


问:
How do I read files and perform calculations in the background before the activity starts?
I have 2 activities, A and B, B has a recyclerview and it reads files from the external storage and shows the meta data along with some validation of the files. This takes a while so the activity loads very slowly. How do I perform the calculations in activity A before the user goes to Activity B so that he/she doesn't have to wait for the data to be loaded in Activity B. I have tried threads and AsyncTasks in Activity B, but they only start running once I'm on Activity B. I want to start doing the processing in the background while the user is on Activity A.

When I tried threads and AsyncTasks, they return the results only after the code in the onCreate of Activity B has done running. So I get errors because the onCreate relies on the results from the background calculations. I tried thread.join() but it takes the same amount of time as without using threads.


问:
My Frontend (Nuxt) can't call the graphql endpoint, I'm ussing docker
Hi have deployed my app in pre-prod env, I have a frontend (nuxt) and backend (strapi), I'm using docker image for front, back, and Nginx.

But the frontend service can't fetch strapi graphql endpoint, but when I connect the local frontend to my pre-prod backend it works well but it isn't the same behavior with the pre-prod frontend.

i have this error when i log the front container :

```<code>---> ERROR >  Network error: request to https://mydomain.dev/graphql failed, reason: connect ETIMEDOUT 161.35.150.4:443

  at new ApolloError (node_modules/apollo-client/bundle.umd.js:92:26)
  at node_modules/apollo-client/bundle.umd.js:1588:34
  at node_modules/apollo-client/bundle.umd.js:2008:15
  at Set.forEach (<anonymous>)
  at node_modules/apollo-client/bundle.umd.js:2006:26
  at Map.forEach (<anonymous>)
  at QueryManager.broadcastQueries (node_modules/apollo-client/bundle.umd.js:2004:20)
  at node_modules/apollo-client/bundle.umd.js:1483:29
  at processTicksAndRejections (node:internal/process/task_queues:96:5)
Error Network error: request to https://mydomain.dev/graphql failed, reason: connect ETIMEDOUT XXX.XXX.XXX.XXX:443
 ---> ERROR >  Network error: request to https://mydomain.dev/graphql failed, reason: connect ETIMEDOUT 161.35.150.4:443
</code>```

nginx.conf

```<code>    events{}

http{
  include mime.types;

  # Expires map
  map $sent_http_content_type $expires {
      default                    off;
      text/html                  epoch;
      text/css                   max;
      application/javascript     max;
      ~image/                    max;
  }

  server {
    listen 80;
    listen [::]:80;

    server_name mydomain.com;
    server_tokens off;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://mydomain.dev$request_uri;
    }
  }

  server {
    listen 443 default_server ssl;
    listen [::]:443 ssl;

    server_name mydomain.dev;

    ssl_certificate /etc/nginx/ssl/live/mydomain.dev/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/live/mydomain.dev/privkey.pem;

    location /admin {
      sendfile on;
      proxy_pass http://backend:1337;
    }

    location /graphql {
      sendfile on;
      proxy_pass http://backend:1337;
    }

    location / {
      sendfile on;
      proxy_pass http://frontend:3000;
    }
  }
}
</code>```

docker-compose.yml

```<code># path: ./docker-compose.yml

version: '3'
services:
  certbot:
    image: certbot/certbot:latest
    volumes:
      - ./certbot/www/:/var/www/certbot/:rw
      - ./certbot/conf/:/etc/letsencrypt/:rw
  frontend:
    container_name: frontend
    image: mydockerhub/app-front:latest
    restart: always
    ports:
      - 3000:3000
  backend:
    container_name: backend
    build: .
    image: mydockerhub/app-back
    restart: always
    env_file: .env
    environment:
      DATABASE_CLIENT: ${DATABASE_CLIENT}
      DATABASE_HOST: myDB
      DATABASE_PORT: ${DATABASE_PORT}
      DATABASE_NAME: ${DATABASE_NAME}
      DATABASE_USERNAME: ${DATABASE_USERNAME}
      DATABASE_PASSWORD: ${DATABASE_PASSWORD}
      JWT_SECRET: ${JWT_SECRET}
      ADMIN_JWT_SECRET: ${ADMIN_JWT_SECRET}
      APP_KEYS: ${APP_KEYS}
      NODE_ENV: ${NODE_ENV}
    ports:
      - '1337:1337'
    depends_on:
      - myDB
    volumes:
      - ./app:/srv/app

  myDB:
    container_name: myDB
    platform: linux/amd64 #for platform error on Apple M1 chips
    restart: unless-stopped
    env_file: .env
    image: mysql:5.7
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_ROOT_PASSWORD: ${DATABASE_PASSWORD}
      MYSQL_PASSWORD: ${DATABASE_PASSWORD}
      MYSQL_DATABASE: ${DATABASE_NAME}
    volumes:
      - strapi-data:/var/lib/mysql
      #- ./data:/var/lib/mysql # if you want to use a bind folder
    ports:
      - '13306:3306'
  webserver:
    container_name: webserver
    image: nginx:latest
    ports:
      - 80:80
      - 443:443
    restart: always
    depends_on:
      - frontend
      - backend
    volumes:
      - ./nginx/conf/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./certbot/www:/var/www/certbot/:ro
      - ./certbot/conf/:/etc/nginx/ssl/:ro

volumes:
  strapi-data:
</code>```

Body:
Hi have deployed my app in pre-prod env, I have a frontend (nuxt) and backend (strapi), I'm using docker image for front, back, and Nginx.

But the frontend service can't fetch strapi graphql endpoint, but when I connect the local frontend to my pre-prod backend it works well but it isn't the same behavior with the pre-prod frontend.

i have this error when i log the front container :

---> ERROR >  Network error: request to https://mydomain.dev/graphql failed, reason: connect ETIMEDOUT 161.35.150.4:443

  at new ApolloError (node_modules/apollo-client/bundle.umd.js:92:26)
  at node_modules/apollo-client/bundle.umd.js:1588:34
  at node_modules/apollo-client/bundle.umd.js:2008:15
  at Set.forEach (<anonymous>)
  at node_modules/apollo-client/bundle.umd.js:2006:26
  at Map.forEach (<anonymous>)
  at QueryManager.broadcastQueries (node_modules/apollo-client/bundle.umd.js:2004:20)
  at node_modules/apollo-client/bundle.umd.js:1483:29
  at processTicksAndRejections (node:internal/process/task_queues:96:5)
Error Network error: request to https://mydomain.dev/graphql failed, reason: connect ETIMEDOUT XXX.XXX.XXX.XXX:443
 ---> ERROR >  Network error: request to https://mydomain.dev/graphql failed, reason: connect ETIMEDOUT 161.35.150.4:443

nginx.conf

    events{}

http{
  include mime.types;

  # Expires map
  map $sent_http_content_type $expires {
      default                    off;
      text/html                  epoch;
      text/css                   max;
      application/javascript     max;
      ~image/                    max;
  }

  server {
    listen 80;
    listen [::]:80;

    server_name mydomain.com;
    server_tokens off;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://mydomain.dev$request_uri;
    }
  }

  server {
    listen 443 default_server ssl;
    listen [::]:443 ssl;

    server_name mydomain.dev;

    ssl_certificate /etc/nginx/ssl/live/mydomain.dev/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/live/mydomain.dev/privkey.pem;

    location /admin {
      sendfile on;
      proxy_pass http://backend:1337;
    }

    location /graphql {
      sendfile on;
      proxy_pass http://backend:1337;
    }

    location / {
      sendfile on;
      proxy_pass http://frontend:3000;
    }
  }
}

docker-compose.yml

# path: ./docker-compose.yml

version: '3'
services:
  certbot:
    image: certbot/certbot:latest
    volumes:
      - ./certbot/www/:/var/www/certbot/:rw
      - ./certbot/conf/:/etc/letsencrypt/:rw
  frontend:
    container_name: frontend
    image: mydockerhub/app-front:latest
    restart: always
    ports:
      - 3000:3000
  backend:
    container_name: backend
    build: .
    image: mydockerhub/app-back
    restart: always
    env_file: .env
    environment:
      DATABASE_CLIENT: ${DATABASE_CLIENT}
      DATABASE_HOST: myDB
      DATABASE_PORT: ${DATABASE_PORT}
      DATABASE_NAME: ${DATABASE_NAME}
      DATABASE_USERNAME: ${DATABASE_USERNAME}
      DATABASE_PASSWORD: ${DATABASE_PASSWORD}
      JWT_SECRET: ${JWT_SECRET}
      ADMIN_JWT_SECRET: ${ADMIN_JWT_SECRET}
      APP_KEYS: ${APP_KEYS}
      NODE_ENV: ${NODE_ENV}
    ports:
      - '1337:1337'
    depends_on:
      - myDB
    volumes:
      - ./app:/srv/app

  myDB:
    container_name: myDB
    platform: linux/amd64 #for platform error on Apple M1 chips
    restart: unless-stopped
    env_file: .env
    image: mysql:5.7
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_ROOT_PASSWORD: ${DATABASE_PASSWORD}
      MYSQL_PASSWORD: ${DATABASE_PASSWORD}
      MYSQL_DATABASE: ${DATABASE_NAME}
    volumes:
      - strapi-data:/var/lib/mysql
      #- ./data:/var/lib/mysql # if you want to use a bind folder
    ports:
      - '13306:3306'
  webserver:
    container_name: webserver
    image: nginx:latest
    ports:
      - 80:80
      - 443:443
    restart: always
    depends_on:
      - frontend
      - backend
    volumes:
      - ./nginx/conf/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./certbot/www:/var/www/certbot/:ro
      - ./certbot/conf/:/etc/nginx/ssl/:ro

volumes:
  strapi-data:


问:
Powershell - Different output when reading from a file vs hard coded variable
I have a file called input.txt with the following line (the file is encoded in UTF-8-BOM)

PDVSA PETROCEDEÑO

I have the following powershell script

```<code>$input = Get-Content -Path input.txt
foreach ($line in $input) {
Write-Output $line
}
Write-Output "PDVSA PETROCEDEÑO"
</code>```

When I run this code I get the following output:

PDVSA PETROCEDEÑO

PDVSA PETROCEDEOÃ'O

So the question is, why am I getting different outputs, and how can I transform the first output into the second?

What I am trying to do is to read from the file with the same format as in the hard-coded output so I can use that string in a SOAP message

Thanks

Body:
I have a file called input.txt with the following line (the file is encoded in UTF-8-BOM)

PDVSA PETROCEDEÑO

I have the following powershell script

$input = Get-Content -Path input.txt
foreach ($line in $input) {
Write-Output $line
}
Write-Output "PDVSA PETROCEDEÑO"

When I run this code I get the following output:

PDVSA PETROCEDEÑO

PDVSA PETROCEDEOÃ'O

So the question is, why am I getting different outputs, and how can I transform the first output into the second?

What I am trying to do is to read from the file with the same format as in the hard-coded output so I can use that string in a SOAP message

Thanks


问:
Computed state not changing in reload page when function modifies state
If I go to /notifications request is made and retrieves data, but when useStore().retrieveNotificationList() is called, doesn't change notifications state. But if I go to another page and click to notifications router-link it does. Any idea?

Routes befores

```<code>router.beforeResolve((to, from, next) => {
  if (!isLoggedIn) {
    useAuthStore().refreshAccessToken()
    .then(() => next() )
  } else {
    next()
  }
})

router.beforeEach(async (to, from, next) => {
    if(to.matched.some(record => record.meta.requiresLogin && !isLoggedIn)){
        next({name: 'login'})
    } else{
        next()
    }
})
</code>```

Store

```<code>export const useStore = defineStore('core', {
    state: () => {
        return {
            notifications: null
        }
    },
    actions: {
        retrieveNotificationList() {
            return new Promise((resolve, reject) => {
                getAPI.get('/api/notifications/')
                .then(response => {
                    this.notifications = response.data
                    resolve()
                })
                .catch(err=> console.error(err))
            })
        },
        deleteNotification(id) {
            getAPI.delete('/api/notifications/' + id)
                .then(() => this.notifications = this.notifications.filter(item => item.id !== id))
        }
    }
})
</code>```

NotificationsView

```<code><template>
        <router-link to="/">Home</router-link> |
    <div :class="{'read':notification.read}" v-for="notification in notifications" :key="notification.id" class="notification">
        <p>{{ notification.message }}</p>
        <button @click="deleteNotification(notification.id)">X</button>
    </div>
</template>

<script setup>
import { useStore } from '../store/index'
import { computed } from 'vue'

useStore().retrieveNotificationList()

const notifications = computed(() => {
    return useStore().notifications
})

function deleteNotification(id) {
    useStore().deleteNotification(id)
}
</script>
</code>```

Body:
If I go to /notifications request is made and retrieves data, but when useStore().retrieveNotificationList() is called, doesn't change notifications state. But if I go to another page and click to notifications router-link it does. Any idea?

Routes befores

router.beforeResolve((to, from, next) => {
  if (!isLoggedIn) {
    useAuthStore().refreshAccessToken()
    .then(() => next() )
  } else {
    next()
  }
})

router.beforeEach(async (to, from, next) => {
    if(to.matched.some(record => record.meta.requiresLogin && !isLoggedIn)){
        next({name: 'login'})
    } else{
        next()
    }
})

Store

export const useStore = defineStore('core', {
    state: () => {
        return {
            notifications: null
        }
    },
    actions: {
        retrieveNotificationList() {
            return new Promise((resolve, reject) => {
                getAPI.get('/api/notifications/')
                .then(response => {
                    this.notifications = response.data
                    resolve()
                })
                .catch(err=> console.error(err))
            })
        },
        deleteNotification(id) {
            getAPI.delete('/api/notifications/' + id)
                .then(() => this.notifications = this.notifications.filter(item => item.id !== id))
        }
    }
})

NotificationsView

<template>
        <router-link to="/">Home</router-link> |

{{ notification.message }}

        <button @click="deleteNotification(notification.id)">X</button>

</template>


问:
How can I create input that accepts Latex syntax?
I'm creating a project that the administrator adds mathematical questions to the system and for that it is necessary to put mathematical formulas

I did some research and saw that Latex is an option

My project is being developed in react


问:
Failure in Custom Exception Handler for HttpMediaTypeNotAcceptableException
I'm trying to add a custom Exception handler, which can add a more understandable response to my Spring Boot Rest API, whenever a person uses wrong Accept: Headers. Looking at my logs, the DefaultExceptionhandler resolves the following:

Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

Writing a Custom Exception Handler, I want to return an HTTP Status BAD_REQUEST and an error message, explaining which Media Types are supported.

I tried the following Code:

```<code>@ControllerAdvice
public class CustomRestExceptionHandler {

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    public ResponseEntity<Error> handleException(
            HttpMediaTypeNotAcceptableException e
    ) {
        List<MediaType> supportedTypes = e.getSupportedMediaTypes();
        List<String> supported = new ArrayList<>();
        for (MediaType type: supportedTypes){
            supported.add(type.getType()+type.getSubtype());
        }
        String error = "Media Type not supported. The following types are supported: " + String.join(", ", supported);

        return new ResponseEntity<>(
                new Error(
                        HttpStatus.BAD_REQUEST,
                        error
                ),
                HttpStatus.BAD_REQUEST
        );
    }
}

</code>```
```<code>@Data
public class Error {
    private final HttpStatus httpStatus;
    private final String message;
}

</code>```

Now, whenever I use the wrong Accept:Header, I get a Warning in my logs:

97  WARN 5368 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler de.sajoconsulting.convertpdfdemo.error.CustomRestExceptionHandler#handleException(HttpMediaTypeNotAcceptableException)

And finally, the DefaultHandler resolves the Exception like normal, leading to the same HTTP Status.

I also took a look at: https://stackoverflow.com/a/74697214/20893655 which suggests it might have to do something with missing Getter and Setters, which I did provide by Lombok's @Data.

Body:
I'm trying to add a custom Exception handler, which can add a more understandable response to my Spring Boot Rest API, whenever a person uses wrong Accept: Headers. Looking at my logs, the DefaultExceptionhandler resolves the following:

Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

Writing a Custom Exception Handler, I want to return an HTTP Status BAD_REQUEST and an error message, explaining which Media Types are supported.

I tried the following Code:

@ControllerAdvice
public class CustomRestExceptionHandler {

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    public ResponseEntity<Error> handleException(
            HttpMediaTypeNotAcceptableException e
    ) {
        List<MediaType> supportedTypes = e.getSupportedMediaTypes();
        List<String> supported = new ArrayList<>();
        for (MediaType type: supportedTypes){
            supported.add(type.getType()+type.getSubtype());
        }
        String error = "Media Type not supported. The following types are supported: " + String.join(", ", supported);

        return new ResponseEntity<>(
                new Error(
                        HttpStatus.BAD_REQUEST,
                        error
                ),
                HttpStatus.BAD_REQUEST
        );
    }
}

@Data
public class Error {
    private final HttpStatus httpStatus;
    private final String message;
}

Now, whenever I use the wrong Accept:Header, I get a Warning in my logs:

97  WARN 5368 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler de.sajoconsulting.convertpdfdemo.error.CustomRestExceptionHandler#handleException(HttpMediaTypeNotAcceptableException)

And finally, the DefaultHandler resolves the Exception like normal, leading to the same HTTP Status.

I also took a look at: https://stackoverflow.com/a/74697214/20893655 which suggests it might have to do something with missing Getter and Setters, which I did provide by Lombok's @Data.


问:
How to point to child elements when vue-tour is initialised in parent component?

<template>

      <q-card id="scrollBody" class="detail-page-wrap" @scroll="handleScroll">
      <childComponent />
      </q-card>

</template>```

Need to point to child component elements, so need to add targets but they aren't coming when static ids are added to parent component and when the tour is instantiated on the parent mount.

Body:
<template>

      <q-card id="scrollBody" class="detail-page-wrap" @scroll="handleScroll">
      <childComponent />
      </q-card>

</template>

Need to point to child component elements, so need to add targets but they aren't coming when static ids are added to parent component and when the tour is instantiated on the parent mount.


问:
segmentation fault in C++ program - valgrind's Invalid write of size 8
I've seen many similar questions, yet I do not arrive to solve the problem in my implementation.

I am working on a C++ program to solve the 2D-heat-equation.
Here I reproduce the blocks of the error only, I've omitted a lot of code doing other stuff and constant values in the equations. Given the math context, I will use matrix vocabulary in some places.

I understand that I may be trying to access unreachable memory, yet I cannot see why.

vector has dimension dim=1001, so vector_[0] should exist and in the loop from i=1...dim-1 everything should be reachable.

matrix_ on the other hand has dimensions (maxT+1, dim). The loop over t in [1...maxT] looks reachable to me and then in the loop over i
the program access each row of the matrix and access it's ith element, since it goes to dim-1 then the indexing matrix_[t][i+1] should also be reachable in the last iteration with i<dim-1 <1001-1=1000 so i=999 therefore in the last iteration it is matrix_[t][1000], that is the last element of the t-row.

myclass.h

```<code>#include <vector>
using vector_double = std::vector<double>;
using matrix2d = std::vector<std::vector<double>>;

class Myclass{
    protected:
        matrix2d matrix_;
        vector_double vector_;
        size_t dim;
        size_t maxT;
        double initValue;

    public:
        Myclass();
        void routine();
};
</code>```

myclass.cpp

```<code>#include "myclass.h"

Myclass::Myclass()
{
    size_t dim = 1001;
    size_t maxT = 1001;
    double initValue = 13.0;
    matrix2d matrix_(maxT+1, vector_double(dim,initValue));
    vector_double vector_(dim);

}

void Myclass::routine()
{
    vector_[0] = initValue;

    for(size_t t=1; t<maxT; t++)
    {
        vector_[0] = matrix_[t][0] + matrix_[t][0];
        for(size_t i=1; i < dim-1; i++)
        {
            vector_[i] = matrix_[t][i-1] + matrix_[t][i] + matrix_[t][i+1];
        }
    }
}
</code>```

so.cpp

```<code>#include "myclass.h"

int main()
{
    Myclass myobject;
    myobject.routine();

return 0;
}
</code>```

I compile with: g++ -g -O1 *.cpp -o out and run valgrind with valgrind --leak-check=yes ./out.

To get the following error:

```<code>==25934== Memcheck, a memory error detector
==25934== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==25934== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==25934== Command: ./out
==25934==
==25934== Invalid write of size 8
==25934==    at 0x109217: Myclass::routine() (myclass.cpp:15)
==25934==    by 0x109577: main (so.cpp:7)
==25934==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==25934==
==25934==
==25934== Process terminating with default action of signal 11 (SIGSEGV)
==25934==  Access not within mapped region at address 0x0
==25934==    at 0x109217: Myclass::routine() (myclass.cpp:15)
==25934==    by 0x109577: main (so.cpp:7)
==25934==  If you believe this happened as a result of a stack
==25934==  overflow in your program's main thread (unlikely but
==25934==  possible), you can try to increase the size of the
==25934==  main thread stack using the --main-stacksize= flag.
==25934==  The main thread stack size used in this run was 8388608.
==25934==
==25934== HEAP SUMMARY:
==25934==     in use at exit: 0 bytes in 0 blocks
==25934==   total heap usage: 1,006 allocs, 1,006 frees, 8,136,784 bytes allocated
==25934==
==25934== All heap blocks were freed -- no leaks are possible
==25934==
==25934== For lists of detected and suppressed errors, rerun with: -s
==25934== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
</code>```

So what I am looking for is the way to make routine actually update the values of vector at each time t of the outer loop, which is not happening because of the segmentation fault.

Thanks

Body:
I've seen many similar questions, yet I do not arrive to solve the problem in my implementation.

I am working on a C++ program to solve the 2D-heat-equation.
Here I reproduce the blocks of the error only, I've omitted a lot of code doing other stuff and constant values in the equations. Given the math context, I will use matrix vocabulary in some places.

I understand that I may be trying to access unreachable memory, yet I cannot see why.

vector has dimension dim=1001, so vector_[0] should exist and in the loop from i=1...dim-1 everything should be reachable.

matrix_ on the other hand has dimensions (maxT+1, dim). The loop over t in [1...maxT] looks reachable to me and then in the loop over i
the program access each row of the matrix and access it's ith element, since it goes to dim-1 then the indexing matrix_[t][i+1] should also be reachable in the last iteration with i<dim-1 <1001-1=1000 so i=999 therefore in the last iteration it is matrix_[t][1000], that is the last element of the t-row.

myclass.h

#include <vector>
using vector_double = std::vector<double>;
using matrix2d = std::vector<std::vector<double>>;

class Myclass{
    protected:
        matrix2d matrix_;
        vector_double vector_;
        size_t dim;
        size_t maxT;
        double initValue;

    public:
        Myclass();
        void routine();
};

myclass.cpp

#include "myclass.h"

Myclass::Myclass()
{
    size_t dim = 1001;
    size_t maxT = 1001;
    double initValue = 13.0;
    matrix2d matrix_(maxT+1, vector_double(dim,initValue));
    vector_double vector_(dim);

}

void Myclass::routine()
{
    vector_[0] = initValue;

    for(size_t t=1; t<maxT; t++)
    {
        vector_[0] = matrix_[t][0] + matrix_[t][0];
        for(size_t i=1; i < dim-1; i++)
        {
            vector_[i] = matrix_[t][i-1] + matrix_[t][i] + matrix_[t][i+1];
        }
    }
}

so.cpp

#include "myclass.h"

int main()
{
    Myclass myobject;
    myobject.routine();

return 0;
}

I compile with: g++ -g -O1 *.cpp -o out and run valgrind with valgrind --leak-check=yes ./out.

To get the following error:

==25934== Memcheck, a memory error detector
==25934== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==25934== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==25934== Command: ./out
==25934==
==25934== Invalid write of size 8
==25934==    at 0x109217: Myclass::routine() (myclass.cpp:15)
==25934==    by 0x109577: main (so.cpp:7)
==25934==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==25934==
==25934==
==25934== Process terminating with default action of signal 11 (SIGSEGV)
==25934==  Access not within mapped region at address 0x0
==25934==    at 0x109217: Myclass::routine() (myclass.cpp:15)
==25934==    by 0x109577: main (so.cpp:7)
==25934==  If you believe this happened as a result of a stack
==25934==  overflow in your program's main thread (unlikely but
==25934==  possible), you can try to increase the size of the
==25934==  main thread stack using the --main-stacksize= flag.
==25934==  The main thread stack size used in this run was 8388608.
==25934==
==25934== HEAP SUMMARY:
==25934==     in use at exit: 0 bytes in 0 blocks
==25934==   total heap usage: 1,006 allocs, 1,006 frees, 8,136,784 bytes allocated
==25934==
==25934== All heap blocks were freed -- no leaks are possible
==25934==
==25934== For lists of detected and suppressed errors, rerun with: -s
==25934== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)

So what I am looking for is the way to make routine actually update the values of vector at each time t of the outer loop, which is not happening because of the segmentation fault.

Thanks


问:
Android multi display - Custom system navigation bar
I'm using Android multi display and displaying my custom launcher on secondary display like monitor. I want to customize monitor's system navigation bar like in Zebra work station connect.
I tried using below code and hide default navigation bar by using this solution. but not able to click buttons in custom navigation view and, when I open any application on monitor, default navigation bar is showing in front. Can any one help in customizing navigation bar like in zebra work station connect?

```<code>private void overLayNavigationBar() {
    if (windowManager == null) {
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    }

    WindowManager.LayoutParams params;
    if (layoutOverlayTaskbar == null) {
        layoutOverlayTaskbar = (ConstraintLayout) LayoutInflater.from(this).inflate(R.layout.layout_navbar_overlay, null);
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_FULLSCREEN |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                        WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                SDUtils.getNavigationBarHeight(this));

        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = SDUtils.getNavigationBarHeight(this);
        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
        params.x = _xOffset;
        params.y = _yOffset;
        windowManager.addView(layoutOverlayTaskbar, params);
    } else {
        params = (WindowManager.LayoutParams) layoutOverlayTaskbar.getLayoutParams();
        params.x = _xOffset;
        params.y = _yOffset;
        windowManager.removeView(layoutOverlayTaskbar);
        layoutOverlayTaskbar.setLayoutParams(params);
        windowManager.addView(layoutOverlayTaskbar, params);
    }
    _xOffset += 40;
    _yOffset += 100;
}

private void setWindowParameters() {
    WindowManager.LayoutParams params = getWindow().getAttributes();
    if (SDUtils.applyDisplayCutoutModeTo(params))
        getWindow().setAttributes(params);
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
</code>```

Body:
I'm using Android multi display and displaying my custom launcher on secondary display like monitor. I want to customize monitor's system navigation bar like in Zebra work station connect.
I tried using below code and hide default navigation bar by using this solution. but not able to click buttons in custom navigation view and, when I open any application on monitor, default navigation bar is showing in front. Can any one help in customizing navigation bar like in zebra work station connect?

private void overLayNavigationBar() {
    if (windowManager == null) {
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    }

    WindowManager.LayoutParams params;
    if (layoutOverlayTaskbar == null) {
        layoutOverlayTaskbar = (ConstraintLayout) LayoutInflater.from(this).inflate(R.layout.layout_navbar_overlay, null);
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_FULLSCREEN |
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                        WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                SDUtils.getNavigationBarHeight(this));

        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = SDUtils.getNavigationBarHeight(this);
        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
        params.x = _xOffset;
        params.y = _yOffset;
        windowManager.addView(layoutOverlayTaskbar, params);
    } else {
        params = (WindowManager.LayoutParams) layoutOverlayTaskbar.getLayoutParams();
        params.x = _xOffset;
        params.y = _yOffset;
        windowManager.removeView(layoutOverlayTaskbar);
        layoutOverlayTaskbar.setLayoutParams(params);
        windowManager.addView(layoutOverlayTaskbar, params);
    }
    _xOffset += 40;
    _yOffset += 100;
}

private void setWindowParameters() {
    WindowManager.LayoutParams params = getWindow().getAttributes();
    if (SDUtils.applyDisplayCutoutModeTo(params))
        getWindow().setAttributes(params);
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
}


问:
How to achieve recyclerview as bottomsheet effect
How to achive this effect with recyclerview
example
https://res.cloudinary.com/djdle8unh/video/upload/v1672401600/bandicam_2022-12-30_17-27-01-233_hehwx3.mp4
i have plan like casting the layout to bottomsheet but i dont know how to get other things like watchlist and other user related details.attching my current movie design</p>


问:
installing uber H3 library in google script
is there someone that could help me in installing uber h3 library in google script?

I'm trying to implement a function that transform a couple of coordinate into an H3_9 geometry, I'm able to do it in python:

```<code>import h3
h3_index = h3.geo_to_h3(lat, lon, 9)
</code>```

but every attempt I made to do the same thing in a google sheet macro result in the same problem, where to find a valid library id to use (chat GPT is suggesting me a lot of IDs but they are not working and I suspect that I need some permission o have visibility on some repository I don't know how to ask for)

the point is that I'm looking for specific H3 Uber library documentation and how to implement it, not a generic answer as per other answered question

Body:
is there someone that could help me in installing uber h3 library in google script?

I'm trying to implement a function that transform a couple of coordinate into an H3_9 geometry, I'm able to do it in python:

import h3
h3_index = h3.geo_to_h3(lat, lon, 9)

but every attempt I made to do the same thing in a google sheet macro result in the same problem, where to find a valid library id to use (chat GPT is suggesting me a lot of IDs but they are not working and I suspect that I need some permission o have visibility on some repository I don't know how to ask for)

the point is that I'm looking for specific H3 Uber library documentation and how to implement it, not a generic answer as per other answered question


问:
::slotted() CSS pseudo-element with Tailwind
I want to use ::slotted() CSS pseudo-element with Tailwind, Tailwind supports most of pseudo-elements (::before, ::after...), but it seems ::slotted is not among them.
Is it possible to add support for ::slotted() CSS pseudo-element by editing a config?

I tried applying slotted:mb-md class to  element and it does not work, looked for docs on how to add support for more pseudo-element, but didn't find anything


问:
Accidently write flutter clean
In between project, I ran the command "flutter clean", now lots of error are showing. When I'm trying to run "flutter pub get" it's no more working, I'm getting following errors"flutter pub get" and "flutter cache repair" are not working, I've also cleared the cache, I've now no idea how to fix it"Flutter cache repair" not working

Tried "flutter pub get" and "flutter pub cache repair" none of them are working. Want to get rid of all the errors.

Title: Accidently write flutter clean


问:
Mongodb Switching db Convention packs
We designed mongodb with account-base databases.Every account has same collections but holding their data seperate databases in mongodb.
But I got memory leak in .net core application.I'm registering convention pack everytime I switched the db.I believe it caused problem.But if I'dont register ı got error.

```<code>protected virtual void SefDefaultConventions()
        {
            var pack = new ConventionPack();
            pack.Add(new LowerCaseElementNameConvention());
            pack.Add(new IgnoreExtraElementsConvention(true));
            pack.Add(new StringIdStoredAsObjectIdConvention());
            ConventionRegistry.Register("Default Conventions", pack, t => true);
        }
</code>```

I'm using mongoDb.Driver 2.11.4 .net 6

Thanks

Title: Mongodb Switching db Convention packs

Body:
We designed mongodb with account-base databases.Every account has same collections but holding their data seperate databases in mongodb.
But I got memory leak in .net core application.I'm registering convention pack everytime I switched the db.I believe it caused problem.But if I'dont register ı got error.

protected virtual void SefDefaultConventions()
        {
            var pack = new ConventionPack();
            pack.Add(new LowerCaseElementNameConvention());
            pack.Add(new IgnoreExtraElementsConvention(true));
            pack.Add(new StringIdStoredAsObjectIdConvention());
            ConventionRegistry.Register("Default Conventions", pack, t => true);
        }

I'm using mongoDb.Driver 2.11.4 .net 6

Thanks


问:
java.lang.IllegalArgumentException: The given id must not be null , OneToMany mapping jpa
I have two SQL tables MiddlewareSection and MiddlewareConfigurations, they have one to many relationship with each other,MiddlewareSection is the Parent table and  MiddlewareConfigurations is the Child table,MiddlewareConfigurations has a foreign key named section referencing the primary key (section_id) of  MiddlewareSection ,I am mapping these two through JPA and hibernate and using DTO and Entity both in order to reduce remote api calls so I am using ObjectMapper to convert entity to dto and dto to entity, In the service class I have an this update method

This is Service class

```<code> public MiddlewareConfigDTO updateMiddlewareConfig(String key_id, MiddlewareConfigDTO middlewareConfigDTO)
    {
        Optional<MiddlewareSections> checkRecord = middlewareSecRepo.findById(middlewareConfigDTO.getSection());
        if (checkRecord.isPresent()) {
            MiddlewareConfigurations middlewareConfigurations = modelMapper.map(middlewareConfigDTO, MiddlewareConfigurations.class);
            middlewareConfigurations.setMiddlewareSectionRequest(checkRecord.get());
            MiddlewareConfigurations save = midwareConfigRepo.save(middlewareConfigurations);
            MiddlewareConfigDTO middlewareConfigDTO1 = modelMapper.map(save, MiddlewareConfigDTO.class);
            middlewareConfigDTO1.setSection(checkRecord.get().getSection_id());
            return middlewareConfigDTO1;
        }
            return null;
    }
</code>```

This is Controller Class

```<code> @PutMapping("/update/{key_id}")
public MiddlewareConfigDTO updateSecRequest(@PathVariable String key_id,
                                            @RequestBody MiddlewareConfigDTO request) {
    return midwareConfigService.updateMiddlewareConfig(key_id,request);
}
</code>```

MiddlewareConfigDto

```<code>  @Data
public class MiddlewareConfigDTO {
    private String key_id;
    private Integer section;
    private String value_id;
    private String description_;
    private int delete_status;
    private Timestamp created_at;
    private Timestamp updated_at;
    private String create_by;
    private String updated_by;
}
</code>```

MiddlewareConfigurations

```<code>    @Entity
@Table(name = "middleware_configurations")
@Data
@NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class MiddlewareConfigurations {
    @ManyToOne
    @JoinColumn(name = "SECTION")
    private MiddlewareSections middlewareSectionRequest;
    @Id
//    @GeneratedValue(generator = "uuid")
//    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String key_id;
    private String value_id;
    private String description_;
    private int delete_status;
    private Timestamp created_at;
    private Timestamp updated_at;
    private String create_by;
    private String updated_by;

    public MiddlewareSections getMiddlewareSectionRequest() {
        return middlewareSectionRequest;
    }

    public void setMiddlewareSectionRequest(MiddlewareSections middlewareSectionRequest) {
        this.middlewareSectionRequest = middlewareSectionRequest;
    }
</code>```

when I hit this using my postman I got this error

java.lang.IllegalArgumentException: The given id must not be null!
at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.3.24.jar:5.3.24]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById(SimpleJpaRepository.java:322) ~[spring-data-jpa-2.7.6.jar:2.7.6]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_261]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_261]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_261]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_261]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.7.6.jar:2.7.6]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.7.6.jar:2.7.6]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.7.6.jar:2.7.6]

this is MiddlewareConfiguration table

This is MiddlewareSection table

Body:
I have two SQL tables MiddlewareSection and MiddlewareConfigurations, they have one to many relationship with each other,MiddlewareSection is the Parent table and  MiddlewareConfigurations is the Child table,MiddlewareConfigurations has a foreign key named section referencing the primary key (section_id) of  MiddlewareSection ,I am mapping these two through JPA and hibernate and using DTO and Entity both in order to reduce remote api calls so I am using ObjectMapper to convert entity to dto and dto to entity, In the service class I have an this update method

This is Service class

 public MiddlewareConfigDTO updateMiddlewareConfig(String key_id, MiddlewareConfigDTO middlewareConfigDTO)
    {
        Optional<MiddlewareSections> checkRecord = middlewareSecRepo.findById(middlewareConfigDTO.getSection());
        if (checkRecord.isPresent()) {
            MiddlewareConfigurations middlewareConfigurations = modelMapper.map(middlewareConfigDTO, MiddlewareConfigurations.class);
            middlewareConfigurations.setMiddlewareSectionRequest(checkRecord.get());
            MiddlewareConfigurations save = midwareConfigRepo.save(middlewareConfigurations);
            MiddlewareConfigDTO middlewareConfigDTO1 = modelMapper.map(save, MiddlewareConfigDTO.class);
            middlewareConfigDTO1.setSection(checkRecord.get().getSection_id());
            return middlewareConfigDTO1;
        }
            return null;
    }

This is Controller Class

 @PutMapping("/update/{key_id}")
public MiddlewareConfigDTO updateSecRequest(@PathVariable String key_id,
                                            @RequestBody MiddlewareConfigDTO request) {
    return midwareConfigService.updateMiddlewareConfig(key_id,request);
}

MiddlewareConfigDto

  @Data
public class MiddlewareConfigDTO {
    private String key_id;
    private Integer section;
    private String value_id;
    private String description_;
    private int delete_status;
    private Timestamp created_at;
    private Timestamp updated_at;
    private String create_by;
    private String updated_by;
}

MiddlewareConfigurations

    @Entity
@Table(name = "middleware_configurations")
@Data
@NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class MiddlewareConfigurations {
    @ManyToOne
    @JoinColumn(name = "SECTION")
    private MiddlewareSections middlewareSectionRequest;
    @Id
//    @GeneratedValue(generator = "uuid")
//    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String key_id;
    private String value_id;
    private String description_;
    private int delete_status;
    private Timestamp created_at;
    private Timestamp updated_at;
    private String create_by;
    private String updated_by;

    public MiddlewareSections getMiddlewareSectionRequest() {
        return middlewareSectionRequest;
    }

    public void setMiddlewareSectionRequest(MiddlewareSections middlewareSectionRequest) {
        this.middlewareSectionRequest = middlewareSectionRequest;
    }

when I hit this using my postman I got this error

java.lang.IllegalArgumentException: The given id must not be null!
at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.3.24.jar:5.3.24]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById(SimpleJpaRepository.java:322) ~[spring-data-jpa-2.7.6.jar:2.7.6]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_261]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_261]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_261]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_261]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.7.6.jar:2.7.6]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.7.6.jar:2.7.6]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.7.6.jar:2.7.6]

this is MiddlewareConfiguration table

This is MiddlewareSection table


问:
Vertical scrolling doesn't work on elementor pro mobile page
The mobile page of my new website, that I build with Elementor shows a buggy vertical scrolling behavior. Whenever it reaches a new section or if I tap on the screen, it stops scrolling and kinda sticks on this section.

website is: www.bababuff.de

Any ideas what to do?

I want it to scroll through the whole site and don't stop at the different sections.


问:
How to fix VSCode personnal shortcuts not working
this is my custom shortcut that navigate previous file when go to file. But not working:

{
  "key": "shift+tab",
  "command": "workbench.action.quickOpenNavigatePreviousInFilePicker",
  "when": "inFilesPicker && inQuickOpen"
}
```
<p>this is my custom shortcut that navigate next file. it's working:</p>
<pre class="lang-json prettyprint-override"><code>{
  "key": "tab",
  "command": "workbench.action.quickOpenNavigateNextInFilePicker",
  "when": "inFilesPicker && inQuickOpen"
}
</code>```

this is default shortcut. is working:

{
  "key": "shift+cmd+p",
  "command": "workbench.action.quickOpenNavigatePreviousInFilePicker",
  "when": "inFilesPicker && inQuickOpen"
}
```

Body:
this is my custom shortcut that navigate previous file when go to file. But not working:

{
  "key": "shift+tab",
  "command": "workbench.action.quickOpenNavigatePreviousInFilePicker",
  "when": "inFilesPicker && inQuickOpen"
}

this is my custom shortcut that navigate next file. it's working:

{
  "key": "tab",
  "command": "workbench.action.quickOpenNavigateNextInFilePicker",
  "when": "inFilesPicker && inQuickOpen"
}

this is default shortcut. is working:

{
  "key": "shift+cmd+p",
  "command": "workbench.action.quickOpenNavigatePreviousInFilePicker",
  "when": "inFilesPicker && inQuickOpen"
}


问:
Extend Joi custom validation by chaining other validators after the custom() method
I'm trying to validate data using joi by using a custom validator but chain other joi validators after the custom method.

For eg:
if the schema receives value: '[1,2,"test"]', i want to first check if the value can be properly parsed as json using JSON.parse(), then make sure the parsed value is a json & then finally validate if the items in the array are strings or numbers.

Currently I have this code:

const schema = Joi.object({
  arrayInput: Joi.string().custom((_val, helper) => {
    try {
      const _parsed = JSON.parse(_val);
      if (_parsed) return _parsed;
    } catch {}
    return helper.message("must be valid json");
  })  // i want to extend this  further to validate the array items like .array().items(Joi.number())
});

schema.validate({ arrayInput: '[1,2,"test"]' });

```
<p>How can I achive this?
I hope I was clear with the information. Please let me know if i can clarify anything further.</p>
<p>I tried chaining other <code>joi</code> validation functions after the <code>custom()</code> function like so:</p>
<pre class="lang-js prettyprint-override"><code>const schema = Joi.object({
  arrayInput: Joi.string().custom((_val, helper) => {
    try {
      const _parsed = JSON.parse(_val);
      if (_parsed) return _parsed;
    } catch {}
    return helper.message("must be valid json");
  }).array().items(...)
});
</code>```

but it didn't work.

Body:
I'm trying to validate data using joi by using a custom validator but chain other joi validators after the custom method.

For eg:
if the schema receives value: '[1,2,"test"]', i want to first check if the value can be properly parsed as json using JSON.parse(), then make sure the parsed value is a json & then finally validate if the items in the array are strings or numbers.

Currently I have this code:

const schema = Joi.object({
  arrayInput: Joi.string().custom((_val, helper) => {
    try {
      const _parsed = JSON.parse(_val);
      if (_parsed) return _parsed;
    } catch {}
    return helper.message("must be valid json");
  })  // i want to extend this  further to validate the array items like .array().items(Joi.number())
});

schema.validate({ arrayInput: '[1,2,"test"]' });

How can I achive this?
I hope I was clear with the information. Please let me know if i can clarify anything further.

I tried chaining other joi validation functions after the custom() function like so:

const schema = Joi.object({
  arrayInput: Joi.string().custom((_val, helper) => {
    try {
      const _parsed = JSON.parse(_val);
      if (_parsed) return _parsed;
    } catch {}
    return helper.message("must be valid json");
  }).array().items(...)
});

but it didn't work.


问:
'React is not defined' when installing component library that I'm trying to create using Rollup and React
I'm trying to create a React component library. I'm using Rollup for bundling the files. I'm generating build folder then running npm pack to get a .tgz file of the library. Then I'm installing that file in another project using file:filename.tgz and npm install. But when I run the server it shows me ReferenceError: React is not defined. I assume this is happening because React is not included in the component library.

rollup.config.js

```<code>import { babel } from "@rollup/plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import terser from "@rollup/plugin-terser";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import sourcemaps from "rollup-plugin-sourcemaps";
const packageJson = require("./package.json");

const config = {
  input: "src/index.js",
  output: [
    {
      file: packageJson.main,
      format: "cjs",
    },
    {
      file: packageJson.module,
      format: "esm",
    },
  ],
  plugins: [
    sourcemaps(),
    babel({
      presets: [
        [
          "@babel/preset-react",
          {
            runtime: "automatic",
          },
        ],
      ],
      plugins: ["@babel/plugin-transform-runtime"],
      babelHelpers: "runtime",
    }),
    resolve(),
    commonjs(),
    terser(),
    peerDepsExternal(),
  ],
  globals: {
    react: "React",
  },
};

export default config;
</code>```

package.json

```<code>{
  "name": "@rahul-wos/pkg-practice",
  "version": "1.0.2",
  "description": "This is my first try at generating a component library",
  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.es.js",
  "type": "module",
  "files": [
    "dist"
  ],
  "scripts": {
    "rollup": "rollup --bundleConfigAsCjs -c ",
    "pack": "rollup --bundleConfigAsCjs -c"
  },
  "author": "Rahul Patil",
  "license": "ISC",
  "peerDependencies": {
    "react": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/plugin-transform-runtime": "^7.19.6",
    "@babel/preset-react": "^7.18.6",
    "@rollup/plugin-babel": "^6.0.3",
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "@rollup/plugin-terser": "^0.2.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "rollup": "^3.9.0",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "rollup-plugin-sourcemaps": "^0.6.3"
  },
  "dependencies": {
    "@babel/runtime": "^7.20.7"
  }
}
</code>```

This is the repo for component library: pkg-practice - Github

I tried searching on stackoverflow and google. Found some results that said I should include react in the component file. I tried doing that but the error still persists.

Body:
I'm trying to create a React component library. I'm using Rollup for bundling the files. I'm generating build folder then running npm pack to get a .tgz file of the library. Then I'm installing that file in another project using file:filename.tgz and npm install. But when I run the server it shows me ReferenceError: React is not defined. I assume this is happening because React is not included in the component library.

rollup.config.js

import { babel } from "@rollup/plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import terser from "@rollup/plugin-terser";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import sourcemaps from "rollup-plugin-sourcemaps";
const packageJson = require("./package.json");

const config = {
  input: "src/index.js",
  output: [
    {
      file: packageJson.main,
      format: "cjs",
    },
    {
      file: packageJson.module,
      format: "esm",
    },
  ],
  plugins: [
    sourcemaps(),
    babel({
      presets: [
        [
          "@babel/preset-react",
          {
            runtime: "automatic",
          },
        ],
      ],
      plugins: ["@babel/plugin-transform-runtime"],
      babelHelpers: "runtime",
    }),
    resolve(),
    commonjs(),
    terser(),
    peerDepsExternal(),
  ],
  globals: {
    react: "React",
  },
};

export default config;

package.json

{
  "name": "@rahul-wos/pkg-practice",
  "version": "1.0.2",
  "description": "This is my first try at generating a component library",
  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.es.js",
  "type": "module",
  "files": [
    "dist"
  ],
  "scripts": {
    "rollup": "rollup --bundleConfigAsCjs -c ",
    "pack": "rollup --bundleConfigAsCjs -c"
  },
  "author": "Rahul Patil",
  "license": "ISC",
  "peerDependencies": {
    "react": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/plugin-transform-runtime": "^7.19.6",
    "@babel/preset-react": "^7.18.6",
    "@rollup/plugin-babel": "^6.0.3",
    "@rollup/plugin-commonjs": "^24.0.0",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "@rollup/plugin-terser": "^0.2.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "rollup": "^3.9.0",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "rollup-plugin-sourcemaps": "^0.6.3"
  },
  "dependencies": {
    "@babel/runtime": "^7.20.7"
  }
}

This is the repo for component library: pkg-practice - Github

I tried searching on stackoverflow and google. Found some results that said I should include react in the component file. I tried doing that but the error still persists.


问:
Calculate balanced mean in R
I have a dataset that has the roughly following structure:

mental health
age
education (as factor)
month

10
18
1
January

8
12
2
March

9
23
2
August

...

I have a total of 10k entries and I am trying to calculate a balanced monthly average of the mental health variable. In other words: I would like to use weights so that each month has a similar covariate balance (similar education, age, etc.)

How can I do that? I know how to use CBPS matching or nearest neighbour matching but only in the context of regression.

Does someone know how this could be done?

Title: Calculate balanced mean in R


问:
Using transform in div doesn't stack properly with its pseudo element in CSS
I am facing an issue with the stacking order of div element with its pseudo-elements ::before and ::after.

In the below code, I have commented this line of code which says, transform: translate(10px, 10px); so it works as expected but if after uncommenting this then div goes behind its pseudo-elements. I am currently learning about z-index and stuck at this problem and I don't know why this problem is occurring.

Any help would be appreciated.

* {
  margin: 0;
}
body {
  background-color: #000d;
}
div {
  width: 100px;
  height: 100px;
  background: black;
  border: 3px solid #fff;
  border-radius: 100%;
  position: relative;
  /* transform: translate(10px, 10px); */
}
div::before,
div::after {
  content: "";
  width: inherit;
  height: inherit;
  border: inherit;
  border-radius: inherit;
  position: absolute;
  display: block;
}
div::before {
  background: red;
  left: 20px;
  top: 20px;
  z-index: -1;
}
div::after {
  background: blue;
  left: 40px;
  top: 40px;
  z-index: -2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

I have tried above code to stack the div to top using z-index with transform.

Body:
I am facing an issue with the stacking order of div element with its pseudo-elements ::before and ::after.

In the below code, I have commented this line of code which says, transform: translate(10px, 10px); so it works as expected but if after uncommenting this then div goes behind its pseudo-elements. I am currently learning about z-index and stuck at this problem and I don't know why this problem is occurring.

Any help would be appreciated.

* {
  margin: 0;
}
body {
  background-color: #000d;
}
div {
  width: 100px;
  height: 100px;
  background: black;
  border: 3px solid #fff;
  border-radius: 100%;
  position: relative;
  /* transform: translate(10px, 10px); */
}
div::before,
div::after {
  content: "";
  width: inherit;
  height: inherit;
  border: inherit;
  border-radius: inherit;
  position: absolute;
  display: block;
}
div::before {
  background: red;
  left: 20px;
  top: 20px;
  z-index: -1;
}
div::after {
  background: blue;
  left: 40px;
  top: 40px;
  z-index: -2;
}

I have tried above code to stack the div to top using z-index with transform.