问:
Github GraphQL explorer - Get contributions per repository for a user
I'm creating a christmas summary for my team and I am trying to use githubs GraphQL Explorer over at https://docs.github.com/en/graphql/overview/explorer

I'm having some trouble to create the query I want to build. I'm trying to get contributions per repo for a user. Can anyone help out?

I tried to build upon a query I found online, but it only gave me per day.

I figured it out!

```<code>{
  search(query: "org:test", type: REPOSITORY, last: 100) {
    nodes {
      ... on Repository {
        name
        defaultBranchRef {
          name
          target {
            ... on Commit {
              history(first: 100, since: "2013-07-11T00:00:00") {
                totalCount
                nodes {
                  ... on Commit {
                    committedDate
                    additions
                    author {
                      name
                      email
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Body:
I'm creating a christmas summary for my team and I am trying to use githubs GraphQL Explorer over at https://docs.github.com/en/graphql/overview/explorer

I'm having some trouble to create the query I want to build. I'm trying to get contributions per repo for a user. Can anyone help out?

I tried to build upon a query I found online, but it only gave me per day.

I figured it out!

{
  search(query: "org:test", type: REPOSITORY, last: 100) {
    nodes {
      ... on Repository {
        name
        defaultBranchRef {
          name
          target {
            ... on Commit {
              history(first: 100, since: "2013-07-11T00:00:00") {
                totalCount
                nodes {
                  ... on Commit {
                    committedDate
                    additions
                    author {
                      name
                      email
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}


来源: stackexchange

问:
Clang ignores `__attribute__((aligned))` when used with an alias template
For writing SIMD code, I'd like to use templates to generate vector types with certain alignment. However, clang seems to ignore the alignment attribute when used with an alias template instead of a type alias.

Consider this code (godbolt):

#include <iostream>
#include <cstdint>

template <typename T=void>
using TemplatedT __attribute__((aligned(8))) = uint32_t;

using ManualT __attribute__((aligned(8))) = uint32_t;

int main() {
    std::cout << "alignof Template: " << alignof(TemplatedT<>) << std::endl;
    std::cout << "alignof Manual:   " << alignof(ManualT) << std::endl;
}
```
<p>With gcc 12.2, both aliases have an alignment of 8, as I would expect.
With clang 15 and trunk, the templated alias has an alignment of 4, ignoring the attribute.</p>
<p>Is this a bug? I looked through the open llvm issues but couldn't find a matching one.</p>
<p>Is there any workaround I can use?</p>
<hr />
<p>Edit: As @HolyBlackCat proposed in the comments, extracting the templating to a wrapping <code>struct</code> seems to be a workaround:</p>
<pre class="lang-cpp prettyprint-override"><code>template<typename ScalarT>
struct Vec {
    using T __attribute__((aligned(8))) = ScalarT;
};
// and then use Vec<uint32_t>::T
</code>```

Edit2:

I've opened an issue with the LLVM project at https://github.com/llvm/llvm-project/issues/59788.

ContentLicense: CC BY-SA 4.0

Body:
For writing SIMD code, I'd like to use templates to generate vector types with certain alignment. However, clang seems to ignore the alignment attribute when used with an alias template instead of a type alias.

Consider this code (godbolt):

#include <iostream>
#include <cstdint>

template <typename T=void>
using TemplatedT __attribute__((aligned(8))) = uint32_t;

using ManualT __attribute__((aligned(8))) = uint32_t;

int main() {
    std::cout << "alignof Template: " << alignof(TemplatedT<>) << std::endl;
    std::cout << "alignof Manual:   " << alignof(ManualT) << std::endl;
}

With gcc 12.2, both aliases have an alignment of 8, as I would expect.
With clang 15 and trunk, the templated alias has an alignment of 4, ignoring the attribute.

Is this a bug? I looked through the open llvm issues but couldn't find a matching one.

Is there any workaround I can use?

Edit: As @HolyBlackCat proposed in the comments, extracting the templating to a wrapping struct seems to be a workaround:

template<typename ScalarT>
struct Vec {
    using T __attribute__((aligned(8))) = ScalarT;
};
// and then use Vec<uint32_t>::T

Edit2:

I've opened an issue with the LLVM project at https://github.com/llvm/llvm-project/issues/59788.


问:
Add/update fields on My Account page in Woocommerce
I need to create My Account page for registered users with changeable fields on backend and frontend.

Now the fields are updated if I change the values through the admin panel. However, if I change the field values through My Account, the fields are not saved or updated.

What do i need to change or add to the code?

I used the following LoicTheAztec's answers:

Add a custom field in Woocommerce Edit Account page

Adding some my account custom fields to admin user pages in Woocommerce

Adding an additional custom field in Woocommerce Edit Account page

My code:

Template:

$user = wp_get_current_user();

<form class="tabs-content__page_inner woocommerce-EditAccountForm edit-account" action="" method="post"

          <?php esc_html_e( 'Телефон', 'woocommerce' ); ?>

               <input type="text" class="tab-field__input woocommerce-Input woocommerce-Input--text input-text" name="account_phone" id="account_phone" value="<?php echo esc_attr( $user->account_phone ); ?>" />

</form>```
</div>
</div>
</p>
<ol start="2">
<li>functions.php</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
add_action('woocommerce_save_account_details', 'save_phone_number_account_details', 20, 1);
function save_phone_number_account_details($user_id) {
    if( isset( $_POST['account_phone'] ) ) {
        update_user_meta( $user_id, 'account_phone', sanitize_text_field( $_POST['account_phone'] ) );
    }
}

//custom field in admin console
add_action( 'show_user_profile', 'add_extra_custom_user_data', 1, 1 );
add_action( 'edit_user_profile', 'add_extra_custom_user_data', 1, 1 );
function add_extra_custom_user_data( $user )
{
?>
<h3><?php _e("Other details",'woocommerce' ); ?></h3>
         <table class="form-table">
             <tr>
                 <th><label for="account_phone"><?php _e( 'Custom phone', 'woocommerce' ); ?></label></th>
                 <td><input type="text" name="account_phone" value="<?php echo esc_attr(get_the_author_meta( 'account_phone', $user->ID )); ?>" class="regular-text" /></td>
             </tr>
         </table>
         <br />
     <?php
}

//save custom field value in admin console
add_action( 'personal_options_update', 'save_extra_custom_user_data' );
add_action( 'edit_user_profile_update', 'save_extra_custom_user_data' );
function save_extra_custom_user_data( $user_id )
{
    if( ! empty($_POST['account_phone']) )
        update_user_meta( $user_id, 'account_phone', sanitize_text_field( $_POST['account_phone'] ) );
}</code>```

Body:
I need to create My Account page for registered users with changeable fields on backend and frontend.

Now the fields are updated if I change the values through the admin panel. However, if I change the field values through My Account, the fields are not saved or updated.

What do i need to change or add to the code?

I used the following LoicTheAztec's answers:

Add a custom field in Woocommerce Edit Account page

Adding some my account custom fields to admin user pages in Woocommerce

Adding an additional custom field in Woocommerce Edit Account page

My code:

Template:

$user = wp_get_current_user();

<form class="tabs-content__page_inner woocommerce-EditAccountForm edit-account" action="" method="post"

          <?php esc_html_e( 'Телефон', 'woocommerce' ); ?>

               <input type="text" class="tab-field__input woocommerce-Input woocommerce-Input--text input-text" name="account_phone" id="account_phone" value="<?php echo esc_attr( $user->account_phone ); ?>" />

</form>

functions.php

<?php
add_action('woocommerce_save_account_details', 'save_phone_number_account_details', 20, 1);
function save_phone_number_account_details($user_id) {
    if( isset( $_POST['account_phone'] ) ) {
        update_user_meta( $user_id, 'account_phone', sanitize_text_field( $_POST['account_phone'] ) );
    }
}

//custom field in admin console
add_action( 'show_user_profile', 'add_extra_custom_user_data', 1, 1 );
add_action( 'edit_user_profile', 'add_extra_custom_user_data', 1, 1 );
function add_extra_custom_user_data( $user )
{
?>

<?php _e("Other details",'woocommerce' ); ?>

                 <?php _e( 'Custom phone', 'woocommerce' ); ?>
                 <input type="text" name="account_phone" value="<?php echo esc_attr(get_the_author_meta( 'account_phone', $user->ID )); ?>" class="regular-text" />

     <?php
}

//save custom field value in admin console
add_action( 'personal_options_update', 'save_extra_custom_user_data' );
add_action( 'edit_user_profile_update', 'save_extra_custom_user_data' );
function save_extra_custom_user_data( $user_id )
{
    if( ! empty($_POST['account_phone']) )
        update_user_meta( $user_id, 'account_phone', sanitize_text_field( $_POST['account_phone'] ) );
}


问:
Can we avoid database calls in a forEach loop in following scenario?
I am developing a chat application. I am using Express JS and MongoDB in backend and Angular in frontend. I have 2 collections. One is Users and another is ChatHistory belwo are the schemas for each.

For Users

```<code>const UserSchema = new mongoose.Schema({
    name:{type: type.String, required: true},
    contact:{type: type.String, required: true},
    email:{type: type.String, required: true},
    password:{type: type.String, required: true},
    age:{type: type.Number, default:0},
    pic:{type: type.String, default:''},
    dob: {type:type.Date, default: ''},
    last_seen: {type:type.Date, default: ''},
    online_status: {type:type.String, default: 'offline'},
    show_last_seen: {type:type.Boolean, default: true},
})
</code>```

and For ChatHistory

```<code>  const ChatHistorySchema = new mongoose.Schema({
        sender_id:{type: type.ObjectId, ref:'Usres', required: true},
        receiver_id:{type: type.ObjectId, ref:'Usres',required: true},
        message:{type: type.String,required: true},
        is_deleted:{type: type.Boolean,default:false},
        target_messages_id:{type:type.String,default:''},
        file_name:{type:type.String,default:''},
        message_read_status:{type: type.Boolean,default:false},
    })
</code>```

I want to display the last received message and count of all unread messages for each user when I am showing the listing of users. So I am doing following way

```<code> userList = await UsersCollection.find({},{name:1,email:1,online_status:1,last_seen:1,pic:1});
//getting all user list

  if(userList.length > 0){

// iterate over each user to get the last message and all unread messages count of each user
    async forEach((obj)=>{

        await getLastMessage();
        await getAllUnreadMessageCount()

    })
  }
</code>```

And I am getting the results. But like we all the know that hitting database in a loop is not a good idea. So I want to know that is there any other optimized way to do the same?
Would be a great help.

Body:
I am developing a chat application. I am using Express JS and MongoDB in backend and Angular in frontend. I have 2 collections. One is Users and another is ChatHistory belwo are the schemas for each.

For Users

const UserSchema = new mongoose.Schema({
    name:{type: type.String, required: true},
    contact:{type: type.String, required: true},
    email:{type: type.String, required: true},
    password:{type: type.String, required: true},
    age:{type: type.Number, default:0},
    pic:{type: type.String, default:''},
    dob: {type:type.Date, default: ''},
    last_seen: {type:type.Date, default: ''},
    online_status: {type:type.String, default: 'offline'},
    show_last_seen: {type:type.Boolean, default: true},
})

and For ChatHistory

  const ChatHistorySchema = new mongoose.Schema({
        sender_id:{type: type.ObjectId, ref:'Usres', required: true},
        receiver_id:{type: type.ObjectId, ref:'Usres',required: true},
        message:{type: type.String,required: true},
        is_deleted:{type: type.Boolean,default:false},
        target_messages_id:{type:type.String,default:''},
        file_name:{type:type.String,default:''},
        message_read_status:{type: type.Boolean,default:false},
    })

I want to display the last received message and count of all unread messages for each user when I am showing the listing of users. So I am doing following way

 userList = await UsersCollection.find({},{name:1,email:1,online_status:1,last_seen:1,pic:1});
//getting all user list

  if(userList.length > 0){

// iterate over each user to get the last message and all unread messages count of each user
    async forEach((obj)=>{

        await getLastMessage();
        await getAllUnreadMessageCount()

    })
  }

And I am getting the results. But like we all the know that hitting database in a loop is not a good idea. So I want to know that is there any other optimized way to do the same?
Would be a great help.


问:
How to get log mel spectrogram of specific shape using librosa
I have some audio files which I want to convert to log mel spectogram. I need the log mel spectogram to be in the shape of (512,512). I changed the n_mels to 512, to get the first dimension 512 but I am unable to change the second dimension to 512 for all audios. I tried experimenting with hop_length values by trial and error, in some audio files it work and in the others it doesn't.How do we get log mel spectrogram of specific shape using librosa?

```<code>path = "path/to/my/file"
scale, sr = librosa.load(path)
mel_spectrogram = librosa.feature.melspectrogram(scale, sr, n_fft=2048, hop_length=512, n_mels=512, fmax=8000)
log_mel_spectrogram = librosa.power_to_db(mel_spectrogram)
librosa.display.specshow(log_mel_spectrogram, x_axis="time", y_axis="mel", sr=sr) ```

```

Body:
I have some audio files which I want to convert to log mel spectogram. I need the log mel spectogram to be in the shape of (512,512). I changed the n_mels to 512, to get the first dimension 512 but I am unable to change the second dimension to 512 for all audios. I tried experimenting with hop_length values by trial and error, in some audio files it work and in the others it doesn't.How do we get log mel spectrogram of specific shape using librosa?

path = "path/to/my/file"
scale, sr = librosa.load(path)
mel_spectrogram = librosa.feature.melspectrogram(scale, sr, n_fft=2048, hop_length=512, n_mels=512, fmax=8000)
log_mel_spectrogram = librosa.power_to_db(mel_spectrogram)
librosa.display.specshow(log_mel_spectrogram, x_axis="time", y_axis="mel", sr=sr) ```


问:
After addOnSuccessListener() the app is redirected to other activity
In my app I have implemented image upload to firebase storage, after upload url of the image is stored in realtime database for future use. Everything is working perfectly except whenever the url of the image is stored in realtime database the app move towards the BottomNavigation. below is my code
Adapter Class from which the app is redirected towards the pictureTakingActivity

```<code>class PrintAdapter(val data:ArrayList<PrintModel>)  : RecyclerView.Adapter<PrintAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        var view = LayoutInflater.from(parent.context).inflate(R.layout.single_row_home, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.name.setText(data.get(position).name)
        Picasso.get().load(data[position].image).into(holder.image)
        Log.d("TAG", "The image is: " + data[position].catName)
        var cat = data.get(position).catName

        holder.itemView.setOnClickListener{
            if (cat.equals("photo")){
                val intent  = Intent(it.context, PictureTakingActivity::class.java)
                it.context.startActivity(intent)
            }
        }
    }

    override fun getItemCount(): Int {
      return  data.size
    }
    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // Both of these can be used to find id
        var name: TextView = itemView.findViewById(R.id.printName)
        var image = itemView.findViewById<ImageView>(R.id.circleImageView1)
    }
}
</code>```

PictureTakingActivity

```<code>class PictureTakingActivity : AppCompatActivity() {
    lateinit var uri: Uri
    lateinit var binding: ActivityPictureTakingBinding
    lateinit var databaseReference: DatabaseReference
    lateinit var firebaseUser: FirebaseUser
    lateinit var id: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPictureTakingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        databaseReference = FirebaseDatabase.getInstance().reference
        firebaseUser = FirebaseAuth.getInstance().currentUser!!
        id = firebaseUser.uid

        binding.takePhoto.setOnClickListener {

            ImagePicker.with(this)
                .crop()
                .galleryMimeTypes(
                    mimeTypes = arrayOf(
                        "image/png",
                        "image/jpg",
                        "image/jpeg"
                    )
                )
                .cameraOnly()
                .compress(1024)
                .maxResultSize(1080, 1080)
                .start()

        }

        binding.uploadGallery.setOnClickListener {
            ImagePicker.with(this)
                .crop()
                .galleryMimeTypes(
                    mimeTypes = arrayOf(
                        "image/png",
                        "image/jpg",
                        "image/jpeg"
                    )
                )
                .galleryOnly()
                .compress(1024)
                .maxResultSize(1080, 1080)
                .start()
        }

        binding.ok.setOnClickListener {
            uploadImage()
        }
        binding.notOk.setOnClickListener {
            ImagePicker.with(this)
                .crop()
                .galleryMimeTypes(
                    mimeTypes = arrayOf(
                        "image/png",
                        "image/jpg",
                        "image/jpeg"
                    )
                )
                .compress(1024)
                .maxResultSize(1080, 1080)
                .start()
        }

    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        //Image Uri will not be null for RESULT_OK
        uri = data?.data!!
        binding.userImage.setImageURI(uri)

        binding.takePhoto.visibility = View.INVISIBLE
        binding.uploadGallery.visibility = View.INVISIBLE

        binding.ok.visibility = View.VISIBLE
        binding.notOk.visibility = View.VISIBLE

        Log.d("TAG", "The uri inside is: $" )
    } else if (resultCode == ImagePicker.RESULT_ERROR) {
        Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show()
    } else {
        Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show()
    }
    }

    private fun uploadImage(){
        val progressBar = ProgressDialog(this)
        progressBar.setMessage("Uploading file...")
        progressBar.setCancelable(false)
        progressBar.show()

        val formatter = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault())
        val now = Date()
        val fileName = formatter.format(now)

        val storageRefrence = FirebaseStorage.getInstance().reference.child(id).child("images/$fileName")
        storageRefrence.putFile(uri).addOnSuccessListener {
            progressBar.dismiss()
            storageRefrence.downloadUrl.addOnSuccessListener {

                databaseReference.child("Users").child(id).child("image").setValue(it.toString()).addOnSuccessListener { // After this line is executed app redirect towards MainActivity

              Toast.makeText(this, "File uploaded successfully", Toast.LENGTH_SHORT).show()
                }

            }

        }.addOnFailureListener{
            progressBar.dismiss()
        }
}
}
</code>```

BottomNavigationActivity

```<code>class BottomNavigationActivity : AppCompatActivity() {
    lateinit var binding:ActivityBottomNavigationBinding
    private val fragment1: Fragment = HomeFragment()
    private val fragment2: Fragment = DocumentsFragment()
    private val fragment3: Fragment = OrdersFragment()
    private val fragment4: Fragment = ProfileFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBottomNavigationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        replaceFrameLayout(fragment1)

        binding.bottomNavigation.setOnItemSelectedListener {
            when(it.itemId){
                R.id.home -> replaceFrameLayout(fragment1)
                R.id.documents -> replaceFrameLayout(fragment2)
                R.id.orders -> replaceFrameLayout(fragment3)
                R.id.profile -> replaceFrameLayout(fragment4)

                else ->{

                }
            }
            true
        }

    }

    private fun replaceFrameLayout(fragment: Fragment){
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.flFragment, fragment)
        fragmentTransaction.commit()
    }

    }
</code>```

I am new in Kotlin so please pardon if this is a simple issue. Thanks in advance

Body:
In my app I have implemented image upload to firebase storage, after upload url of the image is stored in realtime database for future use. Everything is working perfectly except whenever the url of the image is stored in realtime database the app move towards the BottomNavigation. below is my code
Adapter Class from which the app is redirected towards the pictureTakingActivity

class PrintAdapter(val data:ArrayList<PrintModel>)  : RecyclerView.Adapter<PrintAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        var view = LayoutInflater.from(parent.context).inflate(R.layout.single_row_home, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.name.setText(data.get(position).name)
        Picasso.get().load(data[position].image).into(holder.image)
        Log.d("TAG", "The image is: " + data[position].catName)
        var cat = data.get(position).catName

        holder.itemView.setOnClickListener{
            if (cat.equals("photo")){
                val intent  = Intent(it.context, PictureTakingActivity::class.java)
                it.context.startActivity(intent)
            }
        }
    }

    override fun getItemCount(): Int {
      return  data.size
    }
    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // Both of these can be used to find id
        var name: TextView = itemView.findViewById(R.id.printName)
        var image = itemView.findViewById<ImageView>(R.id.circleImageView1)
    }
}

PictureTakingActivity

class PictureTakingActivity : AppCompatActivity() {
    lateinit var uri: Uri
    lateinit var binding: ActivityPictureTakingBinding
    lateinit var databaseReference: DatabaseReference
    lateinit var firebaseUser: FirebaseUser
    lateinit var id: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPictureTakingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        databaseReference = FirebaseDatabase.getInstance().reference
        firebaseUser = FirebaseAuth.getInstance().currentUser!!
        id = firebaseUser.uid

        binding.takePhoto.setOnClickListener {

            ImagePicker.with(this)
                .crop()
                .galleryMimeTypes(
                    mimeTypes = arrayOf(
                        "image/png",
                        "image/jpg",
                        "image/jpeg"
                    )
                )
                .cameraOnly()
                .compress(1024)
                .maxResultSize(1080, 1080)
                .start()

        }

        binding.uploadGallery.setOnClickListener {
            ImagePicker.with(this)
                .crop()
                .galleryMimeTypes(
                    mimeTypes = arrayOf(
                        "image/png",
                        "image/jpg",
                        "image/jpeg"
                    )
                )
                .galleryOnly()
                .compress(1024)
                .maxResultSize(1080, 1080)
                .start()
        }

        binding.ok.setOnClickListener {
            uploadImage()
        }
        binding.notOk.setOnClickListener {
            ImagePicker.with(this)
                .crop()
                .galleryMimeTypes(
                    mimeTypes = arrayOf(
                        "image/png",
                        "image/jpg",
                        "image/jpeg"
                    )
                )
                .compress(1024)
                .maxResultSize(1080, 1080)
                .start()
        }

    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        //Image Uri will not be null for RESULT_OK
        uri = data?.data!!
        binding.userImage.setImageURI(uri)

        binding.takePhoto.visibility = View.INVISIBLE
        binding.uploadGallery.visibility = View.INVISIBLE

        binding.ok.visibility = View.VISIBLE
        binding.notOk.visibility = View.VISIBLE

        Log.d("TAG", "The uri inside is: $" )
    } else if (resultCode == ImagePicker.RESULT_ERROR) {
        Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show()
    } else {
        Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show()
    }
    }

    private fun uploadImage(){
        val progressBar = ProgressDialog(this)
        progressBar.setMessage("Uploading file...")
        progressBar.setCancelable(false)
        progressBar.show()

        val formatter = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault())
        val now = Date()
        val fileName = formatter.format(now)

        val storageRefrence = FirebaseStorage.getInstance().reference.child(id).child("images/$fileName")
        storageRefrence.putFile(uri).addOnSuccessListener {
            progressBar.dismiss()
            storageRefrence.downloadUrl.addOnSuccessListener {

                databaseReference.child("Users").child(id).child("image").setValue(it.toString()).addOnSuccessListener { // After this line is executed app redirect towards MainActivity

              Toast.makeText(this, "File uploaded successfully", Toast.LENGTH_SHORT).show()
                }

            }

        }.addOnFailureListener{
            progressBar.dismiss()
        }
}
}

BottomNavigationActivity

class BottomNavigationActivity : AppCompatActivity() {
    lateinit var binding:ActivityBottomNavigationBinding
    private val fragment1: Fragment = HomeFragment()
    private val fragment2: Fragment = DocumentsFragment()
    private val fragment3: Fragment = OrdersFragment()
    private val fragment4: Fragment = ProfileFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBottomNavigationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        replaceFrameLayout(fragment1)

        binding.bottomNavigation.setOnItemSelectedListener {
            when(it.itemId){
                R.id.home -> replaceFrameLayout(fragment1)
                R.id.documents -> replaceFrameLayout(fragment2)
                R.id.orders -> replaceFrameLayout(fragment3)
                R.id.profile -> replaceFrameLayout(fragment4)

                else ->{

                }
            }
            true
        }

    }

    private fun replaceFrameLayout(fragment: Fragment){
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.flFragment, fragment)
        fragmentTransaction.commit()
    }

    }

I am new in Kotlin so please pardon if this is a simple issue. Thanks in advance


问:
AWS EFS unmounts random times
I need some guidance regarding an issue that comes up every now and then on AWS.
We have an instance hosting 2 applications which every now and then loses its connection with the EFS. This does not happen often but it happens 2 to 3 times a month. The logs only show that the fs-0000000.efs.us-east-1.amazonaws.com is not responding and then timed out.

Then it shows Unmounting /mnt/efs/servername. Further down the log it then shows  mount: /mnt/efs/devserver/artifactory: unknown filesystem type 'efs'.

We then mount it again and it works fine till the next month. Any ideas what would cause this?
Any help would be appreciated.

Contacting AWS support, reading logs, troubleshooting AWS documentation and checking forums.

Title: AWS EFS unmounts random times


问:
db-migrate and db-migrate-pg How to control order of migrations?
Is there a way to run only specific migration file using db-migrate, or to at least execute migrations in a specific order? Some workarounds would be to change the dates in migration file name, or to put all operations into one file, but I'm trying o find some more elegant way to do this.
In the db-migrate documentation the is this command that is supposed to run one migration, but it actually runs all migrations before that as well:</p>
```<code>db-migrate up 20150207135259-myFancyMigration
</code>```

Body:
Is there a way to run only specific migration file using db-migrate, or to at least execute migrations in a specific order? Some workarounds would be to change the dates in migration file name, or to put all operations into one file, but I'm trying o find some more elegant way to do this.
In the db-migrate documentation the is this command that is supposed to run one migration, but it actually runs all migrations before that as well:

db-migrate up 20150207135259-myFancyMigration


问:
Visul Studio 2022 with Visual Assist - GO button gets huge issue
I am using:

current version of Microsoft Visual Studio 2022 (64-bit) - Version 17.4.3.

current version of Visual Assist (Visual Assist build 2022.5)

I have a random problem, when Go button sometimes after pressing some function with ctrl + right click (go to implementation) gets huge.

How it looks like:

How it should look like:

The only solution which makes it smaller again is to close Visual Studio and reopen it again. I have already tried with no success:

Disable Visual Assist and reenable it

ctrl + scroll in many places


问:
How do I implement the imaplib search function?
```<code>import imaplib
import email
from email.header import decode_header
import webbrowser
import os

# account credentials
username = "example@stack.com"
password = "exapleforstack"
imap_server = "imap.one.com"

def clean(text):
    # clean text for creating a folder
    return "".join(c if c.isalnum() else "_" for c in text)

# create an IMAP4 class with SSL
imap = imaplib.IMAP4_SSL(imap_server)
# authenticate
imap.login(username, password)

status, messages = imap.select("INBOX")
imap.search(None, 'SUBJECT', '"exampleforstack"')

# number of top emails to fetch
N = 3
# total number of emails
messages = int(messages[0])

for i in range(messages, messages-N, -1):
    # fetch the email message by ID
    res, msg = imap.fetch(str(i), "(RFC822)")
    for response in msg:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = email.message_from_bytes(response[1])
            # decode the email subject
            subject, encoding = decode_header(msg["Subject"])[0]
            if isinstance(subject, bytes):
                # if it's a bytes, decode to str
                subject = subject.decode(encoding)
            # decode email sender
            From, encoding = decode_header(msg.get("From"))[0]
            if isinstance(From, bytes):
                From = From.decode(encoding)
            print("Subject:", subject)
            print("From:", From)
            # if the email message is multipart
            if msg.is_multipart():
                # iterate over email parts
                for part in msg.walk():
                    # extract content type of email
                    content_type = part.get_content_type()
                    content_disposition = str(part.get("Content-Disposition"))
                    try:
                        # get the email body
                        body = part.get_payload(decode=True).decode()
                    except:
                        pass
                    if content_type == "text/plain" and "attachment" not in content_disposition:
                        # print text/plain emails and skip attachments
                        print(body)
                    elif "attachment" in content_disposition:
                        # download attachment
                        filename = part.get_filename()
                        if filename:
                            folder_name = clean(subject)
                            if not os.path.isdir(folder_name):
                                # make a folder for this email (named after the subject)
                                os.mkdir(folder_name)
                            filepath = os.path.join(folder_name, filename)
                            # download attachment and save it
                            open(filepath, "wb").write(part.get_payload(decode=True))
            else:
                # extract content type of email
                content_type = msg.get_content_type()
                # get the email body
                body = msg.get_payload(decode=True).decode()
                if content_type == "text/plain":
                    # print only text email parts
                    print(body)
            if content_type == "text/html":
                # if it's HTML, create a new HTML file and open it in browser
                folder_name = clean(subject)
                if not os.path.isdir(folder_name):
                    # make a folder for this email (named after the subject)
                    os.mkdir(folder_name)
                filename = "index.html"
                filepath = os.path.join(folder_name, filename)
                # write the file
                open(filepath, "w").write(body)
                # open in the default browser
                webbrowser.open(filepath)
            print("="*100)
# close the connection and logout
imap.close()
imap.logout()
</code>```

I tried using the search method a couple different ways, like:

```<code>res, msg = imap.search(None, 'SUBJECT', "example")
</code>```

and

```<code>    res, msg = imap.search(None, 'SUBJECT, "example"')
</code>```

but my code just gives an error and automatically fetches the most recent 3.

I've tried replacing the line:

```<code>res, msg = imap.fetch(str(i), "(RFC822)")
</code>```

with

```<code>res, msg = imap.search(None, 'SUBJECT', '"example"')
</code>```

but the program returns nothing at all.

how would I go about implementing the search I got this code from pythoncode and altered its credentials.

But I'm not sure why I can't implement the search function.

Body:
import imaplib
import email
from email.header import decode_header
import webbrowser
import os

# account credentials
username = "example@stack.com"
password = "exapleforstack"
imap_server = "imap.one.com"

def clean(text):
    # clean text for creating a folder
    return "".join(c if c.isalnum() else "_" for c in text)

# create an IMAP4 class with SSL
imap = imaplib.IMAP4_SSL(imap_server)
# authenticate
imap.login(username, password)

status, messages = imap.select("INBOX")
imap.search(None, 'SUBJECT', '"exampleforstack"')

# number of top emails to fetch
N = 3
# total number of emails
messages = int(messages[0])

for i in range(messages, messages-N, -1):
    # fetch the email message by ID
    res, msg = imap.fetch(str(i), "(RFC822)")
    for response in msg:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = email.message_from_bytes(response[1])
            # decode the email subject
            subject, encoding = decode_header(msg["Subject"])[0]
            if isinstance(subject, bytes):
                # if it's a bytes, decode to str
                subject = subject.decode(encoding)
            # decode email sender
            From, encoding = decode_header(msg.get("From"))[0]
            if isinstance(From, bytes):
                From = From.decode(encoding)
            print("Subject:", subject)
            print("From:", From)
            # if the email message is multipart
            if msg.is_multipart():
                # iterate over email parts
                for part in msg.walk():
                    # extract content type of email
                    content_type = part.get_content_type()
                    content_disposition = str(part.get("Content-Disposition"))
                    try:
                        # get the email body
                        body = part.get_payload(decode=True).decode()
                    except:
                        pass
                    if content_type == "text/plain" and "attachment" not in content_disposition:
                        # print text/plain emails and skip attachments
                        print(body)
                    elif "attachment" in content_disposition:
                        # download attachment
                        filename = part.get_filename()
                        if filename:
                            folder_name = clean(subject)
                            if not os.path.isdir(folder_name):
                                # make a folder for this email (named after the subject)
                                os.mkdir(folder_name)
                            filepath = os.path.join(folder_name, filename)
                            # download attachment and save it
                            open(filepath, "wb").write(part.get_payload(decode=True))
            else:
                # extract content type of email
                content_type = msg.get_content_type()
                # get the email body
                body = msg.get_payload(decode=True).decode()
                if content_type == "text/plain":
                    # print only text email parts
                    print(body)
            if content_type == "text/html":
                # if it's HTML, create a new HTML file and open it in browser
                folder_name = clean(subject)
                if not os.path.isdir(folder_name):
                    # make a folder for this email (named after the subject)
                    os.mkdir(folder_name)
                filename = "index.html"
                filepath = os.path.join(folder_name, filename)
                # write the file
                open(filepath, "w").write(body)
                # open in the default browser
                webbrowser.open(filepath)
            print("="*100)
# close the connection and logout
imap.close()
imap.logout()

I tried using the search method a couple different ways, like:

res, msg = imap.search(None, 'SUBJECT', "example")

and

    res, msg = imap.search(None, 'SUBJECT, "example"')

but my code just gives an error and automatically fetches the most recent 3.

I've tried replacing the line:

res, msg = imap.fetch(str(i), "(RFC822)")

with

res, msg = imap.search(None, 'SUBJECT', '"example"')

but the program returns nothing at all.

how would I go about implementing the search I got this code from pythoncode and altered its credentials.

But I'm not sure why I can't implement the search function.


问:
Why my custom Model mapper doesn't work properly?
I am creating a REST API using Spring Boot and for my update method I try to map a DTO Object to a domain one:

```<code> public ItemDTO updateItem(Long departmentId, Long itemId, ItemDTO itemDTO) throws ApiException {
        Department department = departmentRepository.findById(departmentId).orElseThrow(
                () -> new ApiException("Department with this id does not exist ",
                        HttpStatus.NOT_FOUND));

        Item foundItem = validateItem(itemId);
        Item convertedItem = mapper.convertToType(itemDTO, Item.class);
        if (convertedItem.getStock() < 0) {
            throw new ApiException("Stock must be a positive value", HttpStatus.BAD_REQUEST);
        }

        if (convertedItem.getStockThreshold() < 0) {
            throw new ApiException("Stock threshold must be a positive value", HttpStatus.BAD_REQUEST);
        }

        itemDTO.setId(itemId);
        itemDTO.setDepartment(mapper.convertToType(department, DepartmentDTO.class));
        foundItem = mapper.convertToType(itemDTO, Item.class);
        itemRepository.save(foundItem);

//        ItemDTO returnItem = mapper.convertToType(convertedItem, ItemDTO.class);
        logger.info("Updated item");
        return itemDTO;
    }
</code>```

And this is my model mapper

```<code>
@Component
public class Mapper {
    private final ModelMapper modelMapper;
    private final Logger logger = LoggerFactory.getLogger(ModelMapper.class);

    public Mapper(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
    }

    public <T> T convertToType(Object source, Class<T> resultClass) {
        logger.debug("converted object from " + source.getClass().getSimpleName() + " to " + resultClass.getSimpleName());
        return modelMapper.map(source, resultClass);
    }
}
</code>```

At this line foundItem = mapper.convertToType(itemDTO, Item.class); it's the problem, before this conversion my foundItem would have a department, after conversion, the department field is null.

Here are my domain and DTO classes

```<code>@NoArgsConstructor

@Getter
@Setter
    public class DepartmentDTO {
    private Long id;
    private String description;
    private List<Item> items;

    public DepartmentDTO(long id, String description) {
        this.id = id;
        this.description = description;
    }

    @Override
    public String toString() {
        return "DepartmentDTO{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", items=" + items +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DepartmentDTO that = (DepartmentDTO) o;
        return Objects.equals(id, that.id) && Objects.equals(description, that.description) && Objects.equals(items, that.items);
    }

//    @Override
//    public int hashCode() {
//        return Objects.hash(id, description, items);
//    }
}
</code>```
```<code>@NoArgsConstructor
@Entity
@Getter
@Setter
@Table(name = "DEPARTMENTS")
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
    @OneToMany(mappedBy = "department", fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    private List<Item> items;
    public Department(Long id, String description) {
        this.id = id;
        this.description = description;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", items=" + items +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Department)) return false;
        Department that = (Department) o;
        return id.equals(that.id) && Objects.equals(description, that.description) && Objects.equals(items, that.items);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, description, items);
    }

}
</code>```
```<code>@AllArgsConstructor

   @NoArgsConstructor
@Setter
public class ItemDTO {
    private Long id;
    private String description;
    private String price;
    private int stock;

    private int stockThreshold;

    private DepartmentDTO department;

public Long getId() {
    return id;
}

public String getDescription() {
    return description;
}

public String getPrice() {
    return price;
}

public int getStock() {
    return stock;
}

public int getStockThreshold() {
    return stockThreshold;
}

public Long getDepartment() {
    return department.getId();
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    ItemDTO itemDTO = (ItemDTO) o;
    return stock == itemDTO.stock && stockThreshold == itemDTO.stockThreshold &&
            id.equals(itemDTO.id) && description.equals(itemDTO.description) &&
            price.equals(itemDTO.price) && department.equals(itemDTO.department);
}

@Override
public int hashCode() {
    return Objects.hash(id, description, price, stock);
}
</code>```

}

```<code>

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "ITEMS")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;
    private String description;
    private String price;
    private int stock;

    private int stockThreshold = 5;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "department_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private Department department;

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", price='" + price + '\'' +
                ", stock=" + stock +
                ", department=" + department +
                '}';
    }
}
</code>```

Body:
I am creating a REST API using Spring Boot and for my update method I try to map a DTO Object to a domain one:

 public ItemDTO updateItem(Long departmentId, Long itemId, ItemDTO itemDTO) throws ApiException {
        Department department = departmentRepository.findById(departmentId).orElseThrow(
                () -> new ApiException("Department with this id does not exist ",
                        HttpStatus.NOT_FOUND));

        Item foundItem = validateItem(itemId);
        Item convertedItem = mapper.convertToType(itemDTO, Item.class);
        if (convertedItem.getStock() < 0) {
            throw new ApiException("Stock must be a positive value", HttpStatus.BAD_REQUEST);
        }

        if (convertedItem.getStockThreshold() < 0) {
            throw new ApiException("Stock threshold must be a positive value", HttpStatus.BAD_REQUEST);
        }

        itemDTO.setId(itemId);
        itemDTO.setDepartment(mapper.convertToType(department, DepartmentDTO.class));
        foundItem = mapper.convertToType(itemDTO, Item.class);
        itemRepository.save(foundItem);

//        ItemDTO returnItem = mapper.convertToType(convertedItem, ItemDTO.class);
        logger.info("Updated item");
        return itemDTO;
    }

And this is my model mapper

@Component
public class Mapper {
    private final ModelMapper modelMapper;
    private final Logger logger = LoggerFactory.getLogger(ModelMapper.class);

    public Mapper(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
    }

    public <T> T convertToType(Object source, Class<T> resultClass) {
        logger.debug("converted object from " + source.getClass().getSimpleName() + " to " + resultClass.getSimpleName());
        return modelMapper.map(source, resultClass);
    }
}

At this line foundItem = mapper.convertToType(itemDTO, Item.class); it's the problem, before this conversion my foundItem would have a department, after conversion, the department field is null.

Here are my domain and DTO classes

@NoArgsConstructor

@Getter
@Setter
    public class DepartmentDTO {
    private Long id;
    private String description;
    private List<Item> items;

    public DepartmentDTO(long id, String description) {
        this.id = id;
        this.description = description;
    }

    @Override
    public String toString() {
        return "DepartmentDTO{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", items=" + items +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DepartmentDTO that = (DepartmentDTO) o;
        return Objects.equals(id, that.id) && Objects.equals(description, that.description) && Objects.equals(items, that.items);
    }

//    @Override
//    public int hashCode() {
//        return Objects.hash(id, description, items);
//    }
}

@NoArgsConstructor
@Entity
@Getter
@Setter
@Table(name = "DEPARTMENTS")
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
    @OneToMany(mappedBy = "department", fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    private List<Item> items;
    public Department(Long id, String description) {
        this.id = id;
        this.description = description;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", items=" + items +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Department)) return false;
        Department that = (Department) o;
        return id.equals(that.id) && Objects.equals(description, that.description) && Objects.equals(items, that.items);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, description, items);
    }

}

@AllArgsConstructor

   @NoArgsConstructor
@Setter
public class ItemDTO {
    private Long id;
    private String description;
    private String price;
    private int stock;

    private int stockThreshold;

    private DepartmentDTO department;

public Long getId() {
    return id;
}

public String getDescription() {
    return description;
}

public String getPrice() {
    return price;
}

public int getStock() {
    return stock;
}

public int getStockThreshold() {
    return stockThreshold;
}

public Long getDepartment() {
    return department.getId();
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    ItemDTO itemDTO = (ItemDTO) o;
    return stock == itemDTO.stock && stockThreshold == itemDTO.stockThreshold &&
            id.equals(itemDTO.id) && description.equals(itemDTO.description) &&
            price.equals(itemDTO.price) && department.equals(itemDTO.department);
}

@Override
public int hashCode() {
    return Objects.hash(id, description, price, stock);
}

}

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "ITEMS")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;
    private String description;
    private String price;
    private int stock;

    private int stockThreshold = 5;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "department_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private Department department;

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", price='" + price + '\'' +
                ", stock=" + stock +
                ", department=" + department +
                '}';
    }
}


问:
Turn off system hotkeys/shortcuts in flutter
Hi I would to turn off system hotkeys. I cant any find package which has blocking functions or allow to block system shortcuts like windows+tab, alt+tab, windows and linux shortcuts/hotkeys. I care about that user cannot exit on my aplication to windows. I know that it can be external or manual methods like Local Group Privacy Editor or Regedit and possibly automation by scripts, but I want make as possible as easly. You guys are my last resort to avoid writing a dart package.

I tried researching pup.dev dart packages, but this package doesn't seem to be there yet


问:
How do I connect firebase in R?
I need authentication, database, storage to serve my application that I am developing in Shiny using Firebase.

Does anyone know how to do it ?

I hope it works correctly as when I use Python, but I can't find any library that is reliable to use in R, I could use the reticulate option, but it would load more processes and make the application slower

Title: How do I connect firebase in R?


问:
Sqlalchemy asyncio not inserting asynchronously
I am attempting to parallelize inserts in sqlalchemy using asyncio and sqlalchemy asyncio. Below is the code I have written - I expect the result to be all of the executions occurring at the same time and then a single commit. However, I am instead getting sequential executions (which I can tell are sequential given the sql alchemy printing each query after it is run, and they are not printing all at once.

UPDATE

I am now implementing in this manner:

```<code>async def insert_table_async(chunk, engine, dry_run, insert_table):
    """async table insert"""
    print("running async functions")
    t_start = time.time()
    connection = await engine.connect()
    await connection.execute(insert_table.insert().values(chunk))
    await connection.commit()
    await connection.close()
    t_end = time.time()
    print("time to insert {0} rows is {1} seconds".format(len(chunk), t_end-t_start))

tasks = []
table = Table("users") # example table
engine = create_async_engine(connect_string, pool_size=500)
split_list = [[records1_2], [record3_4]....] # a list of lists of records balanced for inserting equal sized chunks
for chunk in split_list:
    tasks.append(asyncio.create_task(connection.execute(insert_table_async(chunk, engine, table)))

await asyncio.gather(*tasks)
</code>```

Which prints all the "running async functions" as expected. However, the inserts do not seem to be running asynchronously. When I ran it synchronously, inserts took 1 second each for 10k rows. Now, they're taking 34 seconds, all of them, at the same time. Is there a setting on my RDS (Amazon Aurora serverless) that I have not taken into consideration?

previously

I attempted the following:

```<code>tasks = []
engine = create_async_engine(connect_string, pool_size=500)
split_list = [[records1_2], [record3_4]....] # a list of lists of records balanced for inserting equal sized chunks
for chunk in split_list:
    tasks.append(asyncio.create_task(connection.execute(insert_table.insert().values(chunk)))
tasks.append(asyncio.create_task(connection.commit()))

await asyncio.gather(*tasks)
</code>```

This resulted in the same synchronous process, except the commit occurred at every step.

```<code>tasks = []
engine = create_async_engine(connect_string, pool_size=500)
split_list = [[records1_2], [record3_4]....] # a list of lists of records balanced for inserting equal sized chunks
for chunk in split_list:
    tasks.append(asyncio.create_task(connection.execute(insert_table.insert().values(chunk)))

await asyncio.gather(*tasks)
</code>```

This resulted in no commit of values and a similarly synchronous process.

I am not concerned about locking the database, my writes are all unique and self contained, I just want to write async so I can do many writes all at once. My database is serverless and can increase size as necessary

Body:
I am attempting to parallelize inserts in sqlalchemy using asyncio and sqlalchemy asyncio. Below is the code I have written - I expect the result to be all of the executions occurring at the same time and then a single commit. However, I am instead getting sequential executions (which I can tell are sequential given the sql alchemy printing each query after it is run, and they are not printing all at once.

UPDATE

I am now implementing in this manner:

async def insert_table_async(chunk, engine, dry_run, insert_table):
    """async table insert"""
    print("running async functions")
    t_start = time.time()
    connection = await engine.connect()
    await connection.execute(insert_table.insert().values(chunk))
    await connection.commit()
    await connection.close()
    t_end = time.time()
    print("time to insert {0} rows is {1} seconds".format(len(chunk), t_end-t_start))

tasks = []
table = Table("users") # example table
engine = create_async_engine(connect_string, pool_size=500)
split_list = [[records1_2], [record3_4]....] # a list of lists of records balanced for inserting equal sized chunks
for chunk in split_list:
    tasks.append(asyncio.create_task(connection.execute(insert_table_async(chunk, engine, table)))

await asyncio.gather(*tasks)

Which prints all the "running async functions" as expected. However, the inserts do not seem to be running asynchronously. When I ran it synchronously, inserts took 1 second each for 10k rows. Now, they're taking 34 seconds, all of them, at the same time. Is there a setting on my RDS (Amazon Aurora serverless) that I have not taken into consideration?

previously

I attempted the following:

tasks = []
engine = create_async_engine(connect_string, pool_size=500)
split_list = [[records1_2], [record3_4]....] # a list of lists of records balanced for inserting equal sized chunks
for chunk in split_list:
    tasks.append(asyncio.create_task(connection.execute(insert_table.insert().values(chunk)))
tasks.append(asyncio.create_task(connection.commit()))

await asyncio.gather(*tasks)

This resulted in the same synchronous process, except the commit occurred at every step.

tasks = []
engine = create_async_engine(connect_string, pool_size=500)
split_list = [[records1_2], [record3_4]....] # a list of lists of records balanced for inserting equal sized chunks
for chunk in split_list:
    tasks.append(asyncio.create_task(connection.execute(insert_table.insert().values(chunk)))

await asyncio.gather(*tasks)

This resulted in no commit of values and a similarly synchronous process.

I am not concerned about locking the database, my writes are all unique and self contained, I just want to write async so I can do many writes all at once. My database is serverless and can increase size as necessary


问:
Kubernetes : RabbitMQ pod is spammed with connections from kube-system
I'm currently learning Kubernetes and all its quircks.
I'm currently using a rabbitMQ Deployment, service and pod in my cluster to exchange messages between apps in the cluster. However, I saw an abnormal amount of the rabbitMQ pod restarts.
After installing prometheus and Grafana to see the problem, I saw that the rabbitMQ pod would consume more and more memory and cpu until it gets killed by the OOMkiller every two hours or so. The graph looks like this :

Graph of CPU consumption in my cluster (rabbitmq in red)

After that I looked into the rabbitMQ pod UI, and saw that an app in my cluster (ip 10.224.0.5) was constantly creating new connections, this IP corresponding to my kube-system and my prometheus instance, as shown by the following logs :

```<code>k get all -A -o wide | grep 10.224.0.5
E1223 12:13:48.231908   23198 memcache.go:255] couldn't get resource list for external.metrics.k8s.io/v1beta1: Got empty response for: external.metrics.k8s.io/v1beta1
E1223 12:13:48.311831   23198 memcache.go:255] couldn't get resource list for external.metrics.k8s.io/v1beta1: Got empty response for: external.metrics.k8s.io/v1beta1
kube-system          pod/azure-ip-masq-agent-xh9jk                                1/1     Running   0             25d     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/cloud-node-manager-h5ff5                                 1/1     Running   0             25d     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/csi-azuredisk-node-sf8sn                                 3/3     Running   0             3d15h   10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/csi-azurefile-node-97nbt                                 3/3     Running   0             19d     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/kube-proxy-2s5tn                                         1/1     Running   0             3d15h   10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
monitoring           pod/prometheus-prometheus-node-exporter-dztwx                1/1     Running   0             20h     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
</code>```

Also, I noticed that these connections seem tpo be blocked by rabbitMQ, as the field connection.blocked in the client properties is set to true, as shown in the follwing image:

Print screen of a connection details from rabbitMQ pod's UI

I saw in the documentation that rabbitMQ starts to blocks connections when it hits low on resources, but I set the cpu and memory limits to 1 cpu and 1 Gib RAM, and the connections are blocked from the start anyway.

On the cluster, I'm also using Keda which uses the rabbitmq pod, and polls it every one second to see if there are any messages in a queue (I set pollingInterval to 1 in the yaml). But as I said earlier, it's not Keda that's creating all the connections, it's kube-system. Unless keda uses a component described earlier in the log to poll rabbitmq, and that the Keda's polling interval does not corresponds to seconds (which is highly unlikely as it's written in the docs that this polling intertval is given in seconds), I don't know at all what's going on with all these connections.

The following section contains the yamls of all the components that might be involved with this problem (keda and rabbitmq) :

```<code>rabbitMQ Replica Count.yaml

apiVersion: v1
kind: ReplicationController
metadata:
  labels:
    component: rabbitmq
  name: rabbitmq-controller
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: taskQueue
        component: rabbitmq
    spec:
      containers:
      - image: rabbitmq:3.11.5-management
        name: rabbitmq
        ports:
        - containerPort: 5672
          name: amqp
        - containerPort: 15672
          name: http
        resources:
          limits:
            cpu: 1
            memory: 1Gi
</code>```
```<code>rabbitMQ Service.yaml

apiVersion: v1
kind: Service
metadata:
  labels:
    component: rabbitmq
  name: rabbitmq-service
spec:
  type: LoadBalancer
  ports:
  - port: 5672
    targetPort: 5672
    name: amqp
  - port: 15672
    targetPort: 15672
    name: http
  selector:
    app: taskQueue
    component: rabbitmq
</code>```
```<code>keda JobScaler, Secret and TriggerAuthentication (sample data is just a replacement for fields that I do not want to be revealed :) ):

apiVersion: v1
kind: Secret
metadata:
  name: keda-rabbitmq-secret
data:
  host: sample-host  # base64 encoded value of format amqp://guest:password@localhost:5672/vhost
---
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: keda-trigger-auth-rabbitmq-conn
  namespace: default
spec:
  secretTargetRef:
    - parameter: host
      name: keda-rabbitmq-secret
      key: host
---
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
  name: builder-job-scaler
  namespace: default
spec:
  jobTargetRef:
    parallelism: 1
    completions: 1
    activeDeadlineSeconds: 600
    backoffLimit: 5
    template:
      spec:
        volumes:
        - name: shared-storage
          emptyDir: {}
        initContainers:
        - name: sourcesfetcher
          image: sample image
          volumeMounts:
          - name: shared-storage
            mountPath: /mnt/shared
          env:
          - name: SHARED_STORAGE_MOUNT_POINT
            value: /mnt/shared
          - name: RABBITMQ_ENDPOINT
            value: sample host
          - name: RABBITMQ_QUEUE_NAME
            value: buildOrders
        containers:
        - name: builder
          image: sample image
          volumeMounts:
          - name: shared-storage
            mountPath: /mnt/shared
          env:
          - name: SHARED_STORAGE_MOUNT_POINT
            value: /mnt/shared
          - name: MINIO_ENDPOINT
            value: sample endpoint
          - name: MINIO_PORT
            value: sample port
          - name: MINIO_USESSL
            value: "false"
          - name: MINIO_ROOT_USER
            value: sample user
          - name: MINIO_ROOT_PASSWORD
            value: sampel password
          - name: BUCKET_NAME
            value: "hex"
          - name: SERVER_NAME
            value: sample url
          resources:
            requests:
              cpu: 500m
              memory: 512Mi
            limits:
              cpu: 500m
              memory: 512Mi
        restartPolicy: OnFailure
  pollingInterval: 1
  maxReplicaCount: 2
  minReplicaCount: 0
  rollout:
    strategy: gradual

  triggers:
  - type: rabbitmq
    metadata:
      protocol: amqp
      queueName: buildOrders
      mode: QueueLength
      value: "1"
    authenticationRef:
      name: keda-trigger-auth-rabbitmq-conn
</code>```

Any help would very much appreciated!

Body:
I'm currently learning Kubernetes and all its quircks.
I'm currently using a rabbitMQ Deployment, service and pod in my cluster to exchange messages between apps in the cluster. However, I saw an abnormal amount of the rabbitMQ pod restarts.
After installing prometheus and Grafana to see the problem, I saw that the rabbitMQ pod would consume more and more memory and cpu until it gets killed by the OOMkiller every two hours or so. The graph looks like this :

Graph of CPU consumption in my cluster (rabbitmq in red)

After that I looked into the rabbitMQ pod UI, and saw that an app in my cluster (ip 10.224.0.5) was constantly creating new connections, this IP corresponding to my kube-system and my prometheus instance, as shown by the following logs :

k get all -A -o wide | grep 10.224.0.5
E1223 12:13:48.231908   23198 memcache.go:255] couldn't get resource list for external.metrics.k8s.io/v1beta1: Got empty response for: external.metrics.k8s.io/v1beta1
E1223 12:13:48.311831   23198 memcache.go:255] couldn't get resource list for external.metrics.k8s.io/v1beta1: Got empty response for: external.metrics.k8s.io/v1beta1
kube-system          pod/azure-ip-masq-agent-xh9jk                                1/1     Running   0             25d     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/cloud-node-manager-h5ff5                                 1/1     Running   0             25d     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/csi-azuredisk-node-sf8sn                                 3/3     Running   0             3d15h   10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/csi-azurefile-node-97nbt                                 3/3     Running   0             19d     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
kube-system          pod/kube-proxy-2s5tn                                         1/1     Running   0             3d15h   10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>
monitoring           pod/prometheus-prometheus-node-exporter-dztwx                1/1     Running   0             20h     10.224.0.5    aks-agentpool-37892177-vmss000001   <none>           <none>

Also, I noticed that these connections seem tpo be blocked by rabbitMQ, as the field connection.blocked in the client properties is set to true, as shown in the follwing image:

Print screen of a connection details from rabbitMQ pod's UI

I saw in the documentation that rabbitMQ starts to blocks connections when it hits low on resources, but I set the cpu and memory limits to 1 cpu and 1 Gib RAM, and the connections are blocked from the start anyway.

On the cluster, I'm also using Keda which uses the rabbitmq pod, and polls it every one second to see if there are any messages in a queue (I set pollingInterval to 1 in the yaml). But as I said earlier, it's not Keda that's creating all the connections, it's kube-system. Unless keda uses a component described earlier in the log to poll rabbitmq, and that the Keda's polling interval does not corresponds to seconds (which is highly unlikely as it's written in the docs that this polling intertval is given in seconds), I don't know at all what's going on with all these connections.

The following section contains the yamls of all the components that might be involved with this problem (keda and rabbitmq) :

rabbitMQ Replica Count.yaml

apiVersion: v1
kind: ReplicationController
metadata:
  labels:
    component: rabbitmq
  name: rabbitmq-controller
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: taskQueue
        component: rabbitmq
    spec:
      containers:
      - image: rabbitmq:3.11.5-management
        name: rabbitmq
        ports:
        - containerPort: 5672
          name: amqp
        - containerPort: 15672
          name: http
        resources:
          limits:
            cpu: 1
            memory: 1Gi

rabbitMQ Service.yaml

apiVersion: v1
kind: Service
metadata:
  labels:
    component: rabbitmq
  name: rabbitmq-service
spec:
  type: LoadBalancer
  ports:
  - port: 5672
    targetPort: 5672
    name: amqp
  - port: 15672
    targetPort: 15672
    name: http
  selector:
    app: taskQueue
    component: rabbitmq

keda JobScaler, Secret and TriggerAuthentication (sample data is just a replacement for fields that I do not want to be revealed :) ):

apiVersion: v1
kind: Secret
metadata:
  name: keda-rabbitmq-secret
data:
  host: sample-host  # base64 encoded value of format amqp://guest:password@localhost:5672/vhost
---
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: keda-trigger-auth-rabbitmq-conn
  namespace: default
spec:
  secretTargetRef:
    - parameter: host
      name: keda-rabbitmq-secret
      key: host
---
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
  name: builder-job-scaler
  namespace: default
spec:
  jobTargetRef:
    parallelism: 1
    completions: 1
    activeDeadlineSeconds: 600
    backoffLimit: 5
    template:
      spec:
        volumes:
        - name: shared-storage
          emptyDir: {}
        initContainers:
        - name: sourcesfetcher
          image: sample image
          volumeMounts:
          - name: shared-storage
            mountPath: /mnt/shared
          env:
          - name: SHARED_STORAGE_MOUNT_POINT
            value: /mnt/shared
          - name: RABBITMQ_ENDPOINT
            value: sample host
          - name: RABBITMQ_QUEUE_NAME
            value: buildOrders
        containers:
        - name: builder
          image: sample image
          volumeMounts:
          - name: shared-storage
            mountPath: /mnt/shared
          env:
          - name: SHARED_STORAGE_MOUNT_POINT
            value: /mnt/shared
          - name: MINIO_ENDPOINT
            value: sample endpoint
          - name: MINIO_PORT
            value: sample port
          - name: MINIO_USESSL
            value: "false"
          - name: MINIO_ROOT_USER
            value: sample user
          - name: MINIO_ROOT_PASSWORD
            value: sampel password
          - name: BUCKET_NAME
            value: "hex"
          - name: SERVER_NAME
            value: sample url
          resources:
            requests:
              cpu: 500m
              memory: 512Mi
            limits:
              cpu: 500m
              memory: 512Mi
        restartPolicy: OnFailure
  pollingInterval: 1
  maxReplicaCount: 2
  minReplicaCount: 0
  rollout:
    strategy: gradual

  triggers:
  - type: rabbitmq
    metadata:
      protocol: amqp
      queueName: buildOrders
      mode: QueueLength
      value: "1"
    authenticationRef:
      name: keda-trigger-auth-rabbitmq-conn

Any help would very much appreciated!


问:
how do i cache the large files on the browser to make the loading time faster
Im trying to store model and js files in cache storage using service workers to make the loading time fast but the cache is not being stored and fetched from the cache storage,when I change the version also it is not able to refetch the cache and store them,

```<code>self.addEventListener('fetch', function(event) {});
var CACHE_VERSION = 2.2
var CURRENT_CACHES = {
  prefetch: 'prefetch-cache-v' + CACHE_VERSION
};

self.addEventListener('install', function(event) {
  var urlsToPrefetch = [
    '/',
    'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js',
    'https://use.typekit.net/af/dde969/00000000000000007735b995/30/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3',
    'https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js',
    'https://code.jquery.com/jquery-2.2.4.min.js',
    'https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_packed_assets_loader.js',
    'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose.js',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_web.binarypb',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_packed_assets.data',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_landmark_lite.tflite',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_simd_wasm_bin.wasm',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_simd_wasm_bin.js',
  ];
  self.skipWaiting();
  event.waitUntil(
    caches.open(CURRENT_CACHES.prefetch).then(function(cache) {
      return cache.addAll(urlsToPrefetch);
    })
  );
});

self.addEventListener('activate', function(event) {

  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (expectedCacheNames.indexOf(cacheName) === -1) {

            return caches.delete(cacheName);
          }
        })
        );
    })
    );
});

self.addEventListener('fetch', function(event) {

  if (event.request.headers.get('range')) {
    var pos =
    Number(/^bytes\=(\d+)\-$/g.exec(event.request.headers.get('range'))[1]);

    event.respondWith(
      caches.open(CURRENT_CACHES.prefetch)
      .then(function(cache) {
        return cache.match(event.request.url);
      }).then(function(res) {
        if (!res) {
          return fetch(event.request)
          .then(res => {
            return res.arrayBuffer();
          });
        }
        return res.arrayBuffer();
      }).then(function(ab) {
        return new Response(
          ab.slice(pos),
          {
            status: 206,
            statusText: 'Partial Content',
            headers: [
              ['Content-Range', 'bytes ' + pos + '-' +
                (ab.byteLength - 1) + '/' + ab.byteLength]]
          });
      }));
  } else {

    event.respondWith(

    caches.match(event.request).then(function(response) {
      if (response) {

        return response;
      }

      return fetch(event.request).then(function(response) {

        return response;
      }).catch(function(error) {
        throw error;
      });
    })
    );
  }
});
</code>```

for some reason it works better in linux system, if I do hard refresh it will work sometimes but the files is not fetched from the cache always,even thought the files can be seen in cache storage of the browser

Body:
Im trying to store model and js files in cache storage using service workers to make the loading time fast but the cache is not being stored and fetched from the cache storage,when I change the version also it is not able to refetch the cache and store them,

self.addEventListener('fetch', function(event) {});
var CACHE_VERSION = 2.2
var CURRENT_CACHES = {
  prefetch: 'prefetch-cache-v' + CACHE_VERSION
};

self.addEventListener('install', function(event) {
  var urlsToPrefetch = [
    '/',
    'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js',
    'https://use.typekit.net/af/dde969/00000000000000007735b995/30/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3',
    'https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js',
    'https://code.jquery.com/jquery-2.2.4.min.js',
    'https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_packed_assets_loader.js',
    'https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose.js',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_web.binarypb',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_packed_assets.data',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_landmark_lite.tflite',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_simd_wasm_bin.wasm',
    'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose_solution_simd_wasm_bin.js',
  ];
  self.skipWaiting();
  event.waitUntil(
    caches.open(CURRENT_CACHES.prefetch).then(function(cache) {
      return cache.addAll(urlsToPrefetch);
    })
  );
});

self.addEventListener('activate', function(event) {

  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if (expectedCacheNames.indexOf(cacheName) === -1) {

            return caches.delete(cacheName);
          }
        })
        );
    })
    );
});

self.addEventListener('fetch', function(event) {

  if (event.request.headers.get('range')) {
    var pos =
    Number(/^bytes\=(\d+)\-$/g.exec(event.request.headers.get('range'))[1]);

    event.respondWith(
      caches.open(CURRENT_CACHES.prefetch)
      .then(function(cache) {
        return cache.match(event.request.url);
      }).then(function(res) {
        if (!res) {
          return fetch(event.request)
          .then(res => {
            return res.arrayBuffer();
          });
        }
        return res.arrayBuffer();
      }).then(function(ab) {
        return new Response(
          ab.slice(pos),
          {
            status: 206,
            statusText: 'Partial Content',
            headers: [
              ['Content-Range', 'bytes ' + pos + '-' +
                (ab.byteLength - 1) + '/' + ab.byteLength]]
          });
      }));
  } else {

    event.respondWith(

    caches.match(event.request).then(function(response) {
      if (response) {

        return response;
      }

      return fetch(event.request).then(function(response) {

        return response;
      }).catch(function(error) {
        throw error;
      });
    })
    );
  }
});

for some reason it works better in linux system, if I do hard refresh it will work sometimes but the files is not fetched from the cache always,even thought the files can be seen in cache storage of the browser


问:
OMS Agent not heart beating with error certificate verify failed (unable to get local issuer certificate)
On an Ubuntu 20 machine, OMS Agent not heart beating. In the OMS Agent log, we have the below error message.

```<code>Error sending the telemetry request to OMS agent management service: SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate)
</code>```

The openssl is customized on the box. Few steps are not configured while upgrading openssl but I verified that should not be the issue.

```<code>$ openssl version -a
OpenSSL 1.1.1f  31 Mar 2020 (Library: OpenSSL 1.1.1n  15 Mar 2022)
built on: Thu Dec 22 14:25:22 2022 UTC
platform: linux-x86_64
options:  bn(64,64) rc4(16x,int) des(int) blowfish(ptr)
compiler: gcc -fPIC -pthread -m64 -Wa,--noexecstack -Wall -O3 -DOPENSSL_USE_NODELETE -DL_ENDIAN -DOPENSSL_PIC -DOPENSSL_CPUID_OBJ -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DKECCAK1600_ASM -DRC4_ASM -DMD5_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM -DX25519_ASM -DPOLY1305_ASM -DNDEBUG
OPENSSLDIR: "/usr/local/ssl"
ENGINESDIR: "/usr/local/lib/
</code>```

If we use root user, we are able to connect to ODS endpoint and bing.com without any issues using openssl client.
But if we use omsagent user, we are not running into the same problem connecting to ODS endpoint and bing.com with opensssl client.

I verified that the /etc/ssl/certs has the proper certs configured.

Body:
On an Ubuntu 20 machine, OMS Agent not heart beating. In the OMS Agent log, we have the below error message.

Error sending the telemetry request to OMS agent management service: SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate)

The openssl is customized on the box. Few steps are not configured while upgrading openssl but I verified that should not be the issue.

$ openssl version -a
OpenSSL 1.1.1f  31 Mar 2020 (Library: OpenSSL 1.1.1n  15 Mar 2022)
built on: Thu Dec 22 14:25:22 2022 UTC
platform: linux-x86_64
options:  bn(64,64) rc4(16x,int) des(int) blowfish(ptr)
compiler: gcc -fPIC -pthread -m64 -Wa,--noexecstack -Wall -O3 -DOPENSSL_USE_NODELETE -DL_ENDIAN -DOPENSSL_PIC -DOPENSSL_CPUID_OBJ -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DKECCAK1600_ASM -DRC4_ASM -DMD5_ASM -DAESNI_ASM -DVPAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM -DX25519_ASM -DPOLY1305_ASM -DNDEBUG
OPENSSLDIR: "/usr/local/ssl"
ENGINESDIR: "/usr/local/lib/

If we use root user, we are able to connect to ODS endpoint and bing.com without any issues using openssl client.
But if we use omsagent user, we are not running into the same problem connecting to ODS endpoint and bing.com with opensssl client.

I verified that the /etc/ssl/certs has the proper certs configured.


问:
lpdf luarocks dependency installation external dependency error
I want to use lpdf dependency in the luarocks. When I am trying to install it using rockspec file following error has occurred .

lpdf - https://luarocks.org/modules/tomasguisasola/lpdf/20130702.51-1

```<code>    Error: Failed installing dependency: https://luarocks.org/lpdf-20130702.51-1.src.rock
    - Could not find header file for PDFLIB
    No file pdflib.h in /usr/local/include
    No file pdflib.h in /usr/include
    No file pdflib.h in /include
    You may have to install PDFLIB in your system and/or pass PDFLIB_DIR or PDFLIB_INCDIR
    to the luarocks command.
    Example: luarocks install lpdf PDFLIB_DIR=/usr/local
    Makefile:110: recipe for target 'install' failed
    make: *** [install] Error 1
</code>```

I want to install in on a docker container. Can anyone share an idea on this?

Body:
I want to use lpdf dependency in the luarocks. When I am trying to install it using rockspec file following error has occurred .

lpdf - https://luarocks.org/modules/tomasguisasola/lpdf/20130702.51-1

    Error: Failed installing dependency: https://luarocks.org/lpdf-20130702.51-1.src.rock
    - Could not find header file for PDFLIB
    No file pdflib.h in /usr/local/include
    No file pdflib.h in /usr/include
    No file pdflib.h in /include
    You may have to install PDFLIB in your system and/or pass PDFLIB_DIR or PDFLIB_INCDIR
    to the luarocks command.
    Example: luarocks install lpdf PDFLIB_DIR=/usr/local
    Makefile:110: recipe for target 'install' failed
    make: *** [install] Error 1

I want to install in on a docker container. Can anyone share an idea on this?


问:
Why can not I see my codes result lively in VSCODE? Live server has problem I think
I have installed extensions offline through VSIX file format, because I could not download online due to an unexpected error. My problem is when I would type codes, the result would not appear in browser as live, and if I want see my result I must either close and reopen my browser or switch live server off then on

I have done only either close and reopen my browser or switch live server off then on


问:
What is the command line approach to download a bunch of jars using maven without POM?
I am using maven and trying to download a bunch of jars.
I donot want to generate the POM file so i am using the below command

```<code>mvn dependency:copy -Dartifact=<group>:<artifact-name>:<version> -DoutputDirectory=./localdirectory
</code>```

How can i use a similar command in maven to download a bunch of artifacts without the POM file?
Any examples using artifactItems would help
The below code snippet does not work

```<code>mvn dependency:copy -DartifactItems='com.google.guava:guava:18.0','com.fasterxml.jackson.core:jackson-databind:2.4.3' -DoutputDirectory=./localdirectory
</code>```

Body:
I am using maven and trying to download a bunch of jars.
I donot want to generate the POM file so i am using the below command

mvn dependency:copy -Dartifact=<group>:<artifact-name>:<version> -DoutputDirectory=./localdirectory

How can i use a similar command in maven to download a bunch of artifacts without the POM file?
Any examples using artifactItems would help
The below code snippet does not work

mvn dependency:copy -DartifactItems='com.google.guava:guava:18.0','com.fasterxml.jackson.core:jackson-databind:2.4.3' -DoutputDirectory=./localdirectory


问:
How do I run a tcp server in pyqt?
I configured as below and ran pyqt
However, the ui screen appears and the program ends as it falls into an infinite loop.
How can I run a tcp server when running the program</p>
```<code>host = "127.0.0.1"
port = 8000

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind((host, port))

        server_socket.listen()

        while True:
            connection, addr = server_socket.accept()

            try:
                data = connection.recv(100)

            except socket.error:
                connection.close()

    def initUI(self):

        self.ui = uic.loadUi("./main.ui")
        self.ui.showFullScreen()

if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = MyApp()
   sys.exit(app.exec_())
</code>```

Title: How do I run a tcp server in pyqt?

Body:
I configured as below and ran pyqt
However, the ui screen appears and the program ends as it falls into an infinite loop.
How can I run a tcp server when running the program

host = "127.0.0.1"
port = 8000

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind((host, port))

        server_socket.listen()

        while True:
            connection, addr = server_socket.accept()

            try:
                data = connection.recv(100)

            except socket.error:
                connection.close()

    def initUI(self):

        self.ui = uic.loadUi("./main.ui")
        self.ui.showFullScreen()

if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = MyApp()
   sys.exit(app.exec_())


问:
How to save a document in sharepoint with another user in O365 using REST API
When a user uploads a document in one of my form which is in sharepoint classic site, I need a dedicated account to save the document in my forms document library using REST API.

This is my code:

```<code>var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var url = siteUrl + "/_api/web/folders";
$.ajax({
    url: url,
    type: "POST",
    async: false,
    data: {
        username:"user";
        Password:"*********"';
    }
    data: JSON.stringify({
        '__metadata': { 'type': 'SP.Folder' },
        'ServerRelativeUrl': folderNamePath
    }),
    headers: {
        "accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (response) {
           console.log(response);
    },
    error: function (error) {
        console.log(error);
    }
});
</code>```

I have tried with above code, but I am not getting any response from API,
Please help me.....Thanks in advance.

Body:
When a user uploads a document in one of my form which is in sharepoint classic site, I need a dedicated account to save the document in my forms document library using REST API.

This is my code:

var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var url = siteUrl + "/_api/web/folders";
$.ajax({
    url: url,
    type: "POST",
    async: false,
    data: {
        username:"user";
        Password:"*********"';
    }
    data: JSON.stringify({
        '__metadata': { 'type': 'SP.Folder' },
        'ServerRelativeUrl': folderNamePath
    }),
    headers: {
        "accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (response) {
           console.log(response);
    },
    error: function (error) {
        console.log(error);
    }
});

I have tried with above code, but I am not getting any response from API,
Please help me.....Thanks in advance.


问:
How to trigger onCellEditApproved inside EditField onChange handler in React's MaterialTable?
I am trying to trigger onCellEditApproved when the value of the editable column changes (or onBlur) inside MaterialTable

```<code>            cellEditable={{
                cellStyle: {},
                onCellEditApproved: (newValue, oldValue, rowData, columnDef) => {
                    return new Promise((resolve, reject) => {
                        setTimeout(() => {
                            resolve()
                            let updatedRow = rowData
                            updatedRow.anQty = parseInt(newValue)
                            const updatedRowData = {
                                ...rowData,
                                [columnDef.anQty]: newValue,
                            };
                            setGetCompanyData(prevData => {
                                const index = prevData.indexOf(rowData);
                                return [...prevData.slice(0, index), updatedRowData, ...prevData.slice(index + 1)];
                            });
                        }, 1000);
                    });
                }
            }}
</code>```

onCellEditApproved is triggered when the user press "Enter" and I want to override that behavior with onChange and onBlur, that's why I made a custom EditField:

```<code>            components={{
                EditField: props => {
                    const handleChange = (event) => {
                        //const { onCellEditApproved } = props;
                        props.onChange(event.target.value);
                        //onCellEditApproved(props.value, props.oldValue, props.rowData, props.columnDef);
                    }
                        return <input {...props} type="text" className="test" onChange={handleChange} />
                },
            }}
</code>```

I have tried to get onCellEditApproved event via props inside of EditField but unsuccessfully.

Body:
I am trying to trigger onCellEditApproved when the value of the editable column changes (or onBlur) inside MaterialTable

            cellEditable={{
                cellStyle: {},
                onCellEditApproved: (newValue, oldValue, rowData, columnDef) => {
                    return new Promise((resolve, reject) => {
                        setTimeout(() => {
                            resolve()
                            let updatedRow = rowData
                            updatedRow.anQty = parseInt(newValue)
                            const updatedRowData = {
                                ...rowData,
                                [columnDef.anQty]: newValue,
                            };
                            setGetCompanyData(prevData => {
                                const index = prevData.indexOf(rowData);
                                return [...prevData.slice(0, index), updatedRowData, ...prevData.slice(index + 1)];
                            });
                        }, 1000);
                    });
                }
            }}

onCellEditApproved is triggered when the user press "Enter" and I want to override that behavior with onChange and onBlur, that's why I made a custom EditField:

            components={{
                EditField: props => {
                    const handleChange = (event) => {
                        //const { onCellEditApproved } = props;
                        props.onChange(event.target.value);
                        //onCellEditApproved(props.value, props.oldValue, props.rowData, props.columnDef);
                    }
                        return <input {...props} type="text" className="test" onChange={handleChange} />
                },
            }}

I have tried to get onCellEditApproved event via props inside of EditField but unsuccessfully.


问:
How to enable/disable internet inside flutter app?
How to enable/disable internet inside  flutter app ? I want to control this functionality  using a button.</p>


问:
Is there a way to send open url request from watch app to the iPhone
I need to open a URL in the iPhone's safari using a button on the watchOS app. It's pretty straightforward when there's a companion app installed, but is there a way to do this without a companion app?
Thanks

Using @Environment(\.openURL) inside the watch's view just errors out.


问:
grid.arrange error in R: nrow * ncol >= n is not TRUE
grid.arrange(a,b,c,d,e,f, nrow=3, ncol=2, common.legend = TRUE, legend="bottom", top="x")

is the code i am using but I get the error:
Error in arrangeGrob(...) : nrow * ncol >= n is not TRUE

How do I fix this?


问:
cant retrieve data from firebase realtime in ASP.NET webforms C#
I have login page in ASP.NET webforms using C#.

What I've tried is - this is my admin account model:

```<code>public class AdminAccount
{
    public int Idno { get; set; }
    public string Lname { get; set; }
    public string Fname { get; set; }
    public string Mname { get; set; }
    public string Bdate { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string WRS_Name { get; set; }
    public string Pass { get; set; }
    public string Proof { get; set; }
}
</code>```

My account.aspx.cs:

```<code>public void btnLogin_Click(object sender, EventArgs e)
{
    // Get the email and password entered by the user
    string username = txt_username.Text;
    string password = txt_password.Text;

    // Check if the email and password are valid
    FirebaseResponse response;
    response = twoBigDB.Get("ADMIN/" + username);

    Model.AdminAccount obj = response.ResultAs<Model.AdminAccount>();

    if (obj.Username == username && obj.Pass == password)
    {
        Session["username"] = username;
        Session["password"] = password;
        Session["WRSname"] = obj.WRS_Name;

        // Login successful, redirect to admin homepage
        Response.Redirect("/Admin/AdminIndex.aspx");
    }
    else
    {
        Response.Write("<script>alert('Invalid username or password');</script>");
    }
}
</code>```

My expected output is inside my if condition would be true, Username can fetch data from firebase realtime and with username input by the user.

Body:
I have login page in ASP.NET webforms using C#.

What I've tried is - this is my admin account model:

public class AdminAccount
{
    public int Idno { get; set; }
    public string Lname { get; set; }
    public string Fname { get; set; }
    public string Mname { get; set; }
    public string Bdate { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string WRS_Name { get; set; }
    public string Pass { get; set; }
    public string Proof { get; set; }
}

My account.aspx.cs:

public void btnLogin_Click(object sender, EventArgs e)
{
    // Get the email and password entered by the user
    string username = txt_username.Text;
    string password = txt_password.Text;

    // Check if the email and password are valid
    FirebaseResponse response;
    response = twoBigDB.Get("ADMIN/" + username);

    Model.AdminAccount obj = response.ResultAs<Model.AdminAccount>();

    if (obj.Username == username && obj.Pass == password)
    {
        Session["username"] = username;
        Session["password"] = password;
        Session["WRSname"] = obj.WRS_Name;

        // Login successful, redirect to admin homepage
        Response.Redirect("/Admin/AdminIndex.aspx");
    }
    else
    {
        Response.Write("");
    }
}

My expected output is inside my if condition would be true, Username can fetch data from firebase realtime and with username input by the user.