问:
LinearLayout Causing Lag If Typing Fast on Custom SoftKeyboard
I've been trying to solve a mysterious problem with the SoftKeyboard project I'm working on. The source of the problem from all of the research I've done may be related to the layout file that I've created. Lint complains of too many views beyond 80 and it types fine for my speed but I'm after fact action response from this and can't figure out where the source of the lag is.

I've done all of the Android Manifest tricks and XML tricks I could find, tried converting to the new Constraint Layout Relative Layout made it worse. I don't know how to use Trace View in Android Studio 2.2RC Build so not sure if threads are the issue. But the question I have is how could I make this file more efficient to improve the lag.

Further sometimes when I press a key it fires and others it misses and yet if I randomly toggle all of my fingers super fast across the keypad canvas area like taping my fingers super fast the input seems to keep up with my input events but the output trails behind quite slow like 4-6 seconds behind and it's annoying. For all of the keyboards on Play I see none of them have this issue as I can type super fast and when I stop the input the output stops at the same time.

So I see there are quite a few people who know how to build a great performing keyboard but this one is super slow when trying to type fast. Also if I type a huge amount of data in say like an SMS message it crashes the keyboard and that is the other part really bugging me like there is a buffer limit to this code.

The limit here is 30000 I was only able to paste part of the layout file and since I don't have enough reputation I can't reply..

Can any of the keyboard gurus out here tell me what I'm missing?

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:clickable="false"
    android:focusableInTouchMode="false"
    android:gravity="bottom">

    <LinearLayout
        android:id="@+id/num_keyLay"
        android:layout_width="match_parent"
        android:layout_height="54.2dp"
        android:orientation="horizontal"
        android:weightSum="10"
        android:baselineAligned="false">

        <LinearLayout
            android:id="@+id/ksOne_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksOne_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:background="@drawable/key_drwable_selector"
                android:text="1"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/kstwo_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/kstwo_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="2"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksthree_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksthree_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="3"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksFour_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksFour_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="4"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksFive_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksFive_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="5"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksSix_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksSix_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="6"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksSeven_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksSeven_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="7"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksEight_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksEight_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="8"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksNine_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksNine_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="9"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/ksZero_btn_LiLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/ksZero_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="0"
                android:textSize="25sp"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                tools:ignore="ContentDescription" />

        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/line_firstLay"
        android:layout_width="match_parent"
        android:layout_height="54.2dp"
        android:orientation="horizontal"
        android:weightSum="10"
        tools:ignore="DisableBaselineAlignment">

        <LinearLayout
            android:id="@+id/q_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/q_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="q"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/Q_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="Q"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/w_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/w_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="w"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/W_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="W"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/e_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/e_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="e"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/E_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="E"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/r_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/r_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="r"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/R_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="R"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/t_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/t_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="t"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/T_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="T"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/y_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/y_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="y"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/Y_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="Y"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/u_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/u_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="u"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/U_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="U"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/i_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/i_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="i"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                tools:ignore="ContentDescription" />

            <Button
                android:id="@+id/I_btn"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/key_drwable_selector"
                android:text="I"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:visibility="gone"
                tools:ignore="ContentDescription" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/o_btn_ReLay"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/backgroud_black"
            android:orientation="horizontal" >```

答: I had the simillar problem, turns out, when typing fast, there will be moments when there are two pointers on your touchscreen, you have to deal with that, when yousing onClickListeners the problem arises as the click is registered only when MotionEvent.ACTION_UP occurs, thus if you press one key, and then press another without unpressing the first one, it creates problems, try using onTouchListener instead and overriding MotionEvent.ACTION_DOWN and implementing committext there.


来源: stackexchange

问:
Number format exception when typecasting from string to int in java
I am trying to get something like this to work

```<code>String s="3+33";
int i = Integer.parseInt(s);
String s2= Integer.toString(i);
System.out.println(s2);
</code>```

However, it gives me NumberFormatException. Is there any workaround for this?

答:
There are a method in python, eval(), which can get the result of a string. For java you can use ScriptEngineManager for this purpose.

Please read this answer, it will help you a lot.

https://stackoverflow.com/a/2605051/10837115

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get something like this to work

String s="3+33";
int i = Integer.parseInt(s);
String s2= Integer.toString(i);
System.out.println(s2);

However, it gives me NumberFormatException. Is there any workaround for this?


问:
Trying to pass the value of a label but receiving an error 'Cannot assign value of type 'Organizations?' to type 'String'
I am trying to create a tableview where once a tableview cell is selected, it passes the name of the cell to a new view controller. However, when trying to change the organizationName I receive the error, 'Cannot assign value of type 'Organizations?' to type 'String'. How do I fix this so that the rowTitle of the tableview cell is then displayed as the organizationName on the next viewController?

Here is my code for the first view controller.

```<code>import UIKit

struct Organizations {
var sectionTitle = String()
var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

var searchOrganizations: Organizations?
var organizations = [Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
    Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
    Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"])
]

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}

extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell?.textLabel?.numberOfLines = 3
if searching {
    cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
} else {
    cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
}
return cell!
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedOrganizations = organizations[indexPath.row]
performSegue(withIdentifier: "organizationDetailSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? OrganizationsDetailViewController {
    destination.organization = selectedOrganizations
}
}

}
</code>```

Here is my code for the second view controller.

```<code>import UIKit

class OrganizationsDetailViewController: UIViewController {

@IBOutlet weak var organizationNameLabel: UILabel!

var organization: Organizations? = nil {
    didSet { self.organizationNameLabel.text = organization?.sectionTitle}
} // error is here

var organizationName: String = ""

override func viewDidLoad() {
super.viewDidLoad()

organizationNameLabel.text = organizationName
}
}
</code>```

答:
The error is telling you why. You’re trying to assign the organization to the variable that wants a string.

You want to assign it to the actual organization inside the detailController

Or assign the string value to one of the row titles or whatever value you want to show.

```<code>organizationName = selectedOrganization.rowTitles[indexPath.row]
</code>```

For a cleaner detail I would use the didSetoption inside your detail view controller

```<code>Class DetailViewController:UIViewController {
  var organization:Organizations? = nil
  var selectedRow: Int = 0

  func viewDidLoad() {
    super.viewDidLoad()
    setupLabel()
  }

  private func setupLabel() {
    guard let org = self.organization else {
      print(“no organization set”)
      return
    }
    self.organizationLabel.text = org.rowTitles[selectedRow]
  }
}
</code>```

Then in your tableView VC I would just assign the selected organization to the variable in the detail

So you could add another variable that holds the selected row alongside your selectedOrganization in your tableView controller in your didSelectRow func, set the variable to the selected row and you should be good to go

```<code>var selectedRow = 0

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if let destination = segue.destination as? OrganizationsDetailViewController {
    destination.organization= selectedOrganizations
    destination.selectedRow = selectedRow
  }
}
</code>```

Body:
I am trying to create a tableview where once a tableview cell is selected, it passes the name of the cell to a new view controller. However, when trying to change the organizationName I receive the error, 'Cannot assign value of type 'Organizations?' to type 'String'. How do I fix this so that the rowTitle of the tableview cell is then displayed as the organizationName on the next viewController?

Here is my code for the first view controller.

import UIKit

struct Organizations {
var sectionTitle = String()
var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

var searchOrganizations: Organizations?
var organizations = [Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
    Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
    Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"])
]

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}

extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell?.textLabel?.numberOfLines = 3
if searching {
    cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
} else {
    cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
}
return cell!
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedOrganizations = organizations[indexPath.row]
performSegue(withIdentifier: "organizationDetailSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? OrganizationsDetailViewController {
    destination.organization = selectedOrganizations
}
}

}

Here is my code for the second view controller.

import UIKit

class OrganizationsDetailViewController: UIViewController {

@IBOutlet weak var organizationNameLabel: UILabel!

var organization: Organizations? = nil {
    didSet { self.organizationNameLabel.text = organization?.sectionTitle}
} // error is here

var organizationName: String = ""

override func viewDidLoad() {
super.viewDidLoad()

organizationNameLabel.text = organizationName
}
}

Body:
The error is telling you why. You’re trying to assign the organization to the variable that wants a string.

You want to assign it to the actual organization inside the detailController

Or assign the string value to one of the row titles or whatever value you want to show.

organizationName = selectedOrganization.rowTitles[indexPath.row]

For a cleaner detail I would use the didSetoption inside your detail view controller

Class DetailViewController:UIViewController {
  var organization:Organizations? = nil
  var selectedRow: Int = 0

  func viewDidLoad() {
    super.viewDidLoad()
    setupLabel()
  }

  private func setupLabel() {
    guard let org = self.organization else {
      print(“no organization set”)
      return
    }
    self.organizationLabel.text = org.rowTitles[selectedRow]
  }
}

Then in your tableView VC I would just assign the selected organization to the variable in the detail

So you could add another variable that holds the selected row alongside your selectedOrganization in your tableView controller in your didSelectRow func, set the variable to the selected row and you should be good to go

var selectedRow = 0

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if let destination = segue.destination as? OrganizationsDetailViewController {
    destination.organization= selectedOrganizations
    destination.selectedRow = selectedRow
  }
}


问:
I need to make a sql
**

```<code>SELECT clientName, orderID FROM
Orders INNER JOIN clients ON orders.clientID = clients.clientID;
</code>```

**

I can show every client and each of their orders. Help me correct my SQL syntax, so I am showing the number of orders for each client?

I also want my results to be ordered alphabetically by client name,

please write a new SQL syntax for me!

答:
SELECT clientName, COUNT(*)
FROM Orders INNER JOIN clients ON orders.clientID = clients.clientID
GROUP BY clientName
ORDER BY clientName</p>

Title: I need to make a sql

Body:
**

SELECT clientName, orderID FROM
Orders INNER JOIN clients ON orders.clientID = clients.clientID;

**

I can show every client and each of their orders. Help me correct my SQL syntax, so I am showing the number of orders for each client?

I also want my results to be ordered alphabetically by client name,

please write a new SQL syntax for me!


问:
What will be the SQL oracle query for finding out the maximum experience from hire date?
Have to find the most experienced employee.

```<code>select empno, ename,
from emp
where max(months_between(SYSDATE,hiredate))
</code>```

My software is giving errors on sysdate, so could anyone please verify if this is correct.

答:
You can use:

```<code>select e.*
from emp e
order by hiredate asc
fetch first 1 row only;
</code>```

If you want duplicates, then add with ties.

The above works in Oracle 12C+.  In earlier versions, you need a subquery:

```<code>select e.*
from (select e.*,
             row_number() over (order by hiredate) as seqnum
      from emp e
     ) e
where seqnum = 1;
</code>```

Body:
Have to find the most experienced employee.

select empno, ename,
from emp
where max(months_between(SYSDATE,hiredate))

My software is giving errors on sysdate, so could anyone please verify if this is correct.

Body:
You can use:

select e.*
from emp e
order by hiredate asc
fetch first 1 row only;

If you want duplicates, then add with ties.

The above works in Oracle 12C+.  In earlier versions, you need a subquery:

select e.*
from (select e.*,
             row_number() over (order by hiredate) as seqnum
      from emp e
     ) e
where seqnum = 1;


问:
Linq query syntax to method query syntax
Can anyone help with how to transform this LINQ query syntax to method syntax.
It is because i need to use the Take() method.</p>

```<code>IQueryable<QueueItem> rs = from a in ldb.QueueItems
                           join b in ldb.Robots on a.RobotId equals b.Id
                           join c in ldb.RobotsXEnvironments on b.Id equals c.RobotId
                           join d in ldb.Environments on c.EnvironmentId equals d.Id
                           join e in ldb.Releases on d.Id equals e.EnvironmentId
                           where e.ProcessKey == dropdown || a.Reference == query ||
                                       a.SpecificData.Contains(query) &&
                                       a.StartProcessing >= fromDate && a.EndProcessing <= toDate
                           select a;
</code>```

答:
You can do something like this:</p>

```<code>IQueryable<QueueItem> rs = (from a in ldb.QueueItems
                           join b in ldb.Robots on a.RobotId equals b.Id
                           join c in ldb.RobotsXEnvironments on b.Id equals c.RobotId
                           join d in ldb.Environments on c.EnvironmentId equals d.Id
                           join e in ldb.Releases on d.Id equals e.EnvironmentId
                           where e.ProcessKey == dropdown || a.Reference == query ||
                                       a.SpecificData.Contains(query) &&
                                       a.StartProcessing >= fromDate && a.EndProcessing <= toDate
                           select a).take(number);
</code>```

Body:
Can anyone help with how to transform this LINQ query syntax to method syntax.
It is because i need to use the Take() method.

IQueryable<QueueItem> rs = from a in ldb.QueueItems
                           join b in ldb.Robots on a.RobotId equals b.Id
                           join c in ldb.RobotsXEnvironments on b.Id equals c.RobotId
                           join d in ldb.Environments on c.EnvironmentId equals d.Id
                           join e in ldb.Releases on d.Id equals e.EnvironmentId
                           where e.ProcessKey == dropdown || a.Reference == query ||
                                       a.SpecificData.Contains(query) &&
                                       a.StartProcessing >= fromDate && a.EndProcessing <= toDate
                           select a;

Body:
You can do something like this:

IQueryable<QueueItem> rs = (from a in ldb.QueueItems
                           join b in ldb.Robots on a.RobotId equals b.Id
                           join c in ldb.RobotsXEnvironments on b.Id equals c.RobotId
                           join d in ldb.Environments on c.EnvironmentId equals d.Id
                           join e in ldb.Releases on d.Id equals e.EnvironmentId
                           where e.ProcessKey == dropdown || a.Reference == query ||
                                       a.SpecificData.Contains(query) &&
                                       a.StartProcessing >= fromDate && a.EndProcessing <= toDate
                           select a).take(number);


问:
Unable to understand the function of key in sorting python lists
Sorry I can't understand what happens when key = key:</p>

```<code>def key(x):
    return x[1]

a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=key)
</code>```

答:
The sort function, as chaooder says, needs a named parameter, which is "key". This is the parameter for the funtion, and it is always named "key".

When you call the function, you pass another function as the value for this parameter. You can set whatever name you want for this function.

The thing that is confusing you is that in your code the function you pass as value happens to have the same name as the parameter - "key".

I bet it would not confuse you as much if you have it like this:

def mykey(x):

return x[1]

a = [(1, 2), (3, 1), (5, 10), (11, -3)]

a.sort(key=mykey)

EDIT: user Talon answered the same while I was writing this one, so he beat me to it  :)

Body:
Sorry I can't understand what happens when key = key:

def key(x):
    return x[1]

a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=key)


问:
Add property to object with key in JavaScript
I have a simple code like this:

```<code>var name = 'line1';
var obj = {};
obj.name = [0, 1];
console.log(obj);
</code>```

Key of property is name. But I want to make key='line'. Can you help me?

答:
If I understand correctly, and you want to use the value of the name variable as the property name, you can use this syntax:

```<code>obj[name] = [0, 1]; //obj.line1 will be [0, 1]
</code>```

Object properties can also be accessed with the same syntax arrays use. It is handy in situations like this one.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple code like this:

var name = 'line1';
var obj = {};
obj.name = [0, 1];
console.log(obj);

Key of property is name. But I want to make key='line'. Can you help me?

Body:
If I understand correctly, and you want to use the value of the name variable as the property name, you can use this syntax:

obj[name] = [0, 1]; //obj.line1 will be [0, 1]

Object properties can also be accessed with the same syntax arrays use. It is handy in situations like this one.


问:
Where to place a Provider Widget -- Flutter Provider Package
I am currently learning app development with Flutter and have started learning about the Provider package. I was having some difficulty and was getting the error:

"Could not find the correct Provider above this ... Widget"

I ended up moving the Provider widget to wrap around my MaterialApp widget instead of my Scaffold Widget, and that seemed to fix things.

That being said, I'm not sure why this fixed things. Are we supposed to put our Provider widget around our MaterialApp? If so, can someone please explain why this is needed? If not, can someone explain how to determine where to place the Provider widget in our tree?

答:
If your page is a Stateful widget - inside Widget wrap State with Provider, so you can use it inside of State. This is a much cleaner solution because you won't have to wrap your entire application.

If you need the functionality of Provider everywhere in the app - yes, wrapping the entire app is completely fine, though I'll prefer to use some kind of service for this


问:
Performing a logical or operation of multiple lists in Python
I have a list containing some number of sublists.

```<code>list1=[ [True,False,True,False], [False,False,True,False],[True,False,True,True], .....]
</code>```

I want to perform a logical or of these sublists in Python but the number of sublists is unknown. For two lists I can do numpy.logical_or but how can I do it for multiple sublists?

答:
Following up @ggorlen's answer

```<code>list1 = [
    [True,False,True,False],
    [False,False,True,False],
    [True,False,True,True]
]
[any(l) for l in zip(*list1)]
</code>```

Output

```<code>[True, False, True, True]
</code>```

Body:
I have a list containing some number of sublists.

list1=[ [True,False,True,False], [False,False,True,False],[True,False,True,True], .....]

I want to perform a logical or of these sublists in Python but the number of sublists is unknown. For two lists I can do numpy.logical_or but how can I do it for multiple sublists?

Body:
Following up @ggorlen's answer

list1 = [
    [True,False,True,False],
    [False,False,True,False],
    [True,False,True,True]
]
[any(l) for l in zip(*list1)]

Output

[True, False, True, True]


问:
Pandas Week of the Month Business Day Stock Price Data
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

```<code>def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True
</code>```

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.

答:
```<code>import datetime
from math import ceil

def week_of_month(dt):
    """ Returns the week of the month for the specified date.
    """

    adjusted_dom = dt.day + dt.replace(day=1).day

    return int(ceil(adjusted_dom / 7.0))

def week_of_month_from_str(d_str):
    return week_of_month(datetime.datetime.strptime(d_str, '%Y-%m-%d'))

assert week_of_month_from_str("2020-03-02") == 1
assert week_of_month_from_str("2020-03-07") == 2
assert week_of_month_from_str("2020-03-13") == 2
assert week_of_month_from_str("2020-03-14") == 3
assert week_of_month_from_str("2020-03-20") == 3
assert week_of_month_from_str("2020-06-01") == 1
assert week_of_month_from_str("2020-06-06") == 1
assert week_of_month_from_str("2020-06-07") == 2
assert week_of_month_from_str("2020-06-08") == 2
</code>```

Body:
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.


问:
Data Binding with theme attributes
I am trying out the new Android Databinding Library and I wanted to set the background color of ToolBar using a binding. By default the color should be colorPrimary (from the theme).

Before I was using DataBinding, my toolBar looked like

```<code> <android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        />
</code>```

After adding a binding, I wanted to set its background to colorPrimary if no color is bound - I'm using ternary operator for this (as mentioned in the guide) - but it causes an error, as theme attributes also have a "?" operator before their names. The compiler thinks I'm starting a new ternary operation.

```<code><data>
    <variable name="toolBarBackgroundColor" type="int"/>
</data>
...
<android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@{toolBarBackgroundColor!=0? toolBarBackgroundColor: ?attr/colorPrimary }"
        />
</code>```

So is there a way I can access theme attributes inside a binding operation? Thanks!

Edit

I know I can get the colorPrimary attribute programmatically and bind it through java code. But I'm just wondering if there's an Xml-based solution for this or not.

答:
If the question is still actual for someone, this is the example how to use custom and android attributes
app:textColorAttr="@{error ? com.example.R.attr.textColorError : android.R.attr.textColor}", where textColorAttr implemented using BindingAdapter, error is Boolean and com.example is your package name

Title: Data Binding with theme attributes

Body:
I am trying out the new Android Databinding Library and I wanted to set the background color of ToolBar using a binding. By default the color should be colorPrimary (from the theme).

Before I was using DataBinding, my toolBar looked like

 <android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        />

After adding a binding, I wanted to set its background to colorPrimary if no color is bound - I'm using ternary operator for this (as mentioned in the guide) - but it causes an error, as theme attributes also have a "?" operator before their names. The compiler thinks I'm starting a new ternary operation.

<data>
    <variable name="toolBarBackgroundColor" type="int"/>
</data>
...
<android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@{toolBarBackgroundColor!=0? toolBarBackgroundColor: ?attr/colorPrimary }"
        />

So is there a way I can access theme attributes inside a binding operation? Thanks!

Edit

I know I can get the colorPrimary attribute programmatically and bind it through java code. But I'm just wondering if there's an Xml-based solution for this or not.


问:
Javascript wait asynchronous response in synchronous function
I guess my question is easy but I can not figure it out even searching for days.

There is my practical situation:

I have a form and would like to wait for the return of a stripe asynchronous function before submitting it to my backend as I need the response of the stripe API. I am then using the onsubmit="return validate_form();">
tag in order to manage that by myself in a javascript function.

```<code><form action="/" method="get" id="test" onsubmit="return validate_test_form();">
  <button type="submit" id="iban-test" data-secret="">
    TEST
  </button>
</form>
</code>```

```<code>function validate_test_form() {
  var stripe_result = stripe.confirmCardSetup(clientSecret)

  if (stripe_result.error) {
    // do things
  } else {
    // do other things
  }
  return true;
}
</code>```

As a normal behavior, the form is submitted without waiting for the stripe response as the stripe function is asynchronous and the default validate_test_form function return is true. I am aware of async/await/promise concepts but don't see how I can use them to wait (block UI, with a spinner or other) for the response of stripe as a synchronous behavior.

I imagine this situation must be current and it must be lots way to perform what I am looking for. In either way, could you tell me what are the best practices in this situation.

Thanks a lot for your time.

答:
You need to return false from validate_test_form() immediately (which will cancel submit action) and submit the form once response from Stripe is available.

Since confirmCardSetup returns a Promise, it won't block execution of your function. Instead, you can execute code once Promise returns a result by using .then(func).

function validate_test_form() {
  var stripe_result = stripe.confirmCardSetup(clientSecret)
  stripe_result.then(function(stripe_result) {

    // Hide the progress bar here

    if (stripe_result.error) {
      // do things
    } else {
      // do other things
      // Resubmit the form or use `stripe_result.setupIntent` if needed.
    }
  }); // this will return immediately, so we can continue.

  // Show a progress bar here or whatever

  return false;
}
```

Body:
I guess my question is easy but I can not figure it out even searching for days.

There is my practical situation:

I have a form and would like to wait for the return of a stripe asynchronous function before submitting it to my backend as I need the response of the stripe API. I am then using the onsubmit="return validate_form();">
tag in order to manage that by myself in a javascript function.

<form action="/" method="get" id="test" onsubmit="return validate_test_form();">
  <button type="submit" id="iban-test" data-secret="">
    TEST
  </button>
</form>

function validate_test_form() {
  var stripe_result = stripe.confirmCardSetup(clientSecret)

  if (stripe_result.error) {
    // do things
  } else {
    // do other things
  }
  return true;
}

As a normal behavior, the form is submitted without waiting for the stripe response as the stripe function is asynchronous and the default validate_test_form function return is true. I am aware of async/await/promise concepts but don't see how I can use them to wait (block UI, with a spinner or other) for the response of stripe as a synchronous behavior.

I imagine this situation must be current and it must be lots way to perform what I am looking for. In either way, could you tell me what are the best practices in this situation.

Thanks a lot for your time.


问:
Code not calculating final count as per rate correctly
I was trying to solve the following Problem Statement:

In the city A, there is a disease x, spreading at the rate of 2. The
  rate doubles after every 3 days.

If 2 people were initially infected with the disease, how many people
  will be affected in total after 100 days?

(Hint: Ni+1 = Ni + a*Ni *t where Ni is the ith day patients and Ni+1
  is patients the day after that, a is the increase rate and t is the
  number of days.)

This is the Python code I tried to solve the statement:

```<code>rate = 2
rate_of_rate = 2    # the rate doubles every gap days
gap = 3
initially_infected = 2
final_day = 100

infected = initially_infected
days_passed = 1

while days_passed != final_day:
    if days_passed%gap == 0:
        rate *= rate_of_rate
    infected = infected * rate
    days_passed += 1
print(infected)
</code>```

The answer expected is: 658781418

And the answer I'm getting is:

```<code>7387586092700242099654546576830696772603866567292789055868426442323956818125567473217880665869221255368279336978185916233370357196371072076345487974033022845153783727077340269105240653596212209328236829977000561171160601353019714984950312214004440228069460097961675499715690703175560410535127557079386864191774441606293810308368351268196693882638167250873667663250863266951807800784887663781068841491777971210302562177144021123949168116897834247743963522769738506629596576834286879022276623596962844306405686165635072
</code>```

Where am I doing wrong?

P.S. > I am also not able to understand where the formula is incorporating rate_of_rate

答:
Your program is perfectly correct.

Even if the disease would be

spreading at a constant rate 2, and

initially would be infected only 1 man, and

instead of 100 days would be only 63 days,

your task would be an analogy of well-known “Wheat and chessboard problem” with the result as large as 18,446,744,073,709,551,615.

From the Wikipedia “Wheat and chessboard problem”:

If a chessboard were to have wheat placed upon each square such that
  one grain were placed on the first square, two on the second, four on
  the third, and so on (doubling the number of grains on each subsequent
  square), how many grains of wheat would be on the chessboard at the
  finish?

Body:
I was trying to solve the following Problem Statement:

In the city A, there is a disease x, spreading at the rate of 2. The
  rate doubles after every 3 days.

If 2 people were initially infected with the disease, how many people
  will be affected in total after 100 days?

(Hint: Ni+1 = Ni + a*Ni *t where Ni is the ith day patients and Ni+1
  is patients the day after that, a is the increase rate and t is the
  number of days.)

This is the Python code I tried to solve the statement:

rate = 2
rate_of_rate = 2    # the rate doubles every gap days
gap = 3
initially_infected = 2
final_day = 100

infected = initially_infected
days_passed = 1

while days_passed != final_day:
    if days_passed%gap == 0:
        rate *= rate_of_rate
    infected = infected * rate
    days_passed += 1
print(infected)

The answer expected is: 658781418

And the answer I'm getting is:

7387586092700242099654546576830696772603866567292789055868426442323956818125567473217880665869221255368279336978185916233370357196371072076345487974033022845153783727077340269105240653596212209328236829977000561171160601353019714984950312214004440228069460097961675499715690703175560410535127557079386864191774441606293810308368351268196693882638167250873667663250863266951807800784887663781068841491777971210302562177144021123949168116897834247743963522769738506629596576834286879022276623596962844306405686165635072

Where am I doing wrong?

P.S. > I am also not able to understand where the formula is incorporating rate_of_rate


问:
react + keycloak + rerender forces new authentification
I am using react with keycloak-js and the framework react-keycloak from panz3r (Link to library ) Everything latest version.

I have almost the same structure like this example here: My project
I am using Functional Components and my App.tsx is also used as container -> I have all states defined here, which will be needed over all components.

Therefore my app looks like this (modified it for simplicity):
import packages

```<code>const App: React.FC = () => {
    const keycloakConfig = new (Keycloak as any)({
        realm: 'master',
        url: http://localhost:8280/auth/",
        clientId: 'reactPage',
    });

    const keycloakProviderInitConfig = {
        onLoad: 'check-sso',
    }

    const [data1, setData1] = useState<(Data[])>([]);
    const [data2, setData2] = useState<(Data | null)>(null);
    const [data3, setData3] = useState<(Data[])>([]);

    function onKeycloakEvent(event: any, error: any) {
        console.log('onKeycloakEvent', event, error)
        if (event === "onAuthSuccess") {
          setData1(Set anything);
        }
    }

    function onKeycloakTokens(tokens: any) {
        console.log('onKeycloakTokens', tokens)
    }

    return (
        <KeycloakProvider
            keycloak={keycloakConfig}
            initConfig={keycloakProviderInitConfig}
            onEvent={onKeycloakEvent}
            onTokens={onKeycloakTokens}
        >
            <Router history={myhistory}>
                <div className="App">
                    <MuiThemeProvider theme={theme}>
                        <React.StrictMode>
                            <RouterComponent
                                data1={data1}
                             data2={data2}
                             ...
                        </React.StrictMode>
                    </MuiThemeProvider>
                </div>
            </Router>
        </KeycloakProvider>
    );
};

export default App;
</code>```

The problem:
As soon as I modify any data in the app.tsx container react rerenders the page and the authentification starts again from the beginning.
Now I have an endless loop. It does not matter from where I set any data in the container (app.tsx) as soon as I modify any variable in the container I have a complete rerender of the app and also a new authentification

答: I could fix my problem with adding an extra layer before App.tsx. Maybe not the best solution, but it works</p>

Body:
I am using react with keycloak-js and the framework react-keycloak from panz3r (Link to library ) Everything latest version.

I have almost the same structure like this example here: My project
I am using Functional Components and my App.tsx is also used as container -> I have all states defined here, which will be needed over all components.

Therefore my app looks like this (modified it for simplicity):
import packages

const App: React.FC = () => {
    const keycloakConfig = new (Keycloak as any)({
        realm: 'master',
        url: http://localhost:8280/auth/",
        clientId: 'reactPage',
    });

    const keycloakProviderInitConfig = {
        onLoad: 'check-sso',
    }

    const [data1, setData1] = useState<(Data[])>([]);
    const [data2, setData2] = useState<(Data | null)>(null);
    const [data3, setData3] = useState<(Data[])>([]);

    function onKeycloakEvent(event: any, error: any) {
        console.log('onKeycloakEvent', event, error)
        if (event === "onAuthSuccess") {
          setData1(Set anything);
        }
    }

    function onKeycloakTokens(tokens: any) {
        console.log('onKeycloakTokens', tokens)
    }

    return (
        <KeycloakProvider
            keycloak={keycloakConfig}
            initConfig={keycloakProviderInitConfig}
            onEvent={onKeycloakEvent}
            onTokens={onKeycloakTokens}
        >
            <Router history={myhistory}>

                    <MuiThemeProvider theme={theme}>
                        <React.StrictMode>
                            <RouterComponent
                                data1={data1}
                             data2={data2}
                             ...
                        </React.StrictMode>
                    </MuiThemeProvider>

            </Router>
        </KeycloakProvider>
    );
};

export default App;

The problem:
As soon as I modify any data in the app.tsx container react rerenders the page and the authentification starts again from the beginning.
Now I have an endless loop. It does not matter from where I set any data in the container (app.tsx) as soon as I modify any variable in the container I have a complete rerender of the app and also a new authentification


问:
Expo Permissions returns status of 'undetermined'
In my react native app, I ask for permission to access the camera roll as so:

```<code>  getPermissionAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status !== "granted") {
      alert("Sorry, we need camera roll permissions to make this work!");
    }
    await this.setState({ permission: status === "granted" });
  };

  _pickMedia = async (index, type) => {
    if (this.state.permission != true) {
      await this.getPermissionAsync();
    }
    if (this.state.permission == true) {
        // get image
      } catch (E) {
        console.log(E);
      }
    }
  };
</code>```

This works as expected during testing, but for my published version on Google Play, status is returned as undetermined whether or not the user gives permission. What does this mean?

答:
Upgrading the react-native-community@react-native-permissions to 2.0.0 solves the issue.
Refer : https://github.com/react-native-community/react-native-permissions/issues/295</p>

Body:
In my react native app, I ask for permission to access the camera roll as so:

  getPermissionAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status !== "granted") {
      alert("Sorry, we need camera roll permissions to make this work!");
    }
    await this.setState({ permission: status === "granted" });
  };

  _pickMedia = async (index, type) => {
    if (this.state.permission != true) {
      await this.getPermissionAsync();
    }
    if (this.state.permission == true) {
        // get image
      } catch (E) {
        console.log(E);
      }
    }
  };

This works as expected during testing, but for my published version on Google Play, status is returned as undetermined whether or not the user gives permission. What does this mean?


问:
Calling Windows Form Method from its User Control
I have a User Control on My windows Form, and there is a button on my user control on click of which I want to call its form method.

Thanx

答:
Provide your own public Click event on your user control and subscribe to this event in the form that uses the control.

```<code>public class MyControl : UserControl
{
    // ...

    public event EventHandler Click;

    // ...
}
</code>```

Handle the button's click and then forward it to the public Click event handler:

```<code>protected void button1_Click( object sender, EventArgs args )
{
    var h = Click;
    if ( h != null )
    {
        h( this, args );
    }
}
</code>```

Body:
Provide your own public Click event on your user control and subscribe to this event in the form that uses the control.

public class MyControl : UserControl
{
    // ...

    public event EventHandler Click;

    // ...
}

Handle the button's click and then forward it to the public Click event handler:

protected void button1_Click( object sender, EventArgs args )
{
    var h = Click;
    if ( h != null )
    {
        h( this, args );
    }
}


问:
How to set variable using pipe and awk in GDB?
I would like to store the executable name of the current inferior in a variable. I way to obtain the executable name in the gdb CLI is the following:

```<code> pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'
</code>```

But I am unable to store the output of this expression in a variable. The expression uses single and double quotes, which makes gdb complain if it is combined with set and eval.

```<code>(gdb) set $exec="pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.
(gdb) eval "!echo %s", "pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.
</code>```

Then, how can I store the executable name in a variable? My goal is to pass the executable name to the file command to reload the executable when Autotools are used (see using libtool e gdb).

答:
Your best bet is to use embedded Python. Example:

```<code>gdb -q ./a.out
Reading symbols from ./a.out...

(gdb) start
Temporary breakpoint 1 at 0x1129: file foo.c, line 3.
Starting program: /tmp/a.out

Temporary breakpoint 1, main () at foo.c:3
3         int v1 = 1, v2 = 2, v3 = 42;
(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    process 217200    1 (native)           /tmp/a.out

(gdb) python gdb.execute('set $pid = ' + str(gdb.selected_inferior().pid))
(gdb) p $pid
$1 = 217200
</code>```

Update:

Original question asked for field 4, which is the pid, but it appears that Gorka was actually interested in the file name, which can be found this way:

```<code>(gdb) python gdb.execute('set $f = "' + str(gdb.selected_inferior().progspace.filename) + '"')
(gdb) p $f
$2 = "/tmp/a.out"
</code>```

Documentation: Inferiors, Progspaces

Update 2:

Now I get the file name again with the field 4... but I was obtaining the pid as you said. I cannot figure why this is happening.

You get pid or name depending on whether the inferior is running or not (that's the danger of parsing data that is intended for humans).

When the inferior is not running, info inferiors prints:

```<code>(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    <null>                                 /bin/date
</code>```

When the inferior is currently active, it prints:

```<code>(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    process 118431    2 (native)           /bin/date
</code>```

Body:
I would like to store the executable name of the current inferior in a variable. I way to obtain the executable name in the gdb CLI is the following:

 pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'

But I am unable to store the output of this expression in a variable. The expression uses single and double quotes, which makes gdb complain if it is combined with set and eval.

(gdb) set $exec="pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.
(gdb) eval "!echo %s", "pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.

Then, how can I store the executable name in a variable? My goal is to pass the executable name to the file command to reload the executable when Autotools are used (see using libtool e gdb).

Body:
Your best bet is to use embedded Python. Example:

gdb -q ./a.out
Reading symbols from ./a.out...

(gdb) start
Temporary breakpoint 1 at 0x1129: file foo.c, line 3.
Starting program: /tmp/a.out

Temporary breakpoint 1, main () at foo.c:3
3         int v1 = 1, v2 = 2, v3 = 42;
(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    process 217200    1 (native)           /tmp/a.out

(gdb) python gdb.execute('set $pid = ' + str(gdb.selected_inferior().pid))
(gdb) p $pid
$1 = 217200

Update:

Original question asked for field 4, which is the pid, but it appears that Gorka was actually interested in the file name, which can be found this way:

(gdb) python gdb.execute('set $f = "' + str(gdb.selected_inferior().progspace.filename) + '"')
(gdb) p $f
$2 = "/tmp/a.out"

Documentation: Inferiors, Progspaces

Update 2:

Now I get the file name again with the field 4... but I was obtaining the pid as you said. I cannot figure why this is happening.

You get pid or name depending on whether the inferior is running or not (that's the danger of parsing data that is intended for humans).

When the inferior is not running, info inferiors prints:

(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    <null>                                 /bin/date

When the inferior is currently active, it prints:

(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    process 118431    2 (native)           /bin/date


问:
iPhone Navigation Bar Title text color
It seems the iOS Navigation Bar title color is white by default. Is there a way to change it to a different color?

I am aware of the navigationItem.titleView approach using an image. Since my design skills are limited and I failed to get the standard glossy, I prefer changing the text color.

Any insight would be much appreciated.

答:
Modern approach

The modern way, for the entire navigation controller… do this once, when your navigation controller's root view is loaded.

```<code>[self.navigationController.navigationBar setTitleTextAttributes:
   @{NSForegroundColorAttributeName:[UIColor yellowColor]}];
</code>```

However, this doesn't seem have an effect in subsequent views.

Classic approach

The old way, per view controller (these constants are for iOS 6, but if want to do it per view controller on iOS 7 appearance you'll want the same approach but with different constants):

You need to use a UILabel as the titleView of the navigationItem.

The label should:

Have a clear background color (label.backgroundColor = [UIColor clearColor]).

Use bold 20pt system font (label.font = [UIFont boldSystemFontOfSize: 20.0f]).

Have a shadow of black with 50% alpha (label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]).

You'll want to set the text alignment to centered as well (label.textAlignment = NSTextAlignmentCenter (UITextAlignmentCenter for older SDKs).

Set the label text color to be whatever custom color you'd like. You do want a color that doesn't cause the text to blend into shadow, which would be difficult to read.

I worked this out through trial and error, but the values I came up with are ultimately too simple for them not to be what Apple picked. :)

If you want to verify this, drop this code into initWithNibName:bundle: in PageThreeViewController.m of Apple's NavBar sample. This will replace the text with a yellow label. This should be indistinguishable from the original produced by Apple's code, except for the color.

```<code>- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // this will appear as the title in the navigation bar
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = NSTextAlignmentCenter;
                           // ^-Use UITextAlignmentCenter for older SDKs.
        label.textColor = [UIColor yellowColor]; // change this color
        self.navigationItem.titleView = label;
        label.text = NSLocalizedString(@"PageThreeTitle", @"");
        [label sizeToFit];
    }

    return self;
}
</code>```

Edit: Also, read Erik B's answer below. My code shows the effect, but his code offers a simpler way to drop this into place on an existing view controller.

OwnerDisplayName: Roby

Title: iPhone Navigation Bar Title text color

Body:
Modern approach

The modern way, for the entire navigation controller… do this once, when your navigation controller's root view is loaded.

[self.navigationController.navigationBar setTitleTextAttributes:
   @{NSForegroundColorAttributeName:[UIColor yellowColor]}];

However, this doesn't seem have an effect in subsequent views.

Classic approach

The old way, per view controller (these constants are for iOS 6, but if want to do it per view controller on iOS 7 appearance you'll want the same approach but with different constants):

You need to use a UILabel as the titleView of the navigationItem.

The label should:

Have a clear background color (label.backgroundColor = [UIColor clearColor]).

Use bold 20pt system font (label.font = [UIFont boldSystemFontOfSize: 20.0f]).

Have a shadow of black with 50% alpha (label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]).

You'll want to set the text alignment to centered as well (label.textAlignment = NSTextAlignmentCenter (UITextAlignmentCenter for older SDKs).

Set the label text color to be whatever custom color you'd like. You do want a color that doesn't cause the text to blend into shadow, which would be difficult to read.

I worked this out through trial and error, but the values I came up with are ultimately too simple for them not to be what Apple picked. :)

If you want to verify this, drop this code into initWithNibName:bundle: in PageThreeViewController.m of Apple's NavBar sample. This will replace the text with a yellow label. This should be indistinguishable from the original produced by Apple's code, except for the color.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // this will appear as the title in the navigation bar
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = NSTextAlignmentCenter;
                           // ^-Use UITextAlignmentCenter for older SDKs.
        label.textColor = [UIColor yellowColor]; // change this color
        self.navigationItem.titleView = label;
        label.text = NSLocalizedString(@"PageThreeTitle", @"");
        [label sizeToFit];
    }

    return self;
}

Edit: Also, read Erik B's answer below. My code shows the effect, but his code offers a simpler way to drop this into place on an existing view controller.

OwnerDisplayName: tewha


答:
Try,

```<code>obj[name]
</code>```

or

```<code>obj["line1"]
</code>```

This is known as the bracket notation, and can be used to access any property of an object.

Title: Add property to object with key in JavaScript

Body:
Try,

obj[name]

or

obj["line1"]

This is known as the bracket notation, and can be used to access any property of an object.


问:
What is 'should create' test case in Jasmine
I'm new to Unit testing in Angular using Jasmine and Karma. I'm an intern. I was going through a spec file. I want to know what is meant by should create in this context. TimeselectorComponent is the component that I want to test. I took the code from my senior. The code is like this:

```<code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    beforeEach(async(() => {

        TestBed.configureTestingModule({
            imports: [
                ...
            ],
            providers: [...],
            declarations: [TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    it('should create', () => {
        expect(fixture.componentInstance).toBeTruthy();
    });

    // other test cases
});
</code>```

There are other test cases also but for now I'm curious about 'should create' case. My understanding says that it is trying to test whether the component was initialized/created or not. Please correct me if I'm wrong. Please tell me more about the above code. Would like to know about compileComponent() method also. I checked this link but could understand only a little:

compileComponents() is asynchronous, we must use async()

I'm going through this question also:

Error: Please call “TestBed.compileComponents” before your test

答:
String inside each it block is a test case name. The first test case is should create, which you combine it with string in describe i.e. TimeSelectorComponent, it becomes TimeSelectorComponent should create. This test case is checking whether TimeSelector component is initialized or not. You can also change this string as per your convenience or how you want to write test cases.

Compilecomponents is a method which compiles all components you have mentioned in your test bed. Take task takes time, that's why its asynchronous so that your main thread isn't blocked and if you want to do, you can do some other setup parallely. That's why that async keyword is mandatory so that before each can wait till all async tasks executing inside are finished. Because test case will fail if our components are not ready.

Body:
I'm new to Unit testing in Angular using Jasmine and Karma. I'm an intern. I was going through a spec file. I want to know what is meant by should create in this context. TimeselectorComponent is the component that I want to test. I took the code from my senior. The code is like this:

import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    beforeEach(async(() => {

        TestBed.configureTestingModule({
            imports: [
                ...
            ],
            providers: [...],
            declarations: [TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    it('should create', () => {
        expect(fixture.componentInstance).toBeTruthy();
    });

    // other test cases
});

There are other test cases also but for now I'm curious about 'should create' case. My understanding says that it is trying to test whether the component was initialized/created or not. Please correct me if I'm wrong. Please tell me more about the above code. Would like to know about compileComponent() method also. I checked this link but could understand only a little:

compileComponents() is asynchronous, we must use async()

I'm going through this question also:

Error: Please call “TestBed.compileComponents” before your test


问:
How to call one async function inside another async function in flutter
I have two future functions one for verifying OTP with API and another for setting a password using the API.

When the OTP verification is successful the set password API must be called. How can I do that?

My code is:

```<code>    () async {

var status = await registrationService.verifyOtp(registrationData.mobileNumber,otpController.text);
                                if(status == 'approved'){
                                  print('success');
                                      () async {
                                    var passwordStatus = await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
                                    if(passwordStatus == 'approved'){
                                      print('approved');
                                      Navigator.pushNamed(context, StudMainPage.id);
                                    }
                                    else{
                                      WidgetsBinding.instance.addPostFrameCallback((timeStamp) => _showNewVersionAvailableDialog(context));
                                    }
                                  };
                                 }

    }
</code>```

It shows error or the function is not being called. What should I do now?
Thanks in advance.

答:
Use then Callback

```<code>registrationService.verifyOtp(registrationData.mobileNumber,otpController.text).then((status) {

if(status == 'approved'){
   print('success');

registrationService.setPassword(registrationData.name, registrationData.number, passController.text).then((response) {

//....
})))
</code>```

}

Body:
I have two future functions one for verifying OTP with API and another for setting a password using the API.

When the OTP verification is successful the set password API must be called. How can I do that?

My code is:

    () async {

var status = await registrationService.verifyOtp(registrationData.mobileNumber,otpController.text);
                                if(status == 'approved'){
                                  print('success');
                                      () async {
                                    var passwordStatus = await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
                                    if(passwordStatus == 'approved'){
                                      print('approved');
                                      Navigator.pushNamed(context, StudMainPage.id);
                                    }
                                    else{
                                      WidgetsBinding.instance.addPostFrameCallback((timeStamp) => _showNewVersionAvailableDialog(context));
                                    }
                                  };
                                 }

    }

It shows error or the function is not being called. What should I do now?
Thanks in advance.

Body:
Use then Callback

registrationService.verifyOtp(registrationData.mobileNumber,otpController.text).then((status) {

if(status == 'approved'){
   print('success');

registrationService.setPassword(registrationData.name, registrationData.number, passController.text).then((response) {

//....
})))

}


问:
resource directory name for language variant?
When using a Custom locale in android, the directory names are, for example

```<code>res/drawable-en-rUS
res/values-fr-rCA
</code>```

where the -r specifies a region (country) in which that language is spoken.

What about when also specifying the regional variant?   My client has asked that we support English, Chinese, and three (3) variants of Japanese.  (*)

I set the locale using a customized Application class and code something like this:

```<code>locale = new Locale(lang, country);
Locale.setDefault(locale);
config.locale = locale;
mContext.getResources().updateConfiguration(config,mContext.getResources().getDisplayMetrics());
</code>```

and am using resource directories named like this:

```<code>/res/drawable-en
/res/drawable-cx
/res/drawable-ja
/res/drawable-ja-rHI
/res/drawable-ja-rFU
</code>```

While this works; the bottom two entries are hacks.  I'm using imaginary country names to be the regions, when I actually need them to be something like

```<code>/res/drawable-ja-rJP-vHI
/res/drawable-ja-rJP-vFU
</code>```

to specify the variant within Japan.

There's another Locale() constructor, namely

Locale(String language, String country, String variant);

If I use this as

locale = new Locale("ja", "JP", "hi");

How do I specify the resource directories including language, region, and variant?

The best resource I've found on Providing Alternative Application Resources doesn't show how to do it.

(*) they've requested these Japanese variants:

hiragana only

hiragana with furigana above the kanji

normal with kanji + hiragana

答:
The problem with this is that you can't specify variants as resource folders. From what I can tell, the only purpose for the variant string is to be able to display it to the user. Honestly, I think your 'hack' is probably the best way to go about this.

Even if it were possible some other way, the variants you're using aren't really regional variants anyway, just different ways of writing the same thing. (Personally, I'm a big fan of mixed, but I still only know about 300 kanji, so that gets me in trouble sometimes... it's enough to get around on though!)

Body:
When using a Custom locale in android, the directory names are, for example

res/drawable-en-rUS
res/values-fr-rCA

where the -r specifies a region (country) in which that language is spoken.

What about when also specifying the regional variant?   My client has asked that we support English, Chinese, and three (3) variants of Japanese.  (*)

I set the locale using a customized Application class and code something like this:

locale = new Locale(lang, country);
Locale.setDefault(locale);
config.locale = locale;
mContext.getResources().updateConfiguration(config,mContext.getResources().getDisplayMetrics());

and am using resource directories named like this:

/res/drawable-en
/res/drawable-cx
/res/drawable-ja
/res/drawable-ja-rHI
/res/drawable-ja-rFU

While this works; the bottom two entries are hacks.  I'm using imaginary country names to be the regions, when I actually need them to be something like

/res/drawable-ja-rJP-vHI
/res/drawable-ja-rJP-vFU

to specify the variant within Japan.

There's another Locale() constructor, namely

Locale(String language, String country, String variant);

If I use this as

locale = new Locale("ja", "JP", "hi");

How do I specify the resource directories including language, region, and variant?

The best resource I've found on Providing Alternative Application Resources doesn't show how to do it.

(*) they've requested these Japanese variants:

hiragana only

hiragana with furigana above the kanji

normal with kanji + hiragana


问:
What is bast practice for pom.xml for fix rpm-maven-plugin file /usr/lib/systemd/system conflicts?
I try pack jar and systemd unit to RPM.

My source code https://github.com/patsevanton/consul-demo

https://github.com/patsevanton/consul-demo/blob/master/backend/pom.xml#L120

```<code><mapping>
    <directory>/usr/lib/systemd/system</directory>
    <filemode>644</filemode>
    <username>root</username>
    <sources>
        <source>
            <location>src/main/scripts/backend.service</location>
        </source>
    </sources>
</mapping>
</code>```

i get error:

```<code>Transaction check error:
  file /usr/lib/systemd/system from install of consul-backend-0.0.1-1.noarch conflicts with file from package systemd-219-62.el7_6.2.x86_64
</code>```

What is bast practice for pom.xml for fix rpm-maven-plugin file /usr/lib/systemd/system conflicts ?

答:
Your configuration is trying to create the /usr/lib/systemd/system directory which is wrong. You have to change the configuration of the rpm-maven-plugin like this:

```<code><mapping>
    <directory>/usr/lib/systemd/system</directory>
    <filemode>644</filemode>
    <username>root</username>
    <groupname>root</groupname>
    <directoryIncluded>false</directoryIncluded>
     ..
</code>```

Body:
I try pack jar and systemd unit to RPM.

My source code https://github.com/patsevanton/consul-demo

https://github.com/patsevanton/consul-demo/blob/master/backend/pom.xml#L120

<mapping>
    <directory>/usr/lib/systemd/system</directory>
    <filemode>644</filemode>
    <username>root</username>
    <sources>
        <source>
            <location>src/main/scripts/backend.service</location>
        </source>
    </sources>
</mapping>

i get error:

Transaction check error:
  file /usr/lib/systemd/system from install of consul-backend-0.0.1-1.noarch conflicts with file from package systemd-219-62.el7_6.2.x86_64

What is bast practice for pom.xml for fix rpm-maven-plugin file /usr/lib/systemd/system conflicts ?

Body:
Your configuration is trying to create the /usr/lib/systemd/system directory which is wrong. You have to change the configuration of the rpm-maven-plugin like this:

<mapping>
    <directory>/usr/lib/systemd/system</directory>
    <filemode>644</filemode>
    <username>root</username>
    <groupname>root</groupname>
    <directoryIncluded>false</directoryIncluded>
     ..


问:
How to move caret to console in pycharm?
Is it possible to have a keyboard shortcut to move the caret from editor to console and back in pycharm? I can switch the focus between editor and console using CTRL+TAB, but that doesn't allow me to start typing in the console unless I click in it.

I am using the linux community distribution.

答:
A couple of years later but i found my self in this situations, i believe the other answers are good enough for some but they lack some important information or at least i didn't found it.

You need to look for the term Python or debug console under tools if you want to focus to the console with the caret at it, add a keymap value for that (in my case i added ALT+2), do NOT use the python console under tool windows, for that it will focus on the python console but not the caret at it.

(done with pycharm 2020.1.1 in a ubuntu 20.04 lts machine)


问:
How do you make Terraform wait for cloud-init to finish?
In my Terraform AWS Docker Swarm module I use cloud-init to initialize the EC2 instance.  However, Terraform says the resource is ready before cloud-init finishes.  Is there a way of making it wait for cloud-init to finish, ideally without SSHing or checking for a port to be up using a null resource?

答:
Your managers and workers both use template_cloudinit_config. They also have ec2:CreateTags.

You can use an EC2 resource tag like trajano/terraform-docker-swarm-aws/cloudinit-complete to indicate that the cloudinit has finished.

You could add this final part to each to invoke a tagging script:

part {
    filename     = "tag_complete.sh"
    content      = local.tag_complete_script
    content_type = "text/x-shellscript"
  }

And declare tag_complete_script be the following:

```<code>locals {
  tag_complete_script = <<-EOF
  #!/bin/bash
  instance_id="${TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
&& curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/instance-id}"
  aws ec2 create-tags --resources "$instance_id" --tags 'Key=trajano/terraform-docker-swarm-aws/cloudinit-complete,Value=true'
  EOF
}
</code>```

Then with a null_resource, you wait for the tag to appear (wrote this on my phone, so use it for a general idea, but I don't expect that it will work without testing and edits):

```<code>resource "null_resource" "wait_for_cloudinit" {
  provisioner "local-exec" {
    command = <<-EOF
    #!/bin/bash
    poll_tags="aws ec2 describe-tags --filters 'Name=resource-id,Values=${join(",", aws_instance.managers[*].id)}' 'Name=key,Values=trajano/terraform-docker-swarm-aws/cloudinit-complete' --output text --query 'Tags[*].Value'"
    expected='${join(",", formatlist("true", aws_instance.managers[*].id))}'
    $tags="$($poll_tags)"
    while [[ "$tags" != "$expected" ]] ; do
      $tags="$($poll_tags)"
    done
    EOF
  }
}
</code>```

This way you can have dependencies on null_resource.wait_for_cloudinit on any resources that need to run after cloudinit has completed.

Body:
Your managers and workers both use template_cloudinit_config. They also have ec2:CreateTags.

You can use an EC2 resource tag like trajano/terraform-docker-swarm-aws/cloudinit-complete to indicate that the cloudinit has finished.

You could add this final part to each to invoke a tagging script:

part {
    filename     = "tag_complete.sh"
    content      = local.tag_complete_script
    content_type = "text/x-shellscript"
  }

And declare tag_complete_script be the following:

locals {
  tag_complete_script = <<-EOF
  #!/bin/bash
  instance_id="${TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
&& curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/instance-id}"
  aws ec2 create-tags --resources "$instance_id" --tags 'Key=trajano/terraform-docker-swarm-aws/cloudinit-complete,Value=true'
  EOF
}

Then with a null_resource, you wait for the tag to appear (wrote this on my phone, so use it for a general idea, but I don't expect that it will work without testing and edits):

resource "null_resource" "wait_for_cloudinit" {
  provisioner "local-exec" {
    command = <<-EOF
    #!/bin/bash
    poll_tags="aws ec2 describe-tags --filters 'Name=resource-id,Values=${join(",", aws_instance.managers[*].id)}' 'Name=key,Values=trajano/terraform-docker-swarm-aws/cloudinit-complete' --output text --query 'Tags[*].Value'"
    expected='${join(",", formatlist("true", aws_instance.managers[*].id))}'
    $tags="$($poll_tags)"
    while [[ "$tags" != "$expected" ]] ; do
      $tags="$($poll_tags)"
    done
    EOF
  }
}

This way you can have dependencies on null_resource.wait_for_cloudinit on any resources that need to run after cloudinit has completed.