问:
Why console shows different things when I use querySelector()?
when I use document.querySelector(), At first, I can see html tag in console like this.

```<code>// this is JS code
allProducts.forEach((product) => {
**const productList = document.querySelector('.product-list');**
console.log(productList);
});
</code>```
```<code>// console.log
<div class="product-list">
      <!-- <div class="product">
        <img src="imgs/imgs/blue_s.png">
        <p>female, small size</p>
      </div> -->
    </div>
</code>```

but after page refresh, console shows this.

```<code>//console.log
div.product-list (This is object.)
 accessKey:""
 align: ""
 ariaAtomic: null
 ariaAutoComplete: null
 ariaBrailleLabel: null
 ariaBrailleRoleDescription: null
 ...
</code>```

I read MDN .querySelector() page(https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector).
It says .quesySelector()'s return value type is 'Element'. But still, I don't know which one is 'Element' type and why I had to see html tags like first one before page refresh.

+) I am using Chrome browser.

Body:
when I use document.querySelector(), At first, I can see html tag in console like this.

// this is JS code
allProducts.forEach((product) => {
**const productList = document.querySelector('.product-list');**
console.log(productList);
});

// console.log

but after page refresh, console shows this.

//console.log
div.product-list (This is object.)
 accessKey:""
 align: ""
 ariaAtomic: null
 ariaAutoComplete: null
 ariaBrailleLabel: null
 ariaBrailleRoleDescription: null
 ...

I read MDN .querySelector() page(https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector).
It says .quesySelector()'s return value type is 'Element'. But still, I don't know which one is 'Element' type and why I had to see html tags like first one before page refresh.

+) I am using Chrome browser.


来源: stackexchange

问:
Angular Kendo Editor: How to get Image Selection Properties (Src, Width, height)
I have custom Image Insert Button instead of default Image Insert, Which allows to select image from our Media Library. But, the problem is when an image is already selected and then go for Image Insert I want the image is pre-selected on the Media Library popup and previously defined width and height auto populated. This is a default behavior of Original Image Insert button. But somehow I could not figure out with custom Image Insert button.

EditorComponent SelectionText does not support Image selection and editorComponent.View.State also does not contain any information about selected image properties.

ContentLicense: CC BY-SA 4.0


问:
Bitnami Wordpress with Google Cloud Load Balancer
My setup is Bitnami WordPress and Google Cloud Load Balancer. I've encountered a few issues.

To use a load balancer with Bitnami WordPress, I've to use this

```<code>define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/');
</code>```

That allows the VM to be accessible by both IP and domain. The problem is Google is indexing the VM's IP and some plugins are using the VM's IP too.

Neither can I use HTTPS because the SSL is handled by the Load Balancer. That causes mixed content issues on some pages when some plugins are used. Adding X-Forwarded-Proto doesn't work.

The website will break if I use any other configuration other than

```<code>define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/');
</code>```

I wonder if it is because of my configuration error or is the native behaviour of Bitnami WordPress.

Body:
My setup is Bitnami WordPress and Google Cloud Load Balancer. I've encountered a few issues.

To use a load balancer with Bitnami WordPress, I've to use this

define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/');

That allows the VM to be accessible by both IP and domain. The problem is Google is indexing the VM's IP and some plugins are using the VM's IP too.

Neither can I use HTTPS because the SSL is handled by the Load Balancer. That causes mixed content issues on some pages when some plugins are used. Adding X-Forwarded-Proto doesn't work.

The website will break if I use any other configuration other than

define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/');

I wonder if it is because of my configuration error or is the native behaviour of Bitnami WordPress.


问:
SvelteKit - Asset Handling: Transformed .webp image not found on nested route in Production/Preview
I am loading the transformed .webp image on /about-us/social-responsibilities page. I referred https://kit.svelte.dev/docs/assets#caching-and-inlining for loading assets.

Everything works fine when I run the npm run dev, but transformed images return 404 when I run npm run preview or when I deploy it on vercel.

```<code><script>
import supportImg from '$lib/assets/images/we-support-farmers-soldiers.jpg?webp';
</script>

<div>
<img src={supportImg} loading="lazy">
</div>
</code>```

The image returns 404 because it tries to load it from /about-us/_app/immutable/assets/we-support-farmers-soldiers-17dde5c7.webp. It will work fine if it loads the image from /_app/immutable/assets/we-support-farmers-soldiers-17dde5c7.webp. But I am not able to find the way to do it.

Body:
I am loading the transformed .webp image on /about-us/social-responsibilities page. I referred https://kit.svelte.dev/docs/assets#caching-and-inlining for loading assets.

Everything works fine when I run the npm run dev, but transformed images return 404 when I run npm run preview or when I deploy it on vercel.

The image returns 404 because it tries to load it from /about-us/_app/immutable/assets/we-support-farmers-soldiers-17dde5c7.webp. It will work fine if it loads the image from /_app/immutable/assets/we-support-farmers-soldiers-17dde5c7.webp. But I am not able to find the way to do it.


问:
unreal ERROR: Unable to run because you don't have an apk that is usable on emulator-5554. Looked for -x86
I came to know from unreal forum that unreal 5 can not build 32bit apps without source build, but the emulator I am running is Android Tiramisu Google API level 33 x86_64. Using a default template. I tried on physical phones, once it installed an apk on a older device on Android 7 but could not on Android 10 device and could not on any device recently showing the titled error: unreal ERROR: Unable to run because you don't have an apk that is usable on emulator-5554. Looked for -x86.

Now I would like it to look for x64 apk instead of -x86 apk. Why is it looking for -x86 if it can not build that? And what should I do to run an apk to an emulator/device of latest android? Is it by any chance the emulators fault?


问:
How to make a constexpr that equals -0.0
Any way for me to set a constexpr to negative 0?

A legacy library uses negative 0 to indicate the calculation failed so I want to create a constexpr float fNEGZERO = -0.0.

Normally I would create this using a union between a uint32 and a float and set the uint32 bits to 0x8000'0000. But constexpr doesn't allow having a union access the non-active member. In theory the compiler does the same thing for NaN, +Inf, etc. but looking at numeric_limits it seems like they rely on built in compiler values.


问:
how to create payment method per customer group using dynamic field
i want display selected payment method on checkout page for specific customer group using dymanic field .
this is mycode from system config</p>
```<code><group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1"
                   showInStore="1">
                <label>Configuration</label>
                <field id="enable" translate="label" type="select" sortOrder="2" showInDefault="1" showInWebsite="0" showInStore="0">
                    <label>Enable</label>
                    <source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model>
                </field>
                <field id="dynamic_field" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Payment Method</label>
                   <frontend_model>Vdcstore\PaymentMethod\Block\Adminhtml\Form\Field\Groups</frontend_model>
                <backend_model>Magento\Config\Model\Config\Backend\Serialized\ArraySerialized</backend_model>
                     <depends>
                        <field id="enable">1</field>
                    </depends>
                </field>
            </group>
</code>```

Body:
i want display selected payment method on checkout page for specific customer group using dymanic field .
this is mycode from system config

<group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1"
                   showInStore="1">
                Configuration
                <field id="enable" translate="label" type="select" sortOrder="2" showInDefault="1" showInWebsite="0" showInStore="0">
                    Enable
                    <source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model>
                </field>
                <field id="dynamic_field" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    Payment Method
                   <frontend_model>Vdcstore\PaymentMethod\Block\Adminhtml\Form\Field\Groups</frontend_model>
                <backend_model>Magento\Config\Model\Config\Backend\Serialized\ArraySerialized</backend_model>
                     <depends>
                        <field id="enable">1</field>
                    </depends>
                </field>
            </group>


问:
how can i set that before created view
i writed that button i think that code worked after view created i need work that before created view with onMesure how can i do that ?</p>
```<code>  override fun onBindViewHolder(
    holder: VHolder<ItemMultimediaBinding, MediaResponse.Data>,
    position: Int
) {
        holder.binding?.apply {
        getItem(position)?.let { item ->

            imgMultimedia.loadCompat(item.imageUrl!!)
            cvMultiMedia.setHeight(getScreenHeight()/3) //hown can i do that with onMesure

            imgMultimedia.setOnClickListener(){
                val action = MultiMediaFragmentDirections.actionMultiMediaFragmentToMediaPlayerFragment("title",item)
                imgMultimedia.findNavController().navigate(action)
            }

        }
    }
</code>```

Title: how can i set that before created view

Body:
i writed that button i think that code worked after view created i need work that before created view with onMesure how can i do that ?

  override fun onBindViewHolder(
    holder: VHolder<ItemMultimediaBinding, MediaResponse.Data>,
    position: Int
) {
        holder.binding?.apply {
        getItem(position)?.let { item ->

            imgMultimedia.loadCompat(item.imageUrl!!)
            cvMultiMedia.setHeight(getScreenHeight()/3) //hown can i do that with onMesure

            imgMultimedia.setOnClickListener(){
                val action = MultiMediaFragmentDirections.actionMultiMediaFragmentToMediaPlayerFragment("title",item)
                imgMultimedia.findNavController().navigate(action)
            }

        }
    }


问:
Explicit specialization template member and typedef
Found a curious emergent architecture (it wasn't designed intentionally but was created over time by adding up features) in code base, which looks like this, if dumbed down:

```<code>#include <iostream>
// Base class
template <class T>
struct Base {
   typedef T DataT;
   void foo();
};

// Parameter classes
struct A { int a[2]; };
struct B { int a[3]; };

// In original code Base<> had a complex list of arguments
typedef Base<A> ContainerA;
typedef Base<B> ContainerB;

// what allows to use ContainerA? It's a type name or explicit specialization?
// Class parameters, e.g. T, are unusable in this context  directly.
template<> void ContainerA::foo() {
    std::cout << "ContainerA " << sizeof(DataT) << std::endl;
}

template<> void ContainerB::foo() {
    std::cout << "ContainerB " << sizeof(DataT) << std::endl;
}

int main()
{
    ContainerA a;
    ContainerB b;
    a.foo();
    b.foo();
}
</code>```

Essentially, with multiple derived classes and complex template argument list this use of typedef saves time to type code and makes specialization declarations more readable. But which part of standard says that a typedef can be used in such way?

Code had partial support of C++11, no using = type declarations allowed.

Body:
Found a curious emergent architecture (it wasn't designed intentionally but was created over time by adding up features) in code base, which looks like this, if dumbed down:

#include <iostream>
// Base class
template <class T>
struct Base {
   typedef T DataT;
   void foo();
};

// Parameter classes
struct A { int a[2]; };
struct B { int a[3]; };

// In original code Base<> had a complex list of arguments
typedef Base ContainerA;
typedef Base ContainerB;

// what allows to use ContainerA? It's a type name or explicit specialization?
// Class parameters, e.g. T, are unusable in this context  directly.
template<> void ContainerA::foo() {
    std::cout << "ContainerA " << sizeof(DataT) << std::endl;
}

template<> void ContainerB::foo() {
    std::cout << "ContainerB " << sizeof(DataT) << std::endl;
}

int main()
{
    ContainerA a;
    ContainerB b;
    a.foo();
    b.foo();
}

Essentially, with multiple derived classes and complex template argument list this use of typedef saves time to type code and makes specialization declarations more readable. But which part of standard says that a typedef can be used in such way?

Code had partial support of C++11, no using = type declarations allowed.


问:
Write >1 files (limited by size) from a spark partition
I am fetching an RDBMS table using JDBC with some 10-20 partitions using ROW_NUM. Then from each of these partitions I want to process/format the data, and write one or more files out to file storage based on the file size Each file must be less 500MB. How do I write multiple files out from a single partition? This spark config property 'spark.sql.files.maxRecordsPerFile' wont work for me because each row can be of different size as there is blob data in the row. The size of this blob may vary anywhere from a few hundred bytes to 50MB. So I cannot really limit the write by maxRecordsPerFile.

How do I further split each DB partition, into smaller partitions and then write out the files?
If I do a repartition, it does shuffle across all executors. I am trying to keep all data within the same executor to avoid shuffle. Is it possible to repartition within the same executor core (repartition the current partition), and then write a single file from each?

I tried this to atleats calculate the total size of my payload and then repartition. but this fails with "Local variable numOfPartitions defined in an enclosing scope must be final or effectively final". what am I doing wrong. How can I fix this code?
...

```<code>    int numOfPartitions = 1;
    JavaRDD<String> tgg = xmlDataSet.toJavaRDD().mapPartitions ( xmlRows -> {
        long totalSize = 0;
        List<String> strLst = new ArrayList<String>();
        while (xmlRows.hasNext()) {
            String xmlString = xmlString = blobToString(xmlRows.next());
            totalSize = totalSize + xmlString.getBytes().length;
            strLst.add(xmlString);
            if (totalSize > 10000) {
                numOfPartitions++;
            }

        }
        return strLst.iterator();
    });
</code>```

...

Body:
I am fetching an RDBMS table using JDBC with some 10-20 partitions using ROW_NUM. Then from each of these partitions I want to process/format the data, and write one or more files out to file storage based on the file size Each file must be less 500MB. How do I write multiple files out from a single partition? This spark config property 'spark.sql.files.maxRecordsPerFile' wont work for me because each row can be of different size as there is blob data in the row. The size of this blob may vary anywhere from a few hundred bytes to 50MB. So I cannot really limit the write by maxRecordsPerFile.

How do I further split each DB partition, into smaller partitions and then write out the files?
If I do a repartition, it does shuffle across all executors. I am trying to keep all data within the same executor to avoid shuffle. Is it possible to repartition within the same executor core (repartition the current partition), and then write a single file from each?

I tried this to atleats calculate the total size of my payload and then repartition. but this fails with "Local variable numOfPartitions defined in an enclosing scope must be final or effectively final". what am I doing wrong. How can I fix this code?
...

    int numOfPartitions = 1;
    JavaRDD<String> tgg = xmlDataSet.toJavaRDD().mapPartitions ( xmlRows -> {
        long totalSize = 0;
        List<String> strLst = new ArrayList<String>();
        while (xmlRows.hasNext()) {
            String xmlString = xmlString = blobToString(xmlRows.next());
            totalSize = totalSize + xmlString.getBytes().length;
            strLst.add(xmlString);
            if (totalSize > 10000) {
                numOfPartitions++;
            }

        }
        return strLst.iterator();
    });

...


问:
Powershell delete last page in word document and convert to pdf
I have been trying to write a powershell program that does 4 things:

Opens an existing word document

Removes the last page (usually page #3)

Converts the document to pdf

Saves the converted document using the same name + the text "converted"

I tried writing code myself but I know nothing about powershell. If someone could help me I would greatly appreciate it. My broken code is below.

```<code>
</code>```
```<code># Opening word and document
$word = New-Object -comobject Word.Application
$FileName = “C:\Users\mark\Test document.doc”
$word.Visible = $true
$doc = $word.Documents.Open($FileName)

 #Print ref
 $Missing    = [System.Reflection.Missing]::Value  # Default values
 $BackGround = 0
 $Append     = 0
 $Range      = 4
 $OutputFileName = $FileName + "converted"
 $From       = $Missing
 $To     = $Missing
 $Item       = 0
 $Copies     = 1     # Number of copies
 $Pages      = "1-2"   # Page range

 $Word.printout([ref]$BackGround, [ref]$Append, [ref]$Range, [ref]$OutputFileName, [ref]$From, [ref]$To, [ref]$Item, [ref]$Copies, [ref]$Pages)

# Closing Document and Word
$doc.Close()
</code>```
```<code>
</code>```
```<code></code>```

Body:
I have been trying to write a powershell program that does 4 things:

Opens an existing word document

Removes the last page (usually page #3)

Converts the document to pdf

Saves the converted document using the same name + the text "converted"

I tried writing code myself but I know nothing about powershell. If someone could help me I would greatly appreciate it. My broken code is below.

# Opening word and document
$word = New-Object -comobject Word.Application
$FileName = “C:\Users\mark\Test document.doc”
$word.Visible = $true
$doc = $word.Documents.Open($FileName)

 #Print ref
 $Missing    = [System.Reflection.Missing]::Value  # Default values
 $BackGround = 0
 $Append     = 0
 $Range      = 4
 $OutputFileName = $FileName + "converted"
 $From       = $Missing
 $To     = $Missing
 $Item       = 0
 $Copies     = 1     # Number of copies
 $Pages      = "1-2"   # Page range

 $Word.printout([ref]$BackGround, [ref]$Append, [ref]$Range, [ref]$OutputFileName, [ref]$From, [ref]$To, [ref]$Item, [ref]$Copies, [ref]$Pages)

# Closing Document and Word
$doc.Close()


问:
How to achieve OAuth for Microsoft Azure gov accounts for multiple clients
Microsoft is deprecating basic authentication from Jan 2023 so we are in migration state to move all our customers to OAuth.

For .com customers we have migrated to OAuth by creating app in Azure app directory in a multi tenant way. Here client ID and secret is common for all.

Now we have few .us customers who are gov accounts . As from Microsoft those are categorised as national clouds so each customer has their own client ID and secret which means we need to ask customers to create app in their azure app directory and as then to share client creds to access. But this is not scalable soln as customers grow and we have double digit customers with .us

So how can we achieve multi tenant way for .us customers with common client ID and secret like commercial accounts.

Is it possible or any reference or way forward to achieve this.

Can any one please answer

Till now only solution we think of we need to ask each customer to create app and provide creds to us.

We are not getting any other solution


问:
How to keep the PostgreSQL "System Administration/Information functions" from read-only users
In my case, a read-only user can perform the "System Administration/Information functions".

I tried to restrict those functions by hard-coding that in my code. But that cannot be a proper solution, since there can be new such functions in future releases of PostgreSQL, or functions may get renamed.

So I need to get those functions dynamically. Is there a way to determine which function belong to the "System Administration/Information functions", or how to restrict access to them for a read-only user?


问:
solve the Unification problems in prolog given below
Do these terms unify? Why?

likes(jax, X). and likes(X, jin).

food(X, Y, Z). and food(M, M, M).

food(b, c, d(a)). and food(X, X, X).

In below clause, X will instantiate to what value?

[X|Y]= [likes(jin, black(dog)),likes(kate, dog)].

I need the answer for the above query and justify the answer.


问:
Adding font color in CkEditor5 react js
I am using CKeditor5 with Classic Editor and upload plugin in reactJs. I want to add font color functionality in text editor. As per documentation I've tried to install and use @ckeditor/ckeditor5-font, but it is giving me error of "ckeditor-duplicated-modules". How to add font color in the text editor?</p>
```<code>
import { CKEditor } from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
</code>```
```<code><CKEditor
                    config={{
                      extraPlugins: [uploadPlugin],
                    }}
                    editor={ClassicEditor}
                    data={value}
                    // onInit={(editor) => {}}
                    onReady={(editor) => {}}
                    onChange={this.handleCk5change}
                    className="ckeditor-custom"
                  />
</code>```

Title: Adding font color in CkEditor5 react js

Body:
I am using CKeditor5 with Classic Editor and upload plugin in reactJs. I want to add font color functionality in text editor. As per documentation I've tried to install and use @ckeditor/ckeditor5-font, but it is giving me error of "ckeditor-duplicated-modules". How to add font color in the text editor?

import { CKEditor } from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";

<CKEditor
                    config={{
                      extraPlugins: [uploadPlugin],
                    }}
                    editor={ClassicEditor}
                    data={value}
                    // onInit={(editor) => {}}
                    onReady={(editor) => {}}
                    onChange={this.handleCk5change}
                    className="ckeditor-custom"
                  />


问:
I tried to plot the points of a point cloud using matplotlib but the plot obtained is inclined when compared to original point cloud
I want the plot not to be inclined, can someone help me on this

I took the points with X,Y,Z co-ordinates and tried to plot on python using matplotlib


问:
Import sqlalchemy import *,SSHOperator and BranchPythonOperator
I am writing a python script. On top tried importing some modules from the packages.
I am confused with these lines. Can some one explain in simple terms, the "Meaning" of these lines?

I have just written these lines of code. I am stuck at understanding the difference between 'variable' and 'Variable' with a capital V.


问:
Ajax pagination not works properly and returns failure
I'm working with Laravel 9 and I wanted to make an infinite loader pagination with ajax for my blade.

So at the Controller:

```<code>public function index(Request $request)
    {

        $ques = Question::orderBy('created_at', 'DESC')->where('que_private',0)->paginate(10);
        if($request->ajax()){
            $view = view('frontend.layouts.partials.infinite',compact('ques'))->render();
            return response()->json(['html' => $view]);
        }
        return view('frontend.index', compact('ques'));
    }
</code>```

And in the index.blade.php:

```<code>function loadMoreData(page){
            $.ajax({
                url: '?page=' + page,
                type:'get',
                beforeSend: function ()
                {
                    $(".ajax-load").show();
                }
            })
                .done(function(data){
                    if(data.html == ""){
                        $('.ajax-load').html("");
                        return;
                    }
                    $('.ajax-load').hide();
                    $("#post-data").append(data.html);
                })
                .fail(function(jqXHR,ajaxOptions,thrownError){
                    alert("Server is not responding");
                });
        }
</code>```

And this is infinite.blade.php which ajax loads:

```<code><div id="post-data">
    @foreach($ques as $que)
    ...
    @endforeach
</div>
</code>```

When I test this, the image comes up properly but it returns Server is not responding error alert meaning that .fail(function(jqXHR,ajaxOptions,thrownError){ runs instead.

So what's going wrong here?

How can I solve this issue?

Body:
I'm working with Laravel 9 and I wanted to make an infinite loader pagination with ajax for my blade.

So at the Controller:

public function index(Request $request)
    {

        $ques = Question::orderBy('created_at', 'DESC')->where('que_private',0)->paginate(10);
        if($request->ajax()){
            $view = view('frontend.layouts.partials.infinite',compact('ques'))->render();
            return response()->json(['html' => $view]);
        }
        return view('frontend.index', compact('ques'));
    }

And in the index.blade.php:

function loadMoreData(page){
            $.ajax({
                url: '?page=' + page,
                type:'get',
                beforeSend: function ()
                {
                    $(".ajax-load").show();
                }
            })
                .done(function(data){
                    if(data.html == ""){
                        $('.ajax-load').html("");
                        return;
                    }
                    $('.ajax-load').hide();
                    $("#post-data").append(data.html);
                })
                .fail(function(jqXHR,ajaxOptions,thrownError){
                    alert("Server is not responding");
                });
        }

And this is infinite.blade.php which ajax loads:

    @foreach($ques as $que)
    ...
    @endforeach

When I test this, the image comes up properly but it returns Server is not responding error alert meaning that .fail(function(jqXHR,ajaxOptions,thrownError){ runs instead.

So what's going wrong here?

How can I solve this issue?


问:
Impala fnv_hash() result not matching the one in Python fnv library
I'm using Impala 3.2.0, and when I run fnv_hash(), I can't seem to be able to match the value with the fnv hash I get using Python, may I know why?

```<code>select fnv_hash('test')
7063314956707709637
</code>```
```<code>!pip install fnv
import fnv
fnv.hash(b'test', algorithm=fnv.fnv_1a, bits=64)
18007334074686647077
</code>```

Body:
I'm using Impala 3.2.0, and when I run fnv_hash(), I can't seem to be able to match the value with the fnv hash I get using Python, may I know why?

select fnv_hash('test')
7063314956707709637

!pip install fnv
import fnv
fnv.hash(b'test', algorithm=fnv.fnv_1a, bits=64)
18007334074686647077


问:
Warnings while saving model
I am using the following model for machine translation using transformer with KerasNLP:
`

```<code># Encoder
encoder_inputs = keras.Input(shape=(None,), dtype="int64", name="encoder_inputs")

x = keras_nlp.layers.TokenAndPositionEmbedding(
    vocabulary_size=ENG_VOCAB_SIZE,
    sequence_length=MAX_SEQUENCE_LENGTH,
    embedding_dim=EMBED_DIM,
    mask_zero=True,
)(encoder_inputs)

encoder_outputs = keras_nlp.layers.TransformerEncoder(
    intermediate_dim=INTERMEDIATE_DIM, num_heads=NUM_HEADS
)(inputs=x)
encoder = keras.Model(encoder_inputs, encoder_outputs)

# Decoder
decoder_inputs = keras.Input(shape=(None,), dtype="int64", name="decoder_inputs")
encoded_seq_inputs = keras.Input(shape=(None, EMBED_DIM), name="decoder_state_inputs")

x = keras_nlp.layers.TokenAndPositionEmbedding(
    vocabulary_size=SND_VOCAB_SIZE,
    sequence_length=MAX_SEQUENCE_LENGTH,
    embedding_dim=EMBED_DIM,
    mask_zero=True,
)(decoder_inputs)

x = keras_nlp.layers.TransformerDecoder(
    intermediate_dim=INTERMEDIATE_DIM, num_heads=NUM_HEADS
)(decoder_sequence=x, encoder_sequence=encoded_seq_inputs)
x = keras.layers.Dropout(0.5)(x)
decoder_outputs = keras.layers.Dense(SND_VOCAB_SIZE, activation="softmax")(x)
decoder = keras.Model(
    [
        decoder_inputs,
        encoded_seq_inputs,
    ],
    decoder_outputs,
)
decoder_outputs = decoder([decoder_inputs, encoder_outputs])

transformer = keras.Model(
    [encoder_inputs, decoder_inputs],
    decoder_outputs,
    name="transformer",
)
</code>```

`

`

```<code>transformer.summary()
transformer.compile(
    "rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
hist = transformer.fit(train_ds, epochs=EPOCHS, validation_data=val_ds)
</code>```

`

When I am trying to save the model it is giving me warnings and it is not predicting correctly:

`

```<code>with open('model.pkl', 'wb') as file:
  pickle.dump(transformer, file)
</code>```

`

WARNING:absl:Found untraced functions such as token_embedding1_layer_call_fn, token_embedding1_layer_call_and_return_conditional_losses, position_embedding1_layer_call_fn, position_embedding1_layer_call_and_return_conditional_losses, multi_head_attention_layer_call_fn while saving (showing 5 of 78). These functions will not be directly callable after loading.

Title: Warnings while saving model

Body:
I am using the following model for machine translation using transformer with KerasNLP:
`

# Encoder
encoder_inputs = keras.Input(shape=(None,), dtype="int64", name="encoder_inputs")

x = keras_nlp.layers.TokenAndPositionEmbedding(
    vocabulary_size=ENG_VOCAB_SIZE,
    sequence_length=MAX_SEQUENCE_LENGTH,
    embedding_dim=EMBED_DIM,
    mask_zero=True,
)(encoder_inputs)

encoder_outputs = keras_nlp.layers.TransformerEncoder(
    intermediate_dim=INTERMEDIATE_DIM, num_heads=NUM_HEADS
)(inputs=x)
encoder = keras.Model(encoder_inputs, encoder_outputs)

# Decoder
decoder_inputs = keras.Input(shape=(None,), dtype="int64", name="decoder_inputs")
encoded_seq_inputs = keras.Input(shape=(None, EMBED_DIM), name="decoder_state_inputs")

x = keras_nlp.layers.TokenAndPositionEmbedding(
    vocabulary_size=SND_VOCAB_SIZE,
    sequence_length=MAX_SEQUENCE_LENGTH,
    embedding_dim=EMBED_DIM,
    mask_zero=True,
)(decoder_inputs)

x = keras_nlp.layers.TransformerDecoder(
    intermediate_dim=INTERMEDIATE_DIM, num_heads=NUM_HEADS
)(decoder_sequence=x, encoder_sequence=encoded_seq_inputs)
x = keras.layers.Dropout(0.5)(x)
decoder_outputs = keras.layers.Dense(SND_VOCAB_SIZE, activation="softmax")(x)
decoder = keras.Model(
    [
        decoder_inputs,
        encoded_seq_inputs,
    ],
    decoder_outputs,
)
decoder_outputs = decoder([decoder_inputs, encoder_outputs])

transformer = keras.Model(
    [encoder_inputs, decoder_inputs],
    decoder_outputs,
    name="transformer",
)

`

`

transformer.summary()
transformer.compile(
    "rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
hist = transformer.fit(train_ds, epochs=EPOCHS, validation_data=val_ds)

`

When I am trying to save the model it is giving me warnings and it is not predicting correctly:

`

with open('model.pkl', 'wb') as file:
  pickle.dump(transformer, file)

`

WARNING:absl:Found untraced functions such as token_embedding1_layer_call_fn, token_embedding1_layer_call_and_return_conditional_losses, position_embedding1_layer_call_fn, position_embedding1_layer_call_and_return_conditional_losses, multi_head_attention_layer_call_fn while saving (showing 5 of 78). These functions will not be directly callable after loading.


问:
Capture network traffic using fiddler in Window Subsystem for Android (WSA)
Fiddler is not capturing network traffic of WSA. I want to set proxy in WSA so I can capture network traffic in fiddler, also before setting proxy in WSA, I also need to install Telerik Fiddler Certificate in WSA, how can I do this?

I tried enabling Advanced Networking option in WSA but it didn't worked and network stopped working in WSA

I also googled for how can I set proxy using adb but did not find anything


问:
The edit.blade in Laravel has a submit button for editing changes and updating, but it updated without any changes
Laravel's edit blade has an image tag to insert the image and updates the changes using a button in the form. There is a remove button in img tag that allows to remove and replace an image.
but the image is updated without any changes, and the uploaded image remains blank without any changes that occur on that particular page.

```<code>public function update(Request $request, $id)
    {
        //dd ($request[img_name]);
        $updateData = $request->validate([
            'img_name' => '',
            'name' => 'required|max:255',
            'url' => 'required|max:255',
            'description' => '|max:255',
        ]);
        if(!isset ($updateData['img_name'])){
        $updateData['img_name']='../../img/links/blank_img_link-370x65-min.png';
        }
        Info_links::whereId($id)->update($updateData);
        return redirect('/account/info_links/index')->with('completed', 'Informative link has been updated');

    }
</code>```

I expect it to submit using its submit button without any changes to the edit blade.

Body:
Laravel's edit blade has an image tag to insert the image and updates the changes using a button in the form. There is a remove button in img tag that allows to remove and replace an image.
but the image is updated without any changes, and the uploaded image remains blank without any changes that occur on that particular page.

public function update(Request $request, $id)
    {
        //dd ($request[img_name]);
        $updateData = $request->validate([
            'img_name' => '',
            'name' => 'required|max:255',
            'url' => 'required|max:255',
            'description' => '|max:255',
        ]);
        if(!isset ($updateData['img_name'])){
        $updateData['img_name']='../../img/links/blank_img_link-370x65-min.png';
        }
        Info_links::whereId($id)->update($updateData);
        return redirect('/account/info_links/index')->with('completed', 'Informative link has been updated');

    }

I expect it to submit using its submit button without any changes to the edit blade.


问:
Custom command to Create file/folder, Rename file/folder, Delete file/folder, Move file/folder | react-native-rename
Problem Statement

Hello everyone, I have been trying to rename my project App-name, package name using a single terminal command. I tried react-native-rename but not serving the purpose. Every-time I have to manually change some of the files. I'm looking for some custom & optimised solution.

Solution I'm expecting.

Is there any way to create a file where I can define a file where I can all of the file names to replace App Name or package name, Move package location. And I could execute that file through a command as well.

I'm new to this, please help me. You can just mention the documentation or give me the direction to move forward. that would be a great help.


问:
Auto Checked the Checkbox based on the data in database when Editing the data react, inertia , laravel
I need to auto-check the checkbox based on the data stored in the database. I'm trying to check the checkbox of the list of permissions given to the specified role when I try to edit the specified role, so the user doesn't need to add the permissions from zero. I'm using Laravel as the backend and Reactjs for the front end also Inertiajs as the bridge. I have no idea how to solve this.

I was able to retrieve the data from the controller which is included the specified role and the permission. I just need to auto-check the checkbox based on the data when user jump to edit feature.

export default function EditPermission(props) {
    const { role } = usePage().props

    const { data, setData, put, processing, errors, reset } = useForm({
        name: role.name || '',
        permissions: role.permissions || ''
    })

    const onHandleChange = event => {
        setData(event.target.name, event.target.type === 'checkbox' ? event.target.checked : event.target.value)
    }

    const handleChecked = e => {
        let value = e.target.name

        if (e.target.checked) {
            setData("permissions", [...data.permissions, value])
        } else {
            setData(
                "permissions",
                data.permissions.filter(item => {
                    return item !== value
                })
            )
        }
    }

    const submit = (e) => {
        e.preventDefault()

        put(route('role.update', permission.id))
    }

    return (
        <AuthenticatedLayout auth={props.auth} errors={props.errors}>

                {props.flash.message !== null ? <Flash message={props.flash.message} /> :

}
                <form onSubmit={submit}>

                        <InputLabel forInput="name" value="Role" />

                        <TextInput
                            type="text"
                            name="name"
                            value={data.name}
                            className="m-2 input input-bordered w-full"
                            autoComplete="name"
                            isFocused={true}
                            handleChange={onHandleChange}
                        />

                        <InputError message={errors.name} className="mt-2" />

                            { props.permissions && props.permissions.length > 0 ? props.permissions.map((permissions, i) => {
                                return (

                                        <Checkbox name={permissions.name} value={data.permissions} handleChange={handleChecked} />{permissions.name}

                                )}) :
Permission Belum Ada!

                            }

                        <InputError message={errors.permissions} className="mt-2" />

                        <PrimaryButton className="ml-4" processing={processing}>
                            Update
                        </PrimaryButton>

                </form>

        </AuthenticatedLayout>
    )
}
```


问:
Implementing drag a row from Angular Material table inside a node in angular material tree
I have a material table in following structure:

```<code><table mat-table #mailBox [dataSource]="inboxTableDataSource" class="mat-elevation-z8 demo-table">

  <ng-container matColumnDef="letterNumber">
    <th mat-header-cell *matHeaderCellDef> letter Number </th>
    <td mat-cell *matCellDef="let element"> {{element.letterNumber}} </td>
  </ng-container>

  <ng-container matColumnDef="subject">
    <th mat-header-cell *matHeaderCellDef> subject</th>
    <td mat-cell *matCellDef="let element"> {{element.subject}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row class="smf-gridrow" *matRowDef="let row; columns: displayedColumns;" [class.make-bold]='!row.isRead'
    style="cursor:pointer ;" [cdkContextMenuTriggerFor]="gridContextMenu"></tr>
</table>

<mat-paginator [length]="resultsLength" [pageSize]="15" [pageSizeOptions]="[10, 15, 25, 100]"
  [showFirstLastButtons]="true"></mat-paginator>
</code>```

and beside that I have a material tree as following:

```<code><mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <input type="checkbox" id="btnControl" />
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding (contextmenu)="onContextmenu(node,$event)" (click)="onNodeClick(node,$event)" class="treeNode"  [cdkContextMenuTriggerFor]="inboxFolderContextMenu">
    <!-- use a disabled button to provide padding for tree leaf -->
    <button mat-icon-button disabled></button>
    {{node.name}}
  </mat-tree-node>
  <!-- This is the tree node template for expandable nodes -->
  <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding (contextmenu)="onContextmenu(node,$event)" (ngclick)="onNodeClick(node,$event)"
    class="treeNode"  [cdkContextMenuTriggerFor]="inboxFolderContextMenu">
    <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'Toggle ' + node.name">
      <mat-icon class="mat-icon-rtl-mirror">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.name}}
  </mat-tree-node>
</code>```

I fill both table and tree from a sql server database.

now I'm trying to be able to drag a row from material table inside a node of material tree. is there a way to achieve this goal?

Body:
I have a material table in following structure:

  <ng-container matColumnDef="letterNumber">
     letter Number
     {{element.letterNumber}}
  </ng-container>

  <ng-container matColumnDef="subject">
     subject
     {{element.subject}}
  </ng-container>

<mat-paginator [length]="resultsLength" [pageSize]="15" [pageSizeOptions]="[10, 15, 25, 100]"
  [showFirstLastButtons]="true"></mat-paginator>

and beside that I have a material tree as following:

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <input type="checkbox" id="btnControl" />
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodePadding (contextmenu)="onContextmenu(node,$event)" (click)="onNodeClick(node,$event)" class="treeNode"  [cdkContextMenuTriggerFor]="inboxFolderContextMenu">

    <button mat-icon-button disabled></button>
    {{node.name}}
  </mat-tree-node>

  <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding (contextmenu)="onContextmenu(node,$event)" (ngclick)="onNodeClick(node,$event)"
    class="treeNode"  [cdkContextMenuTriggerFor]="inboxFolderContextMenu">
    <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'Toggle ' + node.name">
      <mat-icon class="mat-icon-rtl-mirror">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.name}}
  </mat-tree-node>

I fill both table and tree from a sql server database.

now I'm trying to be able to drag a row from material table inside a node of material tree. is there a way to achieve this goal?


问:
convert vtk point data to cell data
I want to convert my vtk point data files to cell data files with a specific cell size, my data is basically 100,000 points data moving in a cylinder, and those points have several variables such as velocity and coordination. could anyone help me out with this problem?

I try to use paraview to give them volumn but cannot be a cylinder. The "point data to cell data" filter cannot save my variables correctly, anyone can help with this case? sorry I cannot share my data due to some other reasons, maybe some hints could help me out of this.

Many thanks in advance!

Title: convert vtk point data to cell data


问:
Get Create as Select Table History Statement
Postgres 12

table created as select from other table(s)

```<code>create table t1
as
select t2.col1, t3.col2
from t2
join t3 on t2.colx=t3.coly
where t2.col4='XYZ';
</code>```

if table was created with above 'create as select' statement, is there any possibility that i can get above 'create as select' statement from the table 't1' definition or from somewhere else like 'information schema' etc?

Body:
Postgres 12

table created as select from other table(s)

create table t1
as
select t2.col1, t3.col2
from t2
join t3 on t2.colx=t3.coly
where t2.col4='XYZ';

if table was created with above 'create as select' statement, is there any possibility that i can get above 'create as select' statement from the table 't1' definition or from somewhere else like 'information schema' etc?


问:
Firebase realtime database get the File name only not the link token
Is there any way to remove the link and only get the file name of the file in the code? Im trying to access to load a model in my app that is created in android studio

This one doesn't work because it provides a link instead the name of the file

```<code> FirebaseStorage storage = FirebaseStorage.getInstance();
 StorageReference modelRef = storage.getReference().child(myPlants.getPlantModel());
</code>```

This code works

```<code>  FirebaseStorage storage = FirebaseStorage.getInstance();
  StorageReference modelRef = storage.getReference().child(pre4.glb);
</code>```

Is there a way to get the file name only and not the token? Please help.

The assigned text in the getPlantModel is the link.

Database Screenshot

```<code>public class PlantAR extends AppCompatActivity {
private ProgressDialog progressDialog;
Button downloadButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_plant_ar);

    Intent intent = getIntent();
    MyPlants myPlants = (MyPlants) intent.getSerializableExtra("plants");

    FirebaseApp.initializeApp(this);

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference modelRef = storage.getReference().child("pre6.glb");

    ArFragment arFragment = (ArFragment) getSupportFragmentManager()
            .findFragmentById(R.id.fragmentAR);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Model downloading Please Wait...........");

    downloadButton = findViewById(R.id.downloadModel);
    findViewById(R.id.downloadModel)
            .setOnClickListener(v -> {

                try {
                    File file = File.createTempFile("pre6", "glb");

                    progressDialog.show();

                    modelRef.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                            buildModel(file);

                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }

            });

    arFragment.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {

        AnchorNode anchorNode = new AnchorNode(hitResult.createAnchor());
        anchorNode.setRenderable(renderable);
        arFragment.getArSceneView().getScene().addChild(anchorNode);

    });
}
private ModelRenderable renderable;

private void buildModel(File file) {

    RenderableSource renderableSource = RenderableSource
            .builder()
            .setSource(this, Uri.parse(file.getPath()), RenderableSource.SourceType.GLB)
            .setRecenterMode(RenderableSource.RecenterMode.ROOT)
            .build();

    ModelRenderable
            .builder()
            .setSource(this, renderableSource)
            .setRegistryId(file.getPath())
            .build()
            .thenAccept(modelRenderable -> {
                downloadButton.setVisibility(View.GONE);

                progressDialog.dismiss();

                Toast.makeText(this, "Model built", Toast.LENGTH_SHORT).show();;
                renderable = modelRenderable;
            });

}
</code>```

Body:
Is there any way to remove the link and only get the file name of the file in the code? Im trying to access to load a model in my app that is created in android studio

This one doesn't work because it provides a link instead the name of the file

 FirebaseStorage storage = FirebaseStorage.getInstance();
 StorageReference modelRef = storage.getReference().child(myPlants.getPlantModel());

This code works

  FirebaseStorage storage = FirebaseStorage.getInstance();
  StorageReference modelRef = storage.getReference().child(pre4.glb);

Is there a way to get the file name only and not the token? Please help.

The assigned text in the getPlantModel is the link.

Database Screenshot

public class PlantAR extends AppCompatActivity {
private ProgressDialog progressDialog;
Button downloadButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_plant_ar);

    Intent intent = getIntent();
    MyPlants myPlants = (MyPlants) intent.getSerializableExtra("plants");

    FirebaseApp.initializeApp(this);

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference modelRef = storage.getReference().child("pre6.glb");

    ArFragment arFragment = (ArFragment) getSupportFragmentManager()
            .findFragmentById(R.id.fragmentAR);

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Model downloading Please Wait...........");

    downloadButton = findViewById(R.id.downloadModel);
    findViewById(R.id.downloadModel)
            .setOnClickListener(v -> {

                try {
                    File file = File.createTempFile("pre6", "glb");

                    progressDialog.show();

                    modelRef.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                            buildModel(file);

                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }

            });

    arFragment.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {

        AnchorNode anchorNode = new AnchorNode(hitResult.createAnchor());
        anchorNode.setRenderable(renderable);
        arFragment.getArSceneView().getScene().addChild(anchorNode);

    });
}
private ModelRenderable renderable;

private void buildModel(File file) {

    RenderableSource renderableSource = RenderableSource
            .builder()
            .setSource(this, Uri.parse(file.getPath()), RenderableSource.SourceType.GLB)
            .setRecenterMode(RenderableSource.RecenterMode.ROOT)
            .build();

    ModelRenderable
            .builder()
            .setSource(this, renderableSource)
            .setRegistryId(file.getPath())
            .build()
            .thenAccept(modelRenderable -> {
                downloadButton.setVisibility(View.GONE);

                progressDialog.dismiss();

                Toast.makeText(this, "Model built", Toast.LENGTH_SHORT).show();;
                renderable = modelRenderable;
            });

}


问:
Im getting error in this line "mne.externals.pymatreader import read_mat" and the error is - No module named 'mne.externals'
Im getting error in this line "mne.externals.pymatreader import read_mat" , and the error is -  No module named 'mne.externals'

I want to know how to remove this error


问:
issues running SD (no module named 'ldm.models'; ldm is not a package)
I am trying to run my code on a remote server because I needed more GPU but now I am getting this error and I don't understand how to fix it or what it means.
Has anyone had this issue or know how to fix it? I would really appreciate your help, spent hours already trying to resolve :(

```<code>[2022-12-07 05:27:14] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: Error when calling Cognitive Face API:
status_code: 401
code: 401
message: Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.
[2022-12-07 05:27:14] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: img_url:https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg
[2022-12-07 05:27:15] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: Error when calling Cognitive Face API:
status_code: 401
code: 401
message: Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.
[2022-12-07 05:27:15] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: img_url:/data1/mingmingzhao/label/data_sets_teacher_1w/47017613_1510574400_out-video-jzc70f41fa6f7145b4b66738f81f082b65_f_1510574403268_t_1510575931221.flv_0001.jpg
[]
Traceback (most recent call last):
File "main.py", line 5, in <module>
from ldm.models.diffusion.ddim import DDIMSampler
ModuleNotFoundError: No module named 'ldm.models'; 'ldm' is not a package
</code>```

when I ran this on local computer, had no issue besides it being super slow. not sure what I am missing!

I tried searching online and checking to make sure the ldm package was there, I checked versions of ldm and python.

Body:
I am trying to run my code on a remote server because I needed more GPU but now I am getting this error and I don't understand how to fix it or what it means.
Has anyone had this issue or know how to fix it? I would really appreciate your help, spent hours already trying to resolve :(

[2022-12-07 05:27:14] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: Error when calling Cognitive Face API:
status_code: 401
code: 401
message: Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.
[2022-12-07 05:27:14] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: img_url:https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg
[2022-12-07 05:27:15] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: Error when calling Cognitive Face API:
status_code: 401
code: 401
message: Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.
[2022-12-07 05:27:15] main.py -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  eprint(line:60) :: img_url:/data1/mingmingzhao/label/data_sets_teacher_1w/47017613_1510574400_out-video-jzc70f41fa6f7145b4b66738f81f082b65_f_1510574403268_t_1510575931221.flv_0001.jpg
[]
Traceback (most recent call last):
File "main.py", line 5, in <module>
from ldm.models.diffusion.ddim import DDIMSampler
ModuleNotFoundError: No module named 'ldm.models'; 'ldm' is not a package

when I ran this on local computer, had no issue besides it being super slow. not sure what I am missing!

I tried searching online and checking to make sure the ldm package was there, I checked versions of ldm and python.


问:
My scrollview is not working in react native app
im making scroll component visible when someone pressed on input

this is my itemfinder.js link https://drive.google.com/file/d/182ZQf7Ocx7hiJVfaJJjv_pvP32bL3kaN/view?usp=share_link

this is my file which i called itemfinder component https://drive.google.com/file/d/1dAQPk3Hw9vJ7CM3zbzGpCgDDw_LeGB54/view?usp=share_link

i want to make it scroll
im new to react native
anad im using expo for this

Thank you


问:
How to reset build numbers in Appstoreconnect, testflight?
I messed up build numbers by accident. Is there a way to fix this?


问:
How realise double price range on woocommerce In product card?
How to release it on woocommerce? What plugin can help? for example -> can be viewed here https://gyazo.com/4e51ef9b4d116286499cf99642cde51f. I understand how the calculations work, but I can't find the plugin, maybe someone knows how I can replicate this? thanks for the time!

Tried different plugins, currently I'm using "Additional Product Options" options for prices. This plugin has a slider, but I don't know how I can repeat what I show before.


问:
Swift: type 'any [protocol that conforms to view]' cannot conform to 'View'
I have a protocol that conforms to View:

```<code>public protocol ProtocolView: View {
  ...
}

</code>```

And then I would like to have a View that takes an array of views that conform to ProtocolView and displays them:

```<code>public struct SomeView: View {
  var model: Model

  public var body: some View {
    ScrollView {
      ForEach(0..<model.views.count) { item in
        model.views[item]
      }
    }
  }

  final class Model {
    var views: [any ProtocolView]

    init(views: [any ProtocolView]) {
      self.views = views
    }
  }
}
</code>```

However, when I do this, I get the following error:
type 'any ProtocolView' cannot conform to 'View'
Why does this happen, given that ProtocolView does conform to View, and how would I resolve this?

Body:
I have a protocol that conforms to View:

public protocol ProtocolView: View {
  ...
}

And then I would like to have a View that takes an array of views that conform to ProtocolView and displays them:

public struct SomeView: View {
  var model: Model

  public var body: some View {
    ScrollView {
      ForEach(0..<model.views.count) { item in
        model.views[item]
      }
    }
  }

  final class Model {
    var views: [any ProtocolView]

    init(views: [any ProtocolView]) {
      self.views = views
    }
  }
}

However, when I do this, I get the following error:
type 'any ProtocolView' cannot conform to 'View'
Why does this happen, given that ProtocolView does conform to View, and how would I resolve this?


问:
org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver : Resolved
```<code>
</code>```
```<code>@Value("${mobileapi}")
private String mobileapi;
</code>```
```<code>
@Override
    public String getcircleoperator(String mobilenum)throws JsonMappingException, JsonProcessingException {
        HttpHeaders headers1 = new HttpHeaders();
    HttpEntity<HttpHeaders> request = new HttpEntity<>(headers1);
        RestTemplate restTemplate = new RestTemplate();
        String newapivar=mobileapi+mobilenum.;
        ResponseEntity<String> responsee = restTemplate.exchange(newapivar,HttpMethod.GET,request,String.class);
        System.out.println("check these values new url"+responsee.getBody());

          ObjectMapper mapper = new ObjectMapper();
          MobileNumberResponse browsePlanResponses=mapper.readValue(responsee.getBody(), MobileNumberResponse.class);
        return  null;
    }
</code>```

I was try this code i get the error. in object mapper line throwing the Error. I don't know the why its just happened. can you please help me to solve this issues.

Body:
@Value("${mobileapi}")
private String mobileapi;

@Override
    public String getcircleoperator(String mobilenum)throws JsonMappingException, JsonProcessingException {
        HttpHeaders headers1 = new HttpHeaders();
    HttpEntity<HttpHeaders> request = new HttpEntity<>(headers1);
        RestTemplate restTemplate = new RestTemplate();
        String newapivar=mobileapi+mobilenum.;
        ResponseEntity<String> responsee = restTemplate.exchange(newapivar,HttpMethod.GET,request,String.class);
        System.out.println("check these values new url"+responsee.getBody());

          ObjectMapper mapper = new ObjectMapper();
          MobileNumberResponse browsePlanResponses=mapper.readValue(responsee.getBody(), MobileNumberResponse.class);
        return  null;
    }

I was try this code i get the error. in object mapper line throwing the Error. I don't know the why its just happened. can you please help me to solve this issues.


问:
How to handle an interface leak from leak canary?
I keep getting this leak in the canary about the interface from SubroutineParentItemAdapter Class wherein used in Subroutine Fragment. I do not understand how SubroutineParentItemAdapter.mOnClickListener is leaking and a way to fix it.

┬───

│ GC Root: Input or output parameters in native code

│

├─ dalvik.system.PathClassLoader instance

│    Leaking: NO (SubroutineParentItemAdapter↓ is not leaking and A ClassLoader

│    is never leaking)

│    ↓ ClassLoader.runtimeInternalObjects

├─ java.lang.Object[] array

│    Leaking: NO (SubroutineParentItemAdapter↓ is not leaking)

│    ↓ Object[1914]

├─ com.habitdev.sprout.ui.menu.subroutine.adapter.SubroutineParentItemAdapter

│  class

│    Leaking: NO (a class is never leaking)

│    ↓ static SubroutineParentItemAdapter.mOnClickListener

╰→ com.habitdev.sprout.ui.menu.subroutine.SubroutineFragment instance

     Leaking: YES (ObjectWatcher was watching this because com.habitdev.sprout.

     ui.menu.subroutine.SubroutineFragment received Fragment#onDestroy()

     callback. Conflicts with Fragment#mFragmentManager is not null)

     Retaining 1.2 kB in 34 objects

     key = 7e3f4168-59c3-4b4e-89f8-b7c2112ed785

     watchDurationMillis = 7398

     retainedDurationMillis = 2398

Subroutine.Class

```<code>public class SubroutineFragment extends Fragment implements SubroutineParentItemAdapter.OnClickListener, SubroutineModifyFragment.onClickBackPress {

    private FragmentSubroutineBinding binding;
    protected SubroutineModifyFragment subroutineModifyFragment = new SubroutineModifyFragment();

    public SubroutineFragment() {
        subroutineModifyFragment.setmOnClickBackPress(this);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentSubroutineBinding.inflate(inflater, container, false);
        setRecyclerViewAdapter();
        onBackPress();
        return binding.getRoot();
    }

    /**
     * Initialized and sets adapter for recyclerView
     */
    private void setRecyclerViewAdapter() {
        HabitWithSubroutinesViewModel habitWithSubroutinesViewModel = new ViewModelProvider(requireActivity()).get(HabitWithSubroutinesViewModel.class);
        binding.subroutineRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));

        SubroutineParentItemAdapter parentAdapterItem = new SubroutineParentItemAdapter();
        parentAdapterItem.setHabitsOnReform(habitWithSubroutinesViewModel.getAllHabitOnReform());

        setEmptyRVBackground(parentAdapterItem);

        parentAdapterItem.setmOnClickListener(this);
        parentAdapterItem.setSubroutineLifecycleOwner(getViewLifecycleOwner());
        parentAdapterItem.setHabitWithSubroutinesViewModel(habitWithSubroutinesViewModel);

        binding.subroutineRecyclerView.setAdapter(parentAdapterItem);

        habitWithSubroutinesViewModel.getAllHabitOnReformLiveData().observe(getViewLifecycleOwner(), habits -> {
            parentAdapterItem.setHabitsOnReform(habits);
            setEmptyRVBackground(parentAdapterItem);
        });
    }

    /**
     * Displays No subroutine on reform
     *
     * @param adapter SubroutineParentItemAdapter
     */
    private void setEmptyRVBackground(SubroutineParentItemAdapter adapter) {
        if (adapter.getItemCount() > 0) {
            binding.subroutineEmptyLottieRecyclerView.setVisibility(View.INVISIBLE);
            binding.subroutineEmptyLbl.setVisibility(View.INVISIBLE);
        } else {
            binding.subroutineEmptyLottieRecyclerView.setVisibility(View.VISIBLE);
            binding.subroutineEmptyLbl.setVisibility(View.VISIBLE);
        }
    }

    /**
     * Interface from SubroutineParentItemAdapter
     *
     * @param habit Habit on Modify
     */
    @Override
    public void onModifySubroutine(Habits habit) {
        subroutineModifyFragment.setHabit(habit);
        getChildFragmentManager().beginTransaction()
                .addToBackStack(SubroutineFragment.this.getTag())
                .add(binding.subroutineFrameLayout.getId(), subroutineModifyFragment)
                .commit();
        binding.subroutineContainer.setVisibility(View.GONE);
    }

    /**
     * Interface from SubroutineModify Fragment
     */
    @Override
    public void returnSubroutineFragment() {
        getChildFragmentManager()
                .beginTransaction()
                .remove(subroutineModifyFragment)
                .commit();
        binding.subroutineContainer.setVisibility(View.VISIBLE);
    }

    /**
     * Handle on BackPress
     */
    private void onBackPress() {
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                //Do something
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), callback);
    }

    /**
     * On Fragment Destroy
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
</code>```

Subroutine Parent Item Adapter Class

```<code>public class SubroutineParentItemAdapter extends RecyclerView.Adapter<SubroutineParentItemAdapter.ParentItemViewHolder> {

    private List<Habits> habitsOnReform;
    protected HabitWithSubroutinesViewModel habitWithSubroutinesViewModel;
    protected LifecycleOwner subroutineLifecycleOwner;

    public interface OnClickListener {
        void onModifySubroutine(Habits habit);
    }

    private static OnClickListener mOnClickListener;

    public void setmOnClickListener(OnClickListener mOnClickListener) {
        SubroutineParentItemAdapter.mOnClickListener = mOnClickListener;
    }

    public void setHabitWithSubroutinesViewModel(HabitWithSubroutinesViewModel habitWithSubroutinesViewModel) {
        this.habitWithSubroutinesViewModel = habitWithSubroutinesViewModel;
    }

    public void setSubroutineLifecycleOwner(LifecycleOwner subroutineLifecycleOwner) {
        this.subroutineLifecycleOwner = subroutineLifecycleOwner;
    }

    public SubroutineParentItemAdapter() {}

    @NonNull
    @Override
    public ParentItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ParentItemViewHolder(
                LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_subroutine_parent_item, parent, false)
        );
    }

    @Override
    public void onBindViewHolder(@NonNull ParentItemViewHolder holder, int position) {

        long uid = holder.bindData(habitsOnReform.get(position), mOnClickListener);

        LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(holder.childRecycleView.getContext(), R.anim.layout_animation_fall);
        holder.childRecycleView.setLayoutAnimation(animationController);

        List<Subroutines> habitWithSubroutines;

        habitWithSubroutines = habitWithSubroutinesViewModel.getAllSubroutinesOfHabit(uid);
        SubroutineChildItemAdapter childAdapterItem = new SubroutineChildItemAdapter(habitWithSubroutines);
        holder.childRecycleView.setAdapter(childAdapterItem);

        childAdapterItem.setHabitWithSubroutines(habitWithSubroutines);

        habitWithSubroutinesViewModel.getAllSubroutinesOnReformHabitLiveData(uid).observe(subroutineLifecycleOwner, childAdapterItem::setHabitWithSubroutines);

        setItemTouchHelper(holder, childAdapterItem);
    }

    private void setItemTouchHelper(SubroutineParentItemAdapter.ParentItemViewHolder holder, SubroutineChildItemAdapter childAdapterItem) {

        ItemTouchHelper itemTouchHelper;
        ItemTouchHelper.Callback itemTouchHelperCallback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(0, ItemTouchHelper.END | ItemTouchHelper.START);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public boolean isItemViewSwipeEnabled() {
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                switch (direction) {
                    case ItemTouchHelper.END:
                    case ItemTouchHelper.START:
                        SubroutineChildItemAdapter.ChildItemViewHolder childItemViewHolder;
                        childItemViewHolder = (SubroutineChildItemAdapter.ChildItemViewHolder) viewHolder;
                        childAdapterItem.notifyItemChanged(childItemViewHolder.getAbsoluteAdapterPosition());
                        break;
                }
            }
        };
        itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);
        itemTouchHelper.attachToRecyclerView(holder.childRecycleView);
    }

    @Override
    public int getItemCount() {
        return habitsOnReform.size();
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    public void setHabitsOnReform(List<Habits> habitsOnReform) {
        this.habitsOnReform = habitsOnReform;
    }

    public static class ParentItemViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout itemLayout;
        TextView HabitsTitle;
        Button ModifySubroutine;
        RecyclerView childRecycleView;
        Drawable cloud, amethyst, sunflower, nephritis, bright_sky_blue, alzarin;

        public ParentItemViewHolder(@NonNull View itemView) {
            super(itemView);
            itemLayout = itemView.findViewById(R.id.subroutine_parent_item_layout);
            HabitsTitle = itemView.findViewById(R.id.subroutine_parent_item_habit_title);
            ModifySubroutine = itemView.findViewById(R.id.subroutine_parent_item_modify_subroutine);
            childRecycleView = itemView.findViewById(R.id.subroutine_child_recyclerview);

            cloud = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_cloud_selector);
            amethyst = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_amethyst_selector);
            sunflower = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_sunflower_selector);
            nephritis = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_nephritis_selector);
            bright_sky_blue = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_brightsky_blue_selector);
            alzarin = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_alzarin_selector);
        }

        @SuppressLint("ClickableViewAccessibility")
        long bindData(Habits habit, OnClickListener mOnClickListener) {

            if (habit.getColor().equals(AppColor.ALZARIN.getColor())) {
                itemLayout.setBackground(alzarin);
            } else if (habit.getColor().equals(AppColor.AMETHYST.getColor())) {
                itemLayout.setBackground(amethyst);
            } else if (habit.getColor().equals(AppColor.BRIGHT_SKY_BLUE.getColor())) {
                itemLayout.setBackground(bright_sky_blue);
            } else if (habit.getColor().equals(AppColor.NEPHRITIS.getColor())) {
                itemLayout.setBackground(nephritis);
            } else if (habit.getColor().equals(AppColor.SUNFLOWER.getColor())) {
                itemLayout.setBackground(sunflower);
            } else {
                itemLayout.setBackground(cloud);
            }

            HabitsTitle.setText(habit.getHabit());

            HabitsTitle.setPadding(padding_inPx(10), padding_inPx(0), padding_inPx(10), padding_inPx(5));

            itemLayout.setOnClickListener(view -> {
                childRecycleView.getVisibility();
                if (childRecycleView.getVisibility() == View.GONE) {
                    LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(childRecycleView.getContext(), R.anim.layout_animation_fall);
                    childRecycleView.setLayoutAnimation(animationController);
                    childRecycleView.setVisibility(View.VISIBLE);
                } else {
                    LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(childRecycleView.getContext(), R.anim.layout_animation_up);
                    childRecycleView.setLayoutAnimation(animationController);
                    if (!childRecycleView.isAnimating()) childRecycleView.setVisibility(View.GONE);
                }
            });

            itemLayout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        HabitsTitle.setPadding(padding_inPx(10), padding_inPx(5), padding_inPx(10), padding_inPx(0));
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                        HabitsTitle.setPadding(padding_inPx(10), padding_inPx(0), padding_inPx(10), padding_inPx(5));
                    }
                    return false;
                }
            });

            if (habit.isModifiable()) {
                ModifySubroutine.setOnClickListener(view -> {
                    mOnClickListener.onModifySubroutine(habit); //OnclickListener Here
                });
            } else {
                ModifySubroutine.setVisibility(View.GONE);
            }

            return habit.getPk_habit_uid();
        }

        int padding_inPx(int dp) {
            final float scale = itemLayout.getResources().getDisplayMetrics().density;
            return (int) (dp * scale + 0.5f);
        }
    }

    /**
     * Detach mOnClickListener
     * @param recyclerView
     */
    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        if (mOnClickListener != null) {
            mOnClickListener = null;
        }
    }
}
</code>```

How do you deal with SubroutineParentItemAdapter.mOnClickListener, as Leak Canary Detected?
I tried to fix this by overriding onDetachFromRecyclerView and setting mOnclickListener null, but it does not seem to work. What is the practice of making a custom interface nonleaking?

Body:
I keep getting this leak in the canary about the interface from SubroutineParentItemAdapter Class wherein used in Subroutine Fragment. I do not understand how SubroutineParentItemAdapter.mOnClickListener is leaking and a way to fix it.

┬───

│ GC Root: Input or output parameters in native code

│

├─ dalvik.system.PathClassLoader instance

│    Leaking: NO (SubroutineParentItemAdapter↓ is not leaking and A ClassLoader

│    is never leaking)

│    ↓ ClassLoader.runtimeInternalObjects

├─ java.lang.Object[] array

│    Leaking: NO (SubroutineParentItemAdapter↓ is not leaking)

│    ↓ Object[1914]

├─ com.habitdev.sprout.ui.menu.subroutine.adapter.SubroutineParentItemAdapter

│  class

│    Leaking: NO (a class is never leaking)

│    ↓ static SubroutineParentItemAdapter.mOnClickListener

╰→ com.habitdev.sprout.ui.menu.subroutine.SubroutineFragment instance

     Leaking: YES (ObjectWatcher was watching this because com.habitdev.sprout.

     ui.menu.subroutine.SubroutineFragment received Fragment#onDestroy()

     callback. Conflicts with Fragment#mFragmentManager is not null)

     Retaining 1.2 kB in 34 objects

     key = 7e3f4168-59c3-4b4e-89f8-b7c2112ed785

     watchDurationMillis = 7398

     retainedDurationMillis = 2398

Subroutine.Class

public class SubroutineFragment extends Fragment implements SubroutineParentItemAdapter.OnClickListener, SubroutineModifyFragment.onClickBackPress {

    private FragmentSubroutineBinding binding;
    protected SubroutineModifyFragment subroutineModifyFragment = new SubroutineModifyFragment();

    public SubroutineFragment() {
        subroutineModifyFragment.setmOnClickBackPress(this);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentSubroutineBinding.inflate(inflater, container, false);
        setRecyclerViewAdapter();
        onBackPress();
        return binding.getRoot();
    }

    /**
     * Initialized and sets adapter for recyclerView
     */
    private void setRecyclerViewAdapter() {
        HabitWithSubroutinesViewModel habitWithSubroutinesViewModel = new ViewModelProvider(requireActivity()).get(HabitWithSubroutinesViewModel.class);
        binding.subroutineRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));

        SubroutineParentItemAdapter parentAdapterItem = new SubroutineParentItemAdapter();
        parentAdapterItem.setHabitsOnReform(habitWithSubroutinesViewModel.getAllHabitOnReform());

        setEmptyRVBackground(parentAdapterItem);

        parentAdapterItem.setmOnClickListener(this);
        parentAdapterItem.setSubroutineLifecycleOwner(getViewLifecycleOwner());
        parentAdapterItem.setHabitWithSubroutinesViewModel(habitWithSubroutinesViewModel);

        binding.subroutineRecyclerView.setAdapter(parentAdapterItem);

        habitWithSubroutinesViewModel.getAllHabitOnReformLiveData().observe(getViewLifecycleOwner(), habits -> {
            parentAdapterItem.setHabitsOnReform(habits);
            setEmptyRVBackground(parentAdapterItem);
        });
    }

    /**
     * Displays No subroutine on reform
     *
     * @param adapter SubroutineParentItemAdapter
     */
    private void setEmptyRVBackground(SubroutineParentItemAdapter adapter) {
        if (adapter.getItemCount() > 0) {
            binding.subroutineEmptyLottieRecyclerView.setVisibility(View.INVISIBLE);
            binding.subroutineEmptyLbl.setVisibility(View.INVISIBLE);
        } else {
            binding.subroutineEmptyLottieRecyclerView.setVisibility(View.VISIBLE);
            binding.subroutineEmptyLbl.setVisibility(View.VISIBLE);
        }
    }

    /**
     * Interface from SubroutineParentItemAdapter
     *
     * @param habit Habit on Modify
     */
    @Override
    public void onModifySubroutine(Habits habit) {
        subroutineModifyFragment.setHabit(habit);
        getChildFragmentManager().beginTransaction()
                .addToBackStack(SubroutineFragment.this.getTag())
                .add(binding.subroutineFrameLayout.getId(), subroutineModifyFragment)
                .commit();
        binding.subroutineContainer.setVisibility(View.GONE);
    }

    /**
     * Interface from SubroutineModify Fragment
     */
    @Override
    public void returnSubroutineFragment() {
        getChildFragmentManager()
                .beginTransaction()
                .remove(subroutineModifyFragment)
                .commit();
        binding.subroutineContainer.setVisibility(View.VISIBLE);
    }

    /**
     * Handle on BackPress
     */
    private void onBackPress() {
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                //Do something
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), callback);
    }

    /**
     * On Fragment Destroy
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

Subroutine Parent Item Adapter Class

public class SubroutineParentItemAdapter extends RecyclerView.Adapter<SubroutineParentItemAdapter.ParentItemViewHolder> {

    private List<Habits> habitsOnReform;
    protected HabitWithSubroutinesViewModel habitWithSubroutinesViewModel;
    protected LifecycleOwner subroutineLifecycleOwner;

    public interface OnClickListener {
        void onModifySubroutine(Habits habit);
    }

    private static OnClickListener mOnClickListener;

    public void setmOnClickListener(OnClickListener mOnClickListener) {
        SubroutineParentItemAdapter.mOnClickListener = mOnClickListener;
    }

    public void setHabitWithSubroutinesViewModel(HabitWithSubroutinesViewModel habitWithSubroutinesViewModel) {
        this.habitWithSubroutinesViewModel = habitWithSubroutinesViewModel;
    }

    public void setSubroutineLifecycleOwner(LifecycleOwner subroutineLifecycleOwner) {
        this.subroutineLifecycleOwner = subroutineLifecycleOwner;
    }

    public SubroutineParentItemAdapter() {}

    @NonNull
    @Override
    public ParentItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ParentItemViewHolder(
                LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_subroutine_parent_item, parent, false)
        );
    }

    @Override
    public void onBindViewHolder(@NonNull ParentItemViewHolder holder, int position) {

        long uid = holder.bindData(habitsOnReform.get(position), mOnClickListener);

        LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(holder.childRecycleView.getContext(), R.anim.layout_animation_fall);
        holder.childRecycleView.setLayoutAnimation(animationController);

        List<Subroutines> habitWithSubroutines;

        habitWithSubroutines = habitWithSubroutinesViewModel.getAllSubroutinesOfHabit(uid);
        SubroutineChildItemAdapter childAdapterItem = new SubroutineChildItemAdapter(habitWithSubroutines);
        holder.childRecycleView.setAdapter(childAdapterItem);

        childAdapterItem.setHabitWithSubroutines(habitWithSubroutines);

        habitWithSubroutinesViewModel.getAllSubroutinesOnReformHabitLiveData(uid).observe(subroutineLifecycleOwner, childAdapterItem::setHabitWithSubroutines);

        setItemTouchHelper(holder, childAdapterItem);
    }

    private void setItemTouchHelper(SubroutineParentItemAdapter.ParentItemViewHolder holder, SubroutineChildItemAdapter childAdapterItem) {

        ItemTouchHelper itemTouchHelper;
        ItemTouchHelper.Callback itemTouchHelperCallback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(0, ItemTouchHelper.END | ItemTouchHelper.START);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public boolean isItemViewSwipeEnabled() {
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                switch (direction) {
                    case ItemTouchHelper.END:
                    case ItemTouchHelper.START:
                        SubroutineChildItemAdapter.ChildItemViewHolder childItemViewHolder;
                        childItemViewHolder = (SubroutineChildItemAdapter.ChildItemViewHolder) viewHolder;
                        childAdapterItem.notifyItemChanged(childItemViewHolder.getAbsoluteAdapterPosition());
                        break;
                }
            }
        };
        itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);
        itemTouchHelper.attachToRecyclerView(holder.childRecycleView);
    }

    @Override
    public int getItemCount() {
        return habitsOnReform.size();
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    public void setHabitsOnReform(List<Habits> habitsOnReform) {
        this.habitsOnReform = habitsOnReform;
    }

    public static class ParentItemViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout itemLayout;
        TextView HabitsTitle;
        Button ModifySubroutine;
        RecyclerView childRecycleView;
        Drawable cloud, amethyst, sunflower, nephritis, bright_sky_blue, alzarin;

        public ParentItemViewHolder(@NonNull View itemView) {
            super(itemView);
            itemLayout = itemView.findViewById(R.id.subroutine_parent_item_layout);
            HabitsTitle = itemView.findViewById(R.id.subroutine_parent_item_habit_title);
            ModifySubroutine = itemView.findViewById(R.id.subroutine_parent_item_modify_subroutine);
            childRecycleView = itemView.findViewById(R.id.subroutine_child_recyclerview);

            cloud = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_cloud_selector);
            amethyst = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_amethyst_selector);
            sunflower = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_sunflower_selector);
            nephritis = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_nephritis_selector);
            bright_sky_blue = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_brightsky_blue_selector);
            alzarin = ContextCompat.getDrawable(itemView.getContext(), R.drawable.background_btn_alzarin_selector);
        }

        @SuppressLint("ClickableViewAccessibility")
        long bindData(Habits habit, OnClickListener mOnClickListener) {

            if (habit.getColor().equals(AppColor.ALZARIN.getColor())) {
                itemLayout.setBackground(alzarin);
            } else if (habit.getColor().equals(AppColor.AMETHYST.getColor())) {
                itemLayout.setBackground(amethyst);
            } else if (habit.getColor().equals(AppColor.BRIGHT_SKY_BLUE.getColor())) {
                itemLayout.setBackground(bright_sky_blue);
            } else if (habit.getColor().equals(AppColor.NEPHRITIS.getColor())) {
                itemLayout.setBackground(nephritis);
            } else if (habit.getColor().equals(AppColor.SUNFLOWER.getColor())) {
                itemLayout.setBackground(sunflower);
            } else {
                itemLayout.setBackground(cloud);
            }

            HabitsTitle.setText(habit.getHabit());

            HabitsTitle.setPadding(padding_inPx(10), padding_inPx(0), padding_inPx(10), padding_inPx(5));

            itemLayout.setOnClickListener(view -> {
                childRecycleView.getVisibility();
                if (childRecycleView.getVisibility() == View.GONE) {
                    LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(childRecycleView.getContext(), R.anim.layout_animation_fall);
                    childRecycleView.setLayoutAnimation(animationController);
                    childRecycleView.setVisibility(View.VISIBLE);
                } else {
                    LayoutAnimationController animationController = AnimationUtils.loadLayoutAnimation(childRecycleView.getContext(), R.anim.layout_animation_up);
                    childRecycleView.setLayoutAnimation(animationController);
                    if (!childRecycleView.isAnimating()) childRecycleView.setVisibility(View.GONE);
                }
            });

            itemLayout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        HabitsTitle.setPadding(padding_inPx(10), padding_inPx(5), padding_inPx(10), padding_inPx(0));
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                        HabitsTitle.setPadding(padding_inPx(10), padding_inPx(0), padding_inPx(10), padding_inPx(5));
                    }
                    return false;
                }
            });

            if (habit.isModifiable()) {
                ModifySubroutine.setOnClickListener(view -> {
                    mOnClickListener.onModifySubroutine(habit); //OnclickListener Here
                });
            } else {
                ModifySubroutine.setVisibility(View.GONE);
            }

            return habit.getPk_habit_uid();
        }

        int padding_inPx(int dp) {
            final float scale = itemLayout.getResources().getDisplayMetrics().density;
            return (int) (dp * scale + 0.5f);
        }
    }

    /**
     * Detach mOnClickListener
     * @param recyclerView
     */
    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        if (mOnClickListener != null) {
            mOnClickListener = null;
        }
    }
}

How do you deal with SubroutineParentItemAdapter.mOnClickListener, as Leak Canary Detected?
I tried to fix this by overriding onDetachFromRecyclerView and setting mOnclickListener null, but it does not seem to work. What is the practice of making a custom interface nonleaking?


问:
Is it possible to add multiple DbContext Factories for the same DbContext to the services collection?
Is it possible to add more than 1 DbContextFactory, for the same DbContext, to the services collection in an ASP.NET Core application?

For example, I am trying the following code ...

```<code>services
  .AddDbContextFactory<WibWorkspaceContext, WibWorkspaceContextFactory>();

services
  .AddDbContextFactory<WibWorkspaceContext, WibWorkspaceSystemContextFactory>();
</code>```

I want two different factories for the same DbContext. One factory always signs in using a SQL "admin" account and the other uses user-specific accounts.

I can't seem to figure out how to get this to work, though. How can I specify which one to use on the side of things that grab the service? For example, here's a constructor receiving the service - how does it know which one to use?

```<code>public async Task Invoke(HttpContext httpContext, IDbContextFactory<WibWorkspaceContext> contextFactory, IConfiguration configuration)
</code>```

Is this possible?

Body:
Is it possible to add more than 1 DbContextFactory, for the same DbContext, to the services collection in an ASP.NET Core application?

For example, I am trying the following code ...

services
  .AddDbContextFactory<WibWorkspaceContext, WibWorkspaceContextFactory>();

services
  .AddDbContextFactory<WibWorkspaceContext, WibWorkspaceSystemContextFactory>();

I want two different factories for the same DbContext. One factory always signs in using a SQL "admin" account and the other uses user-specific accounts.

I can't seem to figure out how to get this to work, though. How can I specify which one to use on the side of things that grab the service? For example, here's a constructor receiving the service - how does it know which one to use?

public async Task Invoke(HttpContext httpContext, IDbContextFactory<WibWorkspaceContext> contextFactory, IConfiguration configuration)

Is this possible?


问:
Is there an R function to group categorical variables?
I've started learning R. I have a dataset about price and determinants of the price such as size, room and age. The observation of 'age' can be 'before 1900', '1900-1929', '1930-1949'... and '2007 onwards'.

The 'age' column in the data

I tried to divide those years into two group (before 1900 and after 1900) and create a dummy variable for this with ifelse to put it in a linear regression model. However, when I use the lm function and summary the results, R still shows that I have 10 variables of age ('age_before 1900', 'age_1900-1929'...)

The result in R

I think maybe I was wrong when I used dylpr::recode to name those '1900-1929', '1930-1949'... to 'after 1900'. How can I group those into two class 'before 1900' and 'after 1900'?


问:
click datatable step defination for cucumber watir ruby framework
Does anyone have proper practical step definition for this?

And I click the following likes:
| a |
| b |

Expecting proper step definition to click those elements from datatable


问:
Converting Sagemaker project Cloudformation code to Terraform
I am trying to convert Cloudformation code to Terraform. The YAML file which I have is for the SageMaker project, provided by AWS.
I want to create a CodeCommit repository in Terraform for ModelBuild and ModelDeploy.
I am able to create the repository in Terraform using the below syntax

```<code>resource "aws_codecommit_repository" "test" {
repository_name = "MyTestRepository"
description     = "This is the Sample App Repository"
}
</code>```

This creates an empty repo.
Though when my repo is getting created, at the same time I want to add all necessary files in it from an S3 bucket(seed code provided by AWS)

This is what I have done till now.
For reference purposes the CodeCommit repository in Cloudformation is done using

```<code>ModelBuildCodeCommitRepository:
    Type: AWS::CodeCommit::Repository
    Properties:
      # Max allowed length: 100 chars
      RepositoryName: !Sub sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-modelbuild # max: 10+33+15+10=68
      RepositoryDescription: !Sub SageMaker Model building workflow infrastructure as code for the Project ${SageMakerProjectName}
      Code:
        S3:
          Bucket: sagemaker-servicecatalog-seedcode-eu-west-2
          Key: toolchain/image-build-model-building-workflow-v1.0.zip
        BranchName: main

</code>```

And So far I have defined this in Terraform using

```<code>resource "aws_codecommit_repository" "model_build_code_commit_repository" {
  repository_name = "sagemaker-${var.sage_maker_project_name}-${var.sage_maker_project_id}-modelbuild"
  description     = "SageMaker Model building workflow infrastructure as code for the Project ${var.sage_maker_project_name}"
  default_branch = var.repo_default_branch
}
</code>```

As you can see in Clodformation yaml I want to load the data from S3 bucket in my repo.
I went through their documentation, though was not able to find any solution for this.

Body:
I am trying to convert Cloudformation code to Terraform. The YAML file which I have is for the SageMaker project, provided by AWS.
I want to create a CodeCommit repository in Terraform for ModelBuild and ModelDeploy.
I am able to create the repository in Terraform using the below syntax

resource "aws_codecommit_repository" "test" {
repository_name = "MyTestRepository"
description     = "This is the Sample App Repository"
}

This creates an empty repo.
Though when my repo is getting created, at the same time I want to add all necessary files in it from an S3 bucket(seed code provided by AWS)

This is what I have done till now.
For reference purposes the CodeCommit repository in Cloudformation is done using

ModelBuildCodeCommitRepository:
    Type: AWS::CodeCommit::Repository
    Properties:
      # Max allowed length: 100 chars
      RepositoryName: !Sub sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-modelbuild # max: 10+33+15+10=68
      RepositoryDescription: !Sub SageMaker Model building workflow infrastructure as code for the Project ${SageMakerProjectName}
      Code:
        S3:
          Bucket: sagemaker-servicecatalog-seedcode-eu-west-2
          Key: toolchain/image-build-model-building-workflow-v1.0.zip
        BranchName: main

And So far I have defined this in Terraform using

resource "aws_codecommit_repository" "model_build_code_commit_repository" {
  repository_name = "sagemaker-${var.sage_maker_project_name}-${var.sage_maker_project_id}-modelbuild"
  description     = "SageMaker Model building workflow infrastructure as code for the Project ${var.sage_maker_project_name}"
  default_branch = var.repo_default_branch
}

As you can see in Clodformation yaml I want to load the data from S3 bucket in my repo.
I went through their documentation, though was not able to find any solution for this.


问:
How to configure eslint for particular ECMA features?

The project targets specific version of Node.js. This is the runtime of the code.

There is no transpilation step. JavaScript code is deployed as it is.

Particular Node version can support particular ECMA version partly. I want to use those features that are supported.

Eslint allows for specifying compatibility as ECMA version only, as far as I know.

How can I tell Eslint that a particular ECMA feature is supported?

For example: https://kangax.github.io/compat-table/es2016plus/#node16_9. Node v16.9 supports ES2022 only partly, so I cannot set ecmaVersion to 2022. But I want to use instance class fields, for example, which is supported by Node v16.9.

I know about https://github.com/mysticatea/eslint-plugin-node and its fork https://github.com/eslint-community/eslint-plugin-n, which are supposed to somehow configure Eslint based on the package.engines.node value. But my question is about the core Eslint - is there a way of configuring particular ECMA features that are supported by the runtime?