问:
CMake Block of targets compilation
I´m migrating a huge aplication from OMake to CMake. I need to define a block compilation depending on a parameter passed on make comand line (like on traditional make) for example:

```<code>add_executable(target_1 target_one.c)
add_executable(target_2 target_two.c)
add_executable(target_3 target_three.c)
...
add_executable(target_10 target_ten.c)

TARGETS_1 = target_1 target_2 target_3
TARGETS_2 = target_4 target_5 target_6
TARGETS_3 = target_7 target_8 target_9 target_10
...
...
if(args[1] == TARGETS_1) compile only TARGETS_1
else if(args[1] == TARGETS_2) compile only TARGETS_2
else if(args[1] == TARGETS_3) compile only TARGETS_3
</code>```

Can anyone help me on this?

Title: CMake Block of targets compilation

Body:
I´m migrating a huge aplication from OMake to CMake. I need to define a block compilation depending on a parameter passed on make comand line (like on traditional make) for example:

add_executable(target_1 target_one.c)
add_executable(target_2 target_two.c)
add_executable(target_3 target_three.c)
...
add_executable(target_10 target_ten.c)

TARGETS_1 = target_1 target_2 target_3
TARGETS_2 = target_4 target_5 target_6
TARGETS_3 = target_7 target_8 target_9 target_10
...
...
if(args[1] == TARGETS_1) compile only TARGETS_1
else if(args[1] == TARGETS_2) compile only TARGETS_2
else if(args[1] == TARGETS_3) compile only TARGETS_3

Can anyone help me on this?


来源: stackexchange

问:
Helm - How to integrate secret variables inside a command of busybox image
I am trying to create a file in a busybox image using the following in my statefulset.yaml file in a helm chart:

```<code>    - name: create-file
      image: "busybox:latest"
      imagePullPolicy: Always
      command: ['sh','-c','echo "my-secret-var-here\nanother-secret-here" "/local.d/file.ini" ;']
      volumeMounts:
        - name: local-config-storage
          mountPath: /local.d
</code>```

My question is simple... how can I integrate a variable I have in a secret such as

```<code>    valueFrom:
      secretKeyRef:
        name: mySecret
        key: myKey
</code>```

into the file? In other words, replace my-secret-var-here with the value I have in mySecret under myKey...

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a file in a busybox image using the following in my statefulset.yaml file in a helm chart:

    - name: create-file
      image: "busybox:latest"
      imagePullPolicy: Always
      command: ['sh','-c','echo "my-secret-var-here\nanother-secret-here" "/local.d/file.ini" ;']
      volumeMounts:
        - name: local-config-storage
          mountPath: /local.d

My question is simple... how can I integrate a variable I have in a secret such as

    valueFrom:
      secretKeyRef:
        name: mySecret
        key: myKey

into the file? In other words, replace my-secret-var-here with the value I have in mySecret under myKey...


问:
Can Spring Security delete or update a httpSession attribute previously set?
I'm developing a web which consumes an API. It gets a jwt token from it at login form configured by Spring security and it stores it inside an ´HttpSession´ attribute.

I also need to make some actions over the API from public pages in the web so I perform a jwt request for a "public credential" that I store in that HttpSession.

It's possible that after visiting some of those public URLs which set and use the "public credential" jwt in session the user visits one of the login forms and makes login.

At this point the httpSession attribute isn't set again so the first calls to the API after the login are obtained with the "public credential" jwt token.

I'll be updating some advanced stuff I'm researching
UPDATE:

Inside a HandlerInterceptor (properly added to InterceptorRegistry and preHandle method gets executed.

request.getSession().removeAttribute("attributeName") didn't work


问:
Laravel Model getRelation returns all rows
I got a User Class

```<code>class User extends Model implements
    AuthenticatableContract,
    CanResetPasswordContract,
    AuthorizableContract,
    MustVerifyEmailContract {

    //use HasApiTokens, HasFactory, Notifiable, MustVerifyEmail;

    use MustVerifyEmail, HasApiTokens,Authenticatable, Authorizable, CanResetPassword, Notifiable;

    protected $table = 'users';

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'username',
        'email',
        'password'

    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    public function devices(){

        if($this->is_admin){
            return Device::query();
        }

        return $this->belongsToMany(Device::class);
    }

    public function testseries(){
        $devices = $this->devices();
        dd($devices->getRelation('testseries')->get()->toArray());
    }
}
</code>```

In my case, should I do $devices->get() it gives me a empty collection.

Now I want to get the relation from devices to testseries. But i dont want to get an collection.

I want to call manually later somewhere $user->testseries()->get() because maybe I want to modify something with where.

Is that possible?

Currently $devices->getRelation('testseries')->get() returns an collection of all testseries while $devices->get() give me an empty collection of devices. But I expect an empty collection too because there are no devices, so there shouldnt be any testseries for the user.

I dont want to use $devices->with('testseries') because then I'll get a Collection of Device models with the relation. But I Want a collection of testseries instead.

Is there any way or workaround to get that?

I tried it with pluck, load and with. But nothing gives me my expected result and they are already loaded in a wrong collection format because I want a collection of testserie Model.

EDIT:

Here are all other Model classes:

```<code>class Testserie extends Model
{
    use HasFactory;

    /**
     * @var string[]
     */
    protected $fillable = [
        'device_id',
        'date',

    ];

    public function measurements(): HasMany {
        return $this->hasMany(Measurement::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function device(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo(Device::class);
    }
}
</code>```
```<code>class Device extends Model
{
    use HasFactory;

    /**
     * @return BelongsToMany
     */
    public function users(): BelongsToMany {
        return $this->belongsToMany(User::class);
    }

    /**
     * @return HasMany
     */
    public function testseries(): HasMany {
        return $this->hasMany(Testserie::class);
    }

}
</code>```

Here is a picture of the database structure

Body:
I got a User Class

class User extends Model implements
    AuthenticatableContract,
    CanResetPasswordContract,
    AuthorizableContract,
    MustVerifyEmailContract {

    //use HasApiTokens, HasFactory, Notifiable, MustVerifyEmail;

    use MustVerifyEmail, HasApiTokens,Authenticatable, Authorizable, CanResetPassword, Notifiable;

    protected $table = 'users';

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'username',
        'email',
        'password'

    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    public function devices(){

        if($this->is_admin){
            return Device::query();
        }

        return $this->belongsToMany(Device::class);
    }

    public function testseries(){
        $devices = $this->devices();
        dd($devices->getRelation('testseries')->get()->toArray());
    }
}

In my case, should I do $devices->get() it gives me a empty collection.

Now I want to get the relation from devices to testseries. But i dont want to get an collection.

I want to call manually later somewhere $user->testseries()->get() because maybe I want to modify something with where.

Is that possible?

Currently $devices->getRelation('testseries')->get() returns an collection of all testseries while $devices->get() give me an empty collection of devices. But I expect an empty collection too because there are no devices, so there shouldnt be any testseries for the user.

I dont want to use $devices->with('testseries') because then I'll get a Collection of Device models with the relation. But I Want a collection of testseries instead.

Is there any way or workaround to get that?

I tried it with pluck, load and with. But nothing gives me my expected result and they are already loaded in a wrong collection format because I want a collection of testserie Model.

EDIT:

Here are all other Model classes:

class Testserie extends Model
{
    use HasFactory;

    /**
     * @var string[]
     */
    protected $fillable = [
        'device_id',
        'date',

    ];

    public function measurements(): HasMany {
        return $this->hasMany(Measurement::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function device(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
        return $this->belongsTo(Device::class);
    }
}

class Device extends Model
{
    use HasFactory;

    /**
     * @return BelongsToMany
     */
    public function users(): BelongsToMany {
        return $this->belongsToMany(User::class);
    }

    /**
     * @return HasMany
     */
    public function testseries(): HasMany {
        return $this->hasMany(Testserie::class);
    }

}

Here is a picture of the database structure


问:
Load testing asynchronous SOAP app with HTTP2 request results returned as HTTP2 requests instead of HTTP2 responses
I have been tasked with load testing an app that receives SOAP messages through HTTP/2.0 but does not return HTTP/2.0 responses to the sender. Instead, the app sends what would be a SOAP response message in the form of an HTTP/2.0 request to the original sender*.

My problem is that I need to collect these responses and analyze them but most load testing tools seem to work in standard request-response-postprocessing model. In this case, there is no response so no post processing can be done during the load test. Does anybody have experience with load testing similar applications? What tools would you use for this purpose?

I usually stick to jmeter but it doesn’t seem to be the correct tool for this. I have found a plugin for jmeter that starts a compact HTTP/1.1 server that awaits this kind of “response” but the app in question uses HTTP/2.0. Would this be easier in SoapUI? Or is setting up a webserver to receive and save the “response” data sent by the app the only way to achieve this?

*Side-note: the app sends its requests to an endpoint that is known to the original message sender so this is beside the problem. There are also message identifiers involved, so it is known what request results in what result.


问:
Throttling navigation to prevent the browser from hanging
trying to create office web add-in but getting warning, on installed version of word working fine but on online version it crashes

```<code>common.mjs:177

       Throttling navigation to prevent the browser from hanging. See https://crbug.com/1038223. Command line switch --disable-ipc-flooding-protection can be used to bypass the protection
</code>```

and this is what i am using

```<code>
import { Component, OnInit, } from '@angular/core';
import { DatePipe } from '@angular/common';
import { HttpsCallService } from 'src/app/services/https-call.service';
import { Document } from 'src/app/interfaces/document';
import { Paragraph } from 'src/app/interfaces/paragraph';
import { allComponents, bodyFont,  provideFluentDesignSystem } from '@fluentui/web-components';
import { timeout } from 'rxjs';
import { IfStmt, R3SelectorScopeMode } from '@angular/compiler';
import {
  fluentCheckbox
} from "@fluentui/web-components";

// provideFluentDesignSystem()
//   .register(
//       fluentCheckbox()
//   );

//provideFluentDesignSystem().register(fluentAccordion(), fluentAccordionItem());

let responseCall:any =  '';
let dialogView = true;
let dialogCond = 'true';
let recLocate = false;
provideFluentDesignSystem().register(allComponents);
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

  constructor(
    private datepipe: DatePipe,
    private httpsCallService: HttpsCallService,

    ) { }
</code>```

trying to create addin for word but getting this warning

Body:
trying to create office web add-in but getting warning, on installed version of word working fine but on online version it crashes

common.mjs:177

       Throttling navigation to prevent the browser from hanging. See https://crbug.com/1038223. Command line switch --disable-ipc-flooding-protection can be used to bypass the protection

and this is what i am using

import { Component, OnInit, } from '@angular/core';
import { DatePipe } from '@angular/common';
import { HttpsCallService } from 'src/app/services/https-call.service';
import { Document } from 'src/app/interfaces/document';
import { Paragraph } from 'src/app/interfaces/paragraph';
import { allComponents, bodyFont,  provideFluentDesignSystem } from '@fluentui/web-components';
import { timeout } from 'rxjs';
import { IfStmt, R3SelectorScopeMode } from '@angular/compiler';
import {
  fluentCheckbox
} from "@fluentui/web-components";

// provideFluentDesignSystem()
//   .register(
//       fluentCheckbox()
//   );

//provideFluentDesignSystem().register(fluentAccordion(), fluentAccordionItem());

let responseCall:any =  '';
let dialogView = true;
let dialogCond = 'true';
let recLocate = false;
provideFluentDesignSystem().register(allComponents);
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

  constructor(
    private datepipe: DatePipe,
    private httpsCallService: HttpsCallService,

    ) { }

trying to create addin for word but getting this warning


问:
Problem with compile Unity Build to Android platform
What I can do with this?

I've been getting a lot of compilation errors for a long time, this is just one of them, I hope your answer helps solve this problem

My project has AppLovin and AdJust

That my settings

And I Have this stacktrace:

Building Library\Bee\artifacts\Android\libunity\armeabi-v7a\UnityClassRegistration.o failed with output:
clang++: error: unable to execute command: Couldn't execute program 'D:/UnityProjects/2021.3.15f1/Editor/Data/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/windows-x86_64/bin\clang++.exe': ���� �������� ������� ��� ��� ���������� ��������.  (0x5AF)
0x00007ff79448c77d (Unity) StackWalker::GetCurrentCallstack
0x00007ff794493339 (Unity) StackWalker::ShowCallstack
0x00007ff795400003 (Unity) GetStacktrace
0x00007ff795a9fe1d (Unity) DebugStringToFile
0x00007ff79355a162 (Unity) DebugLogHandler_CUSTOM_Internal_Log
`0x0000026680fd1aea (Mono JIT Code) (wrapper managed-to-native)

Building Library\Bee\artifacts\Android\libunity\arm64-v8a\UnityClassRegistration.o failed with output:
clang++: error: clang frontend command failed due to signal (use -v to see invocation)
Android (6454773 based on r365631c2) clang version 9.0.8 (``https://android.googlesource.com/toolchain/llvm-project`` 98c855489587874b2a325e7a516b99d838599c6f) (based on LLVM 9.0.8svn)
Target: aarch64-unknown-linux-android22
Thread model: posix
InstalledDir: D:/UnityProjects/2021.3.15f1/Editor/Data/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/windows-x86_64/bin
clang++: note: diagnostic msg: PLEASE submit a bug report to ``https://github.com/android-ndk/ndk/issues`` and include the crash backtrace, preprocessed source, and associated run script.
clang++: error: unable to execute command: Couldn't execute program 'D:/UnityProjects/2021.3.15f1/Editor/Data/PlaybackEngines/AndroidPlayer/NDK/toolchains/llvm/prebuilt/windows-x86_64/bin\clang++.exe': ���� �������� ������� ��� ��� ���������� ��������.  (0x5AF)
clang++: note: diagnostic msg: Error generating preprocessed source(s).
0x00007ff79448c77d (Unity) StackWalker::GetCurrentCallstack
0x00007ff794493339 (Unity) StackWalker::ShowCallstack


问:
Is it possible to use metric values with equal tags only once
I have a metric in datadog with three different tags: TagA, TagB and TagC.

When I visualize the metric values in a dashboard, I want that only one metric value will be used with equal tag values.

Example:
These are the metric values:

```<code>1. TagA:v1; TagB:v2; TagC:v3
2. TagA:v2; TagB:v2; TagC:v3
3. TagA:v1; TagB:v2; TagC:v3
4. TagA:v3; TagB:v2; TagC:v3
</code>```

Then I only want the values 1, 2 and 4 to be considered for visualization.

Thanks for any answers

Body:
I have a metric in datadog with three different tags: TagA, TagB and TagC.

When I visualize the metric values in a dashboard, I want that only one metric value will be used with equal tag values.

Example:
These are the metric values:

1. TagA:v1; TagB:v2; TagC:v3
2. TagA:v2; TagB:v2; TagC:v3
3. TagA:v1; TagB:v2; TagC:v3
4. TagA:v3; TagB:v2; TagC:v3

Then I only want the values 1, 2 and 4 to be considered for visualization.

Thanks for any answers


问:
Error 500 in graphql-yoga serveless deploy in vercel
I have a basic graphql-yoga server in port 4001,and i try to deploy to vercel serveless, but i have allways these error:

```<code>This Serverless Function has crashed.

Your connection is working correctly.

Vercel is working correctly.

500: INTERNAL_SERVER_ERROR
Code: FUNCTION_INVOCATION_FAILED
ID: iad1::qs77w-1671197012548-43a160e0d3fb
</code>```

These is my vercel config:

```<code>{
"version": 2,
"builds": [
  {
    "src": "index.js",
    "use": "@now/node"
  }
],
"routes": [
    { "src": "/(.*)", "dest": "index.js" }
  ]
}
</code>```

Body:
I have a basic graphql-yoga server in port 4001,and i try to deploy to vercel serveless, but i have allways these error:

This Serverless Function has crashed.

Your connection is working correctly.

Vercel is working correctly.

500: INTERNAL_SERVER_ERROR
Code: FUNCTION_INVOCATION_FAILED
ID: iad1::qs77w-1671197012548-43a160e0d3fb

These is my vercel config:

{
"version": 2,
"builds": [
  {
    "src": "index.js",
    "use": "@now/node"
  }
],
"routes": [
    { "src": "/(.*)", "dest": "index.js" }
  ]
}


问:
Show hoverinfo in treemap only for child container in plotly treemap HTML
I have created the treemap graph for share market summery, It shows correct information when i hover on child containers but when i hover on the parent container it shows different syntax, i want instead of that syntax some different values or stop hovering on the parent container at all

This is my written whole code.

```<code>import dash
from dash import dcc
from dash import html
import plotly.express as px
import dash_html_components as html
from dash import dcc, html, Input, Output
import dash_bootstrap_components as dbc
import sys
import pandas as pd
from datetime import date
from dash import Dash, html, dcc
import numpy as np
from pandas import Series, DataFrame, json_normalize
from datetime import datetime
import plotly.offline as pyo
import plotly.graph_objs as go
import plotly.io as pio
from numerize import numerize

dash.register_page(__name__,title='Stock Market Summery',path_template="/")

Data_source = "data/dashbaord_ohlc_df_4_processed.csv"
PATH = ['Sector','Symbol']
# PATH = [px.Constant("Market Overview"),'Country','Sector','Symbol','Name','Currency','MarketCapitalization','Earnings_Share','dailyChange%','PE_Ratio%','PEG_Ratio%']
HOVER_DATA = ['Name','Country','Currency','Market Capitalization', 'Most Recent Quarter','PE Ratio%','PEG Ratio%','Earnings Share','Dividend Yield','Operating Margin TTM','Return OnAssets TTM','Return OnEquity TTM','Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange']
value_attribute = 'Market Capitalization'
COLOR = 'dailyChange'
infotext =  "label + percent parent"
Drag_option = ["Dark Theme","Light Theme"]
Country_option = ["India","Australia","USA"]
Hover_Tmp = '<br>Name:%{customdata[0]}'+'<br>Country:%{customdata[1]}'+'<br>Currency:%{customdata[2]}'+'<br>Daily Change: %{customdata[14]}%'+'<br>Market Capitalization:%{value:0.3s}'+'<br>Most Recent Quarter:%{customdata[4]}' +'<br>PE Ratio:%{customdata[5]}%'+'<br>PEG Ratio:%{customdata[6]}%'+'<br>Earnings Share:%{customdata[7]}%' +  '<br>Dividend Yield:%{customdata[8]}' + '<br>Operating Margin TTM:%{customdata[9]}' + '<br>Return OnAssets TTM:%{customdata[10]}' + '<br>Return OnEquity TTM:%{customdata[11]}' + '<br>Quarterly Earnings GrowthYOY:%{customdata[12]}' + '<br>Quarterly Revenue GrowthYOY:%{customdata[13]}'+'<br>'
dark_theme = {'(?)':'black','India':'#012B1E','USA':'#43010A','Australia':'#981125'}
light_theme = {'(?)':'White','India':'#C4F1EC','USA':'#FFD6E7','Australia':'#0DB261'}
color_scale = "#32a870", "#cc1819" ##012B2E  #43010A
input_date = '2022-10-21'

df = pd.read_csv(Data_source, usecols = ['Name','Country','Currency','Market Capitalization', 'Most Recent Quarter','PE Ratio%','PEG Ratio%','Earnings Share','Dividend Yield','Operating Margin TTM','Return OnAssets TTM','Return OnEquity TTM','Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange','date','Sector','Symbol','DailyChangeTreeMap', 'Condition','Description'])
link_ref = '<a href="http://127.0.0.1:9990/info/{}" class="csv_link" style="cursor: pointer;color:white; " target="_self" rel="noopener noreferrer">{}</a>'
df['Symbol'] = df['Symbol'].apply(lambda item: link_ref.format(item, item, "{}"))

df = pd.DataFrame(df)

def filter_df(input_date,country_name):
    input_date = datetime.strptime (str(input_date), '%Y-%m-%d')
    df['date'] = pd.to_datetime(df['date'])
    df.fillna(0, inplace=True)

    if country_name:
        df2 = df[(df['date'] == input_date) & (df['Country']==country_name)]
    else:
        df2 = df
    return df2

def create_dropdown(option, id_value):
    return html.Div(
        [
            dcc.Dropdown(id=id_value, options=option,
                     value=option[0],
                     style = {}
                     ),
        ],
    )

layout = html.Div([
        html.Div(
                children=[html.H1('Stock Market Summary',),
                html.P('''AI predictions, intraday market price action, biggest movers, H1 sectors performance, and more.''',
                )], id="header", className="row flex-display header", style={"display": "flex", "flex-direction": "column"},),

        html.Div(
                html.Div(children=[
                    html.Div(
                    children=create_dropdown(Drag_option, "Theme-select"),className="theme_dropdown",
                ),
                html.Div(children=[html.Div(id='output-container-date-picker-single',),
                dcc.DatePickerSingle(
                    id='my-date-picker-single',
                    min_date_allowed=date(1995, 8, 5),
                    max_date_allowed=date(2023, 9, 19),
                    initial_visible_month=date(2022, 12, 31),
                    date=date(2022, 10, 21),
                    style={'width':'200px'}
                ) ],className="date_container"),
                    html.Button('Theme', id='btn-nclicks-1', n_clicks=0),
                # dcc.Input(type='checkbox',className="toggle-button"),
                html.Div(children=create_dropdown(Country_option,"dd-output-container"),className="contry_dropdown"),
                    ]),className="primary-navigation row flex-display",id="header", style={"margin-bottom": "25px"}
        ),

        html.Div([
                html.Div([
                    dcc.Graph(id="indicatorr")], className="graph create_container2 twelve columns"),
                    ], className="row flex-display"),

        html.Div([
            html.Div([
                html.H3('Thank You',)],className="footer create_container2 twelve columns",)
            ]),

    ],className="main",id="mainContainer", style = {'backgroundColor':'#3d3d3b', 'textAlign': 'center',"display": "flex", "flex-direction": "column"})

@dash.callback(
    Output('indicatorr','figure'),
    Input("Theme-select","value"),
    Input('my-date-picker-single', 'date'),
    Input(component_id='dd-output-container', component_property='value')
)

def update_output(theme_select, my_date_picker_single,dd_output_container):
    """
        Updating Tree MAp as per filter
    """
    if theme_select == 'Dark Theme':
        # color_discrete_map=["#ff4d00","#a13023","#21b811"]
        color_discrete_map=["#ff4d00","#21b811"]
    elif theme_select == 'Light Theme':
            color_discrete_map=["#DC3714","#C0C0C0","#19BD1B","#474745"]
    else:
        color_discrete_map=["#ff4d00","#a13023","#21b811"]

    filtered_df = filter_df(my_date_picker_single,dd_output_container)
    if filtered_df.empty:
        print("Dataframe is empty")
        return "DATAFRAME IS EMPTY"
    else:
        print("NOT EMPTY")
        indicator = px.treemap(filtered_df,
                    color=COLOR,
                    color_continuous_scale=color_discrete_map,
                    path = PATH,
                    # template='plotly_white',
                    maxdepth=3,
                    hover_data=HOVER_DATA,
                    values=value_attribute,
                    color_discrete_map=color_discrete_map)

        indicator.update_traces(textfont_size=16,)
        indicator.update_layout(margin = dict(t=35, l=5, r=5, b=5),
                        paper_bgcolor='rgba(0,0,255,0)',
                        plot_bgcolor='rgba(0,0,255,0)',
                        # coloraxis_showscale=False
                        )
        indicator.data[0].hovertemplate = Hover_Tmp

        # indicator.data[0].texttemplate ="%{label} %<br>Market Cap.:%{value:0.3s}"
        indicator.data[0].texttemplate ="<b>%{label} </b><br><span class='innertext'>%{customdata[14]} %<br>Market Cap.:%{value:0.3s}"

        return indicator
</code>```

here you can see that it's rendering as a html component, as return method

below code is working as my need, but with pio.show() method & in above code i am not using fig.show

```<code>fig1 = px.treemap(df, path=['continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'],
                  color_continuous_scale='RdBu',
                  color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
pio.show(fig1,
         post_script = "/* this works if there is only one Plotly plot on web page */" +
         "setTimeout(function() {" +
         "  el = document.querySelector('div.plotly-graph-div.js-plotly-plot'); " +
         "  /* Plotly event */" +
         "  el.on('plotly_hover', function(d){" +
         "    pth = d.points[0].currentPath;"     +
         "    if(pth === '/' || pth === 'world/') {    /* if root or first root child (a parent) */" +
         "       ght = document.querySelector('g.hoverlayer');"
         "       ght.innerHTML = ''; /* remove hovertext */" +
         "    }" +
         "  });" +
         "}, 200)")
</code>```

i am uploading the screenshots of what i want with the code & what actually i am exprecting

this is homepage

This hover i don't want

This hover only I want

hover effect only on the child element.

Body:
I have created the treemap graph for share market summery, It shows correct information when i hover on child containers but when i hover on the parent container it shows different syntax, i want instead of that syntax some different values or stop hovering on the parent container at all

This is my written whole code.

import dash
from dash import dcc
from dash import html
import plotly.express as px
import dash_html_components as html
from dash import dcc, html, Input, Output
import dash_bootstrap_components as dbc
import sys
import pandas as pd
from datetime import date
from dash import Dash, html, dcc
import numpy as np
from pandas import Series, DataFrame, json_normalize
from datetime import datetime
import plotly.offline as pyo
import plotly.graph_objs as go
import plotly.io as pio
from numerize import numerize

dash.register_page(__name__,title='Stock Market Summery',path_template="/")

Data_source = "data/dashbaord_ohlc_df_4_processed.csv"
PATH = ['Sector','Symbol']
# PATH = [px.Constant("Market Overview"),'Country','Sector','Symbol','Name','Currency','MarketCapitalization','Earnings_Share','dailyChange%','PE_Ratio%','PEG_Ratio%']
HOVER_DATA = ['Name','Country','Currency','Market Capitalization', 'Most Recent Quarter','PE Ratio%','PEG Ratio%','Earnings Share','Dividend Yield','Operating Margin TTM','Return OnAssets TTM','Return OnEquity TTM','Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange']
value_attribute = 'Market Capitalization'
COLOR = 'dailyChange'
infotext =  "label + percent parent"
Drag_option = ["Dark Theme","Light Theme"]
Country_option = ["India","Australia","USA"]
Hover_Tmp = '
Name:%{customdata[0]}'+'
Country:%{customdata[1]}'+'
Currency:%{customdata[2]}'+'
Daily Change: %{customdata[14]}%'+'
Market Capitalization:%{value:0.3s}'+'
Most Recent Quarter:%{customdata[4]}' +'
PE Ratio:%{customdata[5]}%'+'
PEG Ratio:%{customdata[6]}%'+'
Earnings Share:%{customdata[7]}%' +  '
Dividend Yield:%{customdata[8]}' + '
Operating Margin TTM:%{customdata[9]}' + '
Return OnAssets TTM:%{customdata[10]}' + '
Return OnEquity TTM:%{customdata[11]}' + '
Quarterly Earnings GrowthYOY:%{customdata[12]}' + '
Quarterly Revenue GrowthYOY:%{customdata[13]}'+'
'
dark_theme = {'(?)':'black','India':'#012B1E','USA':'#43010A','Australia':'#981125'}
light_theme = {'(?)':'White','India':'#C4F1EC','USA':'#FFD6E7','Australia':'#0DB261'}
color_scale = "#32a870", "#cc1819" ##012B2E  #43010A
input_date = '2022-10-21'

df = pd.read_csv(Data_source, usecols = ['Name','Country','Currency','Market Capitalization', 'Most Recent Quarter','PE Ratio%','PEG Ratio%','Earnings Share','Dividend Yield','Operating Margin TTM','Return OnAssets TTM','Return OnEquity TTM','Quarterly Earnings GrowthYOY','Quarterly Revenue GrowthYOY','dailyChange','date','Sector','Symbol','DailyChangeTreeMap', 'Condition','Description'])
link_ref = '{}'
df['Symbol'] = df['Symbol'].apply(lambda item: link_ref.format(item, item, "{}"))

df = pd.DataFrame(df)

def filter_df(input_date,country_name):
    input_date = datetime.strptime (str(input_date), '%Y-%m-%d')
    df['date'] = pd.to_datetime(df['date'])
    df.fillna(0, inplace=True)

    if country_name:
        df2 = df[(df['date'] == input_date) & (df['Country']==country_name)]
    else:
        df2 = df
    return df2

def create_dropdown(option, id_value):
    return html.Div(
        [
            dcc.Dropdown(id=id_value, options=option,
                     value=option[0],
                     style = {}
                     ),
        ],
    )

layout = html.Div([
        html.Div(
                children=[html.H1('Stock Market Summary',),
                html.P('''AI predictions, intraday market price action, biggest movers, H1 sectors performance, and more.''',
                )], id="header", className="row flex-display header", style={"display": "flex", "flex-direction": "column"},),

        html.Div(
                html.Div(children=[
                    html.Div(
                    children=create_dropdown(Drag_option, "Theme-select"),className="theme_dropdown",
                ),
                html.Div(children=[html.Div(id='output-container-date-picker-single',),
                dcc.DatePickerSingle(
                    id='my-date-picker-single',
                    min_date_allowed=date(1995, 8, 5),
                    max_date_allowed=date(2023, 9, 19),
                    initial_visible_month=date(2022, 12, 31),
                    date=date(2022, 10, 21),
                    style={'width':'200px'}
                ) ],className="date_container"),
                    html.Button('Theme', id='btn-nclicks-1', n_clicks=0),
                # dcc.Input(type='checkbox',className="toggle-button"),
                html.Div(children=create_dropdown(Country_option,"dd-output-container"),className="contry_dropdown"),
                    ]),className="primary-navigation row flex-display",id="header", style={"margin-bottom": "25px"}
        ),

        html.Div([
                html.Div([
                    dcc.Graph(id="indicatorr")], className="graph create_container2 twelve columns"),
                    ], className="row flex-display"),

        html.Div([
            html.Div([
                html.H3('Thank You',)],className="footer create_container2 twelve columns",)
            ]),

    ],className="main",id="mainContainer", style = {'backgroundColor':'#3d3d3b', 'textAlign': 'center',"display": "flex", "flex-direction": "column"})

@dash.callback(
    Output('indicatorr','figure'),
    Input("Theme-select","value"),
    Input('my-date-picker-single', 'date'),
    Input(component_id='dd-output-container', component_property='value')
)

def update_output(theme_select, my_date_picker_single,dd_output_container):
    """
        Updating Tree MAp as per filter
    """
    if theme_select == 'Dark Theme':
        # color_discrete_map=["#ff4d00","#a13023","#21b811"]
        color_discrete_map=["#ff4d00","#21b811"]
    elif theme_select == 'Light Theme':
            color_discrete_map=["#DC3714","#C0C0C0","#19BD1B","#474745"]
    else:
        color_discrete_map=["#ff4d00","#a13023","#21b811"]

    filtered_df = filter_df(my_date_picker_single,dd_output_container)
    if filtered_df.empty:
        print("Dataframe is empty")
        return "DATAFRAME IS EMPTY"
    else:
        print("NOT EMPTY")
        indicator = px.treemap(filtered_df,
                    color=COLOR,
                    color_continuous_scale=color_discrete_map,
                    path = PATH,
                    # template='plotly_white',
                    maxdepth=3,
                    hover_data=HOVER_DATA,
                    values=value_attribute,
                    color_discrete_map=color_discrete_map)

        indicator.update_traces(textfont_size=16,)
        indicator.update_layout(margin = dict(t=35, l=5, r=5, b=5),
                        paper_bgcolor='rgba(0,0,255,0)',
                        plot_bgcolor='rgba(0,0,255,0)',
                        # coloraxis_showscale=False
                        )
        indicator.data[0].hovertemplate = Hover_Tmp

        # indicator.data[0].texttemplate ="%{label} %
Market Cap.:%{value:0.3s}"
        indicator.data[0].texttemplate ="%{label}
%{customdata[14]} %
Market Cap.:%{value:0.3s}"

        return indicator

here you can see that it's rendering as a html component, as return method

below code is working as my need, but with pio.show() method & in above code i am not using fig.show

fig1 = px.treemap(df, path=['continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'],
                  color_continuous_scale='RdBu',
                  color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
pio.show(fig1,
         post_script = "/* this works if there is only one Plotly plot on web page */" +
         "setTimeout(function() {" +
         "  el = document.querySelector('div.plotly-graph-div.js-plotly-plot'); " +
         "  /* Plotly event */" +
         "  el.on('plotly_hover', function(d){" +
         "    pth = d.points[0].currentPath;"     +
         "    if(pth === '/' || pth === 'world/') {    /* if root or first root child (a parent) */" +
         "       ght = document.querySelector('g.hoverlayer');"
         "       ght.innerHTML = ''; /* remove hovertext */" +
         "    }" +
         "  });" +
         "}, 200)")

i am uploading the screenshots of what i want with the code & what actually i am exprecting

this is homepage

This hover i don't want

This hover only I want

hover effect only on the child element.


问:
WPF Control size is not the same as design at runtime
I am creating a WPF application based on a book using Visual Studio 2022 Community. The problem is with how the UI looks different at runtime.

The problem is with the TextBox at the bottom. It only looks like what it suppose to after i try to resize the window a little.

Designer:

Running:

Here is my XAML code:

```<code><Window x:Class="FontViewer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FontViewer"
        mc:Ignorable="d"
        Title="Font Viewer" Height="480" Width="800">
    <DockPanel>
        <Border DockPanel.Dock="Top"
                CornerRadius="6"
                BorderThickness="1"
                BorderBrush="Gray"
                Background="LightGray"
                Padding="8"
                Margin="4 4 4 4"
        >
            <TextBlock FontSize="14"
                       TextWrapping="Wrap">
                Select a font to view from the list below.
                You can change the text by typing in the region at the bottom.
            </TextBlock>
        </Border>
        <ListBox x:Name="FontList"
                 DockPanel.Dock="Left"
                 ItemsSource="{x:Static Fonts.SystemFontFamilies}"
                 Width="160"
                 Margin="4 4 0 4"/>
        <TextBox x:Name="SampleText"
                 DockPanel.Dock="Bottom"
                 MinLines="4"
                 Margin="8 0 8 4"
                 TextWrapping="Wrap"
                 ToolTip="Type here to change the preview text.">
            The quick brown fox jumps over the lazy dog.
        </TextBox>
        <StackPanel Margin="8 4 8 4">
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="10"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="16"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="24"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="32"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
        </StackPanel>
    </DockPanel>
</Window>
</code>```

I have tried to mess around with the Margin but still in vain.

Do you know the how to fix this?

Body:
I am creating a WPF application based on a book using Visual Studio 2022 Community. The problem is with how the UI looks different at runtime.

The problem is with the TextBox at the bottom. It only looks like what it suppose to after i try to resize the window a little.

Designer:

Running:

Here is my XAML code:

<Window x:Class="FontViewer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FontViewer"
        mc:Ignorable="d"
        Title="Font Viewer" Height="480" Width="800">
    <DockPanel>
        <Border DockPanel.Dock="Top"
                CornerRadius="6"
                BorderThickness="1"
                BorderBrush="Gray"
                Background="LightGray"
                Padding="8"
                Margin="4 4 4 4"
        >
            <TextBlock FontSize="14"
                       TextWrapping="Wrap">
                Select a font to view from the list below.
                You can change the text by typing in the region at the bottom.
            </TextBlock>
        </Border>
        <ListBox x:Name="FontList"
                 DockPanel.Dock="Left"
                 ItemsSource="{x:Static Fonts.SystemFontFamilies}"
                 Width="160"
                 Margin="4 4 0 4"/>
        <TextBox x:Name="SampleText"
                 DockPanel.Dock="Bottom"
                 MinLines="4"
                 Margin="8 0 8 4"
                 TextWrapping="Wrap"
                 ToolTip="Type here to change the preview text.">
            The quick brown fox jumps over the lazy dog.
        </TextBox>
        <StackPanel Margin="8 4 8 4">
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="10"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="16"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="24"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
            <TextBlock Text="{Binding ElementName=SampleText, Path=Text}"
                       FontFamily="{Binding ElementName=FontList, Path=SelectedItem}"
                       FontSize="32"
                       TextWrapping="Wrap"
                       Margin="0 0 0 4"/>
        </StackPanel>
    </DockPanel>
</Window>

I have tried to mess around with the Margin but still in vain.

Do you know the how to fix this?


问:
Failed to deserialize Avro record : Getting ArrayIndexOutOfBoundsException
I am trying to read from Kafka with Avro format using Pyflink

My Program is this :

```<code>from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors.kafka import FlinkKafkaConsumer
from pyflink.datastream.formats.avro import AvroRowDeserializationSchema,AvroSchema
from pyflink.table import StreamTableEnvironment

avro_schema = """{"type":"record","name":"NewName","fields":[{"name":"id","type":"long"},{"name":"UserId","type":["null","long"],"default":null},{"name":"fffId","type":["null","int"],"default":null},{"name":"gtbId","type":["null","string"],"default":null},{"name":"TimeofTrans","type":["null",{"type":"long","connect.version":1,"connect.name":"org.apache.kafka.connect.data.Timestamp","logicalType":"timestamp-millis"}],"default":null},{"name":"CheckType","type":["null","string"],"default":null}],"connect.name":"NewName"}"""

# initial setup
env = StreamExecutionEnvironment.get_execution_environment()

env.add_jars("file:///Desktop/Projects/streaming/flink_py_test/flink-sql-connector-kafka-1.16.0.jar")
env.add_jars("file:///Desktop/Projects/streaming/flink_py_test/flink-sql-avro-1.16.0.jar")

# getting the table env for SQL
deserialization_schema = AvroRowDeserializationSchema(
    avro_schema_string=avro_schema
)

kafka_consumer = FlinkKafkaConsumer(
    topics='NewTopicName',
    deserialization_schema=deserialization_schema,
    properties={'bootstrap.servers': '172.10.10.10:9092,172.20.10.10:9092,172.30.10.10:9092', 'group.id': 'test_group_1'}
)
kafka_consumer.set_start_from_latest()
source = env.add_source(kafka_consumer).print()

env.execute()
</code>```

It is giving ArrayIndexOutOfBoundException. I have tried using the KafkaConsumer class and FlinkKafkaConsumer class to create a consumer and tried to specify the deserialization using the AvroDeserializationSchema. None of them worked.

```<code>    org.apache.flink.runtime.client.JobExecutionException: Job execution failed.
        at org.apache.flink.runtime.jobmaster.JobResult.toJobExecutionResult(JobResult.java:144)
        at org.apache.flink.runtime.minicluster.MiniClusterJobClient.lambda$getJobExecutionResult$3(MiniClusterJobClient.java:141)
        at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:642)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073)
        at org.apache.flink.runtime.rpc.akka.AkkaInvocationHandler.lambda$invokeRpc$1(AkkaInvocationHandler.java:268)
        at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
        at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073)
        at org.apache.flink.util.concurrent.FutureUtils.doForward(FutureUtils.java:1277)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.lambda$null$1(ClassLoadingUtils.java:93)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.runWithContextClassLoader(ClassLoadingUtils.java:68)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.lambda$guardCompletionWithContextClassLoader$2(ClassLoadingUtils.java:92)
        at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
        at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073)
        at org.apache.flink.runtime.concurrent.akka.AkkaFutureUtils$1.onComplete(AkkaFutureUtils.java:47)
        at akka.dispatch.OnComplete.internal(Future.scala:300)
        at akka.dispatch.OnComplete.internal(Future.scala:297)
        at akka.dispatch.japi$CallbackBridge.apply(Future.scala:224)
        at akka.dispatch.japi$CallbackBridge.apply(Future.scala:221)
        at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
        at org.apache.flink.runtime.concurrent.akka.AkkaFutureUtils$DirectExecutionContext.execute(AkkaFutureUtils.java:65)
        at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)
        at scala.concurrent.impl.Promise$DefaultPromise.$anonfun$tryComplete$1(Promise.scala:284)
        at scala.concurrent.impl.Promise$DefaultPromise.$anonfun$tryComplete$1$adapted(Promise.scala:284)
        at scala.concurrent.impl.Promise$DefaultPromise.tryComplete(Promise.scala:284)
        at akka.pattern.PromiseActorRef.$bang(AskSupport.scala:621)
        at akka.pattern.PipeToSupport$PipeableFuture$$anonfun$pipeTo$1.applyOrElse(PipeToSupport.scala:24)
        at akka.pattern.PipeToSupport$PipeableFuture$$anonfun$pipeTo$1.applyOrElse(PipeToSupport.scala:23)
        at scala.concurrent.Future.$anonfun$andThen$1(Future.scala:532)
        at scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
        at scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
        at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
        at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:63)
        at akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:100)
        at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
        at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)
        at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:100)
        at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:49)
        at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:48)
        at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
        at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
        at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
        at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
        at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
    Caused by: org.apache.flink.runtime.JobException: Recovery is suppressed by NoRestartBackoffTimeStrategy
        at org.apache.flink.runtime.executiongraph.failover.flip1.ExecutionFailureHandler.handleFailure(ExecutionFailureHandler.java:139)
        at org.apache.flink.runtime.executiongraph.failover.flip1.ExecutionFailureHandler.getFailureHandlingResult(ExecutionFailureHandler.java:83)
        at org.apache.flink.runtime.scheduler.DefaultScheduler.recordTaskFailure(DefaultScheduler.java:256)
        at org.apache.flink.runtime.scheduler.DefaultScheduler.handleTaskFailure(DefaultScheduler.java:247)
        at org.apache.flink.runtime.scheduler.DefaultScheduler.onTaskFailed(DefaultScheduler.java:240)
        at org.apache.flink.runtime.scheduler.SchedulerBase.onTaskExecutionStateUpdate(SchedulerBase.java:738)
        at org.apache.flink.runtime.scheduler.SchedulerBase.updateTaskExecutionState(SchedulerBase.java:715)
        at org.apache.flink.runtime.scheduler.SchedulerNG.updateTaskExecutionState(SchedulerNG.java:78)
        at org.apache.flink.runtime.jobmaster.JobMaster.updateTaskExecutionState(JobMaster.java:477)
        at jdk.internal.reflect.GeneratedMethodAccessor11.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.lambda$handleRpcInvocation$1(AkkaRpcActor.java:309)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.runWithContextClassLoader(ClassLoadingUtils.java:83)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRpcInvocation(AkkaRpcActor.java:307)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRpcMessage(AkkaRpcActor.java:222)
        at org.apache.flink.runtime.rpc.akka.FencedAkkaRpcActor.handleRpcMessage(FencedAkkaRpcActor.java:84)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleMessage(AkkaRpcActor.java:168)
        at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:24)
        at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:20)
        at scala.PartialFunction.applyOrElse(PartialFunction.scala:123)
        at scala.PartialFunction.applyOrElse$(PartialFunction.scala:122)
        at akka.japi.pf.UnitCaseStatement.applyOrElse(CaseStatements.scala:20)
        at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:171)
        at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:172)
        at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:172)
        at akka.actor.Actor.aroundReceive(Actor.scala:537)
        at akka.actor.Actor.aroundReceive$(Actor.scala:535)
        at akka.actor.AbstractActor.aroundReceive(AbstractActor.scala:220)
        at akka.actor.ActorCell.receiveMessage(ActorCell.scala:580)
        at akka.actor.ActorCell.invoke(ActorCell.scala:548)
        at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:270)
        at akka.dispatch.Mailbox.run(Mailbox.scala:231)
        at akka.dispatch.Mailbox.exec(Mailbox.scala:243)
        ... 5 more
    Caused by: java.io.IOException: Failed to deserialize Avro record.
        at org.apache.flink.formats.avro.AvroRowDeserializationSchema.deserialize(AvroRowDeserializationSchema.java:167)
        at org.apache.flink.formats.avro.AvroRowDeserializationSchema.deserialize(AvroRowDeserializationSchema.java:85)
        at org.apache.flink.api.common.serialization.DeserializationSchema.deserialize(DeserializationSchema.java:82)
        at org.apache.flink.streaming.connectors.kafka.internals.KafkaDeserializationSchemaWrapper.deserialize(KafkaDeserializationSchemaWrapper.java:58)
        at org.apache.flink.streaming.connectors.kafka.internals.KafkaFetcher.partitionConsumerRecordsHandler(KafkaFetcher.java:179)
        at org.apache.flink.streaming.connectors.kafka.internals.KafkaFetcher.runFetchLoop(KafkaFetcher.java:142)
        at org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumerBase.run(FlinkKafkaConsumerBase.java:826)
        at org.apache.flink.streaming.api.operators.StreamSource.run(StreamSource.java:110)
        at org.apache.flink.streaming.api.operators.StreamSource.run(StreamSource.java:67)
        at org.apache.flink.streaming.runtime.tasks.SourceStreamTask$LegacySourceFunctionThread.run(SourceStreamTask.java:333)
    Caused by: java.lang.ArrayIndexOutOfBoundsException: Index 25 out of bounds for length 2
        at org.apache.flink.avro.shaded.org.apache.avro.io.parsing.Symbol$Alternative.getSymbol(Symbol.java:460)
        at org.apache.flink.avro.shaded.org.apache.avro.io.ResolvingDecoder.readIndex(ResolvingDecoder.java:283)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:188)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:161)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:260)
        at org.apache.flink.avro.shaded.org.apache.avro.specific.SpecificDatumReader.readField(SpecificDatumReader.java:142)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:248)
        at org.apache.flink.avro.shaded.org.apache.avro.specific.SpecificDatumReader.readRecord(SpecificDatumReader.java:123)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:180)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:161)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:154)
        at org.apache.flink.formats.avro.AvroRowDeserializationSchema.deserialize(AvroRowDeserializationSchema.java:164)
        ... 9 more
</code>```

Body:
I am trying to read from Kafka with Avro format using Pyflink

My Program is this :

from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors.kafka import FlinkKafkaConsumer
from pyflink.datastream.formats.avro import AvroRowDeserializationSchema,AvroSchema
from pyflink.table import StreamTableEnvironment

avro_schema = """{"type":"record","name":"NewName","fields":[{"name":"id","type":"long"},{"name":"UserId","type":["null","long"],"default":null},{"name":"fffId","type":["null","int"],"default":null},{"name":"gtbId","type":["null","string"],"default":null},{"name":"TimeofTrans","type":["null",{"type":"long","connect.version":1,"connect.name":"org.apache.kafka.connect.data.Timestamp","logicalType":"timestamp-millis"}],"default":null},{"name":"CheckType","type":["null","string"],"default":null}],"connect.name":"NewName"}"""

# initial setup
env = StreamExecutionEnvironment.get_execution_environment()

env.add_jars("file:///Desktop/Projects/streaming/flink_py_test/flink-sql-connector-kafka-1.16.0.jar")
env.add_jars("file:///Desktop/Projects/streaming/flink_py_test/flink-sql-avro-1.16.0.jar")

# getting the table env for SQL
deserialization_schema = AvroRowDeserializationSchema(
    avro_schema_string=avro_schema
)

kafka_consumer = FlinkKafkaConsumer(
    topics='NewTopicName',
    deserialization_schema=deserialization_schema,
    properties={'bootstrap.servers': '172.10.10.10:9092,172.20.10.10:9092,172.30.10.10:9092', 'group.id': 'test_group_1'}
)
kafka_consumer.set_start_from_latest()
source = env.add_source(kafka_consumer).print()

env.execute()

It is giving ArrayIndexOutOfBoundException. I have tried using the KafkaConsumer class and FlinkKafkaConsumer class to create a consumer and tried to specify the deserialization using the AvroDeserializationSchema. None of them worked.

    org.apache.flink.runtime.client.JobExecutionException: Job execution failed.
        at org.apache.flink.runtime.jobmaster.JobResult.toJobExecutionResult(JobResult.java:144)
        at org.apache.flink.runtime.minicluster.MiniClusterJobClient.lambda$getJobExecutionResult$3(MiniClusterJobClient.java:141)
        at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:642)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073)
        at org.apache.flink.runtime.rpc.akka.AkkaInvocationHandler.lambda$invokeRpc$1(AkkaInvocationHandler.java:268)
        at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
        at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073)
        at org.apache.flink.util.concurrent.FutureUtils.doForward(FutureUtils.java:1277)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.lambda$null$1(ClassLoadingUtils.java:93)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.runWithContextClassLoader(ClassLoadingUtils.java:68)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.lambda$guardCompletionWithContextClassLoader$2(ClassLoadingUtils.java:92)
        at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859)
        at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073)
        at org.apache.flink.runtime.concurrent.akka.AkkaFutureUtils$1.onComplete(AkkaFutureUtils.java:47)
        at akka.dispatch.OnComplete.internal(Future.scala:300)
        at akka.dispatch.OnComplete.internal(Future.scala:297)
        at akka.dispatch.japi$CallbackBridge.apply(Future.scala:224)
        at akka.dispatch.japi$CallbackBridge.apply(Future.scala:221)
        at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
        at org.apache.flink.runtime.concurrent.akka.AkkaFutureUtils$DirectExecutionContext.execute(AkkaFutureUtils.java:65)
        at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)
        at scala.concurrent.impl.Promise$DefaultPromise.$anonfun$tryComplete$1(Promise.scala:284)
        at scala.concurrent.impl.Promise$DefaultPromise.$anonfun$tryComplete$1$adapted(Promise.scala:284)
        at scala.concurrent.impl.Promise$DefaultPromise.tryComplete(Promise.scala:284)
        at akka.pattern.PromiseActorRef.$bang(AskSupport.scala:621)
        at akka.pattern.PipeToSupport$PipeableFuture$$anonfun$pipeTo$1.applyOrElse(PipeToSupport.scala:24)
        at akka.pattern.PipeToSupport$PipeableFuture$$anonfun$pipeTo$1.applyOrElse(PipeToSupport.scala:23)
        at scala.concurrent.Future.$anonfun$andThen$1(Future.scala:532)
        at scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
        at scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
        at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
        at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:63)
        at akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:100)
        at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
        at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)
        at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:100)
        at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:49)
        at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:48)
        at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
        at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
        at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
        at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
        at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
    Caused by: org.apache.flink.runtime.JobException: Recovery is suppressed by NoRestartBackoffTimeStrategy
        at org.apache.flink.runtime.executiongraph.failover.flip1.ExecutionFailureHandler.handleFailure(ExecutionFailureHandler.java:139)
        at org.apache.flink.runtime.executiongraph.failover.flip1.ExecutionFailureHandler.getFailureHandlingResult(ExecutionFailureHandler.java:83)
        at org.apache.flink.runtime.scheduler.DefaultScheduler.recordTaskFailure(DefaultScheduler.java:256)
        at org.apache.flink.runtime.scheduler.DefaultScheduler.handleTaskFailure(DefaultScheduler.java:247)
        at org.apache.flink.runtime.scheduler.DefaultScheduler.onTaskFailed(DefaultScheduler.java:240)
        at org.apache.flink.runtime.scheduler.SchedulerBase.onTaskExecutionStateUpdate(SchedulerBase.java:738)
        at org.apache.flink.runtime.scheduler.SchedulerBase.updateTaskExecutionState(SchedulerBase.java:715)
        at org.apache.flink.runtime.scheduler.SchedulerNG.updateTaskExecutionState(SchedulerNG.java:78)
        at org.apache.flink.runtime.jobmaster.JobMaster.updateTaskExecutionState(JobMaster.java:477)
        at jdk.internal.reflect.GeneratedMethodAccessor11.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.lambda$handleRpcInvocation$1(AkkaRpcActor.java:309)
        at org.apache.flink.runtime.concurrent.akka.ClassLoadingUtils.runWithContextClassLoader(ClassLoadingUtils.java:83)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRpcInvocation(AkkaRpcActor.java:307)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleRpcMessage(AkkaRpcActor.java:222)
        at org.apache.flink.runtime.rpc.akka.FencedAkkaRpcActor.handleRpcMessage(FencedAkkaRpcActor.java:84)
        at org.apache.flink.runtime.rpc.akka.AkkaRpcActor.handleMessage(AkkaRpcActor.java:168)
        at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:24)
        at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:20)
        at scala.PartialFunction.applyOrElse(PartialFunction.scala:123)
        at scala.PartialFunction.applyOrElse$(PartialFunction.scala:122)
        at akka.japi.pf.UnitCaseStatement.applyOrElse(CaseStatements.scala:20)
        at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:171)
        at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:172)
        at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:172)
        at akka.actor.Actor.aroundReceive(Actor.scala:537)
        at akka.actor.Actor.aroundReceive$(Actor.scala:535)
        at akka.actor.AbstractActor.aroundReceive(AbstractActor.scala:220)
        at akka.actor.ActorCell.receiveMessage(ActorCell.scala:580)
        at akka.actor.ActorCell.invoke(ActorCell.scala:548)
        at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:270)
        at akka.dispatch.Mailbox.run(Mailbox.scala:231)
        at akka.dispatch.Mailbox.exec(Mailbox.scala:243)
        ... 5 more
    Caused by: java.io.IOException: Failed to deserialize Avro record.
        at org.apache.flink.formats.avro.AvroRowDeserializationSchema.deserialize(AvroRowDeserializationSchema.java:167)
        at org.apache.flink.formats.avro.AvroRowDeserializationSchema.deserialize(AvroRowDeserializationSchema.java:85)
        at org.apache.flink.api.common.serialization.DeserializationSchema.deserialize(DeserializationSchema.java:82)
        at org.apache.flink.streaming.connectors.kafka.internals.KafkaDeserializationSchemaWrapper.deserialize(KafkaDeserializationSchemaWrapper.java:58)
        at org.apache.flink.streaming.connectors.kafka.internals.KafkaFetcher.partitionConsumerRecordsHandler(KafkaFetcher.java:179)
        at org.apache.flink.streaming.connectors.kafka.internals.KafkaFetcher.runFetchLoop(KafkaFetcher.java:142)
        at org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumerBase.run(FlinkKafkaConsumerBase.java:826)
        at org.apache.flink.streaming.api.operators.StreamSource.run(StreamSource.java:110)
        at org.apache.flink.streaming.api.operators.StreamSource.run(StreamSource.java:67)
        at org.apache.flink.streaming.runtime.tasks.SourceStreamTask$LegacySourceFunctionThread.run(SourceStreamTask.java:333)
    Caused by: java.lang.ArrayIndexOutOfBoundsException: Index 25 out of bounds for length 2
        at org.apache.flink.avro.shaded.org.apache.avro.io.parsing.Symbol$Alternative.getSymbol(Symbol.java:460)
        at org.apache.flink.avro.shaded.org.apache.avro.io.ResolvingDecoder.readIndex(ResolvingDecoder.java:283)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:188)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:161)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:260)
        at org.apache.flink.avro.shaded.org.apache.avro.specific.SpecificDatumReader.readField(SpecificDatumReader.java:142)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:248)
        at org.apache.flink.avro.shaded.org.apache.avro.specific.SpecificDatumReader.readRecord(SpecificDatumReader.java:123)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:180)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:161)
        at org.apache.flink.avro.shaded.org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:154)
        at org.apache.flink.formats.avro.AvroRowDeserializationSchema.deserialize(AvroRowDeserializationSchema.java:164)
        ... 9 more


问:
Promise based system to handle global state in MV3 chrome extensions (now that we cant use stateful global variables)
So I'm in the process of migrating from an MV2(persistent background page) extension to an MV3(non-persistent service worker). Now we cant use global variables to store any kind of state(Eg let's say a click counter). So according to official migration docs of google in order to tackle the problem we should use chrome Storage API as our single source of truth. But we also need to take care of "clearing" storage as we don't want global variables to persist across different browser sessions. (Eg:-Think of a case where an extension counts how many tabs are opened in a single  browser "session").

I developed a promise based solution to handle state . Here is what I did .

I store a global object in chrome storage  which stores all app state

I have a promise globalVariablesFetched that resolves with the global variables value and initializes globals variable after fetching data from storage

There is a function waitForGlobalsFetch that takes a fn & returns a wrapper fn .The returned fn is nothing but the callback passed in argument awaited for the globalVariablesFetched promise. All event listeners that read/write global state need to be wrapped in this.

You would notice i have done

```<code>if (isResponseCallback) return true;
</code>```

This allows us to return true based on whether/not we are calling responseCallback inside listener. here responsecallback is nothing but the callback for onmessage (if any). Since we are going to call callback asynchronously(if any) we return true to inform it to keep connection alive.

Whenever Im setting/updating global state im updating both local & storage copy.

OnInstalled and onStartup i have cleared globals as its a new "session", so get rid of old state. We have a initializeGlobals function that initializes all globals with default state

So this is my system so far . It works fine now . But im not sure if it is totally correct or if I am missing something. Is this an accurate way of doing it ? Are there any better ways?

If someone who has migrated/is in the process to MV3 can share your methods.

background.js

```<code>let globals=null; //stateful global variables object

//fetch all the global variables first .
const globalVariablesFetched = new Promise((resolve,reject)=>{
    chrome.storage.local.get(["globals"], (obj) => {
        globals=obj.globals;
        resolve(obj);
      });
})

/**
 * wrapper function to make callback wait till globals are fetched
 * use this if a function has dependency on stateful global variables
 * @param  {Function} callback function which needs to await global fetch
 * @param {boolean} isResponseCallback if wrapped function is an event listener which calls sendResponse callback(of sendMessage)
 * @return {Function} Wrapped function that awaits globalsFetch
 */
 function waitForGlobalsFetch(callback,isResponseCallback=false)
 {
    const wrappedFn = (...args)=>{
        globalVariablesFetched.then(()=>callback(...args));
        if (isResponseCallback) return true;
        //return true lets us call response callback (for onMessage) asynchronously
    }
    return wrappedFn;
 }

/**
 * sets global variable in chrome storage and also updates local copy
 */
function setGlobalProperty(keyname,value)
{
    if (globals) globals[keyname]=value;
    globalVariablesFetched.then(()=>{
        globals[keyname]=value; // update (temporary)local copy
        chrome.storage.local.set({ globals }); //update storage copy
    })
}

//need to (re)initialize global variables at the start of a session eg when chrome is reopened
function initializeGlobals()
{
    //wait till globalsVariables are fetched to overwrite ,in order to avoid race condition
    globalVariablesFetched.then(()=>{
        globals = {
            openedTabs: [],
            clickCount:0
        };
        chrome.storage.local.set({ globals });
    });
}

//extension refresh
chrome.runtime.onInstalled.addListener(initializeGlobals);

//chrome closed and then started again
chrome.runtime.onStartup.addListener(initializeGlobals);
</code>```

Note - Sorry for long & opinion based question . I dont see much discussion/articles around state management in MV3.

Body:
So I'm in the process of migrating from an MV2(persistent background page) extension to an MV3(non-persistent service worker). Now we cant use global variables to store any kind of state(Eg let's say a click counter). So according to official migration docs of google in order to tackle the problem we should use chrome Storage API as our single source of truth. But we also need to take care of "clearing" storage as we don't want global variables to persist across different browser sessions. (Eg:-Think of a case where an extension counts how many tabs are opened in a single  browser "session").

I developed a promise based solution to handle state . Here is what I did .

I store a global object in chrome storage  which stores all app state

I have a promise globalVariablesFetched that resolves with the global variables value and initializes globals variable after fetching data from storage

There is a function waitForGlobalsFetch that takes a fn & returns a wrapper fn .The returned fn is nothing but the callback passed in argument awaited for the globalVariablesFetched promise. All event listeners that read/write global state need to be wrapped in this.

You would notice i have done

if (isResponseCallback) return true;

This allows us to return true based on whether/not we are calling responseCallback inside listener. here responsecallback is nothing but the callback for onmessage (if any). Since we are going to call callback asynchronously(if any) we return true to inform it to keep connection alive.

Whenever Im setting/updating global state im updating both local & storage copy.

OnInstalled and onStartup i have cleared globals as its a new "session", so get rid of old state. We have a initializeGlobals function that initializes all globals with default state

So this is my system so far . It works fine now . But im not sure if it is totally correct or if I am missing something. Is this an accurate way of doing it ? Are there any better ways?

If someone who has migrated/is in the process to MV3 can share your methods.

background.js

let globals=null; //stateful global variables object

//fetch all the global variables first .
const globalVariablesFetched = new Promise((resolve,reject)=>{
    chrome.storage.local.get(["globals"], (obj) => {
        globals=obj.globals;
        resolve(obj);
      });
})

/**
 * wrapper function to make callback wait till globals are fetched
 * use this if a function has dependency on stateful global variables
 * @param  {Function} callback function which needs to await global fetch
 * @param {boolean} isResponseCallback if wrapped function is an event listener which calls sendResponse callback(of sendMessage)
 * @return {Function} Wrapped function that awaits globalsFetch
 */
 function waitForGlobalsFetch(callback,isResponseCallback=false)
 {
    const wrappedFn = (...args)=>{
        globalVariablesFetched.then(()=>callback(...args));
        if (isResponseCallback) return true;
        //return true lets us call response callback (for onMessage) asynchronously
    }
    return wrappedFn;
 }

/**
 * sets global variable in chrome storage and also updates local copy
 */
function setGlobalProperty(keyname,value)
{
    if (globals) globals[keyname]=value;
    globalVariablesFetched.then(()=>{
        globals[keyname]=value; // update (temporary)local copy
        chrome.storage.local.set({ globals }); //update storage copy
    })
}

//need to (re)initialize global variables at the start of a session eg when chrome is reopened
function initializeGlobals()
{
    //wait till globalsVariables are fetched to overwrite ,in order to avoid race condition
    globalVariablesFetched.then(()=>{
        globals = {
            openedTabs: [],
            clickCount:0
        };
        chrome.storage.local.set({ globals });
    });
}

//extension refresh
chrome.runtime.onInstalled.addListener(initializeGlobals);

//chrome closed and then started again
chrome.runtime.onStartup.addListener(initializeGlobals);

Note - Sorry for long & opinion based question . I dont see much discussion/articles around state management in MV3.


问:
How to migrate GKE Ingress from TCP to External HTTPS loadbalancer
So our current situation is that we are running a GKE cluster with a TCP Proxy loadbalancer with regional IP. Many of our domains are managed externally (by customers).

For quite some time we want to migrate towards a external HTTPS loadbalancer. There is (as far as I'm aware) no direct upgrade path, because the external HTTPS loadbalancer uses a global static IP. Because of the setup above this can't be done instantly, but needs to plan for a longer migration.

I haven't found any documentation towards resolving this situation. My first guess would be to run both loadbalancer (with same paths) in parallel for some time or point the TCP Proxy loadbalancer towards the external HTTPS one. How would that work?


问:
BufferedImage text poor quality with antialiasing and high DPI
I'm trying to write a String to a BufferedImage but it is either horribly pixelated (without antialiasing) or blurry (with antialiasing).

I've tried increasing the DPI when I write the image to an OutputStream and whilst there is some improvement - it's still not great.

Here is the code to generate the image:

```<code>    BufferedImage generateImage(String text) throws IOException {
        Font font = new Font("Arial", Font.BOLD, 10);
        int height;
        int width;
        BufferedImage temp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D tempGraphics = temp.createGraphics();
        tempGraphics.setFont(font);
        FontMetrics metrics = tempGraphics.getFontMetrics();
        height= metrics.getHeight();
        width = metrics.stringWidth(text);

        final BufferedImage image = new BufferedImage(height + 1, width + 1, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics = image.createGraphics();

        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        graphics.setFont(FONT);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width + 1, heigth + 1);
        graphics.setColor(Color.BLACK);
        graphics.drawString(text, 1, metrics.getAscent() + 1.5f);
        graphics.dispose();

        return image;
    }
</code>```

And here is the code to write the image to a byte array:

```<code>    byte[] imageToOutputStream(BufferedImage image) throws IOException {
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam writeParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
        IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);

        setDpi(metadata);

        writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        writeParam.setCompressionQuality(1f);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);

        writer.setOutput(ios);
        writer.write(metadata, new IIOImage(image, null, metadata), writeParam);

        baos.toByteArray();
    }
</code>```

And finally the code to set the DPI of the metadata used to write the image:

```<code>    void setDpiJpg(IIOMetadata metadata) throws IIOInvalidTreeException {
        String metadataFormat = "javax_imageio_jpeg_image_1.0";
        IIOMetadataNode root = new IIOMetadataNode(metadataFormat);
        IIOMetadataNode jpegVariety = new IIOMetadataNode("JPEGvariety");
        IIOMetadataNode markerSequence = new IIOMetadataNode("markerSequence");

        IIOMetadataNode app0JFIF = new IIOMetadataNode("app0JFIF");
        app0JFIF.setAttribute("majorVersion", "1");
        app0JFIF.setAttribute("minorVersion", "2");
        app0JFIF.setAttribute("thumbWidth", "0");
        app0JFIF.setAttribute("thumbHeight", "0");
        app0JFIF.setAttribute("resUnits", "01");
        app0JFIF.setAttribute("Xdensity", String.valueOf(300));
        app0JFIF.setAttribute("Ydensity", String.valueOf(300));

        root.appendChild(jpegVariety);
        root.appendChild(markerSequence);
        jpegVariety.appendChild(app0JFIF);

        metadata.mergeTree(metadataFormat, root);
    }
</code>```

I've read here that it has something to do with the scale of the image but I must admit I'm lost.

Body:
I'm trying to write a String to a BufferedImage but it is either horribly pixelated (without antialiasing) or blurry (with antialiasing).

I've tried increasing the DPI when I write the image to an OutputStream and whilst there is some improvement - it's still not great.

Here is the code to generate the image:

    BufferedImage generateImage(String text) throws IOException {
        Font font = new Font("Arial", Font.BOLD, 10);
        int height;
        int width;
        BufferedImage temp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D tempGraphics = temp.createGraphics();
        tempGraphics.setFont(font);
        FontMetrics metrics = tempGraphics.getFontMetrics();
        height= metrics.getHeight();
        width = metrics.stringWidth(text);

        final BufferedImage image = new BufferedImage(height + 1, width + 1, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics = image.createGraphics();

        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        graphics.setFont(FONT);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width + 1, heigth + 1);
        graphics.setColor(Color.BLACK);
        graphics.drawString(text, 1, metrics.getAscent() + 1.5f);
        graphics.dispose();

        return image;
    }

And here is the code to write the image to a byte array:

    byte[] imageToOutputStream(BufferedImage image) throws IOException {
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam writeParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
        IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);

        setDpi(metadata);

        writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        writeParam.setCompressionQuality(1f);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);

        writer.setOutput(ios);
        writer.write(metadata, new IIOImage(image, null, metadata), writeParam);

        baos.toByteArray();
    }

And finally the code to set the DPI of the metadata used to write the image:

    void setDpiJpg(IIOMetadata metadata) throws IIOInvalidTreeException {
        String metadataFormat = "javax_imageio_jpeg_image_1.0";
        IIOMetadataNode root = new IIOMetadataNode(metadataFormat);
        IIOMetadataNode jpegVariety = new IIOMetadataNode("JPEGvariety");
        IIOMetadataNode markerSequence = new IIOMetadataNode("markerSequence");

        IIOMetadataNode app0JFIF = new IIOMetadataNode("app0JFIF");
        app0JFIF.setAttribute("majorVersion", "1");
        app0JFIF.setAttribute("minorVersion", "2");
        app0JFIF.setAttribute("thumbWidth", "0");
        app0JFIF.setAttribute("thumbHeight", "0");
        app0JFIF.setAttribute("resUnits", "01");
        app0JFIF.setAttribute("Xdensity", String.valueOf(300));
        app0JFIF.setAttribute("Ydensity", String.valueOf(300));

        root.appendChild(jpegVariety);
        root.appendChild(markerSequence);
        jpegVariety.appendChild(app0JFIF);

        metadata.mergeTree(metadataFormat, root);
    }

I've read here that it has something to do with the scale of the image but I must admit I'm lost.


问:
Marker from Svg in Google Maps is not showing the Image from url
I have these markers in google maps

I am generating them from an svg with an <image> that has a network image.

The problem is, the markers image that should be inside is not being displayed.

Here's the code that I use to generate the marker:

```<code>import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart' show BitmapDescriptor;
import 'dart:ui' as ui;

Future<BitmapDescriptor> getAssetImageMarker(String networkImage) async {
  Size size = const Size(30, 30);
  String svgString = '''
    <svg width="100" height="100" >
      <defs>
        <pattern id="image-pattern" x="0" y="0" width="100" height="100" patternUnits="userSpaceOnUse" >
          <image href="https://images.unsplash.com/photo-1608848461950-0fe51dfc41cb" x="0" y="0" width="100" height="120" />
        </pattern>
      </defs>
      <circle cx="50" cy="50" r="40" stroke="orange" stroke-width="4" fill="url(#image-pattern)" />
    </svg>
''';

  final svgDrawableRoot = await svg.fromSvgString(svgString, 'debug: ${svgString.codeUnits}');

  final ratio = ui.window.devicePixelRatio.ceil();
  final width = size.width.ceil() * ratio;
  final height = size.height.ceil() * ratio;
  final picture = svgDrawableRoot.toPicture(
    size: Size(
      width.toDouble(),
      height.toDouble(),
    ),
  );
  final image = await picture.toImage(width, height);
  final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  final uInt8List = byteData!.buffer.asUint8List();
  return BitmapDescriptor.fromBytes(uInt8List);
}

</code>```

Is there something I am doing wrong? I tried canvas approach but this is how I got it working first.

I hope you can help me. Thanks in advance.

Body:
I have these markers in google maps

I am generating them from an svg with an <image> that has a network image.

The problem is, the markers image that should be inside is not being displayed.

Here's the code that I use to generate the marker:

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart' show BitmapDescriptor;
import 'dart:ui' as ui;

Future<BitmapDescriptor> getAssetImageMarker(String networkImage) async {
  Size size = const Size(30, 30);
  String svgString = '''
    <svg width="100" height="100" >
      <defs>
        <pattern id="image-pattern" x="0" y="0" width="100" height="100" patternUnits="userSpaceOnUse" >
          <image href="https://images.unsplash.com/photo-1608848461950-0fe51dfc41cb" x="0" y="0" width="100" height="120" />
        </pattern>
      </defs>
      <circle cx="50" cy="50" r="40" stroke="orange" stroke-width="4" fill="url(#image-pattern)" />
    </svg>
''';

  final svgDrawableRoot = await svg.fromSvgString(svgString, 'debug: ${svgString.codeUnits}');

  final ratio = ui.window.devicePixelRatio.ceil();
  final width = size.width.ceil() * ratio;
  final height = size.height.ceil() * ratio;
  final picture = svgDrawableRoot.toPicture(
    size: Size(
      width.toDouble(),
      height.toDouble(),
    ),
  );
  final image = await picture.toImage(width, height);
  final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
  final uInt8List = byteData!.buffer.asUint8List();
  return BitmapDescriptor.fromBytes(uInt8List);
}

Is there something I am doing wrong? I tried canvas approach but this is how I got it working first.

I hope you can help me. Thanks in advance.


问:
Android Jetpack Compose androidx.compose.material.SwipeToDismiss suspend fun dismiss(DismissDirection) does not trigger rememberDismissState change
My current Android application employs Jetpack Compose androidx.compose.material.SwipeToDismiss to support swipe actions on my applications lists.

This all works fine for users swipes, as I have this code to detect swipe direction and react accordingly

```<code>val dismissState = rememberDismissState(
                        confirmStateChange = { dismissValue ->
                            when (dismissValue) {
                                DismissValue.Default -> doNothing()
                                DismissValue.DismissedToEnd -> onSwipeRight(item)
                                DismissValue.DismissedToStart -> onSwipeLeft(item)
                            }
                            true
                        }
                    )
</code>```

I also have this code for when a user clicks on a list items action button to trigger dismiss as well...

```<code>IconButton(onClick = { /*TODO*/ }) {
    Icon(
        modifier = Modifier.debounceClickable {
            scope.launch {
                dismissState.dismiss(DismissDirection.StartToEnd)
                onSave(item)
            }
        },
        imageVector = Icons.Default.Save,
        contentDescription = "Save Item"
    )
}
</code>```

I was expecting calling dismissState.dismiss(DismissDirection.StartToEnd) would trigger a change in my remembered state and call the associated action. however it doesnt, I have to also call my onSave(item) function as well as triggering the dismiss.

Why is this?
Is my expectation wrong?
Is there any way I can simply call dismissState.dismiss(DismissDirection.StartToEnd) to trigger my call to onSwipeLeft(item)?

Body:
My current Android application employs Jetpack Compose androidx.compose.material.SwipeToDismiss to support swipe actions on my applications lists.

This all works fine for users swipes, as I have this code to detect swipe direction and react accordingly

val dismissState = rememberDismissState(
                        confirmStateChange = { dismissValue ->
                            when (dismissValue) {
                                DismissValue.Default -> doNothing()
                                DismissValue.DismissedToEnd -> onSwipeRight(item)
                                DismissValue.DismissedToStart -> onSwipeLeft(item)
                            }
                            true
                        }
                    )

I also have this code for when a user clicks on a list items action button to trigger dismiss as well...

IconButton(onClick = { /*TODO*/ }) {
    Icon(
        modifier = Modifier.debounceClickable {
            scope.launch {
                dismissState.dismiss(DismissDirection.StartToEnd)
                onSave(item)
            }
        },
        imageVector = Icons.Default.Save,
        contentDescription = "Save Item"
    )
}

I was expecting calling dismissState.dismiss(DismissDirection.StartToEnd) would trigger a change in my remembered state and call the associated action. however it doesnt, I have to also call my onSave(item) function as well as triggering the dismiss.

Why is this?
Is my expectation wrong?
Is there any way I can simply call dismissState.dismiss(DismissDirection.StartToEnd) to trigger my call to onSwipeLeft(item)?


问:
Server Crash due to this error Next.js project Error: npm ERR! command failed | npm ERR! signal SIGHUP | npm ERR! command sh -c next start
Next.js project build on server. After some time server crash due to this error. Please check the attached screen shot. Please help me if you have any idea.

I have tried removed node_modules and package-lock.json file and rebuild project.

I have make build with this command:

npm run build


问:
Github actions: use env variable on another env variable?
I'm trying to reuse some common variables that act as bases for other variables. But I'm not sure how to reuse it.

In my workflow I tried this:

```<code>env:
  REGISTRY: ghcr.io
  MY_REPO: ${{ env.REGISTRY }}/versada/monodoo
  MY_MAIN_TAG: ${{ env.MY_REPO }}:16.0
</code>```

If add this, what happens weirdly is that my workflow is entirely ignored and not run at all. No errors, nothing. I would expect to at least get some kind of error, saying something is not right.

Body:
I'm trying to reuse some common variables that act as bases for other variables. But I'm not sure how to reuse it.

In my workflow I tried this:

env:
  REGISTRY: ghcr.io
  MY_REPO: ${{ env.REGISTRY }}/versada/monodoo
  MY_MAIN_TAG: ${{ env.MY_REPO }}:16.0

If add this, what happens weirdly is that my workflow is entirely ignored and not run at all. No errors, nothing. I would expect to at least get some kind of error, saying something is not right.


问:
Dash v2.7+ does not support Internet Explorer. Please use a newer browser
I am trying to follow along with a Dash tutorial for python. However, when I try opening a tab with my localhost port on which my Dash App is meant to be running on, nothing is shown. When I inspect the source code I am told "Dash v2.7+ does not support Internet Explorer. Please use a newer browser.". However, I am using Microsoft Edge and Google Chrome so that does not really make sense to me.

Here is my source code:

```<code>from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
from plotly import express as px
import plotly.graph_objects as go

import pandas as pd
import numpy as np
import requests

app = Dash()
app.layout = html.Div(
    [
        html.H1("Hello World")
    ]
)

app.run_server(debug=True, port = 8152)
</code>```

I was therefore wondering what the issue is as I have tried looking it up but there does not seem to be an answer?

Body:
I am trying to follow along with a Dash tutorial for python. However, when I try opening a tab with my localhost port on which my Dash App is meant to be running on, nothing is shown. When I inspect the source code I am told "Dash v2.7+ does not support Internet Explorer. Please use a newer browser.". However, I am using Microsoft Edge and Google Chrome so that does not really make sense to me.

Here is my source code:

from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
from plotly import express as px
import plotly.graph_objects as go

import pandas as pd
import numpy as np
import requests

app = Dash()
app.layout = html.Div(
    [
        html.H1("Hello World")
    ]
)

app.run_server(debug=True, port = 8152)

I was therefore wondering what the issue is as I have tried looking it up but there does not seem to be an answer?


问:
Abstract Method Error while UI testing in Compose with MockK
I'm trying to test WorkoutScreen with the following code block.
I created a function called setView to test ViewState in different situations.

```<code>@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class WorkoutScreenTest {

    @get:Rule(order = 0)
    val hiltRule = HiltAndroidRule(this)

    @get:Rule(order = 1)
    val composeTestRule = createComposeRule()

    private val workoutViewModel = mockk<WorkoutViewModel>()

    private val playerManager = mockk<ExoplayerManager>()

    @Before
    fun setup() = runOnUiThread {
        hiltRule.inject()
        MockKAnnotations.init(this, true)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun isCircularProgressDisplayed_whenLoading() = runTest {
        setView(isLoading = true, viewState = WorkoutViewState.Loading)
        composeTestRule.onNodeWithTag("workout_loading_indicator").assertIsDisplayed()
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun isErrorTextDisplayed_whenError() = runTest {
        setView(isLoading = true, viewState = WorkoutViewState.Error("error message"))
        composeTestRule.onNodeWithText("Something went wrong").assertIsDisplayed()
    }

    private fun setView(isLoading: Boolean, viewState: WorkoutViewState) {
        runOnUiThread {
            val loading = MutableStateFlow(isLoading)
            val state = MutableStateFlow(viewState)
            val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
            coEvery { playerManager.isLoading } answers { loading }
            coEvery { workoutViewModel.state } answers { state }
            coEvery { workoutViewModel.loadExercise(20001) } answers { }
            composeTestRule.setContent {
                AppTheme {
                    WorkoutScreen(viewModel = workoutViewModel, navController = navController)
                }
            }
        }
    }
}
</code>```

This code was actually working. But after a while I started getting this error.
java.lang.AbstractMethodError: abstract method "boolean kotlin.reflect.KClass.isValue()"

What am I doing wrong or what am I missing?

Body:
I'm trying to test WorkoutScreen with the following code block.
I created a function called setView to test ViewState in different situations.

@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class WorkoutScreenTest {

    @get:Rule(order = 0)
    val hiltRule = HiltAndroidRule(this)

    @get:Rule(order = 1)
    val composeTestRule = createComposeRule()

    private val workoutViewModel = mockk<WorkoutViewModel>()

    private val playerManager = mockk<ExoplayerManager>()

    @Before
    fun setup() = runOnUiThread {
        hiltRule.inject()
        MockKAnnotations.init(this, true)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun isCircularProgressDisplayed_whenLoading() = runTest {
        setView(isLoading = true, viewState = WorkoutViewState.Loading)
        composeTestRule.onNodeWithTag("workout_loading_indicator").assertIsDisplayed()
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun isErrorTextDisplayed_whenError() = runTest {
        setView(isLoading = true, viewState = WorkoutViewState.Error("error message"))
        composeTestRule.onNodeWithText("Something went wrong").assertIsDisplayed()
    }

    private fun setView(isLoading: Boolean, viewState: WorkoutViewState) {
        runOnUiThread {
            val loading = MutableStateFlow(isLoading)
            val state = MutableStateFlow(viewState)
            val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
            coEvery { playerManager.isLoading } answers { loading }
            coEvery { workoutViewModel.state } answers { state }
            coEvery { workoutViewModel.loadExercise(20001) } answers { }
            composeTestRule.setContent {
                AppTheme {
                    WorkoutScreen(viewModel = workoutViewModel, navController = navController)
                }
            }
        }
    }
}

This code was actually working. But after a while I started getting this error.
java.lang.AbstractMethodError: abstract method "boolean kotlin.reflect.KClass.isValue()"

What am I doing wrong or what am I missing?