问:
Pandas multi index partial selection using list of tuples
Consider the following dataframe

```<code>import pandas as pd
import numpy as np

arr = np.random.random((2, 4))
mdf = pd.DataFrame({'cid': ['c1', 'c2']})
pdf = pd.DataFrame({'doc_id': ['d1', 'd1', 'd2', 'd2'], 'passage_id': ['p1', 'p2', 'p1', 'p2']})
index = pd.MultiIndex.from_frame(mdf.join(pdf, how='cross'))
df = pd.DataFrame({'score': arr.flatten()}, index=index)
</code>```

df is

```<code>                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
        d2       p1          0.326029
                 p2          0.979832
c2      d1       p1          0.147153
                 p2          0.381807
        d2       p1          0.525054
                 p2          0.245478
</code>```

Now If i try to index using a list of tuples using only two levels

df.loc[[('c1', 'd1'), ('c2', 'd2')]]

I get the following error:

ValueError: operands could not be broadcast together with shapes (2,2) (3,) (2,2)

Why is this error happening ?

I expected the answer to be:

```<code>                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
c2      d2       p1          0.525054
                 p2          0.245478
</code>```

答:
A little bit over thinking since we need the multiple index dataframe</p>
```<code>inputtuple =pd.DataFrame([('c1', 'd1'), ('c2', 'd2')],columns = ['cid','doc_id'])
out = df.reset_index().merge(inputtuple).set_index(df.index.names)
Out[199]:
                          score
cid doc_id passage_id
c1  d1     p1          0.428390
           p2          0.931326
c2  d2     p1          0.160805
           p2          0.476747
</code>```

Body:
Consider the following dataframe

import pandas as pd
import numpy as np

arr = np.random.random((2, 4))
mdf = pd.DataFrame({'cid': ['c1', 'c2']})
pdf = pd.DataFrame({'doc_id': ['d1', 'd1', 'd2', 'd2'], 'passage_id': ['p1', 'p2', 'p1', 'p2']})
index = pd.MultiIndex.from_frame(mdf.join(pdf, how='cross'))
df = pd.DataFrame({'score': arr.flatten()}, index=index)

df is

                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
        d2       p1          0.326029
                 p2          0.979832
c2      d1       p1          0.147153
                 p2          0.381807
        d2       p1          0.525054
                 p2          0.245478

Now If i try to index using a list of tuples using only two levels

df.loc[[('c1', 'd1'), ('c2', 'd2')]]

I get the following error:

ValueError: operands could not be broadcast together with shapes (2,2) (3,) (2,2)

Why is this error happening ?

I expected the answer to be:

                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
c2      d2       p1          0.525054
                 p2          0.245478

Body:
A little bit over thinking since we need the multiple index dataframe

inputtuple =pd.DataFrame([('c1', 'd1'), ('c2', 'd2')],columns = ['cid','doc_id'])
out = df.reset_index().merge(inputtuple).set_index(df.index.names)
Out[199]:
                          score
cid doc_id passage_id
c1  d1     p1          0.428390
           p2          0.931326
c2  d2     p1          0.160805
           p2          0.476747


来源: stackexchange

问:
Is there a way to import images from a Wiki table into a spreadsheet?
I'm trying to import a MediaWiki table from here: https://hotwheels.fandom.com/wiki/List_of_2021_Hot_Wheels

I want to be able to also pull the images, but when I use ImportHtml in sheets (like so: =ImportHtml("https://hotwheels.fandom.com/wiki/List_of_2021_Hot_Wheels", "table", 1)), the "photos" column is just blank:

Is there anything I can do here? I would be alright if, at the very least, I could pull the link to the photo to put there if I can't pull the photos themselves.

答:
In this case IMPORTHTML can't access links or images that's why the images are not retrieved when calling the function, a solution could be that you call the image directly by using the IMAGE function in Sheets. To do this however you will first need to limit the columns that you are retrieving from the table:

```<code>=QUERY(ImportHtml("https://hotwheels.fandom.com/wiki/List_of_2021_Hot_Wheels", "table", 1), "SELECT Col1,Col2,Col3,Col4,Col5")
</code>```

Then you will need to manually add the last column and import the image:

```<code>=IMAGE("https://static.wikia.nocookie.net/hotwheels/images/a/a9/GRX90_-_The_Nash.jpg/revision/latest?cb=20210812001135")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In this case IMPORTHTML can't access links or images that's why the images are not retrieved when calling the function, a solution could be that you call the image directly by using the IMAGE function in Sheets. To do this however you will first need to limit the columns that you are retrieving from the table:

=QUERY(ImportHtml("https://hotwheels.fandom.com/wiki/List_of_2021_Hot_Wheels", "table", 1), "SELECT Col1,Col2,Col3,Col4,Col5")

Then you will need to manually add the last column and import the image:

=IMAGE("https://static.wikia.nocookie.net/hotwheels/images/a/a9/GRX90_-_The_Nash.jpg/revision/latest?cb=20210812001135")


问:
Should a internal C# app be compiled with business logic?
[background]

So, I've got a C# application that was written before I got here.  I'm not in the dev org, at this time, but I am the tech lead in my sub-group within the internet marketing org.  My responsibility is process automation, minimal desktop support, and custom apps that make our lives easier.

[/background]

[app details]

We've got an app that creates a custom database file from a list of URLs.  It was designed to have one input file, and two output files for the two applications that use these sort of db files.  The rule for the difference between the two output files is compiled into the code.

[/app details]

Should an internal C# app be compiled with business logic that can't be changed without it being re-built?

答: If the logic is changed on a regular basis, you should avoid building it into the program. On the other hand, since it is internal, I'm guessing that the process required to rebuild the app is minimal or non-existent, so it may not make much of a difference.</p>

OwnerDisplayName: Sean Ochoa

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Elie


问:
How to fetch data from rest api by specific id or name using flutter
This is the api I want to use and I want to get data on Only India.
I am not getting how to get the data by country name.

https://api.covid19api.com/summary

Thanks in advance.!!

答:
Either you can get the from this API and then select the data for India from the response or you can change the URL of the API a little bit and change it to

```<code>https://api.covid19api.com/country/india
</code>```

you will get data for India only.

Body:
Either you can get the from this API and then select the data for India from the response or you can change the URL of the API a little bit and change it to

https://api.covid19api.com/country/india

you will get data for India only.


问:
gitlab k3s runner WARNING: Checking for jobs... failed x509: certificate signed by unknown authority
I have an issue with a gitlab-runner installed via the application panel on gitlab to a k3s rancher cluster. It was working fine then today gitlab was restarted and started giving out this error.

I found out where the gitlab certificate is and where to copy it but I do not have sudo on the POD :

```<code>bash-5.0$ cd gitlab-runner/
bash: cd: gitlab-runner/: Permission denied
bash-5.0$ pwd
</code>```

If i do not install the Runner via the application panel from the Gitlab site it doesn't work properly (meaning I install it via helm with -f values but it will not work with Autodevops and it will not create a pod for each CI as expected)

Any workaround or solution would be greatly appreciated :)

Thank you in advance.

答:
In the same boat here.
Solved my issue copying my self signed certs to all my worker nodes at

```<code>user@worker01:~$ sudo cp gitlab.hostname.com.crt /usr/local/share/ca-certificates/
user@worker02:~$ sudo cp gitlab.hostname.com.crt /usr/local/share/ca-certificates/
user@worker03:~$ sudo cp gitlab.hostname.com.crt /usr/local/share/ca-certificates/
</code>```

After this run the cert update. In my case ubuntu we can run the command below on all worker nodes

```<code>sudo update-ca-certificates --fresh
</code>```

We may need to restarted all worker nodes, also a k3s-agent restart would have done the same.

```<code>sudo systemctl status k3s-agent.service
</code>```

Body:
I have an issue with a gitlab-runner installed via the application panel on gitlab to a k3s rancher cluster. It was working fine then today gitlab was restarted and started giving out this error.

I found out where the gitlab certificate is and where to copy it but I do not have sudo on the POD :

bash-5.0$ cd gitlab-runner/
bash: cd: gitlab-runner/: Permission denied
bash-5.0$ pwd

If i do not install the Runner via the application panel from the Gitlab site it doesn't work properly (meaning I install it via helm with -f values but it will not work with Autodevops and it will not create a pod for each CI as expected)

Any workaround or solution would be greatly appreciated :)

Thank you in advance.

Body:
In the same boat here.
Solved my issue copying my self signed certs to all my worker nodes at

user@worker01:~$ sudo cp gitlab.hostname.com.crt /usr/local/share/ca-certificates/
user@worker02:~$ sudo cp gitlab.hostname.com.crt /usr/local/share/ca-certificates/
user@worker03:~$ sudo cp gitlab.hostname.com.crt /usr/local/share/ca-certificates/

After this run the cert update. In my case ubuntu we can run the command below on all worker nodes

sudo update-ca-certificates --fresh

We may need to restarted all worker nodes, also a k3s-agent restart would have done the same.

sudo systemctl status k3s-agent.service


问:
ReportLab numbering with nested bullet points
I'm struggeling with ReportLab which I would like to use to generate a PDF as a request from Django from a view.

I try to get a numbered list with bullet points in between like that

Text1-blabla

Bullet-blabla

Bullet-blabla

Text2 blabla

But what I receive is:

Text1-blabla

Bullet-blabla

Bullet-blabla

Text2 blabla

How can I suppres the "2." infront of the bullets or how can I skip it for that region?

This is my code

```<code>lf = ListFlowable([ ListItem(Paragraph(text1, styles["Normal"])),
        ListFlowable([ListItem(Paragraph(text1a, styles["Normal"])),
                    ListItem(Paragraph(text1b, styles["Normal"])),
                    ListItem(Paragraph(text1c, styles["Normal"])),
                    ListItem(Paragraph(text1d, styles["Normal"])),
                 ], bulletType='bullet', bulletFontSize= 5, bulletOffsetY= -2, leftIndent=10, start='circle'),
        ListItem(Paragraph(text2, styles["Normal"]))
        ], bulletType='1')
</code>```

Thank you!

答:
You can turn off the numbering for one list item by inserting the nested list into ListItem with value argument set to 0:

ListFlowable([
Paragraph(...),
ListItem(ListFlowable(...nested list...), value=0)
ListItem(Paragraph(...), value=2) # to let the list go on
])</p>

Body:
I'm struggeling with ReportLab which I would like to use to generate a PDF as a request from Django from a view.

I try to get a numbered list with bullet points in between like that

Text1-blabla

Bullet-blabla

Bullet-blabla

Text2 blabla

But what I receive is:

Text1-blabla

Bullet-blabla

Bullet-blabla

Text2 blabla

How can I suppres the "2." infront of the bullets or how can I skip it for that region?

This is my code

lf = ListFlowable([ ListItem(Paragraph(text1, styles["Normal"])),
        ListFlowable([ListItem(Paragraph(text1a, styles["Normal"])),
                    ListItem(Paragraph(text1b, styles["Normal"])),
                    ListItem(Paragraph(text1c, styles["Normal"])),
                    ListItem(Paragraph(text1d, styles["Normal"])),
                 ], bulletType='bullet', bulletFontSize= 5, bulletOffsetY= -2, leftIndent=10, start='circle'),
        ListItem(Paragraph(text2, styles["Normal"]))
        ], bulletType='1')

Thank you!


问:
Observer events in JS Prototype - two events at the same time
I have an input box that takes a number that gets verified in function opConfig.reloadPrice(). I set 2 observers one the same element, on 'change' it executes the code when I click outside the box or use tab-if the change has been made. On 'keypress' it checks if the return key was pressed then executes the code AND it also triggers the 'change' observer!! So in this case the function opConfig.reloadPrice()  gets executed twice (and I end up with two identical alert boxes).
The code that I have now:

```<code><input type="text" value="" name="options[1]" id="options_1" onkeypress="return disableEnterKey(event)">

Event.observe($('options_1'), 'change', function(e){
   opConfig.reloadPrice();
});
Event.observe($('options_1'),'keypress', function(e){
  if (e.keyCode == Event.KEY_RETURN)
    opConfig.reloadPrice();
});
</code>```

I've tried several different solutions (I've tried 'blur' event, putting one observer in the other... )

I'm looking for a solution similar to this one
jQuery-Two events at the same time

Thanks a million

EDIT-Solved:

Thanks to katspaugh I solved this. There were few things that were not clear to me, one of them is:  'keypress' event is observed before 'change' event, which is why you can set variables in one observer and check them later in another (this is also why it took me a while to understand katspaughs code :-)  ).

Anyway, I change the code a bit that it suits me:

```<code>var enterPressed = 0;

Event.observe($('options_1'), 'change', function(){
  if (enterPressed !== 1) {
    opConfig.reloadPrice();
  }
  enterPressed = 0;
  });

Event.observe($('options_1'), 'keypress', function(e){
if ((e.keyCode == Event.KEY_RETURN) || (e.keyCode == Event.KEY_TAB)) {
  enterPressed = 1;
  opConfig.reloadPrice();
}
else
  enterPressed = 0;
});
</code>```

Cheers,

jazkat

答:
Save the current value of the input field in an upper-scope variable (up-value).

If the value changes in one of the events, fire the handler and update the upvalue:

```<code>var oldVal;

$('options_1').observe(
  'change', function () {
      var val = this.value;
      if (oldVal !== val) {
          oldVal = val;
          opConfig.reloadPrice();
      }
  }
).observe(
    'keypress', function(e) {
        oldVal = this.value;
        if (e.keyCode == Event.KEY_RETURN) {
            opConfig.reloadPrice();
        }
    }
);
</code>```

Also, you'd better remove the inline listener in HTML (and never add them again):

```<code><input type="text" name="options[1]" id="options_1" />
</code>```

Demo.

ContentLicense: CC BY-SA 3.0

Body:
I have an input box that takes a number that gets verified in function opConfig.reloadPrice(). I set 2 observers one the same element, on 'change' it executes the code when I click outside the box or use tab-if the change has been made. On 'keypress' it checks if the return key was pressed then executes the code AND it also triggers the 'change' observer!! So in this case the function opConfig.reloadPrice()  gets executed twice (and I end up with two identical alert boxes).
The code that I have now:

<input type="text" value="" name="options[1]" id="options_1" onkeypress="return disableEnterKey(event)">

Event.observe($('options_1'), 'change', function(e){
   opConfig.reloadPrice();
});
Event.observe($('options_1'),'keypress', function(e){
  if (e.keyCode == Event.KEY_RETURN)
    opConfig.reloadPrice();
});

I've tried several different solutions (I've tried 'blur' event, putting one observer in the other... )

I'm looking for a solution similar to this one
jQuery-Two events at the same time

Thanks a million

EDIT-Solved:

Thanks to katspaugh I solved this. There were few things that were not clear to me, one of them is:  'keypress' event is observed before 'change' event, which is why you can set variables in one observer and check them later in another (this is also why it took me a while to understand katspaughs code :-)  ).

Anyway, I change the code a bit that it suits me:

var enterPressed = 0;

Event.observe($('options_1'), 'change', function(){
  if (enterPressed !== 1) {
    opConfig.reloadPrice();
  }
  enterPressed = 0;
  });

Event.observe($('options_1'), 'keypress', function(e){
if ((e.keyCode == Event.KEY_RETURN) || (e.keyCode == Event.KEY_TAB)) {
  enterPressed = 1;
  opConfig.reloadPrice();
}
else
  enterPressed = 0;
});

Cheers,

jazkat

Body:
Save the current value of the input field in an upper-scope variable (up-value).

If the value changes in one of the events, fire the handler and update the upvalue:

var oldVal;

$('options_1').observe(
  'change', function () {
      var val = this.value;
      if (oldVal !== val) {
          oldVal = val;
          opConfig.reloadPrice();
      }
  }
).observe(
    'keypress', function(e) {
        oldVal = this.value;
        if (e.keyCode == Event.KEY_RETURN) {
            opConfig.reloadPrice();
        }
    }
);

Also, you'd better remove the inline listener in HTML (and never add them again):

<input type="text" name="options[1]" id="options_1" />

Demo.


问:
"java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState" when show BottomSheetDialogFragment
I came across with problem when i'm trying to open BottomSheetDialogFragment in Fragment, using callback result from another fragment, that is nested in another activity.

All further demonstrations is abstractions of real case in the project with established application architecture which can't be change.
Let's i will explain you.

I have the main host Activity called "MainActivity" which contains BaseFragment

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.flContainer.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
    }

    override fun onStart() {
        super.onStart()

        supportFragmentManager.beginTransaction()
            .add(R.id.flContainer, BaseFragment())
            .addToBackStack(BaseFragment.TAG)
            .commitAllowingStateLoss()
    }

    override fun onResume() {
        super.onResume()

        Log.e("VadymTag", "MainActivity onResume")
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        Log.e("VadymTag", "MainActivity onSaveInstanceState")
    }

    override fun onPause() {
        super.onPause()

        Log.e("VadymTag", "MainActivity onPause")

    }
}
</code>```

This BaseFragment open login screen using LoginActivity which contains LoginFragment because its necessary to authorize user.

```<code>class BaseFragment : Fragment() {
    private var _binding: FragmentBaseBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentBaseBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        _binding?.bOpenLogin?.setOnClickListener {
            startActivity(Intent(requireContext(), LoginActivity::class.java))
        }

        MainNavigator.openBottomSheet = ::openBottomSheet
    }

    override fun onResume() {
        super.onResume()

        Log.e("VadymTag", "BaseFragment onResume")

    }

    fun openBottomSheet() {
        val bottomSheetFragment = MyBottomSheetDialog()

        bottomSheetFragment.show(childFragmentManager, MyBottomSheetDialog.TAG)
    }

    override fun onPause() {
        super.onPause()

        Log.e("VadymTag", "BaseFragment onPause")

    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        Log.e("VadymTag", "BaseFragment onSaveInstanceState")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        val TAG = BaseFragment::class.java.simpleName
    }
}
</code>```

Also LoginActivity handles result of sucess / failed login using supportFragmentManager.setFragmentResultListener (.... For this example FragmentResultListener handles any changes successfull.
LoginActivity asks MainNavigator to open BottomSheetDialogFragment from BaseFragment where was called login, for authorization user and finishes.

```<code>class LoginActivity : AppCompatActivity() {

        private lateinit var binding: LoginMainBinding

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

            binding = LoginMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
        }

        override fun onStart() {
            super.onStart()

            supportFragmentManager.beginTransaction()
                .add(R.id.flLoginContainer, LoginFragment())
                .addToBackStack(LoginFragment.TAG)
                .commit()

            initLoginListener()
        }

        fun initLoginListener() {
            supportFragmentManager
                .setFragmentResultListener(LOGIN_KEY, this) { _, bundle ->
                    MainNavigator.openBottomSheet()
                    finish()
                }
        }

        companion object {
            const val LOGIN_KEY = "login_key"
            const val LOGIN_FIELD = "login_key"

        }
    }
</code>```

LoginFragment

```<code>    class LoginFragment : Fragment() {

    private var _binding: LoginFragmentBinding? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = LoginFragmentBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        _binding?.bLoginSuccess?.setOnClickListener {
            parentFragmentManager.setFragmentResult(LOGIN_KEY, bundleOf(LOGIN_FIELD to true))

        }
    }

    companion object {
        val TAG = LoginFragment::class.java.simpleName
    }
}
</code>```

MainNavigator is abstraction used for navigation cross tho whole application.

```<code>    object MainNavigator {

    var openBottomSheet: () -> Unit = {}
}
</code>```

MainNavigator calls BaseFragment to open BottomSheetDialogFragment.

```<code>class MyBottomSheetDialog : BottomSheetDialogFragment() {

        private var _binding: FragmentMyBottomSheetBinding? = null

        private val binding get() = _binding!!

        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {

            _binding = FragmentMyBottomSheetBinding.inflate(inflater, container, false)
            return binding.root
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)

        }

        override fun onDestroyView() {
            super.onDestroyView()
            _binding = null
        }

        companion object {
            val TAG = MyBottomSheetDialog::class.java.simpleName
        }
    }
</code>```

When LoginActivity calls MainNavigator to open BottomSheetDialogFragment. - happens  2022-02-08 19:49:58.285 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: BaseFragment onPause 2022-02-08 19:49:58.286 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: MainActivity onPause 2022-02-08 19:49:58.790 0-0/? E/init: updatable process 'console' exited 4 times in 4 minutes 2022-02-08 19:49:59.027 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: BaseFragment onSaveInstanceState 2022-02-08 19:49:59.031 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: MainActivity onSaveInstanceState 2022-02-08 19:49:59.799 20135-20135/com.vadim.stackoverflowquestion E/AndroidRuntime: FATAL EXCEPTION: main Process: com.galazjukvadim.stackoverflowquestion, PID: 20135 java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at androidx.fragment.app.FragmentManager.checkStateLoss(FragmentManager.java:1844) at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1884) at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:329) at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:294) at androidx.fragment.app.DialogFragment.show(DialogFragment.java:260) at com.galazjukvadim.stackoverflowquestion.BaseFragment.openBottomSheet(BaseFragment.kt:52) at com.galazjukvadim.stackoverflowquestion.BaseFragment$onViewCreated$2.invoke(BaseFragment.kt:39) at com.galazjukvadim.stackoverflowquestion.BaseFragment$onViewCreated$2.invoke(BaseFragment.kt:39) at com.galazjukvadim.stackoverflowquestion.LoginActivity.initLoginListener$lambda-0(LoginActivity.kt:33) at com.galazjukvadim.stackoverflowquestion.LoginActivity.$r8$lambda$3dwuINVTP3WL69H0HgmUiCWJ7Dw(Unknown Source:0) at com.galazjukvadim.stackoverflowquestion.LoginActivity$$ExternalSyntheticLambda0.onFragmentResult(Unknown Source:2) at androidx.fragment.app.FragmentManager$LifecycleAwareResultListener.onFragmentResult(FragmentManager.java:256) at androidx.fragment.app.FragmentManager.setFragmentResult(FragmentManager.java:865) at com.galazjukvadim.stackoverflowquestion.LoginFragment.onViewCreated$lambda-0(LoginFragment.kt:30) at com.galazjukvadim.stackoverflowquestion.LoginFragment.$r8$lambda$PNHKtYyi4mi0uK7kLsV6wOurKW4(Unknown Source:0)

Its caused following problem called Activity state loss .
Reading following articless: 1, 2 i watched expected behavior .
My BaseFragment and MainActivity have called  onPause and after onSaveInstanceState that triggered throw IllegalStateException: Can not perform this action after onSaveInstanceState .

In this case its affordable to use .commitAllowingStateLoss() to show BottomSheetDialogFragment. But under hood of bottomSheetFragment.show(childFragmentManager, MyBottomSheetDialog.TAG) is used usual ft.commit();

Does anybody know the solution for this?

答:
```<code>        if (!childFragmentManager.isStateSaved) {}
</code>```

Add this check before calling bottomsheet.show() if state is not saved you can execute the transaction or else ignore.

Other approach is to create custom DialogFragment and overide show method and add commitallowstateloss implementation

Body:
I came across with problem when i'm trying to open BottomSheetDialogFragment in Fragment, using callback result from another fragment, that is nested in another activity.

All further demonstrations is abstractions of real case in the project with established application architecture which can't be change.
Let's i will explain you.

I have the main host Activity called "MainActivity" which contains BaseFragment

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.flContainer.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
    }

    override fun onStart() {
        super.onStart()

        supportFragmentManager.beginTransaction()
            .add(R.id.flContainer, BaseFragment())
            .addToBackStack(BaseFragment.TAG)
            .commitAllowingStateLoss()
    }

    override fun onResume() {
        super.onResume()

        Log.e("VadymTag", "MainActivity onResume")
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        Log.e("VadymTag", "MainActivity onSaveInstanceState")
    }

    override fun onPause() {
        super.onPause()

        Log.e("VadymTag", "MainActivity onPause")

    }
}

This BaseFragment open login screen using LoginActivity which contains LoginFragment because its necessary to authorize user.

class BaseFragment : Fragment() {
    private var _binding: FragmentBaseBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentBaseBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        _binding?.bOpenLogin?.setOnClickListener {
            startActivity(Intent(requireContext(), LoginActivity::class.java))
        }

        MainNavigator.openBottomSheet = ::openBottomSheet
    }

    override fun onResume() {
        super.onResume()

        Log.e("VadymTag", "BaseFragment onResume")

    }

    fun openBottomSheet() {
        val bottomSheetFragment = MyBottomSheetDialog()

        bottomSheetFragment.show(childFragmentManager, MyBottomSheetDialog.TAG)
    }

    override fun onPause() {
        super.onPause()

        Log.e("VadymTag", "BaseFragment onPause")

    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        Log.e("VadymTag", "BaseFragment onSaveInstanceState")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        val TAG = BaseFragment::class.java.simpleName
    }
}

Also LoginActivity handles result of sucess / failed login using supportFragmentManager.setFragmentResultListener (.... For this example FragmentResultListener handles any changes successfull.
LoginActivity asks MainNavigator to open BottomSheetDialogFragment from BaseFragment where was called login, for authorization user and finishes.

class LoginActivity : AppCompatActivity() {

        private lateinit var binding: LoginMainBinding

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

            binding = LoginMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
        }

        override fun onStart() {
            super.onStart()

            supportFragmentManager.beginTransaction()
                .add(R.id.flLoginContainer, LoginFragment())
                .addToBackStack(LoginFragment.TAG)
                .commit()

            initLoginListener()
        }

        fun initLoginListener() {
            supportFragmentManager
                .setFragmentResultListener(LOGIN_KEY, this) { _, bundle ->
                    MainNavigator.openBottomSheet()
                    finish()
                }
        }

        companion object {
            const val LOGIN_KEY = "login_key"
            const val LOGIN_FIELD = "login_key"

        }
    }

LoginFragment

    class LoginFragment : Fragment() {

    private var _binding: LoginFragmentBinding? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = LoginFragmentBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        _binding?.bLoginSuccess?.setOnClickListener {
            parentFragmentManager.setFragmentResult(LOGIN_KEY, bundleOf(LOGIN_FIELD to true))

        }
    }

    companion object {
        val TAG = LoginFragment::class.java.simpleName
    }
}

MainNavigator is abstraction used for navigation cross tho whole application.

    object MainNavigator {

    var openBottomSheet: () -> Unit = {}
}

MainNavigator calls BaseFragment to open BottomSheetDialogFragment.

class MyBottomSheetDialog : BottomSheetDialogFragment() {

        private var _binding: FragmentMyBottomSheetBinding? = null

        private val binding get() = _binding!!

        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {

            _binding = FragmentMyBottomSheetBinding.inflate(inflater, container, false)
            return binding.root
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)

        }

        override fun onDestroyView() {
            super.onDestroyView()
            _binding = null
        }

        companion object {
            val TAG = MyBottomSheetDialog::class.java.simpleName
        }
    }

When LoginActivity calls MainNavigator to open BottomSheetDialogFragment. - happens  2022-02-08 19:49:58.285 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: BaseFragment onPause 2022-02-08 19:49:58.286 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: MainActivity onPause 2022-02-08 19:49:58.790 0-0/? E/init: updatable process 'console' exited 4 times in 4 minutes 2022-02-08 19:49:59.027 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: BaseFragment onSaveInstanceState 2022-02-08 19:49:59.031 20135-20135/com.vadim.stackoverflowquestion E/VadymTag: MainActivity onSaveInstanceState 2022-02-08 19:49:59.799 20135-20135/com.vadim.stackoverflowquestion E/AndroidRuntime: FATAL EXCEPTION: main Process: com.galazjukvadim.stackoverflowquestion, PID: 20135 java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at androidx.fragment.app.FragmentManager.checkStateLoss(FragmentManager.java:1844) at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1884) at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:329) at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:294) at androidx.fragment.app.DialogFragment.show(DialogFragment.java:260) at com.galazjukvadim.stackoverflowquestion.BaseFragment.openBottomSheet(BaseFragment.kt:52) at com.galazjukvadim.stackoverflowquestion.BaseFragment$onViewCreated$2.invoke(BaseFragment.kt:39) at com.galazjukvadim.stackoverflowquestion.BaseFragment$onViewCreated$2.invoke(BaseFragment.kt:39) at com.galazjukvadim.stackoverflowquestion.LoginActivity.initLoginListener$lambda-0(LoginActivity.kt:33) at com.galazjukvadim.stackoverflowquestion.LoginActivity.$r8$lambda$3dwuINVTP3WL69H0HgmUiCWJ7Dw(Unknown Source:0) at com.galazjukvadim.stackoverflowquestion.LoginActivity$$ExternalSyntheticLambda0.onFragmentResult(Unknown Source:2) at androidx.fragment.app.FragmentManager$LifecycleAwareResultListener.onFragmentResult(FragmentManager.java:256) at androidx.fragment.app.FragmentManager.setFragmentResult(FragmentManager.java:865) at com.galazjukvadim.stackoverflowquestion.LoginFragment.onViewCreated$lambda-0(LoginFragment.kt:30) at com.galazjukvadim.stackoverflowquestion.LoginFragment.$r8$lambda$PNHKtYyi4mi0uK7kLsV6wOurKW4(Unknown Source:0)

Its caused following problem called Activity state loss .
Reading following articless: 1, 2 i watched expected behavior .
My BaseFragment and MainActivity have called  onPause and after onSaveInstanceState that triggered throw IllegalStateException: Can not perform this action after onSaveInstanceState .

In this case its affordable to use .commitAllowingStateLoss() to show BottomSheetDialogFragment. But under hood of bottomSheetFragment.show(childFragmentManager, MyBottomSheetDialog.TAG) is used usual ft.commit();

Does anybody know the solution for this?

Body:
        if (!childFragmentManager.isStateSaved) {}

Add this check before calling bottomsheet.show() if state is not saved you can execute the transaction or else ignore.

Other approach is to create custom DialogFragment and overide show method and add commitallowstateloss implementation


问:
Uploading file using POST request in Node.js
I have problem uploading file using POST request in Node.js. I have to use request module to accomplish that (no external npms). Server needs it to be multipart request with the file field containing file's data. What seems to be easy it's pretty hard to do in Node.js without using any external module.

I've tried using this example but without success:

```<code>request.post({
  uri: url,
  method: 'POST',
  multipart: [{
    body: '<FILE_DATA>'
  }]
}, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
</code>```

答:
I did it like this:</p>
```<code>// Open file as a readable stream
const fileStream = fs.createReadStream('./my-file.ext');

const form = new FormData();
// Pass file stream directly to form
form.append('my file', fileStream, 'my-file.ext');
</code>```

Body:
I have problem uploading file using POST request in Node.js. I have to use request module to accomplish that (no external npms). Server needs it to be multipart request with the file field containing file's data. What seems to be easy it's pretty hard to do in Node.js without using any external module.

I've tried using this example but without success:

request.post({
  uri: url,
  method: 'POST',
  multipart: [{
    body: '<FILE_DATA>'
  }]
}, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});

Body:
I did it like this:

// Open file as a readable stream
const fileStream = fs.createReadStream('./my-file.ext');

const form = new FormData();
// Pass file stream directly to form
form.append('my file', fileStream, 'my-file.ext');


问:
Simply queries in pandas give different results
I am doing simply queries on a csv document about a genome. I have the following code:

```<code>locus_example = 'Rv0001'

for locus in tuberculosis_data1["Locus"].values:
    if locus_example.rfind(locus):
        result = tuberculosis_data1.loc[tuberculosis_data1['Locus'] == locus]['Sequences'].values
        for r in result:
            print(r)
        break
</code>```

That gives me the following sequence:

```<code>ATGGACGCGGCTACGACAAGAGTTGGCCTCACCGACTTGACGTTTCGTTTGCTACGAGAGTCTTTCGCCGATGCGGTGTCGTGGGTGGCTAAAAATCTGCCAGCCAGGCCCGCGGTGCCGGTGCTCTCCGGCGTGTTGTTGACCGGCTCGGACAACGGTCTGACGATTTCCGGATTCGACTACGAGGTTTCCGCCGAGGCCCAGGTTGGCGCTGAAATTGTTTCTCCTGGAAGCGTTTTAGTTTCTGGCCGATTGTTGTCCGATATTACCCGGGCGTTGCCTAACAAGCCCGTAGACGTTCATGTCGAAGGTAACCGGGTCGCATTGACCTGCGGTAACGCCAGGTTTTCGCTACCGACGATGCCAGTCGAGGATTATCCGACGCTGCCGACGCTGCCGGAAGAGACCGGATTGTTGCCTGCGGAATTATTCGCCGAGGCAATCAGTCAGGTCGCTATCGCCGCCGGCCGGGACGACACGTTGCCTATGTTGACCGGCATCCGGGTCGAAATCCTCGGTGAGACGGTGGTTTTGGCCGCTACCGACAGGTTTCGCCTGGCTGTTCGAGAACTGAAGTGGTCGGCGTCGTCGCCAGATATCGAAGCGGCTGTGCTGGTCCCGGCCAAGACGCTGGCCGAGGCCGCCAAAGCGGGCATCGGCGGCTCTGACGTTCGTTTGTCGTTGGGTACTGGGCCGGGGGTGGGCAAGGATGGCCTGCTCGGTATCAGTGGGAACGGCAAGCGCAGCACCACGCGACTTCTTGATGCCGAGTTCCCGAAGTTTCGGCAGTTGCTACCAACCGAACACACCGCGGTGGCCACCATGGACGTGGCCGAGTTGATCGAAGCGATCAAGCTGGTTGCGTTGGTAGCTGATCGGGGCGCGCAGGTGCGCATGGAGTTCGCTGATGGCAGCGTGCGGCTTTCTGCGGGTGCCGATGATGTTGGACGAGCCGAGGAAGATCTTGTTGTTGACTATGCCGGTGAACCATTGACGATTGCGTTTAACCCAACCTATCTAACGGACGGTTTGAGTTCGTTGCGCTCGGAGCGAGTGTCTTTCGGGTTTACGACTGCGGGTAAGCCTGCCTTGCTACGTCCGGTGTCCGGGGACGATCGCCCTGTGGCGGGTCTGAATGGCAACGGTCCGTTCCCGGCGGTGTCGACGGACTATGTCTATCTGTTGATGCCGGTTCGGTTGCCGGGCTGA
</code>```

I also have the following code that is supposed to give me the same exact sequence:

```<code>gen_example = 'dnaA'

for gen in tuberculosis_data1["Gen name"].values:
    if gen_example.rfind(gen):
        result = tuberculosis_data1.loc[tuberculosis_data1['Gen name'] == gen]['Sequences'].values
        for r in result:
            print(r)
        break
</code>```

However the result is:

```<code>TTGACCGATGACCCCGGTTCAGGCTTCACCACAGTGTGGAACGCGGTCGTCTCCGAACTTAACGGCGACCCTAAGGTTGACGACGGACCCAGCAGTGATGCTAATCTCAGCGCTCCGCTGACCCCTCAGCAAAGGGCTTGGCTCAATCTCGTCCAGCCATTGACCATCGTCGAGGGGTTTGCTCTGTTATCCGTGCCGAGCAGCTTTGTCCAAAACGAAATCGAGCGCCATCTGCGGGCCCCGATTACCGACGCTCTCAGCCGCCGACTCGGACATCAGATCCAACTCGGGGTCCGCATCGCTCCGCCGGCGACCGACGAAGCCGACGACACTACCGTGCCGCCTTCCGAAAATCCTGCTACCACATCGCCAGACACCACAACCGACAACGACGAGATTGATGACAGCGCTGCGGCACGGGGCGATAACCAGCACAGTTGGCCAAGTTACTTCACCGAGCGCCCGCACAATACCGATTCCGCTACCGCTGGCGTAACCAGCCTTAACCGTCGCTACACCTTTGATACGTTCGTTATCGGCGCCTCCAACCGGTTCGCGCACGCCGCCGCCTTGGCGATCGCAGAAGCACCCGCCCGCGCTTACAACCCCCTGTTCATCTGGGGCGAGTCCGGTCTCGGCAAGACACACCTGCTACACGCGGCAGGCAACTATGCCCAACGGTTGTTCCCGGGAATGCGGGTCAAATATGTCTCCACCGAGGAATTCACCAACGACTTCATTAACTCGCTCCGCGATGACCGCAAGGTCGCATTCAAACGCAGCTACCGCGACGTAGACGTGCTGTTGGTCGACGACATCCAATTCATTGAAGGCAAAGAGGGTATTCAAGAGGAGTTCTTCCACACCTTCAACACCTTGCACAATGCCAACAAGCAAATCGTCATCTCATCTGACCGCCCACCCAAGCAGCTCGCCACCCTCGAGGACCGGCTGAGAACCCGCTTTGAGTGGGGGCTGATCACTGACGTACAACCACCCGAGCTGGAGACCCGCATCGCCATCTTGCGCAAGAAAGCACAGATGGAACGGCTCGCGGTCCCCGACGATGTCCTCGAACTCATCGCCAGCAGTATCGAACGCAATATCCGTGAACTCGAGGGCGCGCTGATCCGGGTCACCGCGTTCGCCTCATTGAACAAAACACCAATCGACAAAGCGCTGGCCGAGATTGTGCTTCGCGATCTGATCGCCGACGCCAACACCATGCAAATCAGCGCGGCGACGATCATGGCTGCCACCGCCGAATACTTCGACACTACCGTCGAAGAGCTTCGCGGGCCCGGCAAGACCCGAGCACTGGCCCAGTCACGACAGATTGCGATGTACCTGTGTCGTGAGCTCACCGATCTTTCGTTGCCCAAAATCGGCCAAGCGTTCGGCCGTGATCACACAACCGTCATGTACGCCCAACGCAAGATCCTGTCCGAGATGGCCGAGCGCCGTGAGGTCTTTGATCACGTCAAAGAACTCACCACTCGCATCCGTCAGCGCTCCAAGCGCTAG
</code>```

The correct sequence for this gen called dnaA for locus Rv0001 is the second one. I understand that there are no more genes called dnaA, not even partially. The sequence for the first result is actually the sequence in the following row of the csv file (Rv002/dnaN)

When I remove one 0 and search Rv001 instead, it gives the correct sequence.

I can't understand why the first search is giving me the sequence for the second row while the second search is giving the correct sequence. Any idea as to why python/pandas are behaving this way?

答:
You have fallen into one of the classic Python traps.  Since 0 is a valid index in a string, the rfind function returns -1 if the string is not found.  Both of your if statements will treat that as a win, not a fail.  You should use if ...rfind(...) >= 0:.

Is pandas really helping you here?  Wouldn't this be easier as a simple list of rows?

Body:
I am doing simply queries on a csv document about a genome. I have the following code:

locus_example = 'Rv0001'

for locus in tuberculosis_data1["Locus"].values:
    if locus_example.rfind(locus):
        result = tuberculosis_data1.loc[tuberculosis_data1['Locus'] == locus]['Sequences'].values
        for r in result:
            print(r)
        break

That gives me the following sequence:

ATGGACGCGGCTACGACAAGAGTTGGCCTCACCGACTTGACGTTTCGTTTGCTACGAGAGTCTTTCGCCGATGCGGTGTCGTGGGTGGCTAAAAATCTGCCAGCCAGGCCCGCGGTGCCGGTGCTCTCCGGCGTGTTGTTGACCGGCTCGGACAACGGTCTGACGATTTCCGGATTCGACTACGAGGTTTCCGCCGAGGCCCAGGTTGGCGCTGAAATTGTTTCTCCTGGAAGCGTTTTAGTTTCTGGCCGATTGTTGTCCGATATTACCCGGGCGTTGCCTAACAAGCCCGTAGACGTTCATGTCGAAGGTAACCGGGTCGCATTGACCTGCGGTAACGCCAGGTTTTCGCTACCGACGATGCCAGTCGAGGATTATCCGACGCTGCCGACGCTGCCGGAAGAGACCGGATTGTTGCCTGCGGAATTATTCGCCGAGGCAATCAGTCAGGTCGCTATCGCCGCCGGCCGGGACGACACGTTGCCTATGTTGACCGGCATCCGGGTCGAAATCCTCGGTGAGACGGTGGTTTTGGCCGCTACCGACAGGTTTCGCCTGGCTGTTCGAGAACTGAAGTGGTCGGCGTCGTCGCCAGATATCGAAGCGGCTGTGCTGGTCCCGGCCAAGACGCTGGCCGAGGCCGCCAAAGCGGGCATCGGCGGCTCTGACGTTCGTTTGTCGTTGGGTACTGGGCCGGGGGTGGGCAAGGATGGCCTGCTCGGTATCAGTGGGAACGGCAAGCGCAGCACCACGCGACTTCTTGATGCCGAGTTCCCGAAGTTTCGGCAGTTGCTACCAACCGAACACACCGCGGTGGCCACCATGGACGTGGCCGAGTTGATCGAAGCGATCAAGCTGGTTGCGTTGGTAGCTGATCGGGGCGCGCAGGTGCGCATGGAGTTCGCTGATGGCAGCGTGCGGCTTTCTGCGGGTGCCGATGATGTTGGACGAGCCGAGGAAGATCTTGTTGTTGACTATGCCGGTGAACCATTGACGATTGCGTTTAACCCAACCTATCTAACGGACGGTTTGAGTTCGTTGCGCTCGGAGCGAGTGTCTTTCGGGTTTACGACTGCGGGTAAGCCTGCCTTGCTACGTCCGGTGTCCGGGGACGATCGCCCTGTGGCGGGTCTGAATGGCAACGGTCCGTTCCCGGCGGTGTCGACGGACTATGTCTATCTGTTGATGCCGGTTCGGTTGCCGGGCTGA

I also have the following code that is supposed to give me the same exact sequence:

gen_example = 'dnaA'

for gen in tuberculosis_data1["Gen name"].values:
    if gen_example.rfind(gen):
        result = tuberculosis_data1.loc[tuberculosis_data1['Gen name'] == gen]['Sequences'].values
        for r in result:
            print(r)
        break

However the result is:

TTGACCGATGACCCCGGTTCAGGCTTCACCACAGTGTGGAACGCGGTCGTCTCCGAACTTAACGGCGACCCTAAGGTTGACGACGGACCCAGCAGTGATGCTAATCTCAGCGCTCCGCTGACCCCTCAGCAAAGGGCTTGGCTCAATCTCGTCCAGCCATTGACCATCGTCGAGGGGTTTGCTCTGTTATCCGTGCCGAGCAGCTTTGTCCAAAACGAAATCGAGCGCCATCTGCGGGCCCCGATTACCGACGCTCTCAGCCGCCGACTCGGACATCAGATCCAACTCGGGGTCCGCATCGCTCCGCCGGCGACCGACGAAGCCGACGACACTACCGTGCCGCCTTCCGAAAATCCTGCTACCACATCGCCAGACACCACAACCGACAACGACGAGATTGATGACAGCGCTGCGGCACGGGGCGATAACCAGCACAGTTGGCCAAGTTACTTCACCGAGCGCCCGCACAATACCGATTCCGCTACCGCTGGCGTAACCAGCCTTAACCGTCGCTACACCTTTGATACGTTCGTTATCGGCGCCTCCAACCGGTTCGCGCACGCCGCCGCCTTGGCGATCGCAGAAGCACCCGCCCGCGCTTACAACCCCCTGTTCATCTGGGGCGAGTCCGGTCTCGGCAAGACACACCTGCTACACGCGGCAGGCAACTATGCCCAACGGTTGTTCCCGGGAATGCGGGTCAAATATGTCTCCACCGAGGAATTCACCAACGACTTCATTAACTCGCTCCGCGATGACCGCAAGGTCGCATTCAAACGCAGCTACCGCGACGTAGACGTGCTGTTGGTCGACGACATCCAATTCATTGAAGGCAAAGAGGGTATTCAAGAGGAGTTCTTCCACACCTTCAACACCTTGCACAATGCCAACAAGCAAATCGTCATCTCATCTGACCGCCCACCCAAGCAGCTCGCCACCCTCGAGGACCGGCTGAGAACCCGCTTTGAGTGGGGGCTGATCACTGACGTACAACCACCCGAGCTGGAGACCCGCATCGCCATCTTGCGCAAGAAAGCACAGATGGAACGGCTCGCGGTCCCCGACGATGTCCTCGAACTCATCGCCAGCAGTATCGAACGCAATATCCGTGAACTCGAGGGCGCGCTGATCCGGGTCACCGCGTTCGCCTCATTGAACAAAACACCAATCGACAAAGCGCTGGCCGAGATTGTGCTTCGCGATCTGATCGCCGACGCCAACACCATGCAAATCAGCGCGGCGACGATCATGGCTGCCACCGCCGAATACTTCGACACTACCGTCGAAGAGCTTCGCGGGCCCGGCAAGACCCGAGCACTGGCCCAGTCACGACAGATTGCGATGTACCTGTGTCGTGAGCTCACCGATCTTTCGTTGCCCAAAATCGGCCAAGCGTTCGGCCGTGATCACACAACCGTCATGTACGCCCAACGCAAGATCCTGTCCGAGATGGCCGAGCGCCGTGAGGTCTTTGATCACGTCAAAGAACTCACCACTCGCATCCGTCAGCGCTCCAAGCGCTAG

The correct sequence for this gen called dnaA for locus Rv0001 is the second one. I understand that there are no more genes called dnaA, not even partially. The sequence for the first result is actually the sequence in the following row of the csv file (Rv002/dnaN)

When I remove one 0 and search Rv001 instead, it gives the correct sequence.

I can't understand why the first search is giving me the sequence for the second row while the second search is giving the correct sequence. Any idea as to why python/pandas are behaving this way?


问:
Is there a way to include Multiple Children inside a Container?
This is full code:

class Application extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
       body: new Container(
         color: Color(0xff258DED),
         height: 400.0,
         alignment: Alignment.center,
         child: new Container(
           height: 200.0,
           width: 200.0,
           decoration: new BoxDecoration(
             image: DecorationImage(
                 image: new AssetImage('assets/logo.png'),
             fit: BoxFit.fill
             ),
             shape: BoxShape.circle
           ),
         ),
         child: new Container(
          child: new Text('Welcome to Prime Message',
            textAlign: TextAlign.center,
            style: TextStyle(
                fontFamily: 'Aleo',
                fontStyle: FontStyle.normal,
                fontWeight: FontWeight.bold,
                fontSize: 25.0,
                color: Colors.white
            ),
          ),
         ),
        ),
      ),
    );
  }
}
```

I tried to add a Container on top and then added two children inside it. First child works fine, but second child giving me error like "the argument for the named parameter 'child' was already specified".

答: Container is a Single-child layout widget. But it can have multiple children by using a Multi-child layout widget as its child.

Body:
This is full code:

class Application extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
       body: new Container(
         color: Color(0xff258DED),
         height: 400.0,
         alignment: Alignment.center,
         child: new Container(
           height: 200.0,
           width: 200.0,
           decoration: new BoxDecoration(
             image: DecorationImage(
                 image: new AssetImage('assets/logo.png'),
             fit: BoxFit.fill
             ),
             shape: BoxShape.circle
           ),
         ),
         child: new Container(
          child: new Text('Welcome to Prime Message',
            textAlign: TextAlign.center,
            style: TextStyle(
                fontFamily: 'Aleo',
                fontStyle: FontStyle.normal,
                fontWeight: FontWeight.bold,
                fontSize: 25.0,
                color: Colors.white
            ),
          ),
         ),
        ),
      ),
    );
  }
}

I tried to add a Container on top and then added two children inside it. First child works fine, but second child giving me error like "the argument for the named parameter 'child' was already specified".


问:
TypeError;Article.find() is not a function in Sails.js
I am using sails.js and getting error Articles.find() is not a function. Following is datastore.js

```<code>    mongodb:{  adapter:require('sails-mongo'),
   url:'mongodb://localhost:27017/articlebase'
 }
</code>```

following is a ArticleController.js

```<code>const Articles = require("../models/Articles");
module.exports = {
  list: (req,res)=>
  {

    Articles.find().exec((err,articles)=>{
    if(err)
    {
      res.send(500,{err:err});
    }
      res.view('articles/articles',{articles:articles});
    });

  }
</code>```

following is models Article.js

```<code>module.exports = {

  attributes: {
title:{
  type:'string'
},
body:{
  type:'string'
},

  },
datastore:'mongodb',
};
</code>```

答:
ArticleController.js should be modified to be with 'async' and 'await'</p>
```<code>const Articles = require("../models/Articles");
module.exports = {
  list: async(req,res)=>
  {

    await Articles.find().exec((err,articles)=>{
    if(err)
    {
      res.send(500,{err:err});
    }
      res.view('articles/articles',{articles:articles});
    });

  }
</code>```

Body:
I am using sails.js and getting error Articles.find() is not a function. Following is datastore.js

    mongodb:{  adapter:require('sails-mongo'),
   url:'mongodb://localhost:27017/articlebase'
 }

following is a ArticleController.js

const Articles = require("../models/Articles");
module.exports = {
  list: (req,res)=>
  {

    Articles.find().exec((err,articles)=>{
    if(err)
    {
      res.send(500,{err:err});
    }
      res.view('articles/articles',{articles:articles});
    });

  }

following is models Article.js

module.exports = {

  attributes: {
title:{
  type:'string'
},
body:{
  type:'string'
},

  },
datastore:'mongodb',
};

Body:
ArticleController.js should be modified to be with 'async' and 'await'

const Articles = require("../models/Articles");
module.exports = {
  list: async(req,res)=>
  {

    await Articles.find().exec((err,articles)=>{
    if(err)
    {
      res.send(500,{err:err});
    }
      res.view('articles/articles',{articles:articles});
    });

  }


问:
Start systemd user service from Rails
I need to start a systemd service from Ruby on Rails. My ruby code is using backticks to call systemctl:

```<code>`systemctl --user start myservice`
</code>```

It's not working and I think it's to do with the user that command is executed by. Rails is running on Passenger and the user for that should be the same as my service.

I've also tried alternative ways to launch a subprocess

答:
(This should be a comment rather than an answer, but I'm still building 'reputation' points, so...)

If Passenger has the same UID that myservice needs to run, then that's not where the problem lies. Nor are the other ways of launching a child likely to change the outcome.

I suggest capturing the output of the subprocess as follows:
systemctl --user start myservice > /tmp/systemctl.output 2>&1 and then inspecting the output file after the subprocess fails.

Title: Start systemd user service from Rails

Body:
I need to start a systemd service from Ruby on Rails. My ruby code is using backticks to call systemctl:

`systemctl --user start myservice`

It's not working and I think it's to do with the user that command is executed by. Rails is running on Passenger and the user for that should be the same as my service.

I've also tried alternative ways to launch a subprocess


问:
How to set the height of CKEditor 5 (Classic Editor)
In CKEditor 4 to change the editor height there was a configuration option: config.height.

How do I change the height of CKEditor 5? (the Classic Editor)

答:
If its in latest version of Angular say 12 or 12+. We can add below style to your components style file.

  :host ::ng-deep .ck-editor__editable_inline { min-height: 300px; }


问:
Enable logical replication on Google Cloud Postgres
Is there anyway to enable logical replication wal_level = logical on Google Cloud Postgres instance? I want to do CDC (change data capture) to stream WAL Record to Apache Kafka. Thanks for your help!

答:
Update:

This feature now is enabled on Google Cloud SQL. To enable wal_level to replication you just need to set the flag cloudsql.logical_decoding as on.

For more details:

https://cloud.google.com/sql/docs/postgres/replication/configure-logical-replication

Note: this issue was solved in August, 30th release.


问:
How to add to a classname in reactjs?
hi how can I add to classname to this code:

```<code>  {
    title: <span className='Time'>Time</span>,
    key: 'time',
    render: ({ created_at }: any) => {
      return utilService.dayjs(created_at).format(`YYYY/MM/DD hh:mm:ss A`)
    },
  },
</code>```

I need to float left for date `YYYY/MM/DD hh:mm:ss A' cuz of that I want to add classname to output.

Must be in reactjs

答:
Wrap the return in div or span:</p>
```<code>{
  title: <span className='Time'>Time</span>,
  key: 'time',
  render: ({ created_at }: any) => {
    return (
      <div className="your-className">
        {utilService.dayjs(created_at).format(`YYYY/MM/DD hh:mm:ss A`)}
      </div>
    );
  },
},
</code>```

Title: How to add to a classname in reactjs?

Body:
hi how can I add to classname to this code:

  {
    title: Time,
    key: 'time',
    render: ({ created_at }: any) => {
      return utilService.dayjs(created_at).format(`YYYY/MM/DD hh:mm:ss A`)
    },
  },

I need to float left for date `YYYY/MM/DD hh:mm:ss A' cuz of that I want to add classname to output.

Must be in reactjs

Body:
Wrap the return in div or span:

{
  title: <span className='Time'>Time</span>,
  key: 'time',
  render: ({ created_at }: any) => {
    return (
      <div className="your-className">
        {utilService.dayjs(created_at).format(`YYYY/MM/DD hh:mm:ss A`)}
      </div>
    );
  },
},


问:
How can I save a graphics object to a bitmap in a "paint" winforms application?
My problem is:
When I try to save the graphics object to a bitmap image it does not save correctly, instead the image is black in color and there is nothing else in the file.

I've seen other answers, but I think it's different when you draw multiple times in the graphics object.

So, here's my attempt, please let me know where my issue is.

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace PenFlip
{
    public partial class Match : Form
    {
        Graphics g;
        private int x = -1;
        private int y = -1;
        private bool moving;
        private Pen pen;
        private Bitmap testBmp;
        public Match()
        {
            InitializeComponent();
            g = panel1.CreateGraphics();
            g.SmoothingMode = SmoothingMode.AntiAlias;
            pen = new Pen(Color.Black, 5);
            pen.StartCap = pen.EndCap = LineCap.Round;
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            PictureBox pictureBox = (PictureBox) sender;
            pen.Color = pictureBox.BackColor;
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            moving = true;
            x = e.X;
            y = e.Y;
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (moving && x != -1 && y != -1)
            {
                g.DrawLine(pen, new Point(x, y), e.Location);
                x = e.X;
                y = e.Y;
            }
        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            moving = false;
            x = -1;
            y = -1;
            g.Save();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // prints out the black image
            testBmp = new Bitmap(400, 200, g);
            testBmp.Save(@"test.bmp", ImageFormat.Bmp);
        }
    }
}
```

答:
Uh, usage of Bitmap is tricky and has a lot of pitfalls (that's why it's use is deprecated, btw). Try to create the Graphics object from an in-memory bitmap, instead of grabbing it from a control. The bitmap should be the primary object, not the Graphics instance. You don't know what the control does to your bitmap.

So in the constructor, do something like:

```<code>        public Match()
        {
            InitializeComponent();
            bitmap = new Bitmap(panel1.Width, panel1.Height, PixelFormat.Format32bppArgb);
            pen = new Pen(Color.Black, 5);
            pen.StartCap = pen.EndCap = LineCap.Round;
        }

</code>```

and in each function, create a graphics object from the bitmap:

```<code>using (var graphics = Graphics.FromImage(image))
                    {
                        graphics.Draw(...);
                    }
</code>```

You need to update the panel manually now, e.g. by attaching to it's OnPaint event.

Body:
Uh, usage of Bitmap is tricky and has a lot of pitfalls (that's why it's use is deprecated, btw). Try to create the Graphics object from an in-memory bitmap, instead of grabbing it from a control. The bitmap should be the primary object, not the Graphics instance. You don't know what the control does to your bitmap.

So in the constructor, do something like:

        public Match()
        {
            InitializeComponent();
            bitmap = new Bitmap(panel1.Width, panel1.Height, PixelFormat.Format32bppArgb);
            pen = new Pen(Color.Black, 5);
            pen.StartCap = pen.EndCap = LineCap.Round;
        }

and in each function, create a graphics object from the bitmap:

using (var graphics = Graphics.FromImage(image))
                    {
                        graphics.Draw(...);
                    }

You need to update the panel manually now, e.g. by attaching to it's OnPaint event.


问:
Laravel ::pluck multiple columns
I need to populate a blade format <select> tag.

I'm aware of the Model::pluck('column1', 'column2') method to populate a select tag.

But in my case, I have to concatenate two columns , and get the id. something like

Model::pluck('column_1 && column_2', 'id')

Is it possible like that ? If yes, what would be the proper syntax?

If not, what would be the best alternative then ?

答:
It's pretty late but you could do something like this:

$data = Model::select('id','column_1','column_2')->get()

and then use it inside blade like:

$data->first_name." ".$data->last_name

Title: Laravel ::pluck multiple columns


问:
AWS Change DNS without affecting Workmail
I have a Wix website and in order to connect my AWS domain to it so

I changed the Nameservers (in registered domains to Wix)

Updated the NS records (in hosted zones to Wix)
*I noticed (when in hosted zones) that when I click "Hosted Zone Details" it has AWS Name servers.

I have WorkMail set up but now it won't find the correct settings (after it was previously working well) and it has the message: "Your Route 53 hosted zone  for this domain needs to be set as authoritative. To learn how to set a hosted zone as authoritative, see Migrating DNS  in the AWS Route 53 Developer Guide."

So, I'm not sure what to do in order to make my domain work with Wix and have my Workmail working correctly. It seems like one or the other unless I'm missing something, any help is appreciated!

答:
Your right, you need to pick one. I dont believe there is a requirement for either of them where your namesevers are hosted - its just they point you towards their own services as its generally easier to setup ;-)

Your old zone in Route 53 will have MX, TXT and CNAME records specifically for workmail. When you switched nameservers you lost those records. Take a look at this page for more info: https://aws.amazon.com/premiumsupport/knowledge-center/add-verify-domain-workmail/

Option 1
Leave your nameservers pointing to WIX and re-setup WorkMail

Option 2
Revert your name servers to Route53 and setup WIX to use route53 (im not familar with Wix but this looks about right - https://support.wix.com/en/article/connecting-a-domain-to-wix-using-the-pointing-method - basically you create an A record for example.com and a CNAME for www.example.com in Route53 with values from Wix.


问:
How do I place an Angular material button at a particular position?
I want to place the following button at the bottom-center of the mat-grid-tile, how can I do it?

.html file:

```<code><mat-grid-list cols="1" rowHeight="400">
  <mat-grid-tile class="example-grid" >
    <div class="button">
      <button mat-button (click)="getQuestions()" routerLink="questions/getAllQuestions" routerLinkActive="active"><strong>Show!</strong> </button>
    </div>
</mat-grid-tile>
  <mat-grid-tile>...</mat-grid-tile>
</mat-grid-list>
</code>```

.css file:

```<code>.button{
  display: table-cell;
  width: 700px;
  color: rgb(0, 0, 0);

}
</code>```

答:
I like to use flexbox utilities for these kinds of things. In your case, you need to first make sure you button div fills the full height/width of the grid tile. Then you can use flexbox to position the content inside the div.

```<code>.button {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
</code>```

Here's a stackblitz demonstrating

Body:
I want to place the following button at the bottom-center of the mat-grid-tile, how can I do it?

.html file:

<mat-grid-list cols="1" rowHeight="400">
  <mat-grid-tile class="example-grid" >

      <button mat-button (click)="getQuestions()" routerLink="questions/getAllQuestions" routerLinkActive="active">Show! </button>

</mat-grid-tile>
  <mat-grid-tile>...</mat-grid-tile>
</mat-grid-list>

.css file:

.button{
  display: table-cell;
  width: 700px;
  color: rgb(0, 0, 0);

}

Body:
I like to use flexbox utilities for these kinds of things. In your case, you need to first make sure you button div fills the full height/width of the grid tile. Then you can use flexbox to position the content inside the div.

.button {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

Here's a stackblitz demonstrating


问:
STM32 I2C HAL FXOS8700 communication problem
I have a STM32F103RE MCU that is connected to a fxos8700cq sensor through I2C2 port.
I've set up the peripherals using stm32cubemx and I'm trying to simply test the communication with the sensor. But as I debug the code, it seems that data transfer is not happening correctly.

These are the i2c settings:

```<code> hi2c2.Instance = I2C2;
  hi2c2.Init.ClockSpeed = 100000;
  hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c2.Init.OwnAddress1 = 0;
  hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c2.Init.OwnAddress2 = 0;
  hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
</code>```

and here is the main code:

```<code> uint8_t send_buffer[1];
    uint8_t receive_buffer[1];
    uint8_t FXOS_ADDR = (FXOS8700_DEVICE_ADDR_SA_11 << 1);

    send_buffer[0] = FXOS8700_WHO_AM_I;
    receive_buffer[0] = 0;
    // chip select for fxos
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2, GPIO_PIN_SET);
    HAL_Delay(500);
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2, GPIO_PIN_RESET);
    HAL_Delay(500);

    ret = HAL_I2C_Master_Transmit(&hi2c2, FXOS_ADDR, send_buffer, 1, 100);
    //ret = HAL_I2C_Master_Transmit_IT(&hi2c2, FXOS_ADDR, send_buffer, 1);
    HAL_Delay(2);
    ret = HAL_I2C_Master_Receive(&hi2c2, FXOS_ADDR, receive_buffer, 1, 100);
    //ret = HAL_I2C_Master_Receive_IT(&hi2c2, FXOS_ADDR, receive_buffer, 1);

    if (receive_buffer[0] == FXOS8700_WHO_AM_I_PROD_VALUE)
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
     else
         HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
</code>```

but after I debug the code, and watch the i2c registers after executing the HAL_I2C_Master_Transmit(&hi2c2, FXOS_ADDR, send_buffer, 1, 100); function I get these values. That means the TXE bit in SR1 register is not set.

I also tried using the interrupt mode but that's not working either. the values of i2c registers after the ret = HAL_I2C_Master_Transmit_IT(&hi2c2, FXOS_ADDR, send_buffer, 1); line are like this.

In all cases the functions return HAL_OK and there is no error.

I've tested the sensor and the board communication using mbed and it works fine. So the hardware has no problem.

答:
You should not need to toggle a chip select when using the device's I2C interface.
The device's chip select signal is only for the SPI interface.
You should have the SA0 and SA1 pins pulled high or low to use the I2C interface and select the device's I2C address.  See table 11 and section 10.2.3 in the datasheet.

HAL_I2C_Master_Transmit() and HAL_I2C_Master_Receive() are not the best functions for reading a register value from the device.  These functions transmit a start condition, the device address, the data, and finally a stop condition.  But this is not what the FXOS8700CQ datasheet recommends in section 10.1.2, "Single-byte read".  It says transmit start condition, device address with W bit, register address, repeat-start condition (notice no stop before repeat start), device address with R bit, then the data, and finally a stop condition.

The HAL_I2C_Mem_Read() function can be used to perform the single-byte read as described in the datasheet.  (i.e., write register address, repeat-start, read data.)  Try something like this.

```<code>uint8_t data_byte = 0;
HAL_StatusTypeDef hal_status = HAL_I2C_Mem_Read(&hi2c2, FXOS_ADDR, FXOS8700_WHO_AM_I, I2C_MEMADD_SIZE_8BIT, &data_byte, 1, 100);
</code>```

If that doesn't help, then check the return value from the HAL library calls.

If that doesn't help, then examine the I2C clock and data signals with a logic analyzer or oscilloscope.

Body:
I have a STM32F103RE MCU that is connected to a fxos8700cq sensor through I2C2 port.
I've set up the peripherals using stm32cubemx and I'm trying to simply test the communication with the sensor. But as I debug the code, it seems that data transfer is not happening correctly.

These are the i2c settings:

 hi2c2.Instance = I2C2;
  hi2c2.Init.ClockSpeed = 100000;
  hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c2.Init.OwnAddress1 = 0;
  hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c2.Init.OwnAddress2 = 0;
  hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;

and here is the main code:

 uint8_t send_buffer[1];
    uint8_t receive_buffer[1];
    uint8_t FXOS_ADDR = (FXOS8700_DEVICE_ADDR_SA_11 << 1);

    send_buffer[0] = FXOS8700_WHO_AM_I;
    receive_buffer[0] = 0;
    // chip select for fxos
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2, GPIO_PIN_SET);
    HAL_Delay(500);
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2, GPIO_PIN_RESET);
    HAL_Delay(500);

    ret = HAL_I2C_Master_Transmit(&hi2c2, FXOS_ADDR, send_buffer, 1, 100);
    //ret = HAL_I2C_Master_Transmit_IT(&hi2c2, FXOS_ADDR, send_buffer, 1);
    HAL_Delay(2);
    ret = HAL_I2C_Master_Receive(&hi2c2, FXOS_ADDR, receive_buffer, 1, 100);
    //ret = HAL_I2C_Master_Receive_IT(&hi2c2, FXOS_ADDR, receive_buffer, 1);

    if (receive_buffer[0] == FXOS8700_WHO_AM_I_PROD_VALUE)
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
     else
         HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);

but after I debug the code, and watch the i2c registers after executing the HAL_I2C_Master_Transmit(&hi2c2, FXOS_ADDR, send_buffer, 1, 100); function I get these values. That means the TXE bit in SR1 register is not set.

I also tried using the interrupt mode but that's not working either. the values of i2c registers after the ret = HAL_I2C_Master_Transmit_IT(&hi2c2, FXOS_ADDR, send_buffer, 1); line are like this.

In all cases the functions return HAL_OK and there is no error.

I've tested the sensor and the board communication using mbed and it works fine. So the hardware has no problem.

Body:
You should not need to toggle a chip select when using the device's I2C interface.
The device's chip select signal is only for the SPI interface.
You should have the SA0 and SA1 pins pulled high or low to use the I2C interface and select the device's I2C address.  See table 11 and section 10.2.3 in the datasheet.

HAL_I2C_Master_Transmit() and HAL_I2C_Master_Receive() are not the best functions for reading a register value from the device.  These functions transmit a start condition, the device address, the data, and finally a stop condition.  But this is not what the FXOS8700CQ datasheet recommends in section 10.1.2, "Single-byte read".  It says transmit start condition, device address with W bit, register address, repeat-start condition (notice no stop before repeat start), device address with R bit, then the data, and finally a stop condition.

The HAL_I2C_Mem_Read() function can be used to perform the single-byte read as described in the datasheet.  (i.e., write register address, repeat-start, read data.)  Try something like this.

uint8_t data_byte = 0;
HAL_StatusTypeDef hal_status = HAL_I2C_Mem_Read(&hi2c2, FXOS_ADDR, FXOS8700_WHO_AM_I, I2C_MEMADD_SIZE_8BIT, &data_byte, 1, 100);

If that doesn't help, then check the return value from the HAL library calls.

If that doesn't help, then examine the I2C clock and data signals with a logic analyzer or oscilloscope.


问:
jQuery dragging (reordering) table rows between multiple tbodies
I'm great with CSS but I largely suck at jQuery. We all have our limitations...

OK with that admission out of the way I'll begin. We have a "favourite products" table, which you can sectionalize into categories (eg, Booze, Sheep, Spoons). Each category is a . Each row (excluding the ) is a product.

I want to enable a user to drag and drop (reorder) the table rows, even between tbodies. I've looked at Table Drag and Drop (DnD) plugin for jQuery but was disappointed to find that it doesn't really support dragging between tbodies - and hasn't been updated for quite some time.

Here is the basic table structure:

```<code><table>
  <thead>
    <tr>
      <th>Favourite</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Spoons</th> <!-- secion title, not draggable -->
    </tr>
    <tr>
      <td>Wooden Spoon</td>
    </tr>
    <tr>
      <td>Metal Spoon</td>
    </tr>
    <tr>
      <td>Plastic Spoon</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <th>Nuclear Bombs</th> <!-- seciont title, not draggable -->
    </tr>
    <tr>
      <td>US Nukes</td>
    </tr>
    <tr>
      <td>Soviet Nukes</td>
   </tr>
 </tbody>
</table>
</code>```

I'm going to need to turn of the "dragability" of certain rows such as the first row in the  - this being the section title.

Is there a better version of a jquery plugin out there that can do what I need? If you can find a better plugin please share and win my "favourite person of the week" award.

Thank you.

答:
you can turn off the dragability in case od table dnd plugin by specifying

```<code><tr class ="nodrag nodrop">
  <th>Favourite</th>
</tr>
</code>```

class nodrag nodrop will not allow drag and drop

and

class nodrag will not allow it to be dragged i hope it helped.

Body:
I'm great with CSS but I largely suck at jQuery. We all have our limitations...

OK with that admission out of the way I'll begin. We have a "favourite products" table, which you can sectionalize into categories (eg, Booze, Sheep, Spoons). Each category is a . Each row (excluding the ) is a product.

I want to enable a user to drag and drop (reorder) the table rows, even between tbodies. I've looked at Table Drag and Drop (DnD) plugin for jQuery but was disappointed to find that it doesn't really support dragging between tbodies - and hasn't been updated for quite some time.

Here is the basic table structure:

      Favourite

      Spoons

      Wooden Spoon

      Metal Spoon

      Plastic Spoon

      Nuclear Bombs

      US Nukes

      Soviet Nukes

I'm going to need to turn of the "dragability" of certain rows such as the first row in the  - this being the section title.

Is there a better version of a jquery plugin out there that can do what I need? If you can find a better plugin please share and win my "favourite person of the week" award.

Thank you.

Body:
you can turn off the dragability in case od table dnd plugin by specifying

<tr class ="nodrag nodrop">
  <th>Favourite</th>
</tr>

class nodrag nodrop will not allow drag and drop

and

class nodrag will not allow it to be dragged i hope it helped.


问:
Retrofit2+SimpleXML Kotlin how to parse XML
How to create data class for this info:

```<code><ValCurs Date="09.02.2022" name="Foreign Currency Market">
 <Valute ID="R01010">
  <NumCode>036</NumCode>
  <CharCode>AUD</CharCode>
  <Nominal>1</Nominal>
  <Name>Australian dollar</Name>
  <Value>53,6768</Value>
 </Valute>
 <Valute ID="R01020A">
  <NumCode>944</NumCode>
  <CharCode>RUB</CharCode>
  <Nominal>1</Nominal>
  <Name>Russian ruble</Name>
  <Value>44,3227</Value>
 </Valute>
...More info like that...
</ValCurs>
</code>```

And how to get this info from response?

答:
Sample code:

xml:

```<code><my-object>
    <message>hello world</message>
    <count>10</count>
</my-object>
</code>```
```<code>
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;

@Default(value = DefaultType.FIELD)
final class MyObject {
  @Element private String message;
  @Element private int count;

  public MyObject() {}

  public MyObject(String message, int count) {
    this.message = message;
    this.count = count;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  public void setCount(int count) {
    this.count = count;
  }

  public int getCount() {
    return count;
  }
}
</code>```
```<code>    Format format = new Format(0, null, new HyphenStyle(), Verbosity.HIGH);
    Persister persister = new Persister(format);
    Retrofit retrofit =
        new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addConverterFactory(SimpleXmlConverterFactory.create(persister))
            .build();
    service = retrofit.create(Service.class);

</code>```
```<code>  interface Service {
    @GET("/")
    Call<MyObject> get();

    @POST("/")
    Call<MyObject> post(@Body MyObject impl);

    @GET("/")
    Call<String> wrongClass();
  }

</code>```

Link: https://github.com/square/retrofit/blob/master/retrofit-converters/simplexml/src/test/java/retrofit2/converter/simplexml/SimpleXmlConverterFactoryTest.java

Body:
How to create data class for this info:

<ValCurs Date="09.02.2022" name="Foreign Currency Market">
 <Valute ID="R01010">
  <NumCode>036</NumCode>
  <CharCode>AUD</CharCode>
  <Nominal>1</Nominal>
  <Name>Australian dollar</Name>
  <Value>53,6768</Value>
 </Valute>
 <Valute ID="R01020A">
  <NumCode>944</NumCode>
  <CharCode>RUB</CharCode>
  <Nominal>1</Nominal>
  <Name>Russian ruble</Name>
  <Value>44,3227</Value>
 </Valute>
...More info like that...
</ValCurs>

And how to get this info from response?

Body:
Sample code:

xml:

<my-object>
    <message>hello world</message>
    <count>10</count>
</my-object>

import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;

@Default(value = DefaultType.FIELD)
final class MyObject {
  @Element private String message;
  @Element private int count;

  public MyObject() {}

  public MyObject(String message, int count) {
    this.message = message;
    this.count = count;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  public void setCount(int count) {
    this.count = count;
  }

  public int getCount() {
    return count;
  }
}

    Format format = new Format(0, null, new HyphenStyle(), Verbosity.HIGH);
    Persister persister = new Persister(format);
    Retrofit retrofit =
        new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addConverterFactory(SimpleXmlConverterFactory.create(persister))
            .build();
    service = retrofit.create(Service.class);

  interface Service {
    @GET("/")
    Call<MyObject> get();

    @POST("/")
    Call<MyObject> post(@Body MyObject impl);

    @GET("/")
    Call<String> wrongClass();
  }

Link: https://github.com/square/retrofit/blob/master/retrofit-converters/simplexml/src/test/java/retrofit2/converter/simplexml/SimpleXmlConverterFactoryTest.java


问:
Applying regex in Spring Cloud Gateway Path predicate
I'm using 3.1.0 version for Spring Cloud Gateway and I need help in checking and fixing the Path predicate filter for my route configuration.

I'm trying to use regex in between a path, the route looks something like this in my config:

```<code>        - id: Route1
          uri: https://example.com
          predicates:
            - Path=/random/path/\d+/update
            - Method=POST
</code>```

Though this is a valid regex, I'm getting 404 error code for requests for path :

/random/path/12/update

Hence I need help to figure out the correct configs for this usecase

答:
It requires a named path segment. See the syntax here. You can then use {mynum} in filters like SetPath

```<code>    - id: Route1
      uri: https://example.com
      predicates:
        - Path=/random/path/{mynum:\d+}/update
        - Method=POST
</code>```

Body:
I'm using 3.1.0 version for Spring Cloud Gateway and I need help in checking and fixing the Path predicate filter for my route configuration.

I'm trying to use regex in between a path, the route looks something like this in my config:

        - id: Route1
          uri: https://example.com
          predicates:
            - Path=/random/path/\d+/update
            - Method=POST

Though this is a valid regex, I'm getting 404 error code for requests for path :

/random/path/12/update

Hence I need help to figure out the correct configs for this usecase

Body:
It requires a named path segment. See the syntax here. You can then use {mynum} in filters like SetPath

    - id: Route1
      uri: https://example.com
      predicates:
        - Path=/random/path/{mynum:\d+}/update
        - Method=POST


问:
PHP: Does echo wait until a function ends before echoing?
I'm learning PHP and am going through some source code I found.
In it there's an ajax request as follows:

```<code>$.post("includes/handlers/ajax_search.php", {query:value, userLoggedIn: user}, function(data) {
    //uses 'data' variable
});
</code>```

What I'm unsure about is, the below code is in the called function and would appear to call echo multiple times. Does the called ajax function wait for all echoes to concatenate before actually echoing or does it act like a sort of a stream?

Some clarification would be really appreciated? Thanks.

```<code>while($row = mysqli_fetch_array($usersReturnedQuery)) {
        $user = new User($con, $userLoggedIn);

        if($row['username'] != $userLoggedIn)
            $mutual_friends = $user->getMutualFriends($row['username']) . " friends in common";
        else
            $mutual_friends == "";

        echo "<div class='resultDisplay'>
                <a href='" . $row['username'] . "' style='color: #1485BD'>
                    <div class='liveSearchProfilePic'>
                        <img src='" . $row['profile_pic'] ."'>
                    </div>

                    <div class='liveSearchText'>
                        " . $row['first_name'] . " " . $row['last_name'] . "
                        <p>" . $row['username'] ."</p>
                        <p id='grey'>" . $mutual_friends ."</p>
                    </div>
                </a>
            </div>";

    }
</code>```

答:
Echo outputs lines instantly. However, PHP has a system write buffer. There is flush() function to instantly output buffer to the output.

However, be mindful, that flush() only flushes PHP buffer, there might be another buffers between PHP and browser: web server's buffer, for example.

Body:
I'm learning PHP and am going through some source code I found.
In it there's an ajax request as follows:

$.post("includes/handlers/ajax_search.php", {query:value, userLoggedIn: user}, function(data) {
    //uses 'data' variable
});

What I'm unsure about is, the below code is in the called function and would appear to call echo multiple times. Does the called ajax function wait for all echoes to concatenate before actually echoing or does it act like a sort of a stream?

Some clarification would be really appreciated? Thanks.

while($row = mysqli_fetch_array($usersReturnedQuery)) {
        $user = new User($con, $userLoggedIn);

        if($row['username'] != $userLoggedIn)
            $mutual_friends = $user->getMutualFriends($row['username']) . " friends in common";
        else
            $mutual_friends == "";

        echo "

                        " . $row['first_name'] . " " . $row['last_name'] . "

" . $row['username'] ."

" . $mutual_friends ."

";

    }


问:
Cannot connect to MySQL database from OVH server
I cannot connect to my database which is hosted on OVH remotely from Flutter's package mysql1 and get the following error:

flutter: SocketException: Failed host lookup: 'saintlouqpweb.mysql.db'
(OS Error: nodename nor servname provided, or not known, errno = 8)

I usually access it through phpMyAdmin where I have three fields to fill: the server, the user, and the password. I use exactly the same values than there with mysql1 on Flutter in addition to the database name (the server field of phpMyAdmin being the host field of mysql1).

I have searched for hours a solution but I still find nothing on this forum and on the web. Everything is always brought back to a 'localhost' server or a problem too different from mine.

Here is the piece of code causing the error :

```<code>Future<List<dynamic>> getData() async
  {
    try {
      final conn = await MySqlConnection.connect(ConnectionSettings(
        host: 'saintlouqpweb.mysql.db', // the exact server name entered on phpMyAdmin
        user: 'myusername',
        password: '*********',
        db: 'mydatabasename',
      ));

    var results = await conn.query(
      'SELECT * FROM `mytable` WHERE ID=1;'
    );

    return results.toList();
    } catch (e) {
      print('$e');
    }
  }
</code>```

I would be grateful if someone can help me about that or experienced the same issue previously.

答:
As suggested by Mark Rotteveel in comment, the host you provided in code sample does not look valid.

You can find you host address in your OVHcloud manager : https://www.ovh.com/manager/web

It is accessible inside Web Cloud->Databases and in the table General Informations

Body:
I cannot connect to my database which is hosted on OVH remotely from Flutter's package mysql1 and get the following error:

flutter: SocketException: Failed host lookup: 'saintlouqpweb.mysql.db'
(OS Error: nodename nor servname provided, or not known, errno = 8)

I usually access it through phpMyAdmin where I have three fields to fill: the server, the user, and the password. I use exactly the same values than there with mysql1 on Flutter in addition to the database name (the server field of phpMyAdmin being the host field of mysql1).

I have searched for hours a solution but I still find nothing on this forum and on the web. Everything is always brought back to a 'localhost' server or a problem too different from mine.

Here is the piece of code causing the error :

Future<List<dynamic>> getData() async
  {
    try {
      final conn = await MySqlConnection.connect(ConnectionSettings(
        host: 'saintlouqpweb.mysql.db', // the exact server name entered on phpMyAdmin
        user: 'myusername',
        password: '*********',
        db: 'mydatabasename',
      ));

    var results = await conn.query(
      'SELECT * FROM `mytable` WHERE ID=1;'
    );

    return results.toList();
    } catch (e) {
      print('$e');
    }
  }

I would be grateful if someone can help me about that or experienced the same issue previously.


问:
C# XML Deserialization where node attribute is case-insensitive even though xml is case sensitive
I am trying to read PackageReferences from an XML document.

My xml files look something like following:

```<code><Project>
  <ItemGroup>
    <PackageReference Update="PackageName" Version="PackageVersion" />
  </ItemGroup>
</Project>
</code>```

AND

```<code><Project>
  <ItemGroup>
    <PackageReference Update="PackageName" version="PackageVersion" />
  </ItemGroup>
</Project>
</code>```

(First example has a capital V in "Version" and the second example has a lowercase v in "version")

I know that XML is case sensitive. Unfortunately, the customers submitting the xml files for processing often make this casing mistake. Due to the number of customers and manual edits to these similar files, it's very difficult to keep this in line. What are my options to have my C# program safely ignore casing? Currently my program only captures values with the capital V in 'Version' and puts a null down for the lowercase 'version' examples. I still need the PackageVersion value in both cases.

Here is my code:

Reader.cs:

```<code>var xmlResolver = new XmlSecureResolver(new XmlUrlResolver(), new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None));
using (var sr = new StringReader(this.FileSystem.File.ReadAllText(path)))
{
  var textReader = new XmlTextReader(sr) { Namespaces = false, XmlResolver = null };
  var serializer = new XmlSerializer(typeof(Project));
  return (Project)serializer.Deserialize(textReader);
}
</code>```

Project.cs partial class:

```<code>{
    using System;
    using System.Xml.Serialization;

    [Serializable]
    public partial class Project
    {
        private ProjectItemGroup[] itemGroupField;

        [XmlElement("ItemGroup")]
        public ProjectItemGroup[] ItemGroup
        {
            //...
        }
    }

    [Serializable]
    public partial class ProjectItemGroup
    {
        private Package[] packageReferenceField;

        [XmlElement("PackageReference")]
        public Package[] PackageReference
        {
            get
            {
                return this.packageReferenceField;
            }
            set
            {
                this.packageReferenceField = value;
            }
        }
    }

}
</code>```

Package.cs

```<code>    [Serializable]
    public class Package
    {
        [XmlAttribute(AttributeName = "Update")]
        public string Id { get; set; }

        [XmlAttribute(AttributeName = "Version")]
        public string Version { get; set; }
    }
</code>```

I looked through all the properties documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmltextreader.namespaces?view=net-6.0 and couldn't see a way to ignore case. (Earlier, I was able to ignore a namespace attribute on the root node as described here: C# XML Deserialization where root node sometimes has namespace attribute)

The options I potentially see are to lowercase the full document and re-write the program to expect all lowercase values. Another option might be to also add a lowercase field for version and somehow combine the results for uppercase Version and lowercase version. Is there something less hacky I am missing?

答:
Thanks @canton7 for your idea to subclass XmlTextReader overriding LocalName. I ended up making the following changes to Reader.cs:

```<code>public class CaseInsensitiveXmlTextReader : XmlTextReader
{
  public CaseInsensitiveXmlTextReader(System.IO.TextReader reader) : base(reader) { }
  public override string LocalName
  {
    get
    {
      if (String.Equals(base.LocalName, "version", StringComparison.Ordinal))
      {
        return "Version";
      }
      else
      {
        return base.LocalName;
      }
    }
  }
}
</code>```

And then I updated the textReader to use the CaseInsensitiveXmlTextReader:

```<code>var textReader = new CaseInsensitiveXmlTextReader(sr) { Namespaces = false, XmlResolver = xmlResolver };
</code>```

Body:
I am trying to read PackageReferences from an XML document.

My xml files look something like following:

<Project>
  <ItemGroup>
    <PackageReference Update="PackageName" Version="PackageVersion" />
  </ItemGroup>
</Project>

AND

<Project>
  <ItemGroup>
    <PackageReference Update="PackageName" version="PackageVersion" />
  </ItemGroup>
</Project>

(First example has a capital V in "Version" and the second example has a lowercase v in "version")

I know that XML is case sensitive. Unfortunately, the customers submitting the xml files for processing often make this casing mistake. Due to the number of customers and manual edits to these similar files, it's very difficult to keep this in line. What are my options to have my C# program safely ignore casing? Currently my program only captures values with the capital V in 'Version' and puts a null down for the lowercase 'version' examples. I still need the PackageVersion value in both cases.

Here is my code:

Reader.cs:

var xmlResolver = new XmlSecureResolver(new XmlUrlResolver(), new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None));
using (var sr = new StringReader(this.FileSystem.File.ReadAllText(path)))
{
  var textReader = new XmlTextReader(sr) { Namespaces = false, XmlResolver = null };
  var serializer = new XmlSerializer(typeof(Project));
  return (Project)serializer.Deserialize(textReader);
}

Project.cs partial class:

{
    using System;
    using System.Xml.Serialization;

    [Serializable]
    public partial class Project
    {
        private ProjectItemGroup[] itemGroupField;

        [XmlElement("ItemGroup")]
        public ProjectItemGroup[] ItemGroup
        {
            //...
        }
    }

    [Serializable]
    public partial class ProjectItemGroup
    {
        private Package[] packageReferenceField;

        [XmlElement("PackageReference")]
        public Package[] PackageReference
        {
            get
            {
                return this.packageReferenceField;
            }
            set
            {
                this.packageReferenceField = value;
            }
        }
    }

}

Package.cs

    [Serializable]
    public class Package
    {
        [XmlAttribute(AttributeName = "Update")]
        public string Id { get; set; }

        [XmlAttribute(AttributeName = "Version")]
        public string Version { get; set; }
    }

I looked through all the properties documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmltextreader.namespaces?view=net-6.0 and couldn't see a way to ignore case. (Earlier, I was able to ignore a namespace attribute on the root node as described here: C# XML Deserialization where root node sometimes has namespace attribute)

The options I potentially see are to lowercase the full document and re-write the program to expect all lowercase values. Another option might be to also add a lowercase field for version and somehow combine the results for uppercase Version and lowercase version. Is there something less hacky I am missing?

Body:
Thanks @canton7 for your idea to subclass XmlTextReader overriding LocalName. I ended up making the following changes to Reader.cs:

public class CaseInsensitiveXmlTextReader : XmlTextReader
{
  public CaseInsensitiveXmlTextReader(System.IO.TextReader reader) : base(reader) { }
  public override string LocalName
  {
    get
    {
      if (String.Equals(base.LocalName, "version", StringComparison.Ordinal))
      {
        return "Version";
      }
      else
      {
        return base.LocalName;
      }
    }
  }
}

And then I updated the textReader to use the CaseInsensitiveXmlTextReader:

var textReader = new CaseInsensitiveXmlTextReader(sr) { Namespaces = false, XmlResolver = xmlResolver };


问:
Error when installing and loading libraries from list in R
I have a function that loads libraries from a list, and installs packages if required:

```<code># List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
    if (!require(x, character.only = T)) {
        install.packages(x)
        library(x)
    }
}

# Load packages
invisible(lapply(lib_List, loadLibrary))
</code>```

For example, in this case library "caret" is not installed. Running the loadLibrary function, the package gets downloaded and installed but this is followed by an error and the library is not loaded. Below the output from the R console:

```<code>Load required package: caret
--- Please select a CRAN mirror for use in this session ---
# Now download notifications follow
The downloaded binary packages are in
    /var/folders/8p/b3t6spn133z5s69hpj1hf4hc0000gn/T//Rtmp8VNEII/downloaded_packages

Error in library(x) : there is no package called ‘x’
In addition: Warning:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘caret’

sessionInfo()
other attached packages:
[1] scales_1.1.1   ggplot2_3.3.5   dplyr_1.0.7
</code>```

If I now run the loadLibrary function again, the new installed package gets loaded:

```<code>invisible(lapply(lib_List, loadLibrary))
Load package: caret

sessionInfo()
other attached packages:
[1] caret_6.0-90   lattice_0.20-45   scales_1.1.1    ggplot2_3.3.5   dplyr_1.0.7
</code>```

Why is the package not loaded the first time I run the loadLibrary function?

答:
I found that the following modified version, which is based on this answer and another post, will install all missing packages and load them without giving a warning:

```<code># List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

# Install missing packages
instpack <- lib_List %in% installed.packages()[,"Package"]
if (any(instpack == FALSE)) {
  install.packages(lib_List[!instpack])
}

# Load packages
invisible(lapply(lib_List, library, character.only = TRUE))
</code>```

It's not the shortest solution, but the advantage is that no additional packages are required.

Body:
I have a function that loads libraries from a list, and installs packages if required:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) {
    if (!require(x, character.only = T)) {
        install.packages(x)
        library(x)
    }
}

# Load packages
invisible(lapply(lib_List, loadLibrary))

For example, in this case library "caret" is not installed. Running the loadLibrary function, the package gets downloaded and installed but this is followed by an error and the library is not loaded. Below the output from the R console:

Load required package: caret
--- Please select a CRAN mirror for use in this session ---
# Now download notifications follow
The downloaded binary packages are in
    /var/folders/8p/b3t6spn133z5s69hpj1hf4hc0000gn/T//Rtmp8VNEII/downloaded_packages

Error in library(x) : there is no package called ‘x’
In addition: Warning:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘caret’

sessionInfo()
other attached packages:
[1] scales_1.1.1   ggplot2_3.3.5   dplyr_1.0.7

If I now run the loadLibrary function again, the new installed package gets loaded:

invisible(lapply(lib_List, loadLibrary))
Load package: caret

sessionInfo()
other attached packages:
[1] caret_6.0-90   lattice_0.20-45   scales_1.1.1    ggplot2_3.3.5   dplyr_1.0.7

Why is the package not loaded the first time I run the loadLibrary function?

Body:
I found that the following modified version, which is based on this answer and another post, will install all missing packages and load them without giving a warning:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

# Install missing packages
instpack <- lib_List %in% installed.packages()[,"Package"]
if (any(instpack == FALSE)) {
  install.packages(lib_List[!instpack])
}

# Load packages
invisible(lapply(lib_List, library, character.only = TRUE))

It's not the shortest solution, but the advantage is that no additional packages are required.


问:
differences between get_directory_client and get_subdirectory_client for azure file share
Azure file share Python SDKs have two similar methods get_directory_client and get_subdirectory_client. It seems both are interacting with directories. But do we need two methods to perform the same task?

答:
Honestly, I find it a bit confusing having to deal with two different methods to do "the same thing". I prefer to instantiate the directory client via the from_connection_string method.

For more information on how to list files from a FileShare, take a look at the following post: "Azure File Share - Recursive Directory Search like os.walk". The approach I reported allows to list files recursively, walking through the directories.