问:
Convert current executing assembly to MetadataReference or an array of bytes
I have a .NET 6.0 project which uses Royslin to compile a C# like language. That scripting language inherits and uses a few classes that my project has.
Currently I use the following code to add a reference to the current assembly:

var options = ScriptOptions.Default
                .WithReferences(Assembly.GetExecutingAssembly())
```

The previous code works fine until I publish my project which is a simple CLI program. When I publish the project, it becomes a single executable so GetExecutingAssembly().Location will be empty. And due to the requirements, I have to keep it as a single file executable. So now I need a way of converting GetExecutingAssembly() to byte[] such that I can use the method MetadataReference.CreateFromImage()

I have tried a few solutions so far:

1- Tried Using BinaryFormatter and serialize the assembly or even single class assembly and I got an error that the type is not serializable even though it has the serializable attribute

2- Tried using Hash from System.Security.Policy, but the Hash class doesn't even exist, and I tried searching for it as COM reference and Nuget package but couldn't find anything

3- I can maybe add the assembly to a resource file however I have multiple projects which means I am going to need to change the resource file when I switch to debug or release mode as well as I will have to add a version of the dll for each project and switch this version according to the current project that is running. If there is a work around this in visual studio build options that would be great.

4- I maybe compile the classes that the scripting language need at run time and generate dll files but I don't see this as efficient

Any suggestions on how to convert the assembly to binary array of even a metadata reference?

Body:
I have a .NET 6.0 project which uses Royslin to compile a C# like language. That scripting language inherits and uses a few classes that my project has.
Currently I use the following code to add a reference to the current assembly:

var options = ScriptOptions.Default
                .WithReferences(Assembly.GetExecutingAssembly())

The previous code works fine until I publish my project which is a simple CLI program. When I publish the project, it becomes a single executable so GetExecutingAssembly().Location will be empty. And due to the requirements, I have to keep it as a single file executable. So now I need a way of converting GetExecutingAssembly() to byte[] such that I can use the method MetadataReference.CreateFromImage()

I have tried a few solutions so far:

1- Tried Using BinaryFormatter and serialize the assembly or even single class assembly and I got an error that the type is not serializable even though it has the serializable attribute

2- Tried using Hash from System.Security.Policy, but the Hash class doesn't even exist, and I tried searching for it as COM reference and Nuget package but couldn't find anything

3- I can maybe add the assembly to a resource file however I have multiple projects which means I am going to need to change the resource file when I switch to debug or release mode as well as I will have to add a version of the dll for each project and switch this version according to the current project that is running. If there is a work around this in visual studio build options that would be great.

4- I maybe compile the classes that the scripting language need at run time and generate dll files but I don't see this as efficient

Any suggestions on how to convert the assembly to binary array of even a metadata reference?


来源: stackexchange

问:
How can I fix having 2 different pytorch versions in different python virtual enviroments running at different speeds on same Ubuntu 20 laptop?
I have gpu rtx 3060-laptop and I have cuda toolkit V11.0.194 and the nvidia driver Version: 520.56.06,CUDA Version: 11.8 and cudnn version 8.7.0.84_cuda11. My laptop is running ubuntu 20.

I created 2 python virtual enviroments using venv for python 3.8. In the first one I installed Pytorch 1.11.0+cu113 and the other I installed Pyotrch Version: 1.7.1+cu110.
I am running the code in here Autonovel and my main problem is that I run the code in the virtual enviroment containing the newer Pytorch(1.11) and the speed of the code per iteration is 14.5 iteration/s but when I run the same exact code but using virtual enviroment with Pytorch(1.7),the speed of the code is 7 iteration/s. Is that normal? I know the versions of Pytorch I guess should be faster from version to another but double the speed? I feel something wrong. I feel there is something missing in the virtual enviroment containing the old verison of Pytorch 1.7.
Put into consideration that both virtual enviroments donot contain the same exact libraries. The newer virtual enviroment containing the higher versions of pytorch contains many more libraries installed compared to this one but I donot see the affect of this.
Any guesses?

I am really out of ideas in here.

Cheers,
Mostafa Haggag

I tried installing different cudatookit versions, I used to work with 11.6 then I went back to 11.0 but still nothing is fixed. I changed the nvidia driver more than once as I thought it might be the problem but it wasnot.

ContentLicense: CC BY-SA 4.0


问:
SQLSTATE[HY000] [2002] (trying to connect via (null)) when connecting to digitalocean managed db
I am using digitalocean managed DB in my laravel app . Everything working fine in tinker mode but when using in app it throws
SQLSTATE[HY000] [2002] (trying to connect via (null))
error . even i can connect it from beekeeper studio.
here's my configuration.

```<code>DB_CONNECTION=mysql
DB_HOST=obilia-***.db.ondigitalocean.com
DB_PORT=25060
DB_DATABASE=defaultdb
DB_USERNAME=**********
DB_PASSWORD=**********
DB_SSLMODE=required
MYSQL_ATTR_SSL_CA=storage/cert/ca-certificate.crt
</code>```

Body:
I am using digitalocean managed DB in my laravel app . Everything working fine in tinker mode but when using in app it throws
SQLSTATE[HY000] [2002] (trying to connect via (null))
error . even i can connect it from beekeeper studio.
here's my configuration.

DB_CONNECTION=mysql
DB_HOST=obilia-***.db.ondigitalocean.com
DB_PORT=25060
DB_DATABASE=defaultdb
DB_USERNAME=**********
DB_PASSWORD=**********
DB_SSLMODE=required
MYSQL_ATTR_SSL_CA=storage/cert/ca-certificate.crt


问:
Blazor WebAssembly EF Core row-level security - pass claims client to server
I'm driving myself mad with this and hoping a better method exists.
The scenario is this: I have written a Blazor Web Assembly application with server hosting. The application needs to implement row-level security (using EF Core) but I need some access permission to be looked up in another database via an API (external supplier so have no control) to be used in the security.

Ideally I'd love the permissions to be managed in AAD but that isn't supported in the external application and is too much overhead to manage manually.

On the client side I use a custom AccountClaimsPrincipalFactory to lookup the correct permissions and create the user claims.

What I'm struggling with is to then to manage this server side, I've looked into using IClaimsTransformation to lookup the claims again but this produces too much overhead as it is called on every request.

I've (not imagining it would work) tried adding claims client side, adding a new identity client side and accessing on the server. All I've really got left I can think of is using the AuthorizationMessageHandler to encrypt values and pass to the server that way as a token, it works as a work around but probably not the best method.

Is there a way to somehow lookup the database values and maintain them within the identity/token so they can just be passed around?

If this is a stupid question, feel free to give me a slap, I've just exhausted my google search terms for it.

Thanks


问:
stop java thread while running
Hi I'm trying to stop a thread while running I know the thread should cooperate so it can be stopped I used a boolean variable but the thread keeps running. is there any way to stop a thread while it's running?
Or can I start and stop a thread with the same button?</p>
```<code>boolean boolean_variable  = true;

     Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                while (boolean_variable) {
                    for (int i = 0; i < 100; i++) {
                        System.out.println("thread running " + i);
                        try {
                            Thread.sleep(400);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

//start the thread
buttonOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                thread.start();
            }
        });

//stop the thread
buttonTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean_variable = false;
            }
        });
</code>```

Title: stop java thread while running

Body:
Hi I'm trying to stop a thread while running I know the thread should cooperate so it can be stopped I used a boolean variable but the thread keeps running. is there any way to stop a thread while it's running?
Or can I start and stop a thread with the same button?

boolean boolean_variable  = true;

     Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                while (boolean_variable) {
                    for (int i = 0; i < 100; i++) {
                        System.out.println("thread running " + i);
                        try {
                            Thread.sleep(400);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

//start the thread
buttonOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                thread.start();
            }
        });

//stop the thread
buttonTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean_variable = false;
            }
        });


问:
Rename a field with a full stop in MongoDB Compass
How can I rename a field in MongoDB compass that I mistakenly created containing a full stop?

```<code>'NVIP_No._of_children_Malaria_vaccinated_during_the_month'
</code>```

The problem is I can view it and it's value analysis from the schema tab, but when I perform a find query from the document tab or check if the field has a value, it returns empty and when I try to rename it with the $rename operator, it does not work

```<code>{'NVIP_No._of_children_Malaria_vaccinated_during_the_month':{$ne:null}}
</code>```
```<code>db.dhis_final_data.updateMany( {}, { $rename: {'NVIP_No._of_children_Malaria_vaccinated_during_the_month': 'NVIP_No_of_children_Malaria_vaccinated_during_the_month' } } )
</code>```

Body:
How can I rename a field in MongoDB compass that I mistakenly created containing a full stop?

'NVIP_No._of_children_Malaria_vaccinated_during_the_month'

The problem is I can view it and it's value analysis from the schema tab, but when I perform a find query from the document tab or check if the field has a value, it returns empty and when I try to rename it with the $rename operator, it does not work

{'NVIP_No._of_children_Malaria_vaccinated_during_the_month':{$ne:null}}

db.dhis_final_data.updateMany( {}, { $rename: {'NVIP_No._of_children_Malaria_vaccinated_during_the_month': 'NVIP_No_of_children_Malaria_vaccinated_during_the_month' } } )


问:
The media module in drupal downloading the third party video into my website
I am facing an issue with media module in drupal. I have a site where I would like to play videos using mediafront. These videos are in a third party site.Using media module I am specifying  the video URL. Then immediately the media module is downloading the video into my site's space. But I want that to be played directly without downloading it into my site's space. Please let me know how I can do this.  </p>

ContentLicense: CC BY-SA 3.0


问:
Calculate in SQL Average number of active subscriptions per quarter
I need a help please
I have a table with such fields: subscription_id, client_id, start_date, end_date.

Subscription is active when started but haven’t ended.

How I can calculate average number of active subscriptions per quarter?

I have issues with getting the active period for each subscription (between start and end date) and then by grouping it by quarters and years

I was trying this sQL ,but it dosen't work

```<code>`WITH total AS (
    SELECT
        QUARTER(w.start_date) AS QUARTER_start, CONCAT("Y", YEAR(w.start_date)," ", "Q-", QUARTER(w.start_date)) AS "startYQ"
        ,QUARTER(w.end_date) AS QUARTER_end, CONCAT("Y", YEAR(w.end_date)," ", "Q-", QUARTER(w.end_date)) AS "endYQ"
        ,count(w.subscription_id) as subscription_id
    FROM work w
    GROUP BY 1,2,3,4
    ORDER BY 2
)

SELECT t.endYQ, AVG(t.subscription_id) as avg_p
FROM total t
group by endYQ
order by 1;`
</code>```

Body:
I need a help please
I have a table with such fields: subscription_id, client_id, start_date, end_date.

Subscription is active when started but haven’t ended.

How I can calculate average number of active subscriptions per quarter?

I have issues with getting the active period for each subscription (between start and end date) and then by grouping it by quarters and years

I was trying this sQL ,but it dosen't work

`WITH total AS (
    SELECT
        QUARTER(w.start_date) AS QUARTER_start, CONCAT("Y", YEAR(w.start_date)," ", "Q-", QUARTER(w.start_date)) AS "startYQ"
        ,QUARTER(w.end_date) AS QUARTER_end, CONCAT("Y", YEAR(w.end_date)," ", "Q-", QUARTER(w.end_date)) AS "endYQ"
        ,count(w.subscription_id) as subscription_id
    FROM work w
    GROUP BY 1,2,3,4
    ORDER BY 2
)

SELECT t.endYQ, AVG(t.subscription_id) as avg_p
FROM total t
group by endYQ
order by 1;`


问:
Custom Map rendering in React/TS/JS
I am trying to load a custom map(ie the data is provided by the user) and wanted to know the means that i can possible render this data onto the screen in a container. The map that is being loaded will have a live data feed being overlayed onto it and be interact-able to some extent. The data being shared by the user will be in GeoJSON or .shp format.

How can I virtualise the entire global coordinate system? I am not concerned regarding an "out of box" approach. I believe I can utilise a svg file and then render the geojson data over it but how do i convert/coorelate each geographical coordinate on the svg?

All my google/stackoverflow search regarding loading and rendering GeoJSON files lead me to utilise a prebuilt map library which would be of no use to me. To give an insight as to how the map could look here is an image.
Sample map being rendered
To add more details regarding the image - it renders an object file that contains GeoJson data. I am not willing to utilise a third party map.

Title: Custom Map rendering in React/TS/JS


问:
hive : full outer join result has repetition rows
every table has remove validation row key, sql like

```<code>select count(*)
from
    dw_rk.f_t_rk_dzxx tb1 full
                              outer join (
        select
            s1.gmsfhm as sfzhm,
            s1.sjjzd_dzbm,
            s1.qxqc,
            s1.xzjd,
            s1.qxc,
            s1.pcs,
            s1.jws,
            s1.dm,
            s1.mph,
            s1.xqqc,
            s1.lfmc,
            s1.dy,
            s1.fh,
            s1.dzqc,
            from_unixtime(unix_timestamp(), 'yyyy-MM-dd HH:dd:ss') as d_timestamp,
            'gaj' as d_deptname,
            'f_s_zw_gaj_ldzh_syrk_rkjbxxb' as d_tabname
        from
            (
                select
                    t0.gmsfhm,
                    t0.sjjzd_dzbm,
                    case
                        when t2.qxmc is null then t1.qxmc
                        else t2.qxmc
                        end as qxqc,
                    t1.xzjd as xzjd,
                    case
                        when t3.qxc is null then t1.qxc
                        else t3.qxc
                        end as qxc,
                    t1.pcs as pcs,
                    t1.jwqmc as jws,
                    t1.dm as dm,
                    t1.mph as mph,
                    t1.xqmc as xqqc,
                    t1.lfmc as lfmc,
                    t1.dy as dy,
                    t1.fh as fh,
                    t1.dzqc as dzqc,
                    row_number() over (
                        partition by t0.gmsfhm
                        order by
                            t0.gxsj,
                            t0.rksj desc
                        ) as num
                from
                    dws.f_s_zw_gaj_ldzh_syrk_rkjbxxb t0
                        left join dws.f_s_zw_ldzh_bzdz_dzjbxxb t1 on t0.sjjzd_dzbm = t1.dzbh
                        left join (
                        select
                            distinct ssxqbm,
                                     qxmc
                        from
                            dws.f_s_zw_ldzh_bzdz_dzjbxxb
                    ) t2 on t0.sjjzd_ssxqdm = t2.ssxqbm
                        left join (
                        select
                            distinct qxcbh,
                                     qxc
                        from
                            dws.f_s_zw_ldzh_bzdz_dzjbxxb
                    ) t3 on t0.sjjzd_sqjcwhdm = t3.qxcbh
                where
                    t0.gmsfhm is not null
            ) s1
        where
                s1.num = 1
    ) tb2 on tb1.sfzhm = tb2.sfzhm;
</code>```

explain is

```<code>STAGE DEPENDENCIES:
  Stage-7 is a root stage
"  Stage-12 depends on stages: Stage-7, Stage-13 , consists of Stage-15, Stage-3"
  Stage-15 has a backup stage: Stage-3
  Stage-11 depends on stages: Stage-15
"  Stage-10 depends on stages: Stage-3, Stage-8, Stage-11 , consists of Stage-14, Stage-4"
  Stage-14 has a backup stage: Stage-4
  Stage-9 depends on stages: Stage-14
"  Stage-5 depends on stages: Stage-4, Stage-9"
  Stage-1 depends on stages: Stage-5
  Stage-4
  Stage-3
  Stage-8 is a root stage
  Stage-16 is a root stage
  Stage-13 depends on stages: Stage-16
  Stage-0 depends on stages: Stage-1
</code>```

when I create middle table to get table2`s data,result is right

Body:
every table has remove validation row key, sql like

select count(*)
from
    dw_rk.f_t_rk_dzxx tb1 full
                              outer join (
        select
            s1.gmsfhm as sfzhm,
            s1.sjjzd_dzbm,
            s1.qxqc,
            s1.xzjd,
            s1.qxc,
            s1.pcs,
            s1.jws,
            s1.dm,
            s1.mph,
            s1.xqqc,
            s1.lfmc,
            s1.dy,
            s1.fh,
            s1.dzqc,
            from_unixtime(unix_timestamp(), 'yyyy-MM-dd HH:dd:ss') as d_timestamp,
            'gaj' as d_deptname,
            'f_s_zw_gaj_ldzh_syrk_rkjbxxb' as d_tabname
        from
            (
                select
                    t0.gmsfhm,
                    t0.sjjzd_dzbm,
                    case
                        when t2.qxmc is null then t1.qxmc
                        else t2.qxmc
                        end as qxqc,
                    t1.xzjd as xzjd,
                    case
                        when t3.qxc is null then t1.qxc
                        else t3.qxc
                        end as qxc,
                    t1.pcs as pcs,
                    t1.jwqmc as jws,
                    t1.dm as dm,
                    t1.mph as mph,
                    t1.xqmc as xqqc,
                    t1.lfmc as lfmc,
                    t1.dy as dy,
                    t1.fh as fh,
                    t1.dzqc as dzqc,
                    row_number() over (
                        partition by t0.gmsfhm
                        order by
                            t0.gxsj,
                            t0.rksj desc
                        ) as num
                from
                    dws.f_s_zw_gaj_ldzh_syrk_rkjbxxb t0
                        left join dws.f_s_zw_ldzh_bzdz_dzjbxxb t1 on t0.sjjzd_dzbm = t1.dzbh
                        left join (
                        select
                            distinct ssxqbm,
                                     qxmc
                        from
                            dws.f_s_zw_ldzh_bzdz_dzjbxxb
                    ) t2 on t0.sjjzd_ssxqdm = t2.ssxqbm
                        left join (
                        select
                            distinct qxcbh,
                                     qxc
                        from
                            dws.f_s_zw_ldzh_bzdz_dzjbxxb
                    ) t3 on t0.sjjzd_sqjcwhdm = t3.qxcbh
                where
                    t0.gmsfhm is not null
            ) s1
        where
                s1.num = 1
    ) tb2 on tb1.sfzhm = tb2.sfzhm;

explain is

STAGE DEPENDENCIES:
  Stage-7 is a root stage
"  Stage-12 depends on stages: Stage-7, Stage-13 , consists of Stage-15, Stage-3"
  Stage-15 has a backup stage: Stage-3
  Stage-11 depends on stages: Stage-15
"  Stage-10 depends on stages: Stage-3, Stage-8, Stage-11 , consists of Stage-14, Stage-4"
  Stage-14 has a backup stage: Stage-4
  Stage-9 depends on stages: Stage-14
"  Stage-5 depends on stages: Stage-4, Stage-9"
  Stage-1 depends on stages: Stage-5
  Stage-4
  Stage-3
  Stage-8 is a root stage
  Stage-16 is a root stage
  Stage-13 depends on stages: Stage-16
  Stage-0 depends on stages: Stage-1

when I create middle table to get table2`s data,result is right


问:
Display pdf byte[] or base64 string to WPF web browser without saving it in a local file
I have a .net web api that get a byte[] from a pdf file, convert it into a base64 string and send it to a frontend, in my case a WPF application.

I'm wondering if it's possible to use directly the base64 string or a byte[] to display my pdf into WPF web browser without saving it in a local temp directory.

I have also tried to convert my byte[] into a MemoryStream and use it as a param in WebBrowser.NavigateToStream() but the result was a black page.

```<code>byte[] bytes = Convert.FromBase64String(mypdfstring);
FileStream = new MemoryStream(bytes);
</code>```
```<code> <WebBrowser utils:WebBrowserUtility.BindableStreamSource="{Binding FileStream}"/>
</code>```
```<code> public static void BindableStreamSourcePropertyChanged(DependencyObject o,     DependencyPropertyChangedEventArgs e) {
            WebBrowser browser = o as WebBrowser;
            if(browser != null)
            {
                Stream stream = e.NewValue as Stream;

                if (stream is null)
                    return;
                stream.Position = 0;
                browser.NavigateToStream(stream);
            }
        }
</code>```

Edit

I have setted to 0 the position of the stream and now the web browser shows my pdf file in this form

```<code>%PDF-1.7 1 0 obj <> stream ÿØÿàJFIF,,ÿÛC     ÿÛC   ÿÀ ° °"ÿÄ ÿÄµ}!1AQa"q2‘¡#B±ÁRÑð$3br‚ %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢
</code>```

is only a small portion

Body:
I have a .net web api that get a byte[] from a pdf file, convert it into a base64 string and send it to a frontend, in my case a WPF application.

I'm wondering if it's possible to use directly the base64 string or a byte[] to display my pdf into WPF web browser without saving it in a local temp directory.

I have also tried to convert my byte[] into a MemoryStream and use it as a param in WebBrowser.NavigateToStream() but the result was a black page.

byte[] bytes = Convert.FromBase64String(mypdfstring);
FileStream = new MemoryStream(bytes);

 <WebBrowser utils:WebBrowserUtility.BindableStreamSource="{Binding FileStream}"/>

 public static void BindableStreamSourcePropertyChanged(DependencyObject o,     DependencyPropertyChangedEventArgs e) {
            WebBrowser browser = o as WebBrowser;
            if(browser != null)
            {
                Stream stream = e.NewValue as Stream;

                if (stream is null)
                    return;
                stream.Position = 0;
                browser.NavigateToStream(stream);
            }
        }

Edit

I have setted to 0 the position of the stream and now the web browser shows my pdf file in this form

%PDF-1.7 1 0 obj <> stream ÿØÿàJFIF,,ÿÛC     ÿÛC   ÿÀ ° °"ÿÄ ÿÄµ}!1AQa"q2‘¡#B±ÁRÑð$3br‚ %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢

is only a small portion


问:
This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization
I'm tryin to reuse JsonSerializationOption in many places and this is my code:

```<code>    public static void ConfigureJsonSerializerOptions(JsonSerializerOptions jsonSerializerOptions)
    {
        jsonSerializerOptions.PropertyNameCaseInsensitive = true;
        jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        jsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
        jsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
        jsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
        jsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
        jsonSerializerOptions.UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode;
        jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        jsonSerializerOptions.AllowTrailingCommas = true;
        jsonSerializerOptions.WriteIndented = true;
    }

    private static JsonSerializerOptions options;

    public static JsonSerializerOptions Options
    {
        get
        {
            if (options == null)
            {
                options = new JsonSerializerOptions();
                ConfigureJsonSerializerOptions(options);
                options.Converters.Add(new JsonStringEnumConverter());
            }
            return options;
        }
    }
</code>```

But I get this error:

An exception of type 'System.InvalidOperationException' occurred in System.Text.Json.dll but was not handled in user code: 'This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization.'

How can I check it? It does not have a IsReadOnly property.

Body:
I'm tryin to reuse JsonSerializationOption in many places and this is my code:

    public static void ConfigureJsonSerializerOptions(JsonSerializerOptions jsonSerializerOptions)
    {
        jsonSerializerOptions.PropertyNameCaseInsensitive = true;
        jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        jsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
        jsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
        jsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
        jsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
        jsonSerializerOptions.UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode;
        jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        jsonSerializerOptions.AllowTrailingCommas = true;
        jsonSerializerOptions.WriteIndented = true;
    }

    private static JsonSerializerOptions options;

    public static JsonSerializerOptions Options
    {
        get
        {
            if (options == null)
            {
                options = new JsonSerializerOptions();
                ConfigureJsonSerializerOptions(options);
                options.Converters.Add(new JsonStringEnumConverter());
            }
            return options;
        }
    }

But I get this error:

An exception of type 'System.InvalidOperationException' occurred in System.Text.Json.dll but was not handled in user code: 'This JsonSerializerOptions instance is read-only or has already been used in serialization or deserialization.'

How can I check it? It does not have a IsReadOnly property.


问:
Visual Studio Community 2022 Android Emulator won't build
I’ve tried almost everything I can think of and none of it has even made a dent.

Whenever I try to execute my application, the device attempts to boot twice, quickly flashing on screen then disappearing, with a warning message inside the temporarily emulated device reading: “Resetting for cold boot: emulator engine failed” (I have tried this from both new devices and devices with force.ColdBoot disabled).

Whenever I try to execute my application, the device attempts to boot twice, quickly flashing on screen then disappearing, with a warning message inside the temporarily emulated device reading: “Resetting for cold boot: emulator engine failed” (I have tried this from both new devices and devices with force.ColdBoot disabled).

Nothing seems out of place in the Android Debug Properties menu.

I have HAXM enabled.

I’ve reinstalled Visual Studio. The emulated devices were still in Android Device Manager in the new version if that matter.

Every thread I’ve searched is either irrelevant, outdated, or merely tangential to my problem.

It changes a bit with each of the modifications I made, but the output from the build is always something like this:

```<code>Build started...
Starting emulator tablet_h-dpi_13_5in_-_api_33 ...
1>------ Build started: Project: MobileApplicationAssessment.Android, Configuration: Debug Any CPU ------
C:\Program Files (x86)\Android\android-sdk\emulator\emulator.EXE -netfast -accel on -avd tablet_h-dpi_13_5in_-_api_33 -prop monodroid.avdname=tablet_h-dpi_13_5in_-_api_33
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment.Android\Properties\AndroidManifest.xml : warning XA4211: AndroidManifest.xml //uses-sdk/@android:targetSdkVersion '31' is less than $(TargetFrameworkVersion) ''. Using API-33 for ACW compilation.
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment\MobileApplicationAssessment.csproj : warning NU1701: Package 'Microsoft.Bcl 1.1.6' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment\MobileApplicationAssessment.csproj : warning NU1701: Package 'Microsoft.Bcl.Async 1.0.165' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment\MobileApplicationAssessment.csproj : warning NU1701: Package 'PCLStorage 1.0.2' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
1>  MobileApplicationAssessment.Android -> C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment.Android\bin\Debug\MobileApplicationAssessment.Android.dll
2>Starting deployment to tablet_h-dpi_13_5in_-_api_33 ...
2>Starting emulator tablet_h-dpi_13_5in_-_api_33 ...
2>C:\Program Files (x86)\Android\android-sdk\emulator\emulator.EXE -netfast -accel on -avd tablet_h-dpi_13_5in_-_api_33 -prop monodroid.avdname=tablet_h-dpi_13_5in_-_api_33
2>Emulator tablet_h-dpi_13_5in_-_api_33 cannot be started.
========== Build: 1 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Elapsed 00:31.315 ==========
========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========
========== Elapsed 00:31.315 ==========
</code>```

Any help would be greatly appreciated, and it’s worth noting I’ve only been using VS for about a year, so I might not know all the terminology and whatnot, so if you could break down those in your answers that would, also, be appreciated.

Body:
I’ve tried almost everything I can think of and none of it has even made a dent.

Whenever I try to execute my application, the device attempts to boot twice, quickly flashing on screen then disappearing, with a warning message inside the temporarily emulated device reading: “Resetting for cold boot: emulator engine failed” (I have tried this from both new devices and devices with force.ColdBoot disabled).

Whenever I try to execute my application, the device attempts to boot twice, quickly flashing on screen then disappearing, with a warning message inside the temporarily emulated device reading: “Resetting for cold boot: emulator engine failed” (I have tried this from both new devices and devices with force.ColdBoot disabled).

Nothing seems out of place in the Android Debug Properties menu.

I have HAXM enabled.

I’ve reinstalled Visual Studio. The emulated devices were still in Android Device Manager in the new version if that matter.

Every thread I’ve searched is either irrelevant, outdated, or merely tangential to my problem.

It changes a bit with each of the modifications I made, but the output from the build is always something like this:

Build started...
Starting emulator tablet_h-dpi_13_5in_-_api_33 ...
1>------ Build started: Project: MobileApplicationAssessment.Android, Configuration: Debug Any CPU ------
C:\Program Files (x86)\Android\android-sdk\emulator\emulator.EXE -netfast -accel on -avd tablet_h-dpi_13_5in_-_api_33 -prop monodroid.avdname=tablet_h-dpi_13_5in_-_api_33
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment.Android\Properties\AndroidManifest.xml : warning XA4211: AndroidManifest.xml //uses-sdk/@android:targetSdkVersion '31' is less than $(TargetFrameworkVersion) ''. Using API-33 for ACW compilation.
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment\MobileApplicationAssessment.csproj : warning NU1701: Package 'Microsoft.Bcl 1.1.6' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment\MobileApplicationAssessment.csproj : warning NU1701: Package 'Microsoft.Bcl.Async 1.0.165' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
1>C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment\MobileApplicationAssessment.csproj : warning NU1701: Package 'PCLStorage 1.0.2' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
1>  MobileApplicationAssessment.Android -> C:\Users\Alistair\source\repos\MobileApplicationAssessment\MobileApplicationAssessment.Android\bin\Debug\MobileApplicationAssessment.Android.dll
2>Starting deployment to tablet_h-dpi_13_5in_-_api_33 ...
2>Starting emulator tablet_h-dpi_13_5in_-_api_33 ...
2>C:\Program Files (x86)\Android\android-sdk\emulator\emulator.EXE -netfast -accel on -avd tablet_h-dpi_13_5in_-_api_33 -prop monodroid.avdname=tablet_h-dpi_13_5in_-_api_33
2>Emulator tablet_h-dpi_13_5in_-_api_33 cannot be started.
========== Build: 1 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Elapsed 00:31.315 ==========
========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========
========== Elapsed 00:31.315 ==========

Any help would be greatly appreciated, and it’s worth noting I’ve only been using VS for about a year, so I might not know all the terminology and whatnot, so if you could break down those in your answers that would, also, be appreciated.


问:
Mailgun API - Send URL as attachment in Send Email not working
I am trying to send url as attachment using Send Email api in Mailgun. But the attachment is not attached. I am using Laravel HTTP client

```<code>$params = [
            'from' => $selected_options['mg_from_email'],
            'to' => $selected_options['mg_to_email'],
            'subject' => $selected_options['mg_subject'],
            'text' => $selected_options['mg_text'],
            'html' => $selected_options['email_body'],
        ];

$response = Http::asForm()->withOptions(['verify' => config('constants.verify_ssl')])->timeout(30)->withHeaders(
            [
                'Content-Type'  => 'multipart/form-data',
                'Authorization' => 'Basic ' . base64_encode('api:'.$api_key)
            ]
        )->attach(
            'attachment', file_get_contents('https://picsum.photos/200'), 'photo.jpg'
        )->post(
            $request_url,
            $params,
        );
</code>```

Can anyone suggest what i am doing wrong here?

There is no error in response and the email is also sent successfully but the attachment is not there.

Body:
I am trying to send url as attachment using Send Email api in Mailgun. But the attachment is not attached. I am using Laravel HTTP client

$params = [
            'from' => $selected_options['mg_from_email'],
            'to' => $selected_options['mg_to_email'],
            'subject' => $selected_options['mg_subject'],
            'text' => $selected_options['mg_text'],
            'html' => $selected_options['email_body'],
        ];

$response = Http::asForm()->withOptions(['verify' => config('constants.verify_ssl')])->timeout(30)->withHeaders(
            [
                'Content-Type'  => 'multipart/form-data',
                'Authorization' => 'Basic ' . base64_encode('api:'.$api_key)
            ]
        )->attach(
            'attachment', file_get_contents('https://picsum.photos/200'), 'photo.jpg'
        )->post(
            $request_url,
            $params,
        );

Can anyone suggest what i am doing wrong here?

There is no error in response and the email is also sent successfully but the attachment is not there.


问:
How can I show the steps failed/error in a Scenario of Feature file in Katalon Studio
I have a feature file where 6 scenarios are written.
I am running the feature file by a Test case and Run Feature File keyword.

So while the full feature file is executed, it is showing error in the Test case potion of Log Viewer, but every scenario and their inside steps are marked as pass(Showing green tick).

So how I can find the error/failure. Please help me.

Screenshots are below:
Click here to see reference image


问:
Getting Spaces in VSCode terminal while compiling code using gcc

My specific problem is that I am getting spaces while compiling C code using gcc, as I am new to vscode so I don't know how to fix it and it is very annoying.

I have tried to reset the VSCode but it doesn't work but I am not getting this error while compiling python code, so i am just guessing it's all mess is because of gcc compiler or any VScode settings.


问:
Flink could not connect to Jobmanager in Docker
I've started a Flink Jobmanager in docker using docker run --rm --name=jobmanager --network flink-network --publish 8081:8081 --env FLINK_PROPERTIES="jobmanager.rpc.address: jobmanager" apache/flink:1.16.0-java11 jobmanager, and I could visit Flink ui at 127.0.0.1:8081.

Then I built a docker image using Dockerfile:

```<code>FROM flink:1.16.0-java11
...
CMD ./bin/flink run --python /usr/local/flink_driver.py
</code>```

And try to run this image by docker run -d --name=flink-driver --network flink-network --env FLINK_PROPERTIES="jobmanager.rpc.address: jobmanager" flink_test:latest. But this container exit with errors:

```<code>...
Caused by: org.apache.flink.shaded.netty4.io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /0.0.0.0:8081
...
</code>```

I've passed the argument jobmanager.rpc.address: jobmanager to the container but it still trying to connect 0.0.0.0:8081, how should I correct my Docker usage?

Body:
I've started a Flink Jobmanager in docker using docker run --rm --name=jobmanager --network flink-network --publish 8081:8081 --env FLINK_PROPERTIES="jobmanager.rpc.address: jobmanager" apache/flink:1.16.0-java11 jobmanager, and I could visit Flink ui at 127.0.0.1:8081.

Then I built a docker image using Dockerfile:

FROM flink:1.16.0-java11
...
CMD ./bin/flink run --python /usr/local/flink_driver.py

And try to run this image by docker run -d --name=flink-driver --network flink-network --env FLINK_PROPERTIES="jobmanager.rpc.address: jobmanager" flink_test:latest. But this container exit with errors:

...
Caused by: org.apache.flink.shaded.netty4.io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /0.0.0.0:8081
...

I've passed the argument jobmanager.rpc.address: jobmanager to the container but it still trying to connect 0.0.0.0:8081, how should I correct my Docker usage?


问:
How can I send the variables from android environment into JavaScript code
I have a webpage which is loaded into webview and inside loadUrl method there is a JavaScript function, which changes the links inside the webpage. If I write the JS code in loadUrl as a single string, it works well. But I need to change the links dynamically, so I need to get the variables from android code into my JS code inside loadUrl method.

I've tried to concatenate the JS code with my String from my Activity, it doesn't work.

```<code>view.loadUrl("javascript:" +
        "document.querySelectorAll('a').forEach(link => link.href =" +
        myString + ")")
</code>```

Body:
I have a webpage which is loaded into webview and inside loadUrl method there is a JavaScript function, which changes the links inside the webpage. If I write the JS code in loadUrl as a single string, it works well. But I need to change the links dynamically, so I need to get the variables from android code into my JS code inside loadUrl method.

I've tried to concatenate the JS code with my String from my Activity, it doesn't work.

view.loadUrl("javascript:" +
        "document.querySelectorAll('a').forEach(link => link.href =" +
        myString + ")")


问:
Powershell pass code to a function, add -errorAction and process in try/catch block
I have a scenario where I am doing any number of things with a network resource, copying files or folders, deleting a ZIP file after it has been unzipped locally, checking an EXE to see if it was downloaded from the internet and needs unblocked, running a software install, etc. And all of these tasks are impacted by things like an installer that hasn't released a file lock on a log file to be deleted, or the unzip hasn't released the file lock on the zip file, or the network is for a fleeting moment "unavailable" so a network file is not found.
I have a technique that works well for handling this scenario, I do a loop and react to the specific exception, and when that exception occurs I just sleep for 6 seconds. The loop happens up to 10 times before I abandon. Here is the code for dealing with an Autodesk log that is still locked by the Autodesk installer.

```<code>        $waitRetryCount = 10
        :waitForAccess do {
            try {
                Remove-Item $odisLogPath -Recurse -errorAction:Stop
                $retry = $False
            } catch {
                if (($PSItem.Exception -is [System.IO.IOException]) -or ($PSItem.Exception.InnerException -and ($PSItem.Exception.InnerException -is [System.IO.IOException]))) {
                    if ($waitRetryCount -eq 0) {
                        $invokeODISLogManagement.log.Add('E_Error deleting ODIS logs: retry limit exceeded')
                        break waitForFolderAccess
                    } else {
                        $retry = $True
                        $waitRetryCount --
                        Start-Sleep -s:6
                    }
                } else {
                    $invokeODISLogManagement.log.Add('E_Error deleting ODIS logs')
                    $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.GetType().FullName)")
                    $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.Message)")
                    if ($PSItem.Exception.InnerException) {
                        $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.InnerException.GetType().FullName)")
                        $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.InnerException.Message)")
                    }
                    $retry = $False
                }
            }
        } while ($retry)
</code>```

The thing is, I would like to convert this to a function, since it needs to be handled in a lot of places. So I would need to pass to the function the specific exception I am looking for and the code to be run in the try block, and get back a log (as a generic.list) that I can then add to the actual log list. The first and last aspects I have, but I am unsure the best approach for the code to try. In the above example it is a single line, Remove-Item $odisLogPath -Recurse -errorAction:Stop, but it could be multiple lines I suspect.

To start playing with this I verified that this does seem to work, at least with a single line of code.

```<code>$code = {Get-Item '\\noServer\folder\file.txt' -errorAction:Stop}
try {
    & $code
} catch {
    Write-Host "$($_.Exception.GetType().FullName)"
}
</code>```

But the error action is going to be duplicated a lot, so I thought to maybe address that within the function, however
$code = {Get-Item '\noServer\folder\file.txt'}

```<code>try {
    & $code -errorAction:Stop
} catch {
    Write-Host "$($_.Exception.GetType().FullName)"
}
</code>```

does NOT work. I get the exception uncaught.

So, my questions are
1: Is this the right direction? I am pretty sure it is but perhaps someone has a gotcha that I am not seeing, yet. :)
2: Is there a mechanism to add the -errorAction:Stop in the try, so I don't need to do it/remember to do it, at every use of this new function.
3: I seem to remember reading about a programming concept of passing code to a function, and I can't remember what that is called, but I would like to know the generic term. Indeed, it probably would help if I could tag it for this post. I had thought it might be lama, but a quick search suggests that is not the case? Being self taught sucks sometimes.

EDIT:
I have now implemented a function, that starts to do what I want.

```<code>function Invoke-PxWaitForAccess {
    param (
        [System.Management.Automation.ScriptBlock]$code,
        [String]$path
    )

    try {
        (& $code -path $path)
    } catch {
        Return "$($_.Exception.GetType().FullName)!!"
    }
}

$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Write-Host "$path!"; Get-Item $path}
Invoke-PxWaitForAccess -code $code -path $path
</code>```

I do wonder if the path couldn't somehow be encapsulated in the $code variable itself, since this implementation means it can ONLY be used where the code being run has a single variable called $path.

And, still wondering if this really is the best, or even a good, way to proceed? Or are there arguments for just implementing my loop 50 some odd times in all the situations where I need this behavior.

Also worth noting that this code does not yet implement the loop or address the fact that different exceptions apply in different situations.

EDIT #2:
And here is a more complete implementation, though it fails because it seems I am not actually passing a type, even though it looks like I am. So I get an error because what is to the right of -is must be an actual type.

```<code>function Invoke-PxWaitForAccess {
    param (
        [System.Management.Automation.ScriptBlock]$code,
        [String]$path,
        [Type]$exceptionType
    )

    $invokeWaitForAccess = @{
        success = $Null
        log = [System.Collections.Generic.List[String]]::new()
    }

    $waitRetryCount = 2
    :waitForAccess do {
        try {
            Write-Host "$path ($waitRetryCount)"
            & $code -path $path
            $retry = $False
        } catch {
            Write-Host "!$($PSItem.Exception.GetType().FullName)"
            if (($PSItem.Exception -is $exceptionType) -or ($PSItem.Exception.InnerException -and ($PSItem.Exception.InnerException -is $exceptionType))) {
                Write-Host "($waitRetryCount)"
                if ($waitRetryCount -eq 0) {
                    $invokeWaitForAccess.log.Add('E_retry limit exceeded')
                    break waitForFolderAccess
                } else {
                    $retry = $True
                    $waitRetryCount --
                    Start-Sleep -s:6
                }
            } else {
                $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.GetType().FullName)")
                $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.Message)")
                if ($PSItem.Exception.InnerException) {
                    $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.InnerException.GetType().FullName)")
                    $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.InnerException.Message)")
                }
                $retry = $False
            }
        }
    } while ($retry)

    if ($invokeWaitForAccess.log.Count -eq 0) {
        $invokeWaitForAccess.success = $True
    } else {
        $invokeWaitForAccess.success = $False
    }

    return $invokeWaitForAccess
}

$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Get-Item $path -errorAction:Stop}
if ($invoke = (Invoke-PxWaitForAccess -code $code -path $path -type ([System.Management.Automation.ItemNotFoundException])).success) {
    Write-Host 'Good'
} else {
    foreach ($line in $invoke.log) {
        Write-Host "$line"
    }
}
</code>```

EDIT #3: This is what I have now, and it seems to work fine. But the code I am passing will sometimes be something like Remove-Object and the error is [System.IO.IOException], but at other times I actually need to return more than an error, like here where the code involves Get-Item. And that means defining the code block outside the function with a reference to the variable inside the function, which seems, fugly,  to me. It may be that what I am trying to do is just more complicated than PowerShell is really designed to handle, but it seems MUCH more likely that there is a more elegant way to do what I am trying to do? Without being able to manipulate the script block from within the function I don't see any good options.
For what it is worth this last example shows a failure where the exception I am accepting for the repeat occurs and hits the limit, as well as an exception that just immediately fails because it is not the exception I am looping on, and an example where I return something. A fourth condition would be when I am trying to delete, and waiting on [System.IO.IOException] and a success would return nothing, no item, and no error log.

```<code>function Invoke-PxWaitForAccess {
    param (
        [System.Management.Automation.ScriptBlock]$code,
        [String]$path,
        [Type]$exceptionType
    )

    $invokeWaitForAccess = @{
        item = $null
        errorLog = [System.Collections.Generic.List[String]]::new()
    }

    $waitRetryCount = 2
    :waitForSuccess do {
        try {
            & $code -path $path
            $retry = $False
        } catch {
            if (($PSItem.Exception -is $exceptionType) -or ($PSItem.Exception.InnerException -and ($PSItem.Exception.InnerException -is $exceptionType))) {
                if ($waitRetryCount -eq 0) {
                    $invokeWaitForAccess.errorLog.Add('E_Retry limit exceeded')
                    break waitForSuccess
                } else {
                    $retry = $True
                    $waitRetryCount --
                    Start-Sleep -s:6
                }
            } else {
                $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.GetType().FullName)")
                $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.Message)")
                if ($PSItem.Exception.InnerException) {
                    $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.InnerException.GetType().FullName)")
                    $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.InnerException.Message)")
                }
                $retry = $False
            }
        }
    } while ($retry)

    return $invokeWaitForAccess
}

CLS
$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Get-Item $path -errorAction:Stop}
$invoke = (Invoke-PxWaitForAccess -code $code -path $path -exceptionType:([System.Management.Automation.ItemNotFoundException]))
if ($invoke.errorLog.count -eq 0) {
    Write-Host "Good $path"
} else {
    foreach ($line in $invoke.errorLog) {
        Write-Host "$line"
    }
}
Write-Host
$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Get-Item $path -errorAction:Stop}
$invoke = (Invoke-PxWaitForAccess -code $code -path $path -exceptionType:([System.IO.IOException]))
if ($invoke.errorLog.count -eq 0) {
    Write-Host "Good $path"
} else {
    foreach ($line in $invoke.errorLog) {
        Write-Host "$line"
    }
}
Write-Host
$path = '\\Mac\iCloud Drive\Px Tools 3.#\# Dev 3.4.5\Definitions.xml'
$code = {param ([String]$path) $invokeWaitForAccess.item = Get-Item $path -errorAction:Stop}
$invoke = (Invoke-PxWaitForAccess -code $code -path $path -exceptionType:([System.Management.Automation.ItemNotFoundException]))
if ($invoke.errorLog.count -eq 0) {
    Write-Host "Good $path !"
    Write-Host "$($invoke.item)"
} else {
    foreach ($line in $invoke.errorLog) {
        Write-Host "$line"
    }
}
Write-Host
</code>```

Body:
I have a scenario where I am doing any number of things with a network resource, copying files or folders, deleting a ZIP file after it has been unzipped locally, checking an EXE to see if it was downloaded from the internet and needs unblocked, running a software install, etc. And all of these tasks are impacted by things like an installer that hasn't released a file lock on a log file to be deleted, or the unzip hasn't released the file lock on the zip file, or the network is for a fleeting moment "unavailable" so a network file is not found.
I have a technique that works well for handling this scenario, I do a loop and react to the specific exception, and when that exception occurs I just sleep for 6 seconds. The loop happens up to 10 times before I abandon. Here is the code for dealing with an Autodesk log that is still locked by the Autodesk installer.

        $waitRetryCount = 10
        :waitForAccess do {
            try {
                Remove-Item $odisLogPath -Recurse -errorAction:Stop
                $retry = $False
            } catch {
                if (($PSItem.Exception -is [System.IO.IOException]) -or ($PSItem.Exception.InnerException -and ($PSItem.Exception.InnerException -is [System.IO.IOException]))) {
                    if ($waitRetryCount -eq 0) {
                        $invokeODISLogManagement.log.Add('E_Error deleting ODIS logs: retry limit exceeded')
                        break waitForFolderAccess
                    } else {
                        $retry = $True
                        $waitRetryCount --
                        Start-Sleep -s:6
                    }
                } else {
                    $invokeODISLogManagement.log.Add('E_Error deleting ODIS logs')
                    $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.GetType().FullName)")
                    $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.Message)")
                    if ($PSItem.Exception.InnerException) {
                        $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.InnerException.GetType().FullName)")
                        $invokeODISLogManagement.log.Add("=_$($PSItem.Exception.InnerException.Message)")
                    }
                    $retry = $False
                }
            }
        } while ($retry)

The thing is, I would like to convert this to a function, since it needs to be handled in a lot of places. So I would need to pass to the function the specific exception I am looking for and the code to be run in the try block, and get back a log (as a generic.list) that I can then add to the actual log list. The first and last aspects I have, but I am unsure the best approach for the code to try. In the above example it is a single line, Remove-Item $odisLogPath -Recurse -errorAction:Stop, but it could be multiple lines I suspect.

To start playing with this I verified that this does seem to work, at least with a single line of code.

$code = {Get-Item '\\noServer\folder\file.txt' -errorAction:Stop}
try {
    & $code
} catch {
    Write-Host "$($_.Exception.GetType().FullName)"
}

But the error action is going to be duplicated a lot, so I thought to maybe address that within the function, however
$code = {Get-Item '\noServer\folder\file.txt'}

try {
    & $code -errorAction:Stop
} catch {
    Write-Host "$($_.Exception.GetType().FullName)"
}

does NOT work. I get the exception uncaught.

So, my questions are
1: Is this the right direction? I am pretty sure it is but perhaps someone has a gotcha that I am not seeing, yet. :)
2: Is there a mechanism to add the -errorAction:Stop in the try, so I don't need to do it/remember to do it, at every use of this new function.
3: I seem to remember reading about a programming concept of passing code to a function, and I can't remember what that is called, but I would like to know the generic term. Indeed, it probably would help if I could tag it for this post. I had thought it might be lama, but a quick search suggests that is not the case? Being self taught sucks sometimes.

EDIT:
I have now implemented a function, that starts to do what I want.

function Invoke-PxWaitForAccess {
    param (
        [System.Management.Automation.ScriptBlock]$code,
        [String]$path
    )

    try {
        (& $code -path $path)
    } catch {
        Return "$($_.Exception.GetType().FullName)!!"
    }
}

$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Write-Host "$path!"; Get-Item $path}
Invoke-PxWaitForAccess -code $code -path $path

I do wonder if the path couldn't somehow be encapsulated in the $code variable itself, since this implementation means it can ONLY be used where the code being run has a single variable called $path.

And, still wondering if this really is the best, or even a good, way to proceed? Or are there arguments for just implementing my loop 50 some odd times in all the situations where I need this behavior.

Also worth noting that this code does not yet implement the loop or address the fact that different exceptions apply in different situations.

EDIT #2:
And here is a more complete implementation, though it fails because it seems I am not actually passing a type, even though it looks like I am. So I get an error because what is to the right of -is must be an actual type.

function Invoke-PxWaitForAccess {
    param (
        [System.Management.Automation.ScriptBlock]$code,
        [String]$path,
        [Type]$exceptionType
    )

    $invokeWaitForAccess = @{
        success = $Null
        log = [System.Collections.Generic.List[String]]::new()
    }

    $waitRetryCount = 2
    :waitForAccess do {
        try {
            Write-Host "$path ($waitRetryCount)"
            & $code -path $path
            $retry = $False
        } catch {
            Write-Host "!$($PSItem.Exception.GetType().FullName)"
            if (($PSItem.Exception -is $exceptionType) -or ($PSItem.Exception.InnerException -and ($PSItem.Exception.InnerException -is $exceptionType))) {
                Write-Host "($waitRetryCount)"
                if ($waitRetryCount -eq 0) {
                    $invokeWaitForAccess.log.Add('E_retry limit exceeded')
                    break waitForFolderAccess
                } else {
                    $retry = $True
                    $waitRetryCount --
                    Start-Sleep -s:6
                }
            } else {
                $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.GetType().FullName)")
                $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.Message)")
                if ($PSItem.Exception.InnerException) {
                    $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.InnerException.GetType().FullName)")
                    $invokeWaitForAccess.log.Add("=_$($PSItem.Exception.InnerException.Message)")
                }
                $retry = $False
            }
        }
    } while ($retry)

    if ($invokeWaitForAccess.log.Count -eq 0) {
        $invokeWaitForAccess.success = $True
    } else {
        $invokeWaitForAccess.success = $False
    }

    return $invokeWaitForAccess
}

$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Get-Item $path -errorAction:Stop}
if ($invoke = (Invoke-PxWaitForAccess -code $code -path $path -type ([System.Management.Automation.ItemNotFoundException])).success) {
    Write-Host 'Good'
} else {
    foreach ($line in $invoke.log) {
        Write-Host "$line"
    }
}

EDIT #3: This is what I have now, and it seems to work fine. But the code I am passing will sometimes be something like Remove-Object and the error is [System.IO.IOException], but at other times I actually need to return more than an error, like here where the code involves Get-Item. And that means defining the code block outside the function with a reference to the variable inside the function, which seems, fugly,  to me. It may be that what I am trying to do is just more complicated than PowerShell is really designed to handle, but it seems MUCH more likely that there is a more elegant way to do what I am trying to do? Without being able to manipulate the script block from within the function I don't see any good options.
For what it is worth this last example shows a failure where the exception I am accepting for the repeat occurs and hits the limit, as well as an exception that just immediately fails because it is not the exception I am looping on, and an example where I return something. A fourth condition would be when I am trying to delete, and waiting on [System.IO.IOException] and a success would return nothing, no item, and no error log.

function Invoke-PxWaitForAccess {
    param (
        [System.Management.Automation.ScriptBlock]$code,
        [String]$path,
        [Type]$exceptionType
    )

    $invokeWaitForAccess = @{
        item = $null
        errorLog = [System.Collections.Generic.List[String]]::new()
    }

    $waitRetryCount = 2
    :waitForSuccess do {
        try {
            & $code -path $path
            $retry = $False
        } catch {
            if (($PSItem.Exception -is $exceptionType) -or ($PSItem.Exception.InnerException -and ($PSItem.Exception.InnerException -is $exceptionType))) {
                if ($waitRetryCount -eq 0) {
                    $invokeWaitForAccess.errorLog.Add('E_Retry limit exceeded')
                    break waitForSuccess
                } else {
                    $retry = $True
                    $waitRetryCount --
                    Start-Sleep -s:6
                }
            } else {
                $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.GetType().FullName)")
                $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.Message)")
                if ($PSItem.Exception.InnerException) {
                    $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.InnerException.GetType().FullName)")
                    $invokeWaitForAccess.errorLog.Add("=_$($PSItem.Exception.InnerException.Message)")
                }
                $retry = $False
            }
        }
    } while ($retry)

    return $invokeWaitForAccess
}

CLS
$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Get-Item $path -errorAction:Stop}
$invoke = (Invoke-PxWaitForAccess -code $code -path $path -exceptionType:([System.Management.Automation.ItemNotFoundException]))
if ($invoke.errorLog.count -eq 0) {
    Write-Host "Good $path"
} else {
    foreach ($line in $invoke.errorLog) {
        Write-Host "$line"
    }
}
Write-Host
$path = '\\noServer\folder\file.txt'
$code = {param ([String]$path) Get-Item $path -errorAction:Stop}
$invoke = (Invoke-PxWaitForAccess -code $code -path $path -exceptionType:([System.IO.IOException]))
if ($invoke.errorLog.count -eq 0) {
    Write-Host "Good $path"
} else {
    foreach ($line in $invoke.errorLog) {
        Write-Host "$line"
    }
}
Write-Host
$path = '\\Mac\iCloud Drive\Px Tools 3.#\# Dev 3.4.5\Definitions.xml'
$code = {param ([String]$path) $invokeWaitForAccess.item = Get-Item $path -errorAction:Stop}
$invoke = (Invoke-PxWaitForAccess -code $code -path $path -exceptionType:([System.Management.Automation.ItemNotFoundException]))
if ($invoke.errorLog.count -eq 0) {
    Write-Host "Good $path !"
    Write-Host "$($invoke.item)"
} else {
    foreach ($line in $invoke.errorLog) {
        Write-Host "$line"
    }
}
Write-Host


问:
When we need to call API from stored procedure OLE method is it secure choice
I want to get data from endpoint and after process pass back to endpoint and its done by OLE method in SQL. I want to ask question is it secure choice (OLE)? And when should we use it?

I have done it by OLE method in SQL, but I want to ask is it secure or any disadvantages of it


问:
Starting fragment but the title is not set up properly in the preference screen
I have two prefrence screens and would like to open the preference screen from the current preference screen.
I have a snackbar where the button "enables" appear so right now the fragment is opening up but the title is not set up properly when the "enable" is clicked.

I tried the methods available on the internet but they are not helping to properly setup the preference screen on the fragment.

Below is the code from where I am calling the fragment the fragment get started but the title doesn't appear.

```<code>requirePreference<Preference>(R.string.answer_buttons_position_preference).setOnPreferenceChangeListener() { _, newValue: Any ->
    val prefs = AnkiDroidApp.getSharedPrefs(requireContext())
    if (prefs.getBoolean(GestureProcessor.PREF_KEY, false) || newValue != "none") {
        true
    } else {
        // TODO add a button on the snackbar that leads directly to the
        // Controls fragment and highlight the gesture preference
        showSnackbar(R.string.full_screen_error_gestures){
            setAction(R.string.gesture_enable_button){
                val frag = ControlsSettingsFragment()
                activity?.supportFragmentManager!!.beginTransaction()
                    .remove(this@AppearanceSettingsFragment)
                    .replace(((view as ViewGroup).parent as View).id,frag)
                    .addToBackStack(null)
                    .commit()

            }
        }
        false
    }
}
</code>```

Below is the ControlSettingFragment I am calling

```<code>class ControlsSettingsFragment : SettingsFragment() {
    override val preferenceResource: Int
        get() = R.xml.preferences_controls
    override val analyticsScreenNameConstant: String
        get() = "prefs.controls"

    override fun initSubscreen() {
        val commandMappingCategory = requirePreference<PreferenceCategory>(R.string.controls_command_mapping_cat_key)
        addAllControlPreferencesToCategory(commandMappingCategory)
    }

    /** Attaches all possible [ControlPreference] elements to a given [PreferenceCategory] */
    fun addAllControlPreferencesToCategory(category: PreferenceCategory) {
        for (command in ViewerCommand.values()) {
            val preference = ControlPreference(category.context).apply {
                setTitle(command.resourceId)
                key = command.preferenceKey
                setDefaultValue(command.defaultValue.toPreferenceString())
            }
            category.addPreference(preference)
        }
    }
}
</code>```

And here is the XML file for the preference screen

```<code><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://arbitrary.app.namespace/com.ichi2.anki"
    xmlns:app1="http://schemas.android.com/apk/res-auto"
    android:title="@string/pref_cat_controls"
    android:key="@string/pref_controls_screen_key">

    <SwitchPreference
        android:defaultValue="false"
        android:disableDependentsState="false"
        android:key="@string/gestures_preference"
        android:summary="@string/gestures_summ"
        android:title="@string/gestures" />
    <SwitchPreference
        android:defaultValue="false"
        android:dependency="@string/gestures_preference"
        android:key="@string/gestures_corner_touch_preference"
        android:summary="@string/gestures_corner_touch_summary"
        android:title="@string/gestures_corner_touch" />
    <SwitchPreference
        android:defaultValue="false"
        android:dependency="@string/gestures_preference"
        android:disableDependentsState="false"
        android:key="@string/nav_drawer_gesture_key"
        android:summary="@string/gestures_fullscreen_nav_drawer_summary"
        android:title="@string/gestures_full_screen_nav_drawer" />
    <com.ichi2.preferences.SeekBarPreferenceCompat
        android:defaultValue="100"
        android:dependency="@string/gestures_preference"
        android:key="@string/pref_swipe_sensitivity_key"
        android:max="180"
        android:text=""
        android:title="@string/swipe_sensitivity"
        app:interval="1"
        app:min="20"
        app1:useSimpleSummaryProvider="true"/>
    <!-- This category is expanded in BindingPreference.setup -->
    <PreferenceCategory android:title="@string/controls_main_category" android:key="@string/controls_command_mapping_cat_key" />
</PreferenceScreen>
</code>```

Here is the actual result after the execution

Body:
I have two prefrence screens and would like to open the preference screen from the current preference screen.
I have a snackbar where the button "enables" appear so right now the fragment is opening up but the title is not set up properly when the "enable" is clicked.

I tried the methods available on the internet but they are not helping to properly setup the preference screen on the fragment.

Below is the code from where I am calling the fragment the fragment get started but the title doesn't appear.

requirePreference<Preference>(R.string.answer_buttons_position_preference).setOnPreferenceChangeListener() { _, newValue: Any ->
    val prefs = AnkiDroidApp.getSharedPrefs(requireContext())
    if (prefs.getBoolean(GestureProcessor.PREF_KEY, false) || newValue != "none") {
        true
    } else {
        // TODO add a button on the snackbar that leads directly to the
        // Controls fragment and highlight the gesture preference
        showSnackbar(R.string.full_screen_error_gestures){
            setAction(R.string.gesture_enable_button){
                val frag = ControlsSettingsFragment()
                activity?.supportFragmentManager!!.beginTransaction()
                    .remove(this@AppearanceSettingsFragment)
                    .replace(((view as ViewGroup).parent as View).id,frag)
                    .addToBackStack(null)
                    .commit()

            }
        }
        false
    }
}

Below is the ControlSettingFragment I am calling

class ControlsSettingsFragment : SettingsFragment() {
    override val preferenceResource: Int
        get() = R.xml.preferences_controls
    override val analyticsScreenNameConstant: String
        get() = "prefs.controls"

    override fun initSubscreen() {
        val commandMappingCategory = requirePreference<PreferenceCategory>(R.string.controls_command_mapping_cat_key)
        addAllControlPreferencesToCategory(commandMappingCategory)
    }

    /** Attaches all possible [ControlPreference] elements to a given [PreferenceCategory] */
    fun addAllControlPreferencesToCategory(category: PreferenceCategory) {
        for (command in ViewerCommand.values()) {
            val preference = ControlPreference(category.context).apply {
                setTitle(command.resourceId)
                key = command.preferenceKey
                setDefaultValue(command.defaultValue.toPreferenceString())
            }
            category.addPreference(preference)
        }
    }
}

And here is the XML file for the preference screen

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://arbitrary.app.namespace/com.ichi2.anki"
    xmlns:app1="http://schemas.android.com/apk/res-auto"
    android:title="@string/pref_cat_controls"
    android:key="@string/pref_controls_screen_key">

    <SwitchPreference
        android:defaultValue="false"
        android:disableDependentsState="false"
        android:key="@string/gestures_preference"
        android:summary="@string/gestures_summ"
        android:title="@string/gestures" />
    <SwitchPreference
        android:defaultValue="false"
        android:dependency="@string/gestures_preference"
        android:key="@string/gestures_corner_touch_preference"
        android:summary="@string/gestures_corner_touch_summary"
        android:title="@string/gestures_corner_touch" />
    <SwitchPreference
        android:defaultValue="false"
        android:dependency="@string/gestures_preference"
        android:disableDependentsState="false"
        android:key="@string/nav_drawer_gesture_key"
        android:summary="@string/gestures_fullscreen_nav_drawer_summary"
        android:title="@string/gestures_full_screen_nav_drawer" />
    <com.ichi2.preferences.SeekBarPreferenceCompat
        android:defaultValue="100"
        android:dependency="@string/gestures_preference"
        android:key="@string/pref_swipe_sensitivity_key"
        android:max="180"
        android:text=""
        android:title="@string/swipe_sensitivity"
        app:interval="1"
        app:min="20"
        app1:useSimpleSummaryProvider="true"/>

    <PreferenceCategory android:title="@string/controls_main_category" android:key="@string/controls_command_mapping_cat_key" />
</PreferenceScreen>

Here is the actual result after the execution


问:
Best way to run bitbucket scheduled pipelines on weekdays
Bitbucket scheduled pipelines UI does not have an option for us to enter a cron expression and we can only run the pipeline hourly, daily or weekly. There is an option to create schedule via API call with cron expression in payload, however, unfortunately it does not accept a complex cron expression.

What could be the best way to achieve running the pipelines just on weekdays?

Looking for a better solution than these.

Have multiple daily pipelines mon-fri.

Have a daily pipeline and a check inside running logic for day.

Is there a better option?


问:
Sentry Integration with FastApi
I have a FastApi application running locally on port 3000 on top of nginx reverse proxy port 80 so I can request localhost/api/v1/docs etc. I have also configured sentry locally and its running on port 9000.

Now I integrate sentry to FastApi using the below code:

sentry_sdk.init(
    dsn="http://<key>@localhost:9000/2",

    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for performance monitoring.
    # We recommend adjusting this value in production,
    traces_sample_rate=1.0,
)
```

In the FastApi logs, it is giving a warning:

sentry_sdk.integrations.logging:sentry_patched_callhandlers:96 - Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f938851c250>: Failed to establish a new connection: [Errno 111] Connection refused')': /api/2/envelope/

I have no idea where I am doing wrong.

I am running 2 nginx docker containers 1 is for FastApi application, 2nd is by default comes with Sentry.

I have tried changing nginx port from 80 to 81 for FastApi but still same warning.

Title: Sentry Integration with FastApi

Body:
I have a FastApi application running locally on port 3000 on top of nginx reverse proxy port 80 so I can request localhost/api/v1/docs etc. I have also configured sentry locally and its running on port 9000.

Now I integrate sentry to FastApi using the below code:

sentry_sdk.init(
    dsn="http://<key>@localhost:9000/2",

    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for performance monitoring.
    # We recommend adjusting this value in production,
    traces_sample_rate=1.0,
)

In the FastApi logs, it is giving a warning:

sentry_sdk.integrations.logging:sentry_patched_callhandlers:96 - Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f938851c250>: Failed to establish a new connection: [Errno 111] Connection refused')': /api/2/envelope/

I have no idea where I am doing wrong.

I am running 2 nginx docker containers 1 is for FastApi application, 2nd is by default comes with Sentry.

I have tried changing nginx port from 80 to 81 for FastApi but still same warning.


问:
Realm Proxy class are not generated
I have updated my Realm from 7.0.0 to 10.13.0. After updating I am facing issues in realm proxy classes. All my old import codes of proxy classes show Cannot resolve symbol 'com_example_android_model_XXXXRealmProxy. I have updated my android target SDK version to 31, So I had to update the Java version from 8 to 11.

App build.gradle

```<code>buildscript {
  dependencies {
    classpath 'com.android.tools.build:gradle:7.3.1'
    classpath "io.realm:realm-gradle-plugin:10.13.0"
    classpath 'de.mobilej.unmock:UnMockPlugin:0.7.6'
    classpath 'com.google.gms:google-services:4.3.14'
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.1'
  }

 repositories {
    google()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    maven { url "https://jitpack.io" }
    maven { url "https://clojars.org/repo/" }
    maven { url "https://plugins.gradle.org/m2/" }
    mavenCentral()
    jcenter()
  }
}

allprojects {
  repositories {
    google()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    maven { url "https://jitpack.io" }
    maven { url 'https://github.com/WickeDev/stetho-realm/raw/master/maven-repo' }
    maven { url "https://clojars.org/repo/" }
    mavenCentral()
    jcenter()
  }
}
</code>```

Project build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'de.mobilej.unmock'
apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'realm-android'
</code>```

Title: Realm Proxy class are not generated

Body:
I have updated my Realm from 7.0.0 to 10.13.0. After updating I am facing issues in realm proxy classes. All my old import codes of proxy classes show Cannot resolve symbol 'com_example_android_model_XXXXRealmProxy. I have updated my android target SDK version to 31, So I had to update the Java version from 8 to 11.

App build.gradle

buildscript {
  dependencies {
    classpath 'com.android.tools.build:gradle:7.3.1'
    classpath "io.realm:realm-gradle-plugin:10.13.0"
    classpath 'de.mobilej.unmock:UnMockPlugin:0.7.6'
    classpath 'com.google.gms:google-services:4.3.14'
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.1'
  }

 repositories {
    google()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    maven { url "https://jitpack.io" }
    maven { url "https://clojars.org/repo/" }
    maven { url "https://plugins.gradle.org/m2/" }
    mavenCentral()
    jcenter()
  }
}

allprojects {
  repositories {
    google()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    maven { url "https://jitpack.io" }
    maven { url 'https://github.com/WickeDev/stetho-realm/raw/master/maven-repo' }
    maven { url "https://clojars.org/repo/" }
    mavenCentral()
    jcenter()
  }
}

Project build.gradle

apply plugin: 'com.android.application'
apply plugin: 'de.mobilej.unmock'
apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'realm-android'


问:
SpeechRecognizer not working in Wear Emulator in Android Studio
I am trying to create a custom voice recognition page, with custom UI, but

```<code>SpeechRecognizer.isRecognitionAvailable(this) is always returning false.
</code>```

I can Input using gboard voice prompt and the mic is working fine, when i tried using RecognizerIntent it was also working.

but SpeechRecognizer is not working , I tried it on a LG wear and it was working fine there.
but in emulator, even with working mic, the checking isRecognitionAvailable is always returning false.

Update
Its not supporting when i select Android 11, ist working fine when I use Android Pie Wear OS Image, and the isRecognitionAvailable is actually returning true, and everything works fine. but i also want the gboard to support, which is not available in android pie versions

Body:
I am trying to create a custom voice recognition page, with custom UI, but

SpeechRecognizer.isRecognitionAvailable(this) is always returning false.

I can Input using gboard voice prompt and the mic is working fine, when i tried using RecognizerIntent it was also working.

but SpeechRecognizer is not working , I tried it on a LG wear and it was working fine there.
but in emulator, even with working mic, the checking isRecognitionAvailable is always returning false.

Update
Its not supporting when i select Android 11, ist working fine when I use Android Pie Wear OS Image, and the isRecognitionAvailable is actually returning true, and everything works fine. but i also want the gboard to support, which is not available in android pie versions


问:
Angular - Migration to libraries - How to handle states
we are currently trying to refactor our Angular-Application, a portal for either employees or employers, to use multiple custom libraries, to get rid of code duplication. Out current structure is as following:

common-folder (components, json-file with texts)

employers-folder (components, json-file with texts)

employees-folder (components, json-file with texts)

client-a (components, json-file with texts)

client-b (components, json-file with texts)

client-c (components, json-file with texts)

... and so on for each different client

Each folder contains components which are used by this project and multiple instances of this project (multiple clients who are basically just different git branches of the same project). So we do have a branch of the same project for each of the clients in the list, which is far from optimal, I know.

Each client-application uses a combination of three of the above folders: either its

an employee-portal, then it uses both common- and employees-folder plus a client-specific-folder, or its

an employer-portal, then it uses both common- and employers-folder  plus a client-specific-folder.

The common-folder contains components and a json-file with texts which are used by both employees and employers-portals, the employer- and employees-folders contain components and texts which are only used by one of the two, respectively.

The texts from the json-files are merged and then loaded by the Translate-Module. So the texts from the common-folder are merged/overwritten by the more specific texts from the employers-folder, which are again merged/overwritten by client-specific texts from the client-folder (if a client wants different texts for a specific key those are defined in the json-file in the client-folder).

As I've said, we now want to move stuff to custom angular-libraries to avoid code duplication, as EACH folder exists in each client-branch of the same project. So my idea was to basically move all stuff under /common into a common-lib, /employees into a employee-lib and same with employers. In the end the client-application only loads its needed libraries, either common and employers or common and employees. Hope you can still follow me.

I'm having trouble now understanding what to move into libraries and what not. I was able to create the libraries in a new angular-application which now contains three library-projects, common-lib, employee-lib and employer-lib. But I'm not sure if I understood module-management of angular...

For example: We are using ui-router to handle our paths/states. But how do I handle this when moving parts of the application into custom libraries? We use nested states to define layouts for our pages, so I guess each library-module which uses  needs to

have the npm-dependencies for ui-router inside the package.json

import the RouterModule in its module

But how do I manage the states if we want to put states into the libraries as well? Our idea was that each library exposes a list of states, like

```<code>// employer.states.ts
export const layoutState: Ng2StateDeclaration = {
    name: 'layout',
    abstract: true,
    component: CwpLayoutComponent,
    resolve: [{
        token: 'menuItems',
        deps: [MenuItemService], resolveFn: (menuItemService) => {
            return menuItemService.initializeAndGetMenuItems().catch(() => {
                console.warn('Getting menuItems.');
            });
        }
    }, {
        token: 'sessionUser',
        deps: [SessionService], resolveFn: (sessionService) => {
            return sessionService.initializeAndGetUser().catch(() => {
               console.warn('Warn getting sessionUser.');
            });
        }
    }, {
        token: 'applicationConfig',
        deps: [ApplicationConfigService], resolveFn: (applicationConfigService) => {
            return applicationConfigService.initializeAndGetApplicationConfig().catch(function ()
        {
                console.warn('Warn getting applicationConfig.');
            });
        }
    }]
};

export const homeState: Ng2StateDeclaration = {
    name: 'layout.home',
    url: '/home',
    component: CwpHomePageComponent
};

export const imprintState: Ng2StateDeclaration = {
    name: 'layout.imprint',
    url: '/imprint',
    component: CwpImprintPageComponent
};

export const privacyState: Ng2StateDeclaration = {
    name: 'layout.privacy',
    url: '/privacy',
    component: CwpPrivacyPageComponent
};

export const disclaimerState: Ng2StateDeclaration = {
    name: 'layout.disclaimer',
    url: '/disclaimer',
    component: CwpDisclaimerPageComponent
};

export const EMPLOYER_STATES: Ng2StateDeclaration[] = [
    layoutState,
    homeState,
    imprintState,
    privacyState,
    disclaimerState
];
</code>```

So our idea was:
There are standard-employee-states and standard-employer-states. So e.g. client-a is an employer-portal-application it uses the common-lib and the employer-lib. In the client-a-application I import the state-list from the employer-lib and merge it with another state-list which is specific to client-a.

```<code>// app.states.ts, belongs to client-a-application - merges state lists
import * as _ from 'lodash-es';
import {EMPLOYER_STATES} from '@cwp/employer-lib';
import {Ng2StateDeclaration} from "@uirouter/angular";
import {CwpTestHomeComponent} from "../components/test-home.component";

export const homeState: Ng2StateDeclaration = {
    name: 'test-home',
    url: '/test-home',
    component: CwpTestHomeComponent
};

const CLIENT_A_STATES: Ng2StateDeclaration[] = [
    homeState
];

export const APPLICATION_STATES = EMPLOYER_STATES.concat(CLIENT_A_STATES));
</code>```

Then I would pass this merged list (called APPLICATION_STATES) into the ui-router config of the app.module.ts:

```<code>@NgModule({
    imports: [
        BrowserModule,
        UIRouterModule.forRoot({
            states: APPLICATION_STATES,
            useHash: true,
            initial: {state: 'test-home'},
            config: routerConfigFn
        }),
        ...
    ]
})
</code>```

But that doesn't seem to work, the state won't load. Do I have to configure states for each library inside the library instead? What I mean: Does every library have to configure its UIRouterModule itself? What about components of the UIRouterModule which we use inside of components in our new libraries, like ui-view? I do have to import UIRouterModule in every module which has components which use anything from UIRouterModule, correct? Would it be sufficient to just import it without any configuration, like

```<code>@NgModule({
    imports: [
        UIRouterModule,
        ...
</code>```

so the compiler won't tell me it doesn't know "ui-view"?

Similar question regarding other 3rd party libraries like ngx-translate which we use... Can I configure it once in my app.module.ts, even if almost every component in the libraries uses e.g. the "| translate"-pipe?

I don't know if I am having a basic misunderstand of how Angular and its modules work, thats why I ask. I'm sorry if my question is to generic / basic... :-(

Body:
we are currently trying to refactor our Angular-Application, a portal for either employees or employers, to use multiple custom libraries, to get rid of code duplication. Out current structure is as following:

common-folder (components, json-file with texts)

employers-folder (components, json-file with texts)

employees-folder (components, json-file with texts)

client-a (components, json-file with texts)

client-b (components, json-file with texts)

client-c (components, json-file with texts)

... and so on for each different client

Each folder contains components which are used by this project and multiple instances of this project (multiple clients who are basically just different git branches of the same project). So we do have a branch of the same project for each of the clients in the list, which is far from optimal, I know.

Each client-application uses a combination of three of the above folders: either its

an employee-portal, then it uses both common- and employees-folder plus a client-specific-folder, or its

an employer-portal, then it uses both common- and employers-folder  plus a client-specific-folder.

The common-folder contains components and a json-file with texts which are used by both employees and employers-portals, the employer- and employees-folders contain components and texts which are only used by one of the two, respectively.

The texts from the json-files are merged and then loaded by the Translate-Module. So the texts from the common-folder are merged/overwritten by the more specific texts from the employers-folder, which are again merged/overwritten by client-specific texts from the client-folder (if a client wants different texts for a specific key those are defined in the json-file in the client-folder).

As I've said, we now want to move stuff to custom angular-libraries to avoid code duplication, as EACH folder exists in each client-branch of the same project. So my idea was to basically move all stuff under /common into a common-lib, /employees into a employee-lib and same with employers. In the end the client-application only loads its needed libraries, either common and employers or common and employees. Hope you can still follow me.

I'm having trouble now understanding what to move into libraries and what not. I was able to create the libraries in a new angular-application which now contains three library-projects, common-lib, employee-lib and employer-lib. But I'm not sure if I understood module-management of angular...

For example: We are using ui-router to handle our paths/states. But how do I handle this when moving parts of the application into custom libraries? We use nested states to define layouts for our pages, so I guess each library-module which uses  needs to

have the npm-dependencies for ui-router inside the package.json

import the RouterModule in its module

But how do I manage the states if we want to put states into the libraries as well? Our idea was that each library exposes a list of states, like

// employer.states.ts
export const layoutState: Ng2StateDeclaration = {
    name: 'layout',
    abstract: true,
    component: CwpLayoutComponent,
    resolve: [{
        token: 'menuItems',
        deps: [MenuItemService], resolveFn: (menuItemService) => {
            return menuItemService.initializeAndGetMenuItems().catch(() => {
                console.warn('Getting menuItems.');
            });
        }
    }, {
        token: 'sessionUser',
        deps: [SessionService], resolveFn: (sessionService) => {
            return sessionService.initializeAndGetUser().catch(() => {
               console.warn('Warn getting sessionUser.');
            });
        }
    }, {
        token: 'applicationConfig',
        deps: [ApplicationConfigService], resolveFn: (applicationConfigService) => {
            return applicationConfigService.initializeAndGetApplicationConfig().catch(function ()
        {
                console.warn('Warn getting applicationConfig.');
            });
        }
    }]
};

export const homeState: Ng2StateDeclaration = {
    name: 'layout.home',
    url: '/home',
    component: CwpHomePageComponent
};

export const imprintState: Ng2StateDeclaration = {
    name: 'layout.imprint',
    url: '/imprint',
    component: CwpImprintPageComponent
};

export const privacyState: Ng2StateDeclaration = {
    name: 'layout.privacy',
    url: '/privacy',
    component: CwpPrivacyPageComponent
};

export const disclaimerState: Ng2StateDeclaration = {
    name: 'layout.disclaimer',
    url: '/disclaimer',
    component: CwpDisclaimerPageComponent
};

export const EMPLOYER_STATES: Ng2StateDeclaration[] = [
    layoutState,
    homeState,
    imprintState,
    privacyState,
    disclaimerState
];

So our idea was:
There are standard-employee-states and standard-employer-states. So e.g. client-a is an employer-portal-application it uses the common-lib and the employer-lib. In the client-a-application I import the state-list from the employer-lib and merge it with another state-list which is specific to client-a.

// app.states.ts, belongs to client-a-application - merges state lists
import * as _ from 'lodash-es';
import {EMPLOYER_STATES} from '@cwp/employer-lib';
import {Ng2StateDeclaration} from "@uirouter/angular";
import {CwpTestHomeComponent} from "../components/test-home.component";

export const homeState: Ng2StateDeclaration = {
    name: 'test-home',
    url: '/test-home',
    component: CwpTestHomeComponent
};

const CLIENT_A_STATES: Ng2StateDeclaration[] = [
    homeState
];

export const APPLICATION_STATES = EMPLOYER_STATES.concat(CLIENT_A_STATES));

Then I would pass this merged list (called APPLICATION_STATES) into the ui-router config of the app.module.ts:

@NgModule({
    imports: [
        BrowserModule,
        UIRouterModule.forRoot({
            states: APPLICATION_STATES,
            useHash: true,
            initial: {state: 'test-home'},
            config: routerConfigFn
        }),
        ...
    ]
})

But that doesn't seem to work, the state won't load. Do I have to configure states for each library inside the library instead? What I mean: Does every library have to configure its UIRouterModule itself? What about components of the UIRouterModule which we use inside of components in our new libraries, like ui-view? I do have to import UIRouterModule in every module which has components which use anything from UIRouterModule, correct? Would it be sufficient to just import it without any configuration, like

@NgModule({
    imports: [
        UIRouterModule,
        ...

so the compiler won't tell me it doesn't know "ui-view"?

Similar question regarding other 3rd party libraries like ngx-translate which we use... Can I configure it once in my app.module.ts, even if almost every component in the libraries uses e.g. the "| translate"-pipe?

I don't know if I am having a basic misunderstand of how Angular and its modules work, thats why I ask. I'm sorry if my question is to generic / basic... :-(