问:
matplotlib subplots figure layout with colorbars
I wrote some code to display a set of 2D fields in a single figure. Each plot should have its own colorbar. However, the final layout is sub-optimal: the individual subplots are very small and there's lots of space between them. What can I do to improve this? A minimal example below:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib import colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.figure import Figure

import numpy as np

NVAR, NLAT, NLON = 2, 181, 360

x = np.random.randn(NVAR, NLAT, NLON)
y1 = np.random.randn(NVAR, NLAT, NLON)
y2 = np.random.randn(NVAR, NLAT, NLON)

N_PLOTS_PER_SAMPLE = 3

def plot_2d_sample(
    ax,
    input_: np.ndarray,
    truth: np.ndarray,
    pred: np.ndarray,
    idx: int,
) -> None:

    cmap = cm.bwr
    cmap.set_bad(color="gray")

    im = ax[0].imshow(truth, cmap=cmap, origin="lower", norm=colors.TwoSlopeNorm(vcenter=0.0))
    ax[0].set_title(f"Truth idx={idx}")
    __set_colorbar(im, ax[0])
    im = ax[1].imshow(pred, cmap=cmap, origin="lower", norm=colors.TwoSlopeNorm(vcenter=0.0))
    ax[1].set_title(f"Prediction idx={idx}")
    __set_colorbar(im, ax[1])
    im = ax[2].imshow(truth - pred, cmap=cmap, origin="lower", norm=colors.TwoSlopeNorm(vcenter=0.0))
    ax[2].set_title("Truth - prediction")
    __set_colorbar(im, ax[2])

def plot_predicted_multilevel_sample(
    x: np.ndarray,
    y_true: np.ndarray,
    y_pred: np.ndarray,
) -> Figure:
    """Plots data for one multilevel sample.
    Args:
        x, y_true, y_pred: arrays of shape (nvar*level, lat, lon)
    Returns:
        The figure object handle.
    """
    n_plots_x, n_plots_y = y_true.shape[0], N_PLOTS_PER_SAMPLE

    figsize = (n_plots_x * 4, n_plots_y * 4)
    fig, ax = plt.subplots(n_plots_x, n_plots_y, figsize=figsize)

    for idx in range(n_plots_x):
        xt = x[idx, ...].squeeze()
        yt = y_true[idx, ...].squeeze()
        yp = y_pred[idx, ...].squeeze()
        if n_plots_x > 1:
            plot_2d_sample(ax[idx, :], xt, yt, yp, idx)
        else:
            plot_2d_sample(ax, xt, yt, yp, idx)
    return fig

def __set_colorbar(im, ax) -> None:
    """Sets up a custom colorbar for an image and axis."""
    # hide x/y-axis ticks
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)
    ax.tick_params(axis="both", which="both", length=0)
    # create colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)

fig = plot_predicted_multilevel_sample(x, y1, y2)
fig.tight_layout()
fig.show()
```

This is the result (it gets worse if I add more subplots):

Body:
I wrote some code to display a set of 2D fields in a single figure. Each plot should have its own colorbar. However, the final layout is sub-optimal: the individual subplots are very small and there's lots of space between them. What can I do to improve this? A minimal example below:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib import colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.figure import Figure

import numpy as np

NVAR, NLAT, NLON = 2, 181, 360

x = np.random.randn(NVAR, NLAT, NLON)
y1 = np.random.randn(NVAR, NLAT, NLON)
y2 = np.random.randn(NVAR, NLAT, NLON)

N_PLOTS_PER_SAMPLE = 3

def plot_2d_sample(
    ax,
    input_: np.ndarray,
    truth: np.ndarray,
    pred: np.ndarray,
    idx: int,
) -> None:

    cmap = cm.bwr
    cmap.set_bad(color="gray")

    im = ax[0].imshow(truth, cmap=cmap, origin="lower", norm=colors.TwoSlopeNorm(vcenter=0.0))
    ax[0].set_title(f"Truth idx={idx}")
    __set_colorbar(im, ax[0])
    im = ax[1].imshow(pred, cmap=cmap, origin="lower", norm=colors.TwoSlopeNorm(vcenter=0.0))
    ax[1].set_title(f"Prediction idx={idx}")
    __set_colorbar(im, ax[1])
    im = ax[2].imshow(truth - pred, cmap=cmap, origin="lower", norm=colors.TwoSlopeNorm(vcenter=0.0))
    ax[2].set_title("Truth - prediction")
    __set_colorbar(im, ax[2])

def plot_predicted_multilevel_sample(
    x: np.ndarray,
    y_true: np.ndarray,
    y_pred: np.ndarray,
) -> Figure:
    """Plots data for one multilevel sample.
    Args:
        x, y_true, y_pred: arrays of shape (nvar*level, lat, lon)
    Returns:
        The figure object handle.
    """
    n_plots_x, n_plots_y = y_true.shape[0], N_PLOTS_PER_SAMPLE

    figsize = (n_plots_x * 4, n_plots_y * 4)
    fig, ax = plt.subplots(n_plots_x, n_plots_y, figsize=figsize)

    for idx in range(n_plots_x):
        xt = x[idx, ...].squeeze()
        yt = y_true[idx, ...].squeeze()
        yp = y_pred[idx, ...].squeeze()
        if n_plots_x > 1:
            plot_2d_sample(ax[idx, :], xt, yt, yp, idx)
        else:
            plot_2d_sample(ax, xt, yt, yp, idx)
    return fig

def __set_colorbar(im, ax) -> None:
    """Sets up a custom colorbar for an image and axis."""
    # hide x/y-axis ticks
    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)
    ax.tick_params(axis="both", which="both", length=0)
    # create colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)

fig = plot_predicted_multilevel_sample(x, y1, y2)
fig.tight_layout()
fig.show()

This is the result (it gets worse if I add more subplots):


来源: stackexchange

问:
Can I turn a raw memory dump (ReadProcessMemory) into a MiniDump file?
I have the following powershell code to dump the process memory from a given process. In this case, cmd.exe.

It opens the given process with PROCESS_ALL_ACCESS and uses VirtualQueryEx to list all the memory regions. For each memory region it finds, it calls ReadProcessMemory and writes the bytes read to a file.

$typeDefinition = @"
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

public static partial class MemApi
{
    [StructLayout(LayoutKind.Sequential)]
    public struct MEMORY_BASIC_INFORMATION64
    {
        public ulong BaseAddress;
        public ulong AllocationBase;
        public int AllocationProtect;
        public int __alignment1;
        public ulong RegionSize;
        public int State;
        public int Protect;
        public int Type;
        public int __alignment2;
    }

    [Flags]
    public enum ProcessAccessFlags : uint
    {
        VM_READ = 0x00000010,
        PROCESS_ALL_ACCESS = 0x001F0FFF
    }
    [DllImport("kernel32.dll")]
    public static extern uint GetLastError();

    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr OpenProcess(
        ProcessAccessFlags dwAccess,
        [MarshalAs(UnmanagedType.Bool)]
        bool bInheritHandle,
        int dwProcId
    );

    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public static extern int VirtualQueryEx(
        IntPtr hProc,
        IntPtr lpAddr,
        out MEMORY_BASIC_INFORMATION64 lpBuf,
        int dwLen
    );

    public static List<MEMORY_BASIC_INFORMATION64> ListMemoryRegions(
        IntPtr hProc
    )
    {
        long maxAddr = 0x00007FFFFFFFFFFF;
        long addr = 0;
        List<MEMORY_BASIC_INFORMATION64> regions = new List<MEMORY_BASIC_INFORMATION64>();

        do
        {
            MEMORY_BASIC_INFORMATION64 m;

            int result = VirtualQueryEx(hProc, (IntPtr)addr, out m, (int)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION64)));

            if (addr == (long)m.BaseAddress + (long)m.RegionSize)
                break;

            addr = (long)m.BaseAddress + (long)m.RegionSize;

            regions.Add(m);
        } while (addr <= maxAddr);

        return regions;
    }

    [DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    public static extern Boolean ReadProcessMemory(
        IntPtr hProc,
        IntPtr lpBaseAddr,
        byte[] lpBuf,
        UInt32 nSize,
        ref UInt32 lpNBytes
    );
}
"@

Add-Type -TypeDefinition $typeDefinition -Language CSharp

$cmd = Get-Process -Name cmd

$handle = [MemApi]::OpenProcess(0x1F0FFF, $false, $cmd.Id)
$regions = [MemApi]::ListMemoryRegions($handle)
$fileStream = [System.IO.File]::OpenWrite("$env:TEMP\cmd.DMP")

Write-Host "$($regions.Count) memory segments have been found"

for ($i = 0; $i -lt $regions.Count; $i++)
{
    Write-Host "Exporting memory region $("{0:d4}/{1:d4}" -f $i, ($regions.Count + 1)) ($("0x{0:X16} - 0x{1:X16}" -f $regions[$i].BaseAddress, ($regions[$i].BaseAddress + $regions[$i].RegionSize)))..."

    try
    {
        $read = 0
        $buff = New-Object byte[] $regions[$i].RegionSize

        if ([MemApi]::ReadProcessMemory($handle, [System.IntPtr]::new($regions[$i].BaseAddress), $buff, $buff.Length, [ref]$read) -eq $true)
        {
            $fileStream.Write($buff, 0, $buff.Length)
        }
    } catch { } finally { }
}

$fileStream.Close()
```

I would like to avoid using dbghelp.dll to do this, but is there a way I can create a MiniDump file out of this raw memory? Would I need to change the code at all or is there an external tool that can convert this?

I've tried to take a look into the MiniDumpWriteDump function to see if I can replicate it at all but I've had no luck.

I've also tried volatility's raw2dmp function, but this has not worked unfortunately.

Apologies if this is completely on the wrong tracks!

Any help would be much appreciated - Merry Christmas!

ContentLicense: CC BY-SA 4.0

Body:
I have the following powershell code to dump the process memory from a given process. In this case, cmd.exe.

It opens the given process with PROCESS_ALL_ACCESS and uses VirtualQueryEx to list all the memory regions. For each memory region it finds, it calls ReadProcessMemory and writes the bytes read to a file.

$typeDefinition = @"
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

public static partial class MemApi
{
    [StructLayout(LayoutKind.Sequential)]
    public struct MEMORY_BASIC_INFORMATION64
    {
        public ulong BaseAddress;
        public ulong AllocationBase;
        public int AllocationProtect;
        public int __alignment1;
        public ulong RegionSize;
        public int State;
        public int Protect;
        public int Type;
        public int __alignment2;
    }

    [Flags]
    public enum ProcessAccessFlags : uint
    {
        VM_READ = 0x00000010,
        PROCESS_ALL_ACCESS = 0x001F0FFF
    }
    [DllImport("kernel32.dll")]
    public static extern uint GetLastError();

    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr OpenProcess(
        ProcessAccessFlags dwAccess,
        [MarshalAs(UnmanagedType.Bool)]
        bool bInheritHandle,
        int dwProcId
    );

    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public static extern int VirtualQueryEx(
        IntPtr hProc,
        IntPtr lpAddr,
        out MEMORY_BASIC_INFORMATION64 lpBuf,
        int dwLen
    );

    public static List<MEMORY_BASIC_INFORMATION64> ListMemoryRegions(
        IntPtr hProc
    )
    {
        long maxAddr = 0x00007FFFFFFFFFFF;
        long addr = 0;
        List<MEMORY_BASIC_INFORMATION64> regions = new List<MEMORY_BASIC_INFORMATION64>();

        do
        {
            MEMORY_BASIC_INFORMATION64 m;

            int result = VirtualQueryEx(hProc, (IntPtr)addr, out m, (int)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION64)));

            if (addr == (long)m.BaseAddress + (long)m.RegionSize)
                break;

            addr = (long)m.BaseAddress + (long)m.RegionSize;

            regions.Add(m);
        } while (addr <= maxAddr);

        return regions;
    }

    [DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    public static extern Boolean ReadProcessMemory(
        IntPtr hProc,
        IntPtr lpBaseAddr,
        byte[] lpBuf,
        UInt32 nSize,
        ref UInt32 lpNBytes
    );
}
"@

Add-Type -TypeDefinition $typeDefinition -Language CSharp

$cmd = Get-Process -Name cmd

$handle = [MemApi]::OpenProcess(0x1F0FFF, $false, $cmd.Id)
$regions = [MemApi]::ListMemoryRegions($handle)
$fileStream = [System.IO.File]::OpenWrite("$env:TEMP\cmd.DMP")

Write-Host "$($regions.Count) memory segments have been found"

for ($i = 0; $i -lt $regions.Count; $i++)
{
    Write-Host "Exporting memory region $("{0:d4}/{1:d4}" -f $i, ($regions.Count + 1)) ($("0x{0:X16} - 0x{1:X16}" -f $regions[$i].BaseAddress, ($regions[$i].BaseAddress + $regions[$i].RegionSize)))..."

    try
    {
        $read = 0
        $buff = New-Object byte[] $regions[$i].RegionSize

        if ([MemApi]::ReadProcessMemory($handle, [System.IntPtr]::new($regions[$i].BaseAddress), $buff, $buff.Length, [ref]$read) -eq $true)
        {
            $fileStream.Write($buff, 0, $buff.Length)
        }
    } catch { } finally { }
}

$fileStream.Close()

I would like to avoid using dbghelp.dll to do this, but is there a way I can create a MiniDump file out of this raw memory? Would I need to change the code at all or is there an external tool that can convert this?

I've tried to take a look into the MiniDumpWriteDump function to see if I can replicate it at all but I've had no luck.

I've also tried volatility's raw2dmp function, but this has not worked unfortunately.

Apologies if this is completely on the wrong tracks!

Any help would be much appreciated - Merry Christmas!


问:
How do I open multiple webviews in flutter, each connecting to a different Proxy server?
I am using flutter, and the packages webview_windows and webview_fluttergoal is to open 5 tabs, each with a different proxy, thus a different IP address.
I hope I can get some help with that, as it's my first flutter job and stakes are high >~<

I tried user agents, but I couldn't see what they can do. can I run multiple flutter instances? for windows?


问:
Laravel Jetstream utton not working anymore
I'm currently making a web application using Laravel Jetsream.
For a Kanban board i started working with Vue. After that i found out that my dropdown button of Jetstream are not working anymore... It is the dropdown button to see the profile links(got to profile, logout)

I can't seem to find the problem.

Thanks for the help!

Screenshot of dropdown

Everything was working like it use to be. Then i found out that the user dropdown wasn't working anymore.

code where the dropdown lives:

```<code><nav x-data="{ open: false }" class="bg-white border-b border-gray-100">
<!-- Primary Navigation Menu -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="flex justify-between h-16">
        <div class="flex">
            <!-- Logo -->
            <div class="shrink-0 flex items-center">
                <a href="{{ route('dashboard') }}">
                    <div class="">
                        <img style="width:100px" class="" src="{{ @asset('images/Soltech_Logo03_V4.png') }}" alt="">
                    </div>
                </a>
            </div>

            <!-- Navigation Links -->
            <div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
                <x-jet-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                    {{ __('Dashboard') }}
                </x-jet-nav-link>

                @if(Auth::user()->haspermissionTo('create users'))
                <x-jet-nav-link href="{{ route('show-create-user') }}" :active="request()->routeIs('show-create-user')">
                    {{ __('Create a user') }}
                </x-jet-nav-link>
                @endif

                @if(Auth::user()->haspermissionTo('see users'))
                <x-jet-nav-link href="{{ route('see-users') }}" :active="request()->routeIs('see-users')">
                    {{ __('See all users') }}
                </x-jet-nav-link>
                @endif

                @if(Auth::user()->haspermissionTo('see projects'))
                <x-jet-nav-link href="{{ route('see-projects') }}" :active="request()->routeIs('see-projects')">
                    {{ __('See all projects') }}
                </x-jet-nav-link>
                @endif

            </div>
        </div>

        <div class="hidden sm:flex sm:items-center sm:ml-6">
            <!-- Teams Dropdown -->
            @if (Laravel\Jetstream\Jetstream::hasTeamFeatures())
                <div class="ml-3 relative">
                    <x-jet-dropdown align="right" width="60">
                        <x-slot name="trigger">
                            <span class="inline-flex rounded-md">
                                <button type="button" class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 bg-white hover:bg-gray-50 hover:text-gray-700 focus:outline-none focus:bg-gray-50 active:bg-gray-50 transition">
                                    {{ Auth::user()->currentTeam->name }}

                                    <svg class="ml-2 -mr-0.5 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M10 3a1 1 0 01.707.293l3 3a1 1 0 01-1.414 1.414L10 5.414 7.707 7.707a1 1 0 01-1.414-1.414l3-3A1 1 0 0110 3zm-3.707 9.293a1 1 0 011.414 0L10 14.586l2.293-2.293a1 1 0 011.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd" />
                                    </svg>
                                </button>
                            </span>
                        </x-slot>

                        <x-slot name="content">
                            <div class="w-60">
                                <!-- Team Management -->
                                <div class="block px-4 py-2 text-xs text-gray-400">
                                    {{ __('Manage Team') }}
                                </div>

                                <!-- Team Settings -->
                                <x-jet-dropdown-link href="{{ route('teams.show', Auth::user()->currentTeam->id) }}">
                                    {{ __('Team Settings') }}
                                </x-jet-dropdown-link>

                                @can('create', Laravel\Jetstream\Jetstream::newTeamModel())
                                    <x-jet-dropdown-link href="{{ route('teams.create') }}">
                                        {{ __('Create New Team') }}
                                    </x-jet-dropdown-link>
                                @endcan

                                <div class="border-t border-gray-100"></div>

                                <!-- Team Switcher -->
                                <div class="block px-4 py-2 text-xs text-gray-400">
                                    {{ __('Switch Teams') }}
                                </div>

                                @foreach (Auth::user()->allTeams() as $team)
                                    <x-jet-switchable-team :team="$team" />
                                @endforeach
                            </div>
                        </x-slot>
                    </x-jet-dropdown>
                </div>
            @endif

            <!-- Settings Dropdown -->
            <div class="ml-3 relative">
                <x-jet-dropdown align="right" width="48">
                    <x-slot name="trigger">
                        @if (Laravel\Jetstream\Jetstream::managesProfilePhotos())
                            <button class="flex text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-gray-300 transition">
                                <img class="h-8 w-8 rounded-full object-cover" src="{{ Auth::user()->profile_photo_url }}" alt="{{ Auth::user()->name }}" />
                            </button>
                        @else
                            <span class="inline-flex rounded-md">
                                <button type="button" class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 bg-white hover:text-gray-700 focus:outline-none transition">
                                    {{ Auth::user()->name }}

                                    <svg class="ml-2 -mr-0.5 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                    </svg>
                                </button>
                            </span>
                        @endif
                    </x-slot>

                    <x-slot name="content">
                        <!-- Account Management -->
                        <div class="block px-4 py-2 text-xs text-gray-400">
                            {{ __('Manage Account') }}
                        </div>

                        <x-jet-dropdown-link href="{{ route('profile.show') }}">
                            {{ __('Profile') }}
                        </x-jet-dropdown-link>

                        @if (Laravel\Jetstream\Jetstream::hasApiFeatures())
                            <x-jet-dropdown-link href="{{ route('api-tokens.index') }}">
                                {{ __('API Tokens') }}
                            </x-jet-dropdown-link>
                        @endif

                        <div class="border-t border-gray-100"></div>

                        <!-- Authentication -->
                        <form method="POST" action="{{ route('logout') }}" x-data>
                            @csrf

                            <x-jet-dropdown-link href="{{ route('logout') }}"
                                     @click.prevent="$root.submit();">
                                {{ __('Log Out') }}
                            </x-jet-dropdown-link>
                        </form>
                    </x-slot>
                </x-jet-dropdown>
            </div>
        </div>

        <!-- Hamburger -->
        <div class="-mr-2 flex items-center sm:hidden">
            <button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition">
                <svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
                    <path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                    <path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>
    </div>
</div>

<!-- Responsive Navigation Menu -->
<div :class="{'block': open, 'hidden': ! open}" class="hidden sm:hidden">
    <div class="pt-2 pb-3 space-y-1">
        <x-jet-responsive-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
            {{ __('Dashboard') }}
        </x-jet-responsive-nav-link>
    </div>

    @if(Auth::user()->haspermissionTo('create users'))
    <div class="pt-2 pb-3 space-y-1">
        <x-jet-responsive-nav-link href="{{ route('show-create-user') }}" :active="request()->routeIs('show-create-user')">
            {{ __('Create a user') }}
        </x-jet-responsive-nav-link>
    </div>
    @endif

    @if(Auth::user()->haspermissionTo('see users'))
    <div class="pt-2 pb-3 space-y-1">
        <x-jet-responsive-nav-link href="{{ route('see-users') }}" :active="request()->routeIs('see-users')">
            {{ __('See all users') }}
        </x-jet-responsive-nav-link>
    </div>
    @endif

    @if(Auth::user()->haspermissionTo('see projects'))
    <div class="pt-2 pb-3 space-y-1">
        <x-jet-nav-link href="{{ route('see-projects') }}" :active="request()->routeIs('see-projects')">
            {{ __('See all projects') }}
        </x-jet-nav-link>
    </div>
    @endif

    <!-- Responsive Settings Options -->
    <div class="pt-4 pb-1 border-t border-gray-200">
        <div class="flex items-center px-4">
            @if (Laravel\Jetstream\Jetstream::managesProfilePhotos())
                <div class="shrink-0 mr-3">
                    <img class="h-10 w-10 rounded-full object-cover" src="{{ Auth::user()->profile_photo_url }}" alt="{{ Auth::user()->name }}" />
                </div>
            @endif

            <div>
                <div class="font-medium text-base text-gray-800">{{ Auth::user()->name }}</div>
                <div class="font-medium text-sm text-gray-500">{{ Auth::user()->email }}</div>
            </div>
        </div>

        <div class="mt-3 space-y-1">
            <!-- Account Management -->
            <x-jet-responsive-nav-link href="{{ route('profile.show') }}" :active="request()->routeIs('profile.show')">
                {{ __('Profile') }}
            </x-jet-responsive-nav-link>

            @if (Laravel\Jetstream\Jetstream::hasApiFeatures())
                <x-jet-responsive-nav-link href="{{ route('api-tokens.index') }}" :active="request()->routeIs('api-tokens.index')">
                    {{ __('API Tokens') }}
                </x-jet-responsive-nav-link>
            @endif

            <!-- Authentication -->
            <form method="POST" action="{{ route('logout') }}" x-data>
                @csrf

                <x-jet-responsive-nav-link href="{{ route('logout') }}"
                               @click.prevent="$root.submit();">
                    {{ __('Log Out') }}
                </x-jet-responsive-nav-link>
            </form>

            <!-- Team Management -->
            @if (Laravel\Jetstream\Jetstream::hasTeamFeatures())
                <div class="border-t border-gray-200"></div>

                <div class="block px-4 py-2 text-xs text-gray-400">
                    {{ __('Manage Team') }}
                </div>

                <!-- Team Settings -->
                <x-jet-responsive-nav-link href="{{ route('teams.show', Auth::user()->currentTeam->id) }}" :active="request()->routeIs('teams.show')">
                    {{ __('Team Settings') }}
                </x-jet-responsive-nav-link>

                @can('create', Laravel\Jetstream\Jetstream::newTeamModel())
                    <x-jet-responsive-nav-link href="{{ route('teams.create') }}" :active="request()->routeIs('teams.create')">
                        {{ __('Create New Team') }}
                    </x-jet-responsive-nav-link>
                @endcan

                <div class="border-t border-gray-200"></div>

                <!-- Team Switcher -->
                <div class="block px-4 py-2 text-xs text-gray-400">
                    {{ __('Switch Teams') }}
                </div>

                @foreach (Auth::user()->allTeams() as $team)
                    <x-jet-switchable-team :team="$team" component="jet-responsive-nav-link" />
                @endforeach
            @endif
        </div>
    </div>
</div>
</code>```

Body:
I'm currently making a web application using Laravel Jetsream.
For a Kanban board i started working with Vue. After that i found out that my dropdown button of Jetstream are not working anymore... It is the dropdown button to see the profile links(got to profile, logout)

I can't seem to find the problem.

Thanks for the help!

Screenshot of dropdown

Everything was working like it use to be. Then i found out that the user dropdown wasn't working anymore.

code where the dropdown lives:

                <x-jet-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                    {{ __('Dashboard') }}
                </x-jet-nav-link>

                @if(Auth::user()->haspermissionTo('create users'))
                <x-jet-nav-link href="{{ route('show-create-user') }}" :active="request()->routeIs('show-create-user')">
                    {{ __('Create a user') }}
                </x-jet-nav-link>
                @endif

                @if(Auth::user()->haspermissionTo('see users'))
                <x-jet-nav-link href="{{ route('see-users') }}" :active="request()->routeIs('see-users')">
                    {{ __('See all users') }}
                </x-jet-nav-link>
                @endif

                @if(Auth::user()->haspermissionTo('see projects'))
                <x-jet-nav-link href="{{ route('see-projects') }}" :active="request()->routeIs('see-projects')">
                    {{ __('See all projects') }}
                </x-jet-nav-link>
                @endif

            @if (Laravel\Jetstream\Jetstream::hasTeamFeatures())

                    <x-jet-dropdown align="right" width="60">
                        <x-slot name="trigger">

                                <button type="button" class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 bg-white hover:bg-gray-50 hover:text-gray-700 focus:outline-none focus:bg-gray-50 active:bg-gray-50 transition">
                                    {{ Auth::user()->currentTeam->name }}

                                    <svg class="ml-2 -mr-0.5 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M10 3a1 1 0 01.707.293l3 3a1 1 0 01-1.414 1.414L10 5.414 7.707 7.707a1 1 0 01-1.414-1.414l3-3A1 1 0 0110 3zm-3.707 9.293a1 1 0 011.414 0L10 14.586l2.293-2.293a1 1 0 011.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd" />
                                    </svg>
                                </button>

                        </x-slot>

                        <x-slot name="content">

                                    {{ __('Manage Team') }}

                                <x-jet-dropdown-link href="{{ route('teams.show', Auth::user()->currentTeam->id) }}">
                                    {{ __('Team Settings') }}
                                </x-jet-dropdown-link>

                                @can('create', Laravel\Jetstream\Jetstream::newTeamModel())
                                    <x-jet-dropdown-link href="{{ route('teams.create') }}">
                                        {{ __('Create New Team') }}
                                    </x-jet-dropdown-link>
                                @endcan

                                    {{ __('Switch Teams') }}

                                @foreach (Auth::user()->allTeams() as $team)
                                    <x-jet-switchable-team :team="$team" />
                                @endforeach

                        </x-slot>
                    </x-jet-dropdown>

            @endif

                <x-jet-dropdown align="right" width="48">
                    <x-slot name="trigger">
                        @if (Laravel\Jetstream\Jetstream::managesProfilePhotos())
                            <button class="flex text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-gray-300 transition">
                                profile_photo_url }}" alt="{{ Auth::user()->name }}" />
                            </button>
                        @else

                                <button type="button" class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 bg-white hover:text-gray-700 focus:outline-none transition">
                                    {{ Auth::user()->name }}

                                    <svg class="ml-2 -mr-0.5 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                    </svg>
                                </button>

                        @endif
                    </x-slot>

                    <x-slot name="content">

                            {{ __('Manage Account') }}

                        <x-jet-dropdown-link href="{{ route('profile.show') }}">
                            {{ __('Profile') }}
                        </x-jet-dropdown-link>

                        @if (Laravel\Jetstream\Jetstream::hasApiFeatures())
                            <x-jet-dropdown-link href="{{ route('api-tokens.index') }}">
                                {{ __('API Tokens') }}
                            </x-jet-dropdown-link>
                        @endif

                        <form method="POST" action="{{ route('logout') }}" x-data>
                            @csrf

                            <x-jet-dropdown-link href="{{ route('logout') }}"
                                     @click.prevent="$root.submit();">
                                {{ __('Log Out') }}
                            </x-jet-dropdown-link>
                        </form>
                    </x-slot>
                </x-jet-dropdown>

            <button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition">
                <svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
                    <path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                    <path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>

        <x-jet-responsive-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
            {{ __('Dashboard') }}
        </x-jet-responsive-nav-link>

    @if(Auth::user()->haspermissionTo('create users'))

        <x-jet-responsive-nav-link href="{{ route('show-create-user') }}" :active="request()->routeIs('show-create-user')">
            {{ __('Create a user') }}
        </x-jet-responsive-nav-link>

    @endif

    @if(Auth::user()->haspermissionTo('see users'))

        <x-jet-responsive-nav-link href="{{ route('see-users') }}" :active="request()->routeIs('see-users')">
            {{ __('See all users') }}
        </x-jet-responsive-nav-link>

    @endif

    @if(Auth::user()->haspermissionTo('see projects'))

        <x-jet-nav-link href="{{ route('see-projects') }}" :active="request()->routeIs('see-projects')">
            {{ __('See all projects') }}
        </x-jet-nav-link>

    @endif

            @if (Laravel\Jetstream\Jetstream::managesProfilePhotos())

                    profile_photo_url }}" alt="{{ Auth::user()->name }}" />

            @endif

{{ Auth::user()->name }}

{{ Auth::user()->email }}

            <x-jet-responsive-nav-link href="{{ route('profile.show') }}" :active="request()->routeIs('profile.show')">
                {{ __('Profile') }}
            </x-jet-responsive-nav-link>

            @if (Laravel\Jetstream\Jetstream::hasApiFeatures())
                <x-jet-responsive-nav-link href="{{ route('api-tokens.index') }}" :active="request()->routeIs('api-tokens.index')">
                    {{ __('API Tokens') }}
                </x-jet-responsive-nav-link>
            @endif

            <form method="POST" action="{{ route('logout') }}" x-data>
                @csrf

                <x-jet-responsive-nav-link href="{{ route('logout') }}"
                               @click.prevent="$root.submit();">
                    {{ __('Log Out') }}
                </x-jet-responsive-nav-link>
            </form>

            @if (Laravel\Jetstream\Jetstream::hasTeamFeatures())

                    {{ __('Manage Team') }}

                <x-jet-responsive-nav-link href="{{ route('teams.show', Auth::user()->currentTeam->id) }}" :active="request()->routeIs('teams.show')">
                    {{ __('Team Settings') }}
                </x-jet-responsive-nav-link>

                @can('create', Laravel\Jetstream\Jetstream::newTeamModel())
                    <x-jet-responsive-nav-link href="{{ route('teams.create') }}" :active="request()->routeIs('teams.create')">
                        {{ __('Create New Team') }}
                    </x-jet-responsive-nav-link>
                @endcan

                    {{ __('Switch Teams') }}

                @foreach (Auth::user()->allTeams() as $team)
                    <x-jet-switchable-team :team="$team" component="jet-responsive-nav-link" />
                @endforeach
            @endif


问:
Recycler View Duplicating Data after Refreshing the page
when i swipe to refresh the data, the first swipe is ok but after that every swipe reload and add the same data over and over again, by the end i have a list with same items over and over I tried to clear before but i don't understand what's wrong with my code, if someone could explain it to me

adapter

```<code>package com.intersoft.packhouse.adapters

import android.app.Activity
import android.text.method.TextKeyListener.clear
import android.text.method.TextKeyListener.clearMetaKeyState
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.intersoft.packhouse.R
import com.intersoft.packhouse.enums.BasicClass
import com.intersoft.packhouse.enums.BasicContext
import com.intersoft.packhouse.fragments.BaseFragment
import com.intersoft.packhouse.printing.PrintListener
import com.intersoft.packhouse.viewholders.*

class BasicAdapter(val context: Activity, val printListener: PrintListener, val frag:BaseFragment,myBasicContext:BasicContext?=null):RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    val inflater = LayoutInflater.from(context)
    var baseClass:BasicClass? = null
    var items = mutableListOf<Any>()
    var original = mutableListOf<Any>()
    var myContext = context
    var myBasicContext = myBasicContext

    override fun getItemViewType(position: Int): Int {
        val item = items[position]
        return BasicClass.fromClaz(item)
            .uniqueId()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when(viewType){
            BasicClass.Crop.uniqueId() -> CropViewHolder(inflater.inflate(R.layout.row_crop, parent, false))
            BasicClass.CropX.uniqueId() -> CropViewHolder(inflater.inflate(R.layout.row_crop, parent, false))
            BasicClass.ColdRoom.uniqueId() -> CRoomViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.ColdCell.uniqueId() -> CellViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.QC.uniqueId() -> QCViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.RmStandards.uniqueId() -> RmStandardViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Supplier.uniqueId() -> SupplierViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Customer.uniqueId() -> CustomerViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.OrderModel.uniqueId() -> OrderViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Receiving.uniqueId() -> ReceivingViewHolder(inflater.inflate(R.layout.row_receiving, parent, false))
            BasicClass.Intake.uniqueId() -> IntakeViewHolder(inflater.inflate(R.layout.row_basic, parent, false), printListener,myBasicContext)
            BasicClass.RmStorage.uniqueId() -> RmStorageViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Requisition.uniqueId() -> RequisitionViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Issuing.uniqueId() -> IssueingViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Vehicle.uniqueId() -> VehicleViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Processing.uniqueId() -> ProcessingViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Packaging.uniqueId() -> PackagingViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Conformance.uniqueId() -> ConformanceViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Dispatch.uniqueId() -> DispatchViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.DispatchedItem.uniqueId() -> DispatchedItemViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Collection.uniqueId() -> CollectionViewHolder(inflater.inflate(R.layout.row_basic, parent, false), frag)
            BasicClass.FarmPurchase.uniqueId() -> FarmPurchaseViewHolder(inflater.inflate(R.layout.row_basic, parent, false), printListener)
            BasicClass.CollectionDispatch.uniqueId() -> CDItemViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Binning.uniqueId() -> BinningViewHolder(myContext,inflater.inflate(R.layout.row_basic, parent, false), printListener)
            BasicClass.SortingLots.uniqueId() -> SortingLotViewHolder(myContext,inflater.inflate(R.layout.row_sorting, parent, false), printListener)
            BasicClass.SortedBins.uniqueId() -> SortedBinsViewHolder(myContext,inflater.inflate(R.layout.row_sorting, parent, false), printListener)
            BasicClass.NewBins.uniqueId() -> NewBinsViewHolder(myContext,inflater.inflate(R.layout.row_sorting, parent, false), printListener)
            BasicClass.ProcessingLots.uniqueId() -> ProcessingLotsViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.BatchSheet.uniqueId() -> BatchSheetViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Reject.uniqueId() -> RejectViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            else -> CropViewHolder(inflater.inflate(R.layout.row_crop, parent, false))

        }
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as? ListHolder<Any>)?.let {
            it.bind(items[position])
        }
    }
}
</code>```

view holder

```<code>package com.intersoft.packhouse.viewholders

import android.view.View
import com.intersoft.packhouse.R
import com.intersoft.packhouse.models.BatchSheet
import com.intersoft.packhouse.utils.toMiscDate
import com.google.gson.Gson

class BatchSheetViewHolder(view: View):BaseHolder(view) , ListHolder<BatchSheet>{

    override fun bind(item: BatchSheet){
        clear()
        icon(R.drawable.ic_human_resources)
        keyValue("Date", item.date)
        keyValue("Duration", "${item.start_time} - ${item.end_time} (${item.duration} mins)")
        keyValue("Lot No", item?.lot?.lot_no)
        keyValue("GRN", "${item?.intake?.prn} ")
        keyValue("Supplier", item?.supplier?.company)
        keyValue("Order No", item?._order?.order_no)
        keyValue("Item",item?.item?.item_name)
        keyValue("No of Boxes", item.no_of_boxes)
        keyValue("Net Weight", item.net_weight)
      //  keyValue("ordered Item", item?.item_name)
//        keyValue("4KGS", item?.lot?.four_kg_boxes)
//        keyValue("10KGS", item?.lot?.ten_kg_boxes)
   //     keyValue("Remarks", item.remarks)

    }

}
</code>```

data class

```<code>package com.intersoft.packhouse.models

import android.content.ClipData

data class BatchSheet(
    var _id:Int? = null,
    var date: String? = null,
    var duration: Int? = null,
    var end_time: String? = null,
    var prn: String? = null,
    var intake: Intake? = null,
    var net_weight: Int? = null,
    var no_of_boxes: Int? = null,
    var _order: Order? = null,
    var remarks: String? = null,
    var item: CropX? = null,
    var supplier: Supplier? = null,
    var start_time: String? = null,
    var lot:ProcessingLots? = null,
    var item_name: String? = null

):Optionable{

    override fun optionTitle(): String? {
        return prn
    }

    override fun optionValue(): Any? {
        return _id
    }

    override fun searchString(): String? {
        return  "${super.searchString()} ${intake?.item?.item_name} ${intake?.prn} ${supplier?.account_name}"
        //TODO:Supplier name add this when its changed to supplier object
    }

}

</code>```

I want the recycler view not to duplicate the data

Body:
when i swipe to refresh the data, the first swipe is ok but after that every swipe reload and add the same data over and over again, by the end i have a list with same items over and over I tried to clear before but i don't understand what's wrong with my code, if someone could explain it to me

adapter

package com.intersoft.packhouse.adapters

import android.app.Activity
import android.text.method.TextKeyListener.clear
import android.text.method.TextKeyListener.clearMetaKeyState
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.intersoft.packhouse.R
import com.intersoft.packhouse.enums.BasicClass
import com.intersoft.packhouse.enums.BasicContext
import com.intersoft.packhouse.fragments.BaseFragment
import com.intersoft.packhouse.printing.PrintListener
import com.intersoft.packhouse.viewholders.*

class BasicAdapter(val context: Activity, val printListener: PrintListener, val frag:BaseFragment,myBasicContext:BasicContext?=null):RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    val inflater = LayoutInflater.from(context)
    var baseClass:BasicClass? = null
    var items = mutableListOf<Any>()
    var original = mutableListOf<Any>()
    var myContext = context
    var myBasicContext = myBasicContext

    override fun getItemViewType(position: Int): Int {
        val item = items[position]
        return BasicClass.fromClaz(item)
            .uniqueId()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when(viewType){
            BasicClass.Crop.uniqueId() -> CropViewHolder(inflater.inflate(R.layout.row_crop, parent, false))
            BasicClass.CropX.uniqueId() -> CropViewHolder(inflater.inflate(R.layout.row_crop, parent, false))
            BasicClass.ColdRoom.uniqueId() -> CRoomViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.ColdCell.uniqueId() -> CellViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.QC.uniqueId() -> QCViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.RmStandards.uniqueId() -> RmStandardViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Supplier.uniqueId() -> SupplierViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Customer.uniqueId() -> CustomerViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.OrderModel.uniqueId() -> OrderViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Receiving.uniqueId() -> ReceivingViewHolder(inflater.inflate(R.layout.row_receiving, parent, false))
            BasicClass.Intake.uniqueId() -> IntakeViewHolder(inflater.inflate(R.layout.row_basic, parent, false), printListener,myBasicContext)
            BasicClass.RmStorage.uniqueId() -> RmStorageViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Requisition.uniqueId() -> RequisitionViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Issuing.uniqueId() -> IssueingViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Vehicle.uniqueId() -> VehicleViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Processing.uniqueId() -> ProcessingViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Packaging.uniqueId() -> PackagingViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Conformance.uniqueId() -> ConformanceViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Dispatch.uniqueId() -> DispatchViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.DispatchedItem.uniqueId() -> DispatchedItemViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Collection.uniqueId() -> CollectionViewHolder(inflater.inflate(R.layout.row_basic, parent, false), frag)
            BasicClass.FarmPurchase.uniqueId() -> FarmPurchaseViewHolder(inflater.inflate(R.layout.row_basic, parent, false), printListener)
            BasicClass.CollectionDispatch.uniqueId() -> CDItemViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Binning.uniqueId() -> BinningViewHolder(myContext,inflater.inflate(R.layout.row_basic, parent, false), printListener)
            BasicClass.SortingLots.uniqueId() -> SortingLotViewHolder(myContext,inflater.inflate(R.layout.row_sorting, parent, false), printListener)
            BasicClass.SortedBins.uniqueId() -> SortedBinsViewHolder(myContext,inflater.inflate(R.layout.row_sorting, parent, false), printListener)
            BasicClass.NewBins.uniqueId() -> NewBinsViewHolder(myContext,inflater.inflate(R.layout.row_sorting, parent, false), printListener)
            BasicClass.ProcessingLots.uniqueId() -> ProcessingLotsViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.BatchSheet.uniqueId() -> BatchSheetViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            BasicClass.Reject.uniqueId() -> RejectViewHolder(inflater.inflate(R.layout.row_basic, parent, false))
            else -> CropViewHolder(inflater.inflate(R.layout.row_crop, parent, false))

        }
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as? ListHolder<Any>)?.let {
            it.bind(items[position])
        }
    }
}

view holder

package com.intersoft.packhouse.viewholders

import android.view.View
import com.intersoft.packhouse.R
import com.intersoft.packhouse.models.BatchSheet
import com.intersoft.packhouse.utils.toMiscDate
import com.google.gson.Gson

class BatchSheetViewHolder(view: View):BaseHolder(view) , ListHolder<BatchSheet>{

    override fun bind(item: BatchSheet){
        clear()
        icon(R.drawable.ic_human_resources)
        keyValue("Date", item.date)
        keyValue("Duration", "${item.start_time} - ${item.end_time} (${item.duration} mins)")
        keyValue("Lot No", item?.lot?.lot_no)
        keyValue("GRN", "${item?.intake?.prn} ")
        keyValue("Supplier", item?.supplier?.company)
        keyValue("Order No", item?._order?.order_no)
        keyValue("Item",item?.item?.item_name)
        keyValue("No of Boxes", item.no_of_boxes)
        keyValue("Net Weight", item.net_weight)
      //  keyValue("ordered Item", item?.item_name)
//        keyValue("4KGS", item?.lot?.four_kg_boxes)
//        keyValue("10KGS", item?.lot?.ten_kg_boxes)
   //     keyValue("Remarks", item.remarks)

    }

}

data class

package com.intersoft.packhouse.models

import android.content.ClipData

data class BatchSheet(
    var _id:Int? = null,
    var date: String? = null,
    var duration: Int? = null,
    var end_time: String? = null,
    var prn: String? = null,
    var intake: Intake? = null,
    var net_weight: Int? = null,
    var no_of_boxes: Int? = null,
    var _order: Order? = null,
    var remarks: String? = null,
    var item: CropX? = null,
    var supplier: Supplier? = null,
    var start_time: String? = null,
    var lot:ProcessingLots? = null,
    var item_name: String? = null

):Optionable{

    override fun optionTitle(): String? {
        return prn
    }

    override fun optionValue(): Any? {
        return _id
    }

    override fun searchString(): String? {
        return  "${super.searchString()} ${intake?.item?.item_name} ${intake?.prn} ${supplier?.account_name}"
        //TODO:Supplier name add this when its changed to supplier object
    }

}

I want the recycler view not to duplicate the data


问:
Remote Shared Object comes undefined - Red5
Cant find any solution for this. Im trying to store some data on remote shared object and retrieve it. At the moment im working locally. Anyway, i read probably all posts on internet about that and still cant understand where is my problem. I managed to store arguments on rso, but when i tried to receive those values, im only getting undefined.
Here is my code for the version when im only working with client side and on server side just watching when client connects to shared objects or changes the value.

```<code>protected function application1_creationCompleteHandler(event:FlexEvent):void {
                var room_id:Number = vars("room");
                connection = new NetConnection();
                connection.connect("rtmp://127.0.0.1/video/" + room_id);
                connection.addEventListener(NetStatusEvent.NET_STATUS, onConnected);
                connection.client = this;
            }

private function onConnected(event:NetStatusEvent) : void {
                if(event.info.code == "NetConnection.Connect.Success") {

                    so = SharedObject.getRemote("video", connection.uri, true);
                    so.addEventListener(SyncEvent.SYNC, onSync);
                    so.connect(connection);
                // if i try to trace so in there it will be undefined

                } else {
                    Alert.show("Unsuccessful Connection", "Information");
                }
</code>```

And finally:

```<code>private function onSync(event:SyncEvent):void {

                for(var i:Object in event.changeList) {
                    var changeObj:Object = event.changeList[i];

                    switch(changeObj.code) {
                        case "success":
                            if(so.data.cameras) {
                                Alert.show(this.so.data.cameras.toString(), "I changed it");
                            } else {
                                Alert.show("I changed", "Information");
                            }
                            break;
                        case "change":
                            if(so.data.cameras)
                                Alert.show(so.data.cameras.toString(), "First");
                            else if (this.so.data.cameras) {
                                Alert.show(this.so.data.cameras.toString(), "Second");
                            } else {
                                Alert.show("Can't found changed value", "Error");
                            }
                            break;
                    }
                }
            }
</code>```

And here we go, i always get the undefined value of cameras, unless im the client who is changing the value, but everybody else gets undefined value. So i cant understand, all listeners a noticed about changes, on the server side code i see that i have changes, and i even opened persistent red5 shared object file and i see there is value, but i just cant retrieve it. Anybody has a solution? I would be very grateful.

Updated:
Answer is here: rso between flex and red5. I can create but cant read

ContentLicense: CC BY-SA 3.0

Body:
Cant find any solution for this. Im trying to store some data on remote shared object and retrieve it. At the moment im working locally. Anyway, i read probably all posts on internet about that and still cant understand where is my problem. I managed to store arguments on rso, but when i tried to receive those values, im only getting undefined.
Here is my code for the version when im only working with client side and on server side just watching when client connects to shared objects or changes the value.

protected function application1_creationCompleteHandler(event:FlexEvent):void {
                var room_id:Number = vars("room");
                connection = new NetConnection();
                connection.connect("rtmp://127.0.0.1/video/" + room_id);
                connection.addEventListener(NetStatusEvent.NET_STATUS, onConnected);
                connection.client = this;
            }

private function onConnected(event:NetStatusEvent) : void {
                if(event.info.code == "NetConnection.Connect.Success") {

                    so = SharedObject.getRemote("video", connection.uri, true);
                    so.addEventListener(SyncEvent.SYNC, onSync);
                    so.connect(connection);
                // if i try to trace so in there it will be undefined

                } else {
                    Alert.show("Unsuccessful Connection", "Information");
                }

And finally:

private function onSync(event:SyncEvent):void {

                for(var i:Object in event.changeList) {
                    var changeObj:Object = event.changeList[i];

                    switch(changeObj.code) {
                        case "success":
                            if(so.data.cameras) {
                                Alert.show(this.so.data.cameras.toString(), "I changed it");
                            } else {
                                Alert.show("I changed", "Information");
                            }
                            break;
                        case "change":
                            if(so.data.cameras)
                                Alert.show(so.data.cameras.toString(), "First");
                            else if (this.so.data.cameras) {
                                Alert.show(this.so.data.cameras.toString(), "Second");
                            } else {
                                Alert.show("Can't found changed value", "Error");
                            }
                            break;
                    }
                }
            }

And here we go, i always get the undefined value of cameras, unless im the client who is changing the value, but everybody else gets undefined value. So i cant understand, all listeners a noticed about changes, on the server side code i see that i have changes, and i even opened persistent red5 shared object file and i see there is value, but i just cant retrieve it. Anybody has a solution? I would be very grateful.

Updated:
Answer is here: rso between flex and red5. I can create but cant read


问:
Stop auto sync of Date and Time on windows machine
I have a requirement where I want to run a test case in PDT time. So I tried to change date and time of my windows machine(a VM) but it gets automatically reverted back to current date and time . I want a help regarding that.

I have time server sync. checkbox off as well as windows time service and hypervisor time service is also off on the VM.

Please post your thoughts


问:
Kafka HTTP Sink Connector giving 415 error
I am new to Kafka connect. In one of our application we decided to use HTTP Sink Connector where data will be consumed from a particular topic and will be sent to an API created in .net.

Data produced in Kafka topic is as per avro schema.

Below is the HTTP sink connector configuration.

```<code>{
"name": "HTTPSinkConnector_1",
"config": {
    "topics": "test_data_topic_1",
    "tasks.max": "1",
    "connector.class": "io.confluent.connect.http.HttpSinkConnector",
    "http.api.url": "http://localhost/messageHandler",
    "request.method": "post",
    "key.converter":"org.apache.kafka.connect.storage.StringConverter",
    "value.converter": "io.confluent.connect.avro.AvroConverter",
    "value.converter.schema.registry.url": "http://schema-registry:8081",
    "confluent.topic.bootstrap.servers": "kafka:19092",
    "confluent.topic.replication.factor": "1",
    "reporter.bootstrap.servers": "kafka:19092",
    "reporter.result.topic.name": "success-responses",
    "reporter.result.topic.replication.factor": "1",
    "reporter.error.topic.name": "error-responses",
    "reporter.error.topic.replication.factor": "1"
}
</code>```

}

Avro Schema:

```<code>{
"fields": [
    {
        "name": "id",
        "type": "string"
    },
    {
        "name": "name",
        "type": "string"
    }
],
"name": "article",
"namespace": "test.data",
"type": "record"
</code>```

}

In the .net API I have created the dto as per above avro schema using avrogen. In the POST call function the receiver object is of that dto class.

The HTTP Sink connector is throwing an 415: unsupported media type error. Could some one please help me what's wrong in config and how message will be received in .net api.

I have also tested the below request to check the endpoint and it is working fine.

```<code>curl --location --request POST 'http://localhost/messageHandler' --header 'Content-Type: text/json' --data-raw '{"id": "11", "name": "hello"}'
</code>```

Body:
I am new to Kafka connect. In one of our application we decided to use HTTP Sink Connector where data will be consumed from a particular topic and will be sent to an API created in .net.

Data produced in Kafka topic is as per avro schema.

Below is the HTTP sink connector configuration.

{
"name": "HTTPSinkConnector_1",
"config": {
    "topics": "test_data_topic_1",
    "tasks.max": "1",
    "connector.class": "io.confluent.connect.http.HttpSinkConnector",
    "http.api.url": "http://localhost/messageHandler",
    "request.method": "post",
    "key.converter":"org.apache.kafka.connect.storage.StringConverter",
    "value.converter": "io.confluent.connect.avro.AvroConverter",
    "value.converter.schema.registry.url": "http://schema-registry:8081",
    "confluent.topic.bootstrap.servers": "kafka:19092",
    "confluent.topic.replication.factor": "1",
    "reporter.bootstrap.servers": "kafka:19092",
    "reporter.result.topic.name": "success-responses",
    "reporter.result.topic.replication.factor": "1",
    "reporter.error.topic.name": "error-responses",
    "reporter.error.topic.replication.factor": "1"
}

}

Avro Schema:

{
"fields": [
    {
        "name": "id",
        "type": "string"
    },
    {
        "name": "name",
        "type": "string"
    }
],
"name": "article",
"namespace": "test.data",
"type": "record"

}

In the .net API I have created the dto as per above avro schema using avrogen. In the POST call function the receiver object is of that dto class.

The HTTP Sink connector is throwing an 415: unsupported media type error. Could some one please help me what's wrong in config and how message will be received in .net api.

I have also tested the below request to check the endpoint and it is working fine.

curl --location --request POST 'http://localhost/messageHandler' --header 'Content-Type: text/json' --data-raw '{"id": "11", "name": "hello"}'


问:
Ejabberd [warning] Unexpected info $gen_event
Warning message, that I'm trying to get rid off.

```<code>[warning] Unexpected info: {'$gen_event',
  {xmlstreamstart,<<"stream:stream">>,
    [{<<"xmlns:stream">>,
      <<"http://etherx.jabber.org/streams">>},
     {<<"xmlns">>,<<"jabber:client">>},
     {<<"version">>,<<"1.0">>},
     {<<"to">>,<<"example.com">>}]}}
</code>```

My users connect via xmpp.js from example.com website

import { client } from '@xmpp/client';

const xmppClient = client({
    service: "ejabberd-ws.example.com",
    domain: "example.com",
    credentials: async(auth) => {
        try {
            const res = await request('https://example.com/ejabberd/config');
            const username = res.data['jid'];
            const password = res.data['password'];
            if (!password) {
                console.error('Xmpp password is empty, null, false or undefined');
                return this.xmpp.disconnect();
            }
            auth({ username, password });
        } catch (e) {
            return this.xmpp.disconnect();
        }
    }
});
```

It is ejabberd version 22.10

Do any of you guys know what exactly is causing this warning message?
I would like to get rid of it or at least understand what is causing it.

Body:
Warning message, that I'm trying to get rid off.

[warning] Unexpected info: {'$gen_event',
  {xmlstreamstart,<<"stream:stream">>,
    [{<<"xmlns:stream">>,
      <<"http://etherx.jabber.org/streams">>},
     {<<"xmlns">>,<<"jabber:client">>},
     {<<"version">>,<<"1.0">>},
     {<<"to">>,<<"example.com">>}]}}

My users connect via xmpp.js from example.com website

import { client } from '@xmpp/client';

const xmppClient = client({
    service: "ejabberd-ws.example.com",
    domain: "example.com",
    credentials: async(auth) => {
        try {
            const res = await request('https://example.com/ejabberd/config');
            const username = res.data['jid'];
            const password = res.data['password'];
            if (!password) {
                console.error('Xmpp password is empty, null, false or undefined');
                return this.xmpp.disconnect();
            }
            auth({ username, password });
        } catch (e) {
            return this.xmpp.disconnect();
        }
    }
});

It is ejabberd version 22.10

Do any of you guys know what exactly is causing this warning message?
I would like to get rid of it or at least understand what is causing it.


问:
How to get rid of this error? SynchronousOnlyOperation: You can't call this from an asynchronous context - use a thread or sync_to_async
I use asynchrony in django and I ran into the following problem:
It is possible to execute a aget() request for the AccountUser model, but the CabinetUser model is not.
When executing a aget() request for the CabinetUser model, I get an error:
SynchronousOnlyOperation: You cannot call this from an asynccontext - use a thread or sync_to_async.

My mоdels:

```<code>class AccountUser(AbstractUser):
    """Модель для пользователей"""
    username_validator = UnicodeUsernameValidator()
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4(),
        editable=False)
    username = models.CharField(
        gettext_lazy("username"),
        max_length=150,
        unique=True,
        help_text=gettext_lazy(
            "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
        ),
        validators=[username_validator, validate_phone_number],
        error_messages={
            "unique": gettext_lazy("A user with that username already exists."),
        },
    )
    class Meta:
        db_table = 'account_user'
        verbose_name = 'Пользователь'
        verbose_name_plural = 'Пользователи'

    def __str__(self):
        return f'Пользователь -> {self.username}'

class CabinetUser(models.Model):
    """ Модель кабинета пользователя"""
    WORK_STATUS_WORKING = 'working'
    WORK_STATUS_FIRED = 'fired'
    WORK_STATUS_VACATION = 'vacation'
    WORK_STATUS_CHOICES = (
        (WORK_STATUS_WORKING, 'Работает'),
        (WORK_STATUS_FIRED, 'Уволен'),
        (WORK_STATUS_VACATION, 'В отпуске')
    )
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4(),
        editable=False)
    is_payment = models.BooleanField(
        default=True,
        verbose_name='Выплаты включены'
        )
    work_rules = models.ForeignKey(
        to=WorkRules,
        verbose_name='Условия работы',
        on_delete=models.CASCADE,
        related_name='cabinet_user',
        )
    role = models.CharField(
        max_length=20,
        choices=[
            ('Director', 'Директор'),
            ('Operator', 'Оператор'),
            ('Driver', 'Водитель'),
            ('Courier', 'Курьер'),
                ],
        verbose_name='Должность',)

    # Для миграций
    cabinet_park = models.ForeignKey(
        to='partner.CabinetPark',
        related_name='cabinet_user',
        verbose_name='Кабинет парка',
        on_delete=models.CASCADE,
        blank=True,
        null=True
    )

    group_commission = models.ForeignKey(
        to='partner.GroupCommission',
        on_delete=models.CASCADE,
        verbose_name='Группа коммиссий',
        blank=True,
        null=True
        )

    phone = models.ManyToManyField(
        to=PhoneNumber,
        verbose_name='Номер телефона',
        help_text='Номер телефона в международном формате (+7 ...)',
        related_name='cabinet_user',)
    profile_user = models.ForeignKey(
        to='ProfileUser',
        on_delete=models.CASCADE,
        related_name='cabinet_user',
        verbose_name='Профиль пользователя'
    )
    work_status = models.CharField(
        choices=WORK_STATUS_CHOICES,
        max_length=9,
        default=WORK_STATUS_WORKING,
        verbose_name='Рабочий статус')
    current_status = models.BooleanField(
        default=False,
        verbose_name='Статус',
        help_text='Статус "на Сайте" Online / Offline')
    balance = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
        verbose_name='Баланс')
    is_new_user = models.BooleanField(
        verbose_name='Новый пользователь',
        blank=True,
        null=True,
        default=True,
        )

    class Meta:
        db_table = 'cabinet_user'
        verbose_name = 'Кабинет пользователя'
        verbose_name_plural = 'Кабинеты пользователей'

    def __str__(self):
        return f'Кабинет пользователя -> {self.profile_user.account_user.username}'

</code>```

It is necessary to get cabinets, for this I use the method:

```<code>class DBPayout:

    async def get_cabinet_user(self, cabinet_id):
        try:
            cabinet = await CabinetUser.objects.aget(id=cabinet_id)
            return cabinet
        except CabinetUser.DoesNotExist as err:
            print(err)
        except SynchronousOnlyOperation as err:
            print(err)
        except Exception as err:
            print(err)
</code>```

I get an error: SynchronousOnlyOperation: You can't call this from an asynchronous context - use a thread or sync_to_async.

I tried to execute a request from the AccountUser model:

```<code>class DBPayout:

    async def get_cabinet_user(self, cabinet_id):
        try:
            cabinet = await AccountUser.objects.aget(id=cabinet_id)
            return cabinet
        except AccountUser.DoesNotExist as err:
            print(err)
        except SynchronousOnlyOperation as err:
            print(err)
        except Exception as err:
            print(err)
</code>```

Here the request is processed and gives a response: AccountUser matching query does not exist.
This is correct, since there is no such entry there. I don't understand why when accessing the CabinetUser model, it writes an asynchronous error.

In settings.py ASGI_APPLICATION is installed.

Body:
I use asynchrony in django and I ran into the following problem:
It is possible to execute a aget() request for the AccountUser model, but the CabinetUser model is not.
When executing a aget() request for the CabinetUser model, I get an error:
SynchronousOnlyOperation: You cannot call this from an asynccontext - use a thread or sync_to_async.

My mоdels:

class AccountUser(AbstractUser):
    """Модель для пользователей"""
    username_validator = UnicodeUsernameValidator()
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4(),
        editable=False)
    username = models.CharField(
        gettext_lazy("username"),
        max_length=150,
        unique=True,
        help_text=gettext_lazy(
            "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
        ),
        validators=[username_validator, validate_phone_number],
        error_messages={
            "unique": gettext_lazy("A user with that username already exists."),
        },
    )
    class Meta:
        db_table = 'account_user'
        verbose_name = 'Пользователь'
        verbose_name_plural = 'Пользователи'

    def __str__(self):
        return f'Пользователь -> {self.username}'

class CabinetUser(models.Model):
    """ Модель кабинета пользователя"""
    WORK_STATUS_WORKING = 'working'
    WORK_STATUS_FIRED = 'fired'
    WORK_STATUS_VACATION = 'vacation'
    WORK_STATUS_CHOICES = (
        (WORK_STATUS_WORKING, 'Работает'),
        (WORK_STATUS_FIRED, 'Уволен'),
        (WORK_STATUS_VACATION, 'В отпуске')
    )
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4(),
        editable=False)
    is_payment = models.BooleanField(
        default=True,
        verbose_name='Выплаты включены'
        )
    work_rules = models.ForeignKey(
        to=WorkRules,
        verbose_name='Условия работы',
        on_delete=models.CASCADE,
        related_name='cabinet_user',
        )
    role = models.CharField(
        max_length=20,
        choices=[
            ('Director', 'Директор'),
            ('Operator', 'Оператор'),
            ('Driver', 'Водитель'),
            ('Courier', 'Курьер'),
                ],
        verbose_name='Должность',)

    # Для миграций
    cabinet_park = models.ForeignKey(
        to='partner.CabinetPark',
        related_name='cabinet_user',
        verbose_name='Кабинет парка',
        on_delete=models.CASCADE,
        blank=True,
        null=True
    )

    group_commission = models.ForeignKey(
        to='partner.GroupCommission',
        on_delete=models.CASCADE,
        verbose_name='Группа коммиссий',
        blank=True,
        null=True
        )

    phone = models.ManyToManyField(
        to=PhoneNumber,
        verbose_name='Номер телефона',
        help_text='Номер телефона в международном формате (+7 ...)',
        related_name='cabinet_user',)
    profile_user = models.ForeignKey(
        to='ProfileUser',
        on_delete=models.CASCADE,
        related_name='cabinet_user',
        verbose_name='Профиль пользователя'
    )
    work_status = models.CharField(
        choices=WORK_STATUS_CHOICES,
        max_length=9,
        default=WORK_STATUS_WORKING,
        verbose_name='Рабочий статус')
    current_status = models.BooleanField(
        default=False,
        verbose_name='Статус',
        help_text='Статус "на Сайте" Online / Offline')
    balance = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
        verbose_name='Баланс')
    is_new_user = models.BooleanField(
        verbose_name='Новый пользователь',
        blank=True,
        null=True,
        default=True,
        )

    class Meta:
        db_table = 'cabinet_user'
        verbose_name = 'Кабинет пользователя'
        verbose_name_plural = 'Кабинеты пользователей'

    def __str__(self):
        return f'Кабинет пользователя -> {self.profile_user.account_user.username}'

It is necessary to get cabinets, for this I use the method:

class DBPayout:

    async def get_cabinet_user(self, cabinet_id):
        try:
            cabinet = await CabinetUser.objects.aget(id=cabinet_id)
            return cabinet
        except CabinetUser.DoesNotExist as err:
            print(err)
        except SynchronousOnlyOperation as err:
            print(err)
        except Exception as err:
            print(err)

I get an error: SynchronousOnlyOperation: You can't call this from an asynchronous context - use a thread or sync_to_async.

I tried to execute a request from the AccountUser model:

class DBPayout:

    async def get_cabinet_user(self, cabinet_id):
        try:
            cabinet = await AccountUser.objects.aget(id=cabinet_id)
            return cabinet
        except AccountUser.DoesNotExist as err:
            print(err)
        except SynchronousOnlyOperation as err:
            print(err)
        except Exception as err:
            print(err)

Here the request is processed and gives a response: AccountUser matching query does not exist.
This is correct, since there is no such entry there. I don't understand why when accessing the CabinetUser model, it writes an asynchronous error.

In settings.py ASGI_APPLICATION is installed.


问:
How to get header information in API Connect Analytics with out using Activity-log policy
Currently we are using "writeToSpulnk" custom policy to export API transaction logs in API Connect. This custom policy we have designed in such a way that it will send request and response headers to Splunk. So here we are not logging header information in API manager Analytics using Activity-log(which is inbuilt in API Connect). Those are set to default only. Now because of some business reasons we decided to remove "writeToSplunk" custom policy and get header information in API manager analytics itself. We want to achieve this task without redeploying any existed APIs.

Could you please suggest us the best way to do this task.

Thanks,
Triveni N.

I tried removing "writeToSplunk" policy by commenting out some code in source file of custom policy and reimported it in API Connect policies. By doing this I am able to stop sending logs to Splunk with out redeploying the APIs. But I want to use same source file to send header information to API manager Analytics. How can I do that?

Thanks,
Triveni N.


问:
Is this the way to check function available on react?
Today i see this code on my current project, a little confuse

```<code> {rating && (
              <View style={rateFunction ? [ratingCont, { justifyContent: "space-between" }] : ratingCont}>
                {this.star &&
                  this.star.map((rate, index) => (
                    <TouchableOpacity
                      key={index}
                      style={ratingIcon}
                      activeOpacity={rateFunction ? 0.3 : 1}
                      onPress={() => rateFunction(index)}>
                      {Icons.Generator.Awesome(
                        "star",
                        rateFunction ? width * 0.09 : 12,
                        rate ? DCColor.BGColor("primary-1") : DCColor.BGColor("disable"),
                      )}
                    </TouchableOpacity>
                  ))}
              </View>
            )}
</code>```

Everything look fine but i hard to understand with rateFunction

Note that this function not pass from anywhere, not a defined function above, just use only on this the code i provide, and it only use on this file

So it that rateFunction ? 0.3 : 1 mean that it will be 0.3 when we press and 1 when not, or in another way, rateFunction will be true if we press???
I never see this type of this before in react

Body:
Today i see this code on my current project, a little confuse

 {rating && (
              <View style={rateFunction ? [ratingCont, { justifyContent: "space-between" }] : ratingCont}>
                {this.star &&
                  this.star.map((rate, index) => (
                    <TouchableOpacity
                      key={index}
                      style={ratingIcon}
                      activeOpacity={rateFunction ? 0.3 : 1}
                      onPress={() => rateFunction(index)}>
                      {Icons.Generator.Awesome(
                        "star",
                        rateFunction ? width * 0.09 : 12,
                        rate ? DCColor.BGColor("primary-1") : DCColor.BGColor("disable"),
                      )}
                    </TouchableOpacity>
                  ))}
              </View>
            )}

Everything look fine but i hard to understand with rateFunction

Note that this function not pass from anywhere, not a defined function above, just use only on this the code i provide, and it only use on this file

So it that rateFunction ? 0.3 : 1 mean that it will be 0.3 when we press and 1 when not, or in another way, rateFunction will be true if we press???
I never see this type of this before in react


问:
How to remove data from sequelize join table
I have 2 tables: Reader and Book many-to-many. The linking table ReaderBooks contains data about books issued to the reader. How can I delete one of the links (let's say the id of the book and the id of the reader were passed, you need to delete the line with these parameters)

```<code>const Book = sequelize.define('Book', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    title: {type: DataTypes.STRING, allowNull: false},
    author: {type: DataTypes.STRING, allowNull: false},
    vendorCode: {type: DataTypes.INTEGER, allowNull: false},
    year: {type: DataTypes.DATEONLY, allowNull: false},
    numberOfCopies: {type: DataTypes.INTEGER}
});

const Reader = sequelize.define('Reader', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    fullName: {type: DataTypes.STRING, allowNull: false},
    birth: {type: DataTypes.DATEONLY, allowNull: false}
});

const ReaderBook = sequelize.define('ReaderBook', {
});

Reader.belongsToMany(Book, {through: 'ReaderBook'});
Book.belongsToMany(Reader, {through: 'ReaderBook'});

module.exports = {Book, Reader, ReaderBook};
</code>```

returnBook:

```<code>async returnBook(req, res) {
        try {
            const {idReader, idBook} = req.body;
            const book = await Book.findByPk(idBook);
            const reader = await Reader.findByPk(idReader);
            if (!reader || !book) {
                return res.status(400).json({message: 'Reader or Book does not exist'});
            }
            await reader.removeBook({
                include: {
                    model: Book,
                    where: {
                        id: idBook
                    }
                },
                where: {
                    id: idReader
                }
            });
            return res.json("Test");
        } catch (e) {
            console.log(e.message);
            return res.status(400).json({message: 'Error returning a book to a reader'});
        }
    };
</code>```

Body:
I have 2 tables: Reader and Book many-to-many. The linking table ReaderBooks contains data about books issued to the reader. How can I delete one of the links (let's say the id of the book and the id of the reader were passed, you need to delete the line with these parameters)

const Book = sequelize.define('Book', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    title: {type: DataTypes.STRING, allowNull: false},
    author: {type: DataTypes.STRING, allowNull: false},
    vendorCode: {type: DataTypes.INTEGER, allowNull: false},
    year: {type: DataTypes.DATEONLY, allowNull: false},
    numberOfCopies: {type: DataTypes.INTEGER}
});

const Reader = sequelize.define('Reader', {
    id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    fullName: {type: DataTypes.STRING, allowNull: false},
    birth: {type: DataTypes.DATEONLY, allowNull: false}
});

const ReaderBook = sequelize.define('ReaderBook', {
});

Reader.belongsToMany(Book, {through: 'ReaderBook'});
Book.belongsToMany(Reader, {through: 'ReaderBook'});

module.exports = {Book, Reader, ReaderBook};

returnBook:

async returnBook(req, res) {
        try {
            const {idReader, idBook} = req.body;
            const book = await Book.findByPk(idBook);
            const reader = await Reader.findByPk(idReader);
            if (!reader || !book) {
                return res.status(400).json({message: 'Reader or Book does not exist'});
            }
            await reader.removeBook({
                include: {
                    model: Book,
                    where: {
                        id: idBook
                    }
                },
                where: {
                    id: idReader
                }
            });
            return res.json("Test");
        } catch (e) {
            console.log(e.message);
            return res.status(400).json({message: 'Error returning a book to a reader'});
        }
    };


问:
JOptionPane message does not show when entering the wrong value
```<code> @Override
   public void actionPerformed(ActionEvent e){

      if(e.getSource() == back){
       frame.dispose();
         home h = new home();
      }

      //rent button

      if(e.getSource() == rent){
            double money = 0;
            money = Double.parseDouble(txtinsertmoney.getText());

            try{
               if(blackadam.isSelected()){
               money = money - 1009.00;
               }

               if(up.isSelected()){
               money = money - 212.00;
               }

               if(terminator.isSelected()){
               money = money - 220.00;
               }

               if(justiceleague.isSelected()){
               money = money - 1100.00;
               }

               if(yourname.isSelected()){
               money = money - 1200;
               }

               if(starwars.isSelected()){
               money = money - 275;
               }
               if(demonslayer.isSelected()){
               money = money - 1100;
               }
               if(madmax.isSelected()){
               money = money - 825;
               }
               if(topgun.isSelected()){
               money = money - 220;
               }
               if(predator.isSelected()){
               money = money - 400;
               }
               if(nul.isSelected()){
               money = money - 220;
               }

               else{
               txtchange.setText(Double.toString(money));
               }

            }
            catch(NumberFormatException ex){
               JOptionPane.showMessageDialog(frame,"ERROR","ERROR",JOptionPane.ERROR_MESSAGE );
            }

      }

</code>```

I am trying to display a JOptionPane when entering a String value instead of double. It should pop out with a displayed message as "ERROR" but it does not show. I am also using a try and catch method. ..................................................................................................................................................................................................................................................................................................................................

Body:
 @Override
   public void actionPerformed(ActionEvent e){

      if(e.getSource() == back){
       frame.dispose();
         home h = new home();
      }

      //rent button

      if(e.getSource() == rent){
            double money = 0;
            money = Double.parseDouble(txtinsertmoney.getText());

            try{
               if(blackadam.isSelected()){
               money = money - 1009.00;
               }

               if(up.isSelected()){
               money = money - 212.00;
               }

               if(terminator.isSelected()){
               money = money - 220.00;
               }

               if(justiceleague.isSelected()){
               money = money - 1100.00;
               }

               if(yourname.isSelected()){
               money = money - 1200;
               }

               if(starwars.isSelected()){
               money = money - 275;
               }
               if(demonslayer.isSelected()){
               money = money - 1100;
               }
               if(madmax.isSelected()){
               money = money - 825;
               }
               if(topgun.isSelected()){
               money = money - 220;
               }
               if(predator.isSelected()){
               money = money - 400;
               }
               if(nul.isSelected()){
               money = money - 220;
               }

               else{
               txtchange.setText(Double.toString(money));
               }

            }
            catch(NumberFormatException ex){
               JOptionPane.showMessageDialog(frame,"ERROR","ERROR",JOptionPane.ERROR_MESSAGE );
            }

      }

I am trying to display a JOptionPane when entering a String value instead of double. It should pop out with a displayed message as "ERROR" but it does not show. I am also using a try and catch method. ..................................................................................................................................................................................................................................................................................................................................