问:
I cannot take a value from EditText and work with that value
I can't solve the following problem for hours.
I try to get user-entered values from EditText so I can work with them.

```<code>public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
        Pattern.compile("^" + "(?=.*[0-9])" +
                "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");

public EditText editPrijmeni, editJmeno, editEmail, editPwd, editPwd2;

public String Mess = null;

public String jmeno, prijmeni, email, heslo, heslo2;
 Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_registrace);

    TextView login = (TextView) findViewById(R.id.lnkLogin);
    login.setMovementMethod(LinkMovementMethod.getInstance());
    login.setOnClickListener(this);

    editJmeno = (EditText) findViewById(R.id.txtJmeno);
    jmeno = editJmeno.getText().toString().trim();

    editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
    prijmeni = editPrijmeni.getEditableText().toString().trim();

    editEmail = (EditText) findViewById(R.id.txtEmail);
    email = editEmail.getEditableText().toString().trim();

    editPwd = (EditText) findViewById(R.id.txtPassword);
    heslo = editPwd.getEditableText().toString().trim();

    editPwd2 = (EditText) findViewById(R.id.txtPassword2);
    heslo2 = editPwd2.getEditableText().toString().trim();

    btn = (Button) findViewById(R.id.btnRegistrace);
    btn.setOnClickListener(this);

}

public boolean validujPrijmeni() {
     if(prijmeni.isEmpty()) {
         Mess = "Příjmení" + "\n";
         return false;

     } else {
         return true;
     }

}

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.lnkLogin:
            Intent intent = new Intent(Registrace.this, Login.class);
            startActivity(intent);
            break;
        case R.id.btnRegistrace:
            Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

            if(!prijmeni.isEmpty()) {
                Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
            }
            break;
    }

}
}
</code>```

To make sure EditText values are stored correctly, I try to display them using Toast text.
But after filling in the value and pressing the button I still get the "else" block from the if statement for an empty EditText from the "switch". I'm not sure if the constructor declaration should be in the onCreate body or outside.
Could anyone help me please ???
Thank you very much.

Here is layout.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">

<TextView
    android:id="@+id/loginscrn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:text="Registrace"
    android:textSize="20dp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/fstTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Příjmení" />
<EditText
    android:id="@+id/txtPrijmeni"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/secTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Jméno"/>
<EditText
    android:id="@+id/txtJmeno"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10"/>
<TextView
    android:id="@+id/thirdTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/fourTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />

<TextView
    android:id="@+id/fiveTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo, znova pro kontrolu"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />
<Button
    android:id="@+id/btnRegistrace"
    android:onClick="Registrace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:text="Registrovat" />
<TextView android:id="@+id/lnkLogin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dp"
    android:text="Jste již registrován?? Přihlaste se zde."
    android:gravity="center"
    android:textSize="20dp"
    android:textColor="#3F51B5"
    android:onClick="test"/>
</code>```

答:
you are getting values from edittext in on create.it's actually wrong cause in that time those edittexts are empty.the correct action is to get text from edittext in on click of register button

before

```<code>case R.id.btnRegistrace:
        Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

        if(!prijmeni.isEmpty()) {
            Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
        }
        break;
</code>```

after

```<code>case R.id.btnRegistrace:
        Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

        if(!editJmeno.getText().toString().isEmpty()) {
            Toast.makeText(this, editJmeno.getText().toString(), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
        }
        break;
</code>```

Body:
I can't solve the following problem for hours.
I try to get user-entered values from EditText so I can work with them.

public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
        Pattern.compile("^" + "(?=.*[0-9])" +
                "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");

public EditText editPrijmeni, editJmeno, editEmail, editPwd, editPwd2;

public String Mess = null;

public String jmeno, prijmeni, email, heslo, heslo2;
 Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_registrace);

    TextView login = (TextView) findViewById(R.id.lnkLogin);
    login.setMovementMethod(LinkMovementMethod.getInstance());
    login.setOnClickListener(this);

    editJmeno = (EditText) findViewById(R.id.txtJmeno);
    jmeno = editJmeno.getText().toString().trim();

    editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
    prijmeni = editPrijmeni.getEditableText().toString().trim();

    editEmail = (EditText) findViewById(R.id.txtEmail);
    email = editEmail.getEditableText().toString().trim();

    editPwd = (EditText) findViewById(R.id.txtPassword);
    heslo = editPwd.getEditableText().toString().trim();

    editPwd2 = (EditText) findViewById(R.id.txtPassword2);
    heslo2 = editPwd2.getEditableText().toString().trim();

    btn = (Button) findViewById(R.id.btnRegistrace);
    btn.setOnClickListener(this);

}

public boolean validujPrijmeni() {
     if(prijmeni.isEmpty()) {
         Mess = "Příjmení" + "\n";
         return false;

     } else {
         return true;
     }

}

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.lnkLogin:
            Intent intent = new Intent(Registrace.this, Login.class);
            startActivity(intent);
            break;
        case R.id.btnRegistrace:
            Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

            if(!prijmeni.isEmpty()) {
                Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
            }
            break;
    }

}
}

To make sure EditText values are stored correctly, I try to display them using Toast text.
But after filling in the value and pressing the button I still get the "else" block from the if statement for an empty EditText from the "switch". I'm not sure if the constructor declaration should be in the onCreate body or outside.
Could anyone help me please ???
Thank you very much.

Here is layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">

<TextView
    android:id="@+id/loginscrn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:text="Registrace"
    android:textSize="20dp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/fstTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Příjmení" />
<EditText
    android:id="@+id/txtPrijmeni"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/secTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:layout_marginTop="15dp"
    android:text="Jméno"/>
<EditText
    android:id="@+id/txtJmeno"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10"/>
<TextView
    android:id="@+id/thirdTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:ems="10" />
<TextView
    android:id="@+id/fourTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />

<TextView
    android:id="@+id/fiveTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Heslo, znova pro kontrolu"
    android:layout_marginLeft="100dp" />
<EditText
    android:id="@+id/txtPassword2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:inputType="textPassword"
    android:ems="10" />
<Button
    android:id="@+id/btnRegistrace"
    android:onClick="Registrace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="100dp"
    android:text="Registrovat" />
<TextView android:id="@+id/lnkLogin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dp"
    android:text="Jste již registrován?? Přihlaste se zde."
    android:gravity="center"
    android:textSize="20dp"
    android:textColor="#3F51B5"
    android:onClick="test"/>

Body:
you are getting values from edittext in on create.it's actually wrong cause in that time those edittexts are empty.the correct action is to get text from edittext in on click of register button

before

case R.id.btnRegistrace:
        Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

        if(!prijmeni.isEmpty()) {
            Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
        }
        break;

after

case R.id.btnRegistrace:
        Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();

        if(!editJmeno.getText().toString().isEmpty()) {
            Toast.makeText(this, editJmeno.getText().toString(), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
        }
        break;


来源: stackexchange

问:
Blazor Hosted (ASP.NET) HTTP Error 500.19 - Internal Server Error
From what I understand this error occurs when the web.config is not configured properly. However when I publish the app the following web.config gets generated

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\Lotus.Server.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: 85a43eb6-3576-401d-b025-a15a2cc377b6-->
</code>```

I first thought of installing URL Rewrite, this did not solve the problem. I am stressing out have tried almost everything any ideas on how to resolve it?

The error page looks like this:

答:
I had this same problem and I was trying to fix it for 4 days. Then I found the solution.

Firstly you need to download dotnet hosting

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/hosting-bundle?view=aspnetcore-7.0#direct-download-current-version

Then after instalation try to restart IIS with cmd (run as admin and then write iisreset).
If error page has changed we are going in good direction :)

Now it should say that you are using wrong module (which indeed is true).

Open IIS, get to your website and check installed modules. On list you should be able to see AspNetCoreModule but not AspNetCoreModuleV2.

go to:
%ProgramFiles%\IIS\Asp.Net Core Module\V2

and copy aspnetcorev2.dll

Then go into %SystemRoot%\system32\inetsrv\ and paste it

Now after this, open config folder in %SystemRoot%\system32\inetsrv\ and then open applicationHost.

IMPORTANT
At this stage you need to turn off your iis

Now find this line:

```<code><add name="AspNetCoreModule" image="%SystemRoot%\system32\inetsrv\aspnetcore.dll" />
</code>```

and add under it:

```<code><add name="AspNetCoreModuleV2" image="%SystemRoot%\system32\inetsrv\aspnetcorev2.dll" />
</code>```

And this same goes with this one:

```<code><add name="AspNetCoreModule" />
</code>```

add under it:

```<code><add name="AspNetCoreModuleV2" />
</code>```

Now save it, overwrite old one, and enable IIS. Go to your website, check modules and at the list you should be able to see AspNetCoreModuleV2:

[AspNetCoreModule and AspNetCoreModuleV2 on list][1]
[1]: https://i.stack.imgur.com/jC0JC.png

ContentLicense: CC BY-SA 4.0

Body:
From what I understand this error occurs when the web.config is not configured properly. However when I publish the app the following web.config gets generated

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\Lotus.Server.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

I first thought of installing URL Rewrite, this did not solve the problem. I am stressing out have tried almost everything any ideas on how to resolve it?

The error page looks like this:

Body:
I had this same problem and I was trying to fix it for 4 days. Then I found the solution.

Firstly you need to download dotnet hosting

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/hosting-bundle?view=aspnetcore-7.0#direct-download-current-version

Then after instalation try to restart IIS with cmd (run as admin and then write iisreset).
If error page has changed we are going in good direction :)

Now it should say that you are using wrong module (which indeed is true).

Open IIS, get to your website and check installed modules. On list you should be able to see AspNetCoreModule but not AspNetCoreModuleV2.

go to:
%ProgramFiles%\IIS\Asp.Net Core Module\V2

and copy aspnetcorev2.dll

Then go into %SystemRoot%\system32\inetsrv\ and paste it

Now after this, open config folder in %SystemRoot%\system32\inetsrv\ and then open applicationHost.

IMPORTANT
At this stage you need to turn off your iis

Now find this line:

<add name="AspNetCoreModule" image="%SystemRoot%\system32\inetsrv\aspnetcore.dll" />

and add under it:

<add name="AspNetCoreModuleV2" image="%SystemRoot%\system32\inetsrv\aspnetcorev2.dll" />

And this same goes with this one:

<add name="AspNetCoreModule" />

add under it:

<add name="AspNetCoreModuleV2" />

Now save it, overwrite old one, and enable IIS. Go to your website, check modules and at the list you should be able to see AspNetCoreModuleV2:

[AspNetCoreModule and AspNetCoreModuleV2 on list][1]
[1]: https://i.stack.imgur.com/jC0JC.png


问:
leveldb semantic error, continuously receiving errors from podfiles
I was trying to run my application in the simulator and all of a sudden I receive an error from leveldb-library podfile that I think I never touched.

The error comes from a line of code inside the file and says  No member named 'NoBarrier_Store' in 'std::__1::atomic<unsigned long>'
I don't know what to do here since I don't think to have touched any of this podfile ever.
the only thing that I've done and maybe has something to do with this errors is installing a deprecated library. It's called ImagePicker and maybe that installation had some interference with the other podFiles. But apart from that I don't think to have done anything influential.

Depending on when I run I receive some other errors from other podfiles such as Lottie-ios and nanopb that I cannot understand.

I don't know what to do now, I've already tried to pod install all the pods from terminal but nothing changed...
Thanks to anyone that can help.

答:
Open Terminal for your project location and use these below commands:-

```<code>step 1:- open podfile
step 2:- copy your all pods and remove all pods and save the file
step 3:- pod install
step 4:- open podfile
step 5:- paste your all pods again and save the file
step 6:- pod install
step 7:- exit
</code>```

It will solve your problem :) .

Body:
Open Terminal for your project location and use these below commands:-

step 1:- open podfile
step 2:- copy your all pods and remove all pods and save the file
step 3:- pod install
step 4:- open podfile
step 5:- paste your all pods again and save the file
step 6:- pod install
step 7:- exit

It will solve your problem :) .


问:
Editing an existing List<String> item
i want to edit list , but i dont know how can i achieve it.

i have pasted my code below

```<code>Container(
              child: ListView.builder(

                  itemCount: filterList.length,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int intex) {
                  //  return MenuList(filterList[intex]);

                    return Container
                      (
                      height:75,
                      //color: Colors.blue,
                      child: Card(
                        elevation: 1.0,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(3.0)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                              child: Row(
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.only(left:8.0),
                                    child: Container(
                                      child: Image(image:AssetImage("images/beef_burger.jpg"),
                                        width: 70,height: 50,),
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Container(
                                      child: Column(

                                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[

                                          Container(
                                            width: MediaQuery.of(context).size.width/2.2,
                                            //  color: Colors.blue,
                                            child: Text(filterList[intex].itemName,maxLines: 1,),
                                          ),
                                          Container(
                                            child: Text("AED ${filterList[intex].itemPrice}",style: TextStyle(color: Colors.grey),),
                                          ),
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),

                            Container(
                              // color: Colors.red,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,

                                children: <Widget>[
                                  Container(
                                    width: 50,
                                    height: 50,
                                    // color: Colors.blue,
                                    child: FlatButton(onPressed: (){

                                      if(filterList[intex].counter > 0){
                                        setState(() {
                                          filterList[intex].counter--;
                                        });

                                      }

                                    }, child: Image(image: AssetImage("images/minus.png"),width: 20,height: 20,),),
                                  ),
                                  Container(
                                    child: Text("${filterList[intex].counter}"),
                                  ),
                                  Container(
                                    width: 50,
                                    height: 50,
                                    //  color: Colors.green,
                                    child: FlatButton(onPressed: () async{

                                      setState(() {
                                        filterList[intex].counter++;
                                      });

                                      cartItemList.add({"itemObj":filterList[intex],"quantity":filterList[intex].counter});

                                      //  cartItemList = [{"index":widget.intex,"itemObj":widget.items,"quantity":_itemCount}];

                                      print(addedItems(cartItemList));

                                      final prefs = await SharedPreferences.getInstance();
                                      await prefs.setStringList('itemList', addedItems(cartItemList));

                                    }, child: Image(image: AssetImage("images/plus.png"),width: 20,height: 20,),),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),

                    );

                  }),
            ),
</code>```

i have converted list to list to store in shared preference

```<code>List<String> addedItems(List<dynamic> cartList){

 try {
  var res = cartList.map((v) =>
  json.encode(v)).toList();
  listNew = res;
   return res;
   } catch (err) {
   // Just in case
   return [];
   }
</code>```

when i add item to the cartlist i gets output as

added one item

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":1}]

added same item again

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":1}, {"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2}]

added different item

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":1}, {"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2}, {"itemObj":{"item_price":20.0,"item_name":"English Breakfast","item_img":" ","item_code":"002","item_discount":0.0,"item_id":71,"category_id":12},"quantity":1}]

but i want output as when i add same item again

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2}]

答:
List has no built in functionality to only add unique items.
You could use a map or check manually if the item already exist.

To check you can use the indexWhere method:
https://api.flutter.dev/flutter/dart-core/List/indexWhere.html

Title: Editing an existing List<String> item

Body:
i want to edit list , but i dont know how can i achieve it.

i have pasted my code below

Container(
              child: ListView.builder(

                  itemCount: filterList.length,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int intex) {
                  //  return MenuList(filterList[intex]);

                    return Container
                      (
                      height:75,
                      //color: Colors.blue,
                      child: Card(
                        elevation: 1.0,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(3.0)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                              child: Row(
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.only(left:8.0),
                                    child: Container(
                                      child: Image(image:AssetImage("images/beef_burger.jpg"),
                                        width: 70,height: 50,),
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Container(
                                      child: Column(

                                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[

                                          Container(
                                            width: MediaQuery.of(context).size.width/2.2,
                                            //  color: Colors.blue,
                                            child: Text(filterList[intex].itemName,maxLines: 1,),
                                          ),
                                          Container(
                                            child: Text("AED ${filterList[intex].itemPrice}",style: TextStyle(color: Colors.grey),),
                                          ),
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ),

                            Container(
                              // color: Colors.red,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,

                                children: <Widget>[
                                  Container(
                                    width: 50,
                                    height: 50,
                                    // color: Colors.blue,
                                    child: FlatButton(onPressed: (){

                                      if(filterList[intex].counter > 0){
                                        setState(() {
                                          filterList[intex].counter--;
                                        });

                                      }

                                    }, child: Image(image: AssetImage("images/minus.png"),width: 20,height: 20,),),
                                  ),
                                  Container(
                                    child: Text("${filterList[intex].counter}"),
                                  ),
                                  Container(
                                    width: 50,
                                    height: 50,
                                    //  color: Colors.green,
                                    child: FlatButton(onPressed: () async{

                                      setState(() {
                                        filterList[intex].counter++;
                                      });

                                      cartItemList.add({"itemObj":filterList[intex],"quantity":filterList[intex].counter});

                                      //  cartItemList = [{"index":widget.intex,"itemObj":widget.items,"quantity":_itemCount}];

                                      print(addedItems(cartItemList));

                                      final prefs = await SharedPreferences.getInstance();
                                      await prefs.setStringList('itemList', addedItems(cartItemList));

                                    }, child: Image(image: AssetImage("images/plus.png"),width: 20,height: 20,),),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),

                    );

                  }),
            ),

i have converted list to list to store in shared preference

List<String> addedItems(List<dynamic> cartList){

 try {
  var res = cartList.map((v) =>
  json.encode(v)).toList();
  listNew = res;
   return res;
   } catch (err) {
   // Just in case
   return [];
   }

when i add item to the cartlist i gets output as

added one item

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":1}]

added same item again

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":1}, {"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2}]

added different item

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":1}, {"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2}, {"itemObj":{"item_price":20.0,"item_name":"English Breakfast","item_img":" ","item_code":"002","item_discount":0.0,"item_id":71,"category_id":12},"quantity":1}]

but i want output as when i add same item again

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2}]


问:
Java wildcard strange behaviour when class is generic
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

```<code>package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}
</code>```

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

```<code>public class Test<T> {
...
}
</code>```

,

```<code>Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog
</code>```

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

答:
If you add <T> to your Test class and then populate the generic with something the compile error will return

```<code>new Test<String>().test(mammalList);
</code>```

My guess is that because Test generic was not defined, the compiler decides it doesn't have enough information to check anything beyond that level.

ContentLicense: CC BY-SA 3.0

Body:
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

public class Test<T> {
...
}

,

Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

Body:
If you add <T> to your Test class and then populate the generic with something the compile error will return

new Test<String>().test(mammalList);

My guess is that because Test generic was not defined, the compiler decides it doesn't have enough information to check anything beyond that level.


问:
React Js can't Run using npm start
I want to run my project, but  npm start error -_-</p>

```<code>npm ERR! errno 1
npm ERR! breednder-project@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the breednder-project@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/aziz/.npm/_logs/2020-02-15T09_11_32_000Z-debug.log```
</code>```

答:
Did you try recovering your dependencies?
run npm install

and make sure from Node and npm version at least
npm more than 6 and node more than 10

```<code>npm -v
node -v
</code>```

and finally, try to delete the node_modules and package-lock
and do npm i again

Title: React Js can't Run using npm start

Body:
I want to run my project, but  npm start error -_-

npm ERR! errno 1
npm ERR! breednder-project@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the breednder-project@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/aziz/.npm/_logs/2020-02-15T09_11_32_000Z-debug.log```

Body:
Did you try recovering your dependencies?
run npm install

and make sure from Node and npm version at least
npm more than 6 and node more than 10

npm -v
node -v

and finally, try to delete the node_modules and package-lock
and do npm i again


问:
NSTableView toolTipFor cell - How to display tooltips for cells?
I have a view-based TableView, the delegate Outlet of the TableView is set to my ViewController. My ViewController implements the NSTableViewDelegate protocol and has the method toopTipFor cell method implemented.
However, If I hover the mouse over any cell, no tooltip is displayed and the method is not even called.

I have created a small sample XCode project, you can download it here:
https://ranger81.de/_sub/temp/ToolTipTest.zip

Here is a code snippet:

Thank you very much!

答: tableView(_:toolTipFor:rect:tableColumn:row:mouseLocation:) is only valid for NSCell-based table views. Implement the tooltip in the cell view or its subviews.


问:
what is my mistake in the code and why is that error for?
So basically I have to write a code which tells the user to input numbers (as variables I named them number1, number2, number3 ...) until I get the answer of zero once you add each number that they inputted then which the sum is equal to zero I should print how many numbers they inputted so the answer they got was zero, now the main thing is that I know how to write that code but there is an error that I get:</p>

```<code>Traceback (most recent call last):
      File "Solution.py", line 13, in <module>
    sys.exit()
    NameError: name 'sys' is not defined
</code>```

答:
Maybe try using

from sys import *

and just use exit(0) when you want to sys.exit()

Body:
So basically I have to write a code which tells the user to input numbers (as variables I named them number1, number2, number3 ...) until I get the answer of zero once you add each number that they inputted then which the sum is equal to zero I should print how many numbers they inputted so the answer they got was zero, now the main thing is that I know how to write that code but there is an error that I get:

Traceback (most recent call last):
      File "Solution.py", line 13, in <module>
    sys.exit()
    NameError: name 'sys' is not defined


问:
Python iterate over all possible combinations on boolean variables
I have 6 booleas variables in a dict and I want to run my code on all all their possible iteration.
so I have:

```<code>params["is_A"] = True/False
params["is_B"] = True/False
...
</code>```

and then for all possible combinations, I want to call

```<code>my_func(params)
</code>```

What is the best way to do so?

答:
itertools.product can generate all the combinations:

```<code>import itertools

names = 'is_A is_B is_C is_D is_E is_F'.split()

def my_func(params):
    print(params)

for p in itertools.product([True,False],repeat=6):
    params = dict(zip(names,p))
    my_func(params)
</code>```

Output:

```<code>{'is_A': True, 'is_B': True, 'is_C': True, 'is_D': True, 'is_E': True, 'is_F': True}
{'is_A': True, 'is_B': True, 'is_C': True, 'is_D': True, 'is_E': True, 'is_F': False}
...
{'is_A': False, 'is_B': False, 'is_C': False, 'is_D': False, 'is_E': False, 'is_F': True}
{'is_A': False, 'is_B': False, 'is_C': False, 'is_D': False, 'is_E': False, 'is_F': False}
</code>```

Body:
I have 6 booleas variables in a dict and I want to run my code on all all their possible iteration.
so I have:

params["is_A"] = True/False
params["is_B"] = True/False
...

and then for all possible combinations, I want to call

my_func(params)

What is the best way to do so?

Body:
itertools.product can generate all the combinations:

import itertools

names = 'is_A is_B is_C is_D is_E is_F'.split()

def my_func(params):
    print(params)

for p in itertools.product([True,False],repeat=6):
    params = dict(zip(names,p))
    my_func(params)

Output:

{'is_A': True, 'is_B': True, 'is_C': True, 'is_D': True, 'is_E': True, 'is_F': True}
{'is_A': True, 'is_B': True, 'is_C': True, 'is_D': True, 'is_E': True, 'is_F': False}
...
{'is_A': False, 'is_B': False, 'is_C': False, 'is_D': False, 'is_E': False, 'is_F': True}
{'is_A': False, 'is_B': False, 'is_C': False, 'is_D': False, 'is_E': False, 'is_F': False}


问:
How to run ktor application?
I've created a Ktor application with Gradle and I followed the tutorial on https://ktor.io/quickstart/quickstart/gradle.html#initial.

At the end it says:

And then go to Run -> Edit Configurations select the blog.BlogAppKt
  configuration and change its Main class to:
  io.ktor.server.netty.EngineMain

Now when we run the new configuration, the application will start
  again.

I am searching for the option but could not find it:

The gradle file looks as follows:

```<code>plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "org.example"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}
</code>```

Update

I'v tried following configuration:

But as you can, there is a error message.

What do I have to add to run the Ktor app?

答: It might be easier if you install the Ktor plugin on intellij. That's the first thing I do usually when starting a Ktor project. </p>

Title: How to run ktor application?

Body:
I've created a Ktor application with Gradle and I followed the tutorial on https://ktor.io/quickstart/quickstart/gradle.html#initial.

At the end it says:

And then go to Run -> Edit Configurations select the blog.BlogAppKt
  configuration and change its Main class to:
  io.ktor.server.netty.EngineMain

Now when we run the new configuration, the application will start
  again.

I am searching for the option but could not find it:

The gradle file looks as follows:

plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "org.example"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}

Update

I'v tried following configuration:

But as you can, there is a error message.

What do I have to add to run the Ktor app?


问:
How to change two variables at the same time in flutter?

Goal:

I am trying to create list of items which have a counter to decrement or increase, and at the same time a total is shown with the final price.

Problem:

The problem is that both variables cannot be changed at the same time because they are a setState and I don't know how to do it asynchronously.

I also don't know how to convert this class to a widget that can be called normal to build the list.

```<code>class FlutterExample extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return new Scaffold(
     body: new ListView(
       children: new List.generate(5, (i)=>new ListTileItem(
         title: "Item#$i",
       )),
     ),
   );
 }

}
class ListTileItem extends StatefulWidget {
final  String title;
 ListTileItem({this.title});
 @override
 _ListTileItemState createState() => new _ListTileItemState();
}

class _ListTileItemState extends State<ListTileItem> {
 int _itemCount = 0;
 @override
 Widget build(BuildContext context) {
   return new Container(

     child: new Row(
       children: <Widget>[
          IconButton(icon: new Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--),),
           new Text(_itemCount.toString()),
           new IconButton(icon: new Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++))
       ],
     ),
   );
 }
}

</code>```

答:
As Darish says, the Widget which holding the state is supposed to be the Parent, in this case Flutter Example. It needs to provide ListTileItem with functions that change the state of the variables.

I made a quick change with your code. You can try it on DartPad

Snippet:

```<code>class FlutterExample extends StatefulWidget {
  @override
  _FlutterExampleState createState() => _FlutterExampleState();
}

class _FlutterExampleState extends State<FlutterExample> {
  int total = 0;
  List<int> individualCount = [];
  List<String> individualTitle = [];

  @override
  void initState() {
    List.generate(5, (i) {
      individualCount.add(0);
      individualTitle.add('item ${i + 1}');
    });
    super.initState();
  }

  void increment(int index) {
    setState(() {
      individualCount[index]++;
      total++;
    });
  }

  void decrement(int index) {
    setState(() {
      individualCount[index]--;
      total--;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 120,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Text('total: $total', style: TextStyle(fontSize: 24)),
          SizedBox(height: 24),
          Expanded(
            child: ListView.builder(
              itemCount: individualCount.length,
              itemBuilder: (context, index) {
                return ListTileItem(
                  title: individualTitle[index],
                  count: individualCount[index],
                  decrement: () => decrement(index),
                  increment: () => increment(index),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class ListTileItem extends StatelessWidget {
  final String title;
  final int count;
  final Function decrement;
  final Function increment;

  ListTileItem({this.title, this.count, this.decrement, this.increment});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('$title'),
        Row(
          children: <Widget>[
            IconButton(
              icon: Icon(Icons.remove),
              onPressed: decrement,
            ),
            Text('$count'),
            IconButton(
              icon: Icon(Icons.add),
              onPressed: increment,
            )
          ],
        ),
      ],
    );
  }
}
</code>```

Body:
Goal:

I am trying to create list of items which have a counter to decrement or increase, and at the same time a total is shown with the final price.

Problem:

The problem is that both variables cannot be changed at the same time because they are a setState and I don't know how to do it asynchronously.

I also don't know how to convert this class to a widget that can be called normal to build the list.

class FlutterExample extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return new Scaffold(
     body: new ListView(
       children: new List.generate(5, (i)=>new ListTileItem(
         title: "Item#$i",
       )),
     ),
   );
 }

}
class ListTileItem extends StatefulWidget {
final  String title;
 ListTileItem({this.title});
 @override
 _ListTileItemState createState() => new _ListTileItemState();
}

class _ListTileItemState extends State<ListTileItem> {
 int _itemCount = 0;
 @override
 Widget build(BuildContext context) {
   return new Container(

     child: new Row(
       children: <Widget>[
          IconButton(icon: new Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--),),
           new Text(_itemCount.toString()),
           new IconButton(icon: new Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++))
       ],
     ),
   );
 }
}

Body:
As Darish says, the Widget which holding the state is supposed to be the Parent, in this case Flutter Example. It needs to provide ListTileItem with functions that change the state of the variables.

I made a quick change with your code. You can try it on DartPad

Snippet:

class FlutterExample extends StatefulWidget {
  @override
  _FlutterExampleState createState() => _FlutterExampleState();
}

class _FlutterExampleState extends State<FlutterExample> {
  int total = 0;
  List<int> individualCount = [];
  List<String> individualTitle = [];

  @override
  void initState() {
    List.generate(5, (i) {
      individualCount.add(0);
      individualTitle.add('item ${i + 1}');
    });
    super.initState();
  }

  void increment(int index) {
    setState(() {
      individualCount[index]++;
      total++;
    });
  }

  void decrement(int index) {
    setState(() {
      individualCount[index]--;
      total--;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 120,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Text('total: $total', style: TextStyle(fontSize: 24)),
          SizedBox(height: 24),
          Expanded(
            child: ListView.builder(
              itemCount: individualCount.length,
              itemBuilder: (context, index) {
                return ListTileItem(
                  title: individualTitle[index],
                  count: individualCount[index],
                  decrement: () => decrement(index),
                  increment: () => increment(index),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class ListTileItem extends StatelessWidget {
  final String title;
  final int count;
  final Function decrement;
  final Function increment;

  ListTileItem({this.title, this.count, this.decrement, this.increment});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('$title'),
        Row(
          children: <Widget>[
            IconButton(
              icon: Icon(Icons.remove),
              onPressed: decrement,
            ),
            Text('$count'),
            IconButton(
              icon: Icon(Icons.add),
              onPressed: increment,
            )
          ],
        ),
      ],
    );
  }
}


问:
Safari Extension Invalid Code Signature Identifier
Facts:

I am trying to upload an app to the app store.

I am deploying via xcode archive distribution

I have setup an app appstoreconnect.apple.com

I have setup an ID on developer.apple.com

When I try to deploy and it getting signed I get this error

```<code>App Store Connect Operation Error
ERROR ITMS-90334: “Invalid Code Signature Identifier. The identifier “my_app_id-55554333a757b7473a4b4s7f65bd545a78w88836” in your code signature for “My App Name” must match its Bundle Identifier “my_app_id”
</code>```

55554333a757b7473a4b4s7f65bd545a78w88836 is just an example of what it looks like.  I have changed the real value because I'm not sure what it is

I have no idea where this number is coming from.  I have searched my xcode for it, nothing.

I declare my Bundle Identifier I very explicitly just just my_app_id. Why is this number being appended to the bundle id?

Help?

答: Try once with auto signing instead of manual signing.</p>

Body:
Facts:

I am trying to upload an app to the app store.

I am deploying via xcode archive distribution

I have setup an app appstoreconnect.apple.com

I have setup an ID on developer.apple.com

When I try to deploy and it getting signed I get this error

App Store Connect Operation Error
ERROR ITMS-90334: “Invalid Code Signature Identifier. The identifier “my_app_id-55554333a757b7473a4b4s7f65bd545a78w88836” in your code signature for “My App Name” must match its Bundle Identifier “my_app_id”

55554333a757b7473a4b4s7f65bd545a78w88836 is just an example of what it looks like.  I have changed the real value because I'm not sure what it is

I have no idea where this number is coming from.  I have searched my xcode for it, nothing.

I declare my Bundle Identifier I very explicitly just just my_app_id. Why is this number being appended to the bundle id?

Help?


问:
php, how to run a link when check box checked?
```<code><input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';
</code>```

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

```<code>if ($('#checket:checked').val() !== undefined) {
</code>```

// Insert code here.
}

答:
If you have more than one checkbox, put the URL in the value of the checkbox and add a class to all the checkboxes you want to do this:

```<code><input type="checkbox" name="checket" id="checket" class="checkedurl" value="<?=$url?>" />
<script type="text/javascript">
$(document).ready(function(){
   $('input.checkedurl').click(function() {
      if ($(this).is(':checked')) {
          var checkurl = $(this).val();
          var postvars = "url="+checkurl;
          $.ajax({
             url: "scripttostore.php",
             type: 'post',
             data: postvars,
             cache: false,
             success: function () {
                location.href = checkurl;
             }
          });
      }
});
</script>
</code>```

If it's all checkboxes on the page you don't have to use the class, you could just use $('input[type=checkbox]')

The scripttostore.php would be what you use to store the url information.

Body:
<input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

if ($('#checket:checked').val() !== undefined) {

// Insert code here.
}

Body:
If you have more than one checkbox, put the URL in the value of the checkbox and add a class to all the checkboxes you want to do this:

<input type="checkbox" name="checket" id="checket" class="checkedurl" value="<?=$url?>" />
<script type="text/javascript">
$(document).ready(function(){
   $('input.checkedurl').click(function() {
      if ($(this).is(':checked')) {
          var checkurl = $(this).val();
          var postvars = "url="+checkurl;
          $.ajax({
             url: "scripttostore.php",
             type: 'post',
             data: postvars,
             cache: false,
             success: function () {
                location.href = checkurl;
             }
          });
      }
});
</script>

If it's all checkboxes on the page you don't have to use the class, you could just use $('input[type=checkbox]')

The scripttostore.php would be what you use to store the url information.


问:
Pickle persistence file needs to be deleted for telegram bot to work
I am using the PicklePersistence example provided in python telegram bot github.

https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/persistentconversationbot.py

Sometimes the bot doesn't /start. After troubleshooting, I discovered that the problem is caused by the pickle persistence file. To get /start to work, I had to delete persistence file. It seems the persistence file is corrupted.

What can be done to make the pickle persistence file more robust against corruption?

I am using python telegram bot 12.4.2 and python v3.7

答:
I will answer my own question.

The reason /start cannot be reentered is due to the state machine of the bot. Because persistence was turned on, this state is always remembered even after the bot is shut down and restarted.

The solution to fix my problem was to set allow_reentry to True. Verified to work in my case.

https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.conversationhandler.html


问:
kubernetes pods http: TLS handshake error from x.x.x.x:38676: EOF
When starting cert-manager I get the following message

TLS handshake error from 10.42.152.128:38676: EOF

```<code>$ kubectl -n cert-manager logs cert-manager-webhook-8575f88c85-l4tlw
I0214 19:41:28.147106       1 main.go:64]  "msg"="enabling TLS as certificate file flags specified"
I0214 19:41:28.147365       1 server.go:126]  "msg"="listening for insecure healthz connections"  "address"=":6080"
I0214 19:41:28.147418       1 server.go:138]  "msg"="listening for secure connections"  "address"=":10250"
I0214 19:41:28.147437       1 server.go:155]  "msg"="registered pprof handlers"
I0214 19:41:28.147570       1 tls_file_source.go:144]  "msg"="detected private key or certificate data on disk has changed. reloading certificate"
2020/02/14 19:43:32 http: TLS handshake error from 10.42.152.128:38676: EOF
</code>```

Interestingly there is not pod with that IP

```<code>$ kubectl get pod -o wide --all-namespaces | grep 128
cert-manager    cert-manager-webhook-8575f88c85-l4tlw             1/1     Running     0          4m56s   10.42.112.128   node002   <none>           <none>
</code>```

Similar error on the cert-manager pod

```<code>E0214 19:38:22.540589       1 controller.go:131] cert-manager/controller/ingress-shim "msg"="re-queuing item  due to error processing" "error"="Internal error occurred: failed calling webhook \"webhook.cert-manager.io\": Post https://cert-manager-webhook.cert-manager.svc:443/mutate?timeout=30s: net/http: TLS handshake timeout" "key"="kube-system/dashboard-kubernetes-dashboard"
</code>```

I have two ClusterIssuer

```<code>kubectl get ClusterIssuer --namespace cert-manager
NAME              READY   AGE
letsencrypt-prd   True    42d
letsencrypt-stg   True    42d
</code>```

But no certificate yet:

```<code>kubectl get certificate --all-namespaces
No resources found
</code>```

When I try to request a certificate I get the same error

```<code>kubectl apply -f mycert.yml
Error from server (InternalError): error when creating "cert-wyssmann-dev.yml": Internal error occurred: failed calling webhook "webhook.cert-manager.io": Post https://cert-manager-webhook.cert-manager.svc:443/mutate?timeout=30s: net/http: TLS handshake timeout
</code>```

I am not sure how exactly can I get to the bottom of the problem. I ran sonobouy to see if this helps me, however test failed on 2 of my 3 nodes.

```<code>Plugin: e2e
Status: failed
Total: 1
Passed: 0
Failed: 1
Skipped: 0

Failed tests:
Container e2e is in a terminated state (exit code 1) due to reason: Error:

Plugin: systemd-logs
Status: failed
Total: 3
Passed: 1
Failed: 2
Skipped: 0

Failed tests:
timeout waiting for results
</code>```

For the failing nodes I can see this in the sonobouy logs

```<code>E0214 19:38:22.540589       1 controller.go:131] cert-manager/controller/ingress-shim "msg"="re-queuing item  due to error processing" "error"="Internal error occurred: failed calling webhook \"webhook.cert-manager.io\": Post https://cert-manager-webhook.cert-manager.svc:443/mutate?timeout=30s: net/http: TLS handshake timeout" "key"="kube-system/dashboard-kubernetes-dashboard"
</code>```

答: If you really don't need the webhook then one quick way to solve this is to disable the webhook as per documentation </p>

Body:
When starting cert-manager I get the following message

TLS handshake error from 10.42.152.128:38676: EOF

$ kubectl -n cert-manager logs cert-manager-webhook-8575f88c85-l4tlw
I0214 19:41:28.147106       1 main.go:64]  "msg"="enabling TLS as certificate file flags specified"
I0214 19:41:28.147365       1 server.go:126]  "msg"="listening for insecure healthz connections"  "address"=":6080"
I0214 19:41:28.147418       1 server.go:138]  "msg"="listening for secure connections"  "address"=":10250"
I0214 19:41:28.147437       1 server.go:155]  "msg"="registered pprof handlers"
I0214 19:41:28.147570       1 tls_file_source.go:144]  "msg"="detected private key or certificate data on disk has changed. reloading certificate"
2020/02/14 19:43:32 http: TLS handshake error from 10.42.152.128:38676: EOF

Interestingly there is not pod with that IP

$ kubectl get pod -o wide --all-namespaces | grep 128
cert-manager    cert-manager-webhook-8575f88c85-l4tlw             1/1     Running     0          4m56s   10.42.112.128   node002   <none>           <none>

Similar error on the cert-manager pod

E0214 19:38:22.540589       1 controller.go:131] cert-manager/controller/ingress-shim "msg"="re-queuing item  due to error processing" "error"="Internal error occurred: failed calling webhook \"webhook.cert-manager.io\": Post https://cert-manager-webhook.cert-manager.svc:443/mutate?timeout=30s: net/http: TLS handshake timeout" "key"="kube-system/dashboard-kubernetes-dashboard"

I have two ClusterIssuer

kubectl get ClusterIssuer --namespace cert-manager
NAME              READY   AGE
letsencrypt-prd   True    42d
letsencrypt-stg   True    42d

But no certificate yet:

kubectl get certificate --all-namespaces
No resources found

When I try to request a certificate I get the same error

kubectl apply -f mycert.yml
Error from server (InternalError): error when creating "cert-wyssmann-dev.yml": Internal error occurred: failed calling webhook "webhook.cert-manager.io": Post https://cert-manager-webhook.cert-manager.svc:443/mutate?timeout=30s: net/http: TLS handshake timeout

I am not sure how exactly can I get to the bottom of the problem. I ran sonobouy to see if this helps me, however test failed on 2 of my 3 nodes.

Plugin: e2e
Status: failed
Total: 1
Passed: 0
Failed: 1
Skipped: 0

Failed tests:
Container e2e is in a terminated state (exit code 1) due to reason: Error:

Plugin: systemd-logs
Status: failed
Total: 3
Passed: 1
Failed: 2
Skipped: 0

Failed tests:
timeout waiting for results

For the failing nodes I can see this in the sonobouy logs

E0214 19:38:22.540589       1 controller.go:131] cert-manager/controller/ingress-shim "msg"="re-queuing item  due to error processing" "error"="Internal error occurred: failed calling webhook \"webhook.cert-manager.io\": Post https://cert-manager-webhook.cert-manager.svc:443/mutate?timeout=30s: net/http: TLS handshake timeout" "key"="kube-system/dashboard-kubernetes-dashboard"


问:
React - Substitute for `setState` Callback in Functional Components?
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

```<code>const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}
</code>```

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

答:
You can use useEffect hook to achieve this.

```<code>setOpenDoor(!openDoor);

useEffect(() => {
   // Here your next setState function
}, [openDoor]);
</code>```

For more information on hooks please check out https://reactjs.org/docs/hooks-effect.html

Body:
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

Body:
You can use useEffect hook to achieve this.

setOpenDoor(!openDoor);

useEffect(() => {
   // Here your next setState function
}, [openDoor]);

For more information on hooks please check out https://reactjs.org/docs/hooks-effect.html


问:
Can I decompile any game which is written in C# or any other language through java decompiler tool?
There are lots of game which are made using Unity 3d or unreal game engine. I am able to decompile an apk which is made from android studio but i don't know whether it works in those games because I don't even know from which software they had been made or which language they had been written.

Can I easily decompile them too using java decompilers or do I have to use any other method (I don't know any other method more than of java. If there is any, please tell).

By the way, and for detail, I want to decompile mad dex android game.

答:
A decompiler for Java decompiles JVM bytecode. It has no idea what CLR bytecode (the one used by C#) looks like.

So to answer your question: no, you can't use a decompiler made for Java to decompile something that is not meant to be run on a JVM. You'll have to find a decompiler for CLR bytecode.


问:
django_filters filtering by a field not working
I am trying to use django_filters to Filter a model based on a field.

these are the models :

```<code>class Provider(models.Model):
    name=models.CharField(max_length=100)
    lat=models.DecimalField(max_digits=9,decimal_places=6)
    lon=models.DecimalField(max_digits=9,decimal_places=6)
    address_line1=models.CharField(max_length=255)
    address_line2=models.CharField(max_length=255)
    user=models.ForeignKey(User,on_delete=models.CASCADE)

    class Meta:
        db_table='providers'

class Service(models.Model):
    name = models.CharField(max_length=50)
    provider=models.ForeignKey(Provider,on_delete=models.CASCADE)
    class Meta:
        db_table='services'
</code>```

I am using a ModelViewSet

```<code>class ServiceList(viewsets.ModelViewSet):

    queryset=Service.objects.all()
    serializer_class=ServiceSerilaizer
    filterset_class=ServiceFilter

</code>```

and here is my Filter class:

```<code>from django_filters import rest_framework as filters

class ServiceFilter(filters.FilterSet):
    provider=filters.NumberFilter(lookup_expr='iexact')
    class Meta:
        model=Service
        fields=["provider_id"]

</code>```

I have defined the URL like this in my urls.py

```<code>router_service = routers.DefaultRouter()
router_service.register("services", ServiceList, basename='services')

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^api/', include(router_service.urls)),
    path('api/auth/',include('djoser.urls')),
    path('api/auth/',include('djoser.urls.authtoken')),
]
</code>```

Now when I hit the URL: http://127.0.0.1:8000/api/services/?provider_id=1

I get all the services, not just the ones for provider_id=1.
Can anyone help? Am I missing something?

答:
You are probably missing:

```<code>DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", ),
</code>```

in your setting.py file

Alternatively, you can also set that in your viewset as follows:

```<code>class ServiceList(viewsets.ModelViewSet):

    queryset=Service.objects.all()
    serializer_class=ServiceSerilaizer
    filterset_class=ServiceFilter
    filter_backends = (filters.DjangoFilterBackend,)
</code>```

Body:
I am trying to use django_filters to Filter a model based on a field.

these are the models :

class Provider(models.Model):
    name=models.CharField(max_length=100)
    lat=models.DecimalField(max_digits=9,decimal_places=6)
    lon=models.DecimalField(max_digits=9,decimal_places=6)
    address_line1=models.CharField(max_length=255)
    address_line2=models.CharField(max_length=255)
    user=models.ForeignKey(User,on_delete=models.CASCADE)

    class Meta:
        db_table='providers'

class Service(models.Model):
    name = models.CharField(max_length=50)
    provider=models.ForeignKey(Provider,on_delete=models.CASCADE)
    class Meta:
        db_table='services'

I am using a ModelViewSet

class ServiceList(viewsets.ModelViewSet):

    queryset=Service.objects.all()
    serializer_class=ServiceSerilaizer
    filterset_class=ServiceFilter

and here is my Filter class:

from django_filters import rest_framework as filters

class ServiceFilter(filters.FilterSet):
    provider=filters.NumberFilter(lookup_expr='iexact')
    class Meta:
        model=Service
        fields=["provider_id"]

I have defined the URL like this in my urls.py

router_service = routers.DefaultRouter()
router_service.register("services", ServiceList, basename='services')

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^api/', include(router_service.urls)),
    path('api/auth/',include('djoser.urls')),
    path('api/auth/',include('djoser.urls.authtoken')),
]

Now when I hit the URL: http://127.0.0.1:8000/api/services/?provider_id=1

I get all the services, not just the ones for provider_id=1.
Can anyone help? Am I missing something?

Body:
You are probably missing:

DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", ),

in your setting.py file

Alternatively, you can also set that in your viewset as follows:

class ServiceList(viewsets.ModelViewSet):

    queryset=Service.objects.all()
    serializer_class=ServiceSerilaizer
    filterset_class=ServiceFilter
    filter_backends = (filters.DjangoFilterBackend,)


问:
Binding Button IsEnabled to StackPanel has Children
I'm wondering if I can bind my Button isEnabled to my StackPanel Children (has children). If the stackpanel has children, then my button is enabled, no children my button is disabled. Currently I just handle this in code, but I started wondering if this was something I could bind. Thanks for any thoughts...</p>

答:
Actually since you deal with a bool you can invert the logic and do it without converters:

```<code><StackPanel Name="sp" />
<Button Content="A Button">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=sp, Path=Children.Count}" Value="0">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

Using this you run into some problems in terms of getting updates since Children.Count is not a DP, you can use an ItemsControl though to get around that (it pretty much behaves like a StackPanel by default):

```<code><ItemsControl Name="ic" />
<Button Content="A Button">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=ic, Path=Items.Count}" Value="0">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

Body:
Actually since you deal with a bool you can invert the logic and do it without converters:

<StackPanel Name="sp" />
<Button Content="A Button">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=sp, Path=Children.Count}" Value="0">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Using this you run into some problems in terms of getting updates since Children.Count is not a DP, you can use an ItemsControl though to get around that (it pretty much behaves like a StackPanel by default):

<ItemsControl Name="ic" />
<Button Content="A Button">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=ic, Path=Items.Count}" Value="0">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>


问:
How to go from one tab to another tab in AvalonDock when a button or key is pressed?
I created a view from SampleDockWindowView and I like to go to the other view created window when a button is pressed.

I've already tried Application.Current.Windows. This array is just empty.

```<code>window2 win2= new window2();
        win2.Show();
</code>```

I would image something like this but with avalondock tabs. not necessarily new window but just to show the existing window when a button is pressed

答:
The following example shows how to cycle through all document tabs of the custom DocumentManager when a Ctrl + Right key combination is pressed (in this example the DocumentManager control is required to have focus):

MainWindow.xaml

```<code><Window>
  <Window.DataContext>
    <local:MainViewModel />
  </Window.DataContext>

  <Grid>

    <!--
      Border to capture keyboard events of the DocumentManager UserControl.
      To capture keys in a different scope i.e. more globally,
      move the input bindings to a parent control.
    -->
    <Border>
      <!-- Bind keyboard keys to a ICommand. -->
      <Border.InputBindings>
        <KeyBinding Key="Right"
                    Modifiers="Control"
                    Command="{Binding NavigateToNextDocument}"/>
      </Border.InputBindings>

      <DocumentManager x:Name="DocumentManager" />
    </Border>
  </Grid
</Window>
</code>```

DocumentManager.xaml

```<code><UserControl>
  <Grid>
    <xceed:DockingManager DocumentsSource="{Binding DocumentMainPool}">

      <xceed:DockingManager.LayoutItemTemplate>
        <DataTemplate DataType="{x:Type local:Document}">
          <TextBlock Text="{Binding Title}" />
        </DataTemplate>
      </xceed:DockingManager.LayoutItemTemplate>

      <xceed:DockingManager.LayoutItemContainerStyle>
        <Style TargetType="xcad:LayoutItem">
          <Setter Property="Title"
                  Value="{Binding Model.Title}" />
          <Setter Property="ToolTip"
                  Value="{Binding Model.Title}" />

          <!-- Important -->
          <Setter Property="IsSelected"
                  Value="{Binding Model.IsSelected, Mode=TwoWay}" />
        </Style>
      </xceed:DockingManager.LayoutItemContainerStyle>

      <xceed:LayoutRoot>
        <xceed:LayoutPanel>
          <xceed:LayoutDocumentPaneGroup>

            <!-- *** Dynamically created content (by view model) *** -->
            <xceed:LayoutDocumentPane />

          </xceed:LayoutDocumentPaneGroup>
        </xceed:LayoutPanel>
      </xceed:LayoutRoot>
    </xceed:DockingManager>

  </Grid>
</UserControl>
</code>```

MainViewModel.cs

```<code>class MainViewModel : INotifyProeprtyChanged
{
  public MainViewModel()
  {
    this.DocumentMainPool = new ObservableCollection<IDocument>()
    {
      new Document("First Document"),
      new Document("Second Document")
    };
  }

  private ObservableCollection<IDocument> documentMainPool;
  public ObservableCollection<IDocument> DocumentMainPool
  {
    get => this.documentMainPool;
    set
    {
      this.documentMainPool = value;
      OnPropertyChanged();
    }
  }

  public ICommand NavigateToNextDocument => new RelayCommand(param => CycleNextDocuments());

  private void CycleNextDocuments()
  {
    // Only one or no document -> nothing to cycle through
    if (this.DocumentMainPool.Count < 2)
    {
      return;
    }

    IDocument currentlySelectedDocument = this.DocumentMainPool.FirstOrDefault(document => document.IsSelected);
    int currentDocumentIndex = this.DocumentMainPool.IndexOf(currentlySelectedDocument);

    // If last document reached, show first again
    if (currentDocumentIndex == this.DocumentMainPool.Count - 1)
    {
      this.DocumentMainPool.FirstOrDefault().IsSelected = true;
      return;
    }

    IDocument nextDocument = this.DocumentMainPool
      .Skip(currentDocumentIndex + 1)
      .Take(1)
      .FirstOrDefault();
    nextDocument.IsSelected = true;
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}
</code>```

IDocument.cs

```<code>// Important: IsSelected must raise PropertyChanged
public interface IDocument : INotifyPropertyChanged
{
  string Title { get; set; }
  bool IsSelected { get; set; }
}
</code>```

Document.cs

```<code>public class Document : IDocument
{
  public Document(string title)
  {
    this.Title = title;
  }

  #region Implementation of IDocument

  public string Title { get; set; }

  private bool isSelected;
  public bool IsSelected
  {
    get => this.isSelected;
    set
    {
      this.isSelected = value;
      OnPropertyChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  #endregion
}
</code>```

RelayCommand.cs

Implementation taken from Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern:

```<code>public class RelayCommand : ICommand
{
    #region Fields
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;
    #endregion // Fields
    #region Constructors
    public RelayCommand(Action<object> execute) : this(execute, null) { }
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute; _canExecute = canExecute;
    }
    #endregion // Constructors

    #region ICommand Members
    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public void Execute(object parameter) { _execute(parameter); }
    #endregion // ICommand Members
}
</code>```

Body:
I created a view from SampleDockWindowView and I like to go to the other view created window when a button is pressed.

I've already tried Application.Current.Windows. This array is just empty.

window2 win2= new window2();
        win2.Show();

I would image something like this but with avalondock tabs. not necessarily new window but just to show the existing window when a button is pressed

Body:
The following example shows how to cycle through all document tabs of the custom DocumentManager when a Ctrl + Right key combination is pressed (in this example the DocumentManager control is required to have focus):

MainWindow.xaml

<Window>
  <Window.DataContext>
    <local:MainViewModel />
  </Window.DataContext>

  <Grid>

    <!--
      Border to capture keyboard events of the DocumentManager UserControl.
      To capture keys in a different scope i.e. more globally,
      move the input bindings to a parent control.
    -->
    <Border>
      <!-- Bind keyboard keys to a ICommand. -->
      <Border.InputBindings>
        <KeyBinding Key="Right"
                    Modifiers="Control"
                    Command="{Binding NavigateToNextDocument}"/>
      </Border.InputBindings>

      <DocumentManager x:Name="DocumentManager" />
    </Border>
  </Grid
</Window>

DocumentManager.xaml

<UserControl>
  <Grid>
    <xceed:DockingManager DocumentsSource="{Binding DocumentMainPool}">

      <xceed:DockingManager.LayoutItemTemplate>
        <DataTemplate DataType="{x:Type local:Document}">
          <TextBlock Text="{Binding Title}" />
        </DataTemplate>
      </xceed:DockingManager.LayoutItemTemplate>

      <xceed:DockingManager.LayoutItemContainerStyle>
        <Style TargetType="xcad:LayoutItem">
          <Setter Property="Title"
                  Value="{Binding Model.Title}" />
          <Setter Property="ToolTip"
                  Value="{Binding Model.Title}" />

          <!-- Important -->
          <Setter Property="IsSelected"
                  Value="{Binding Model.IsSelected, Mode=TwoWay}" />
        </Style>
      </xceed:DockingManager.LayoutItemContainerStyle>

      <xceed:LayoutRoot>
        <xceed:LayoutPanel>
          <xceed:LayoutDocumentPaneGroup>

            <!-- *** Dynamically created content (by view model) *** -->
            <xceed:LayoutDocumentPane />

          </xceed:LayoutDocumentPaneGroup>
        </xceed:LayoutPanel>
      </xceed:LayoutRoot>
    </xceed:DockingManager>

  </Grid>
</UserControl>

MainViewModel.cs

class MainViewModel : INotifyProeprtyChanged
{
  public MainViewModel()
  {
    this.DocumentMainPool = new ObservableCollection<IDocument>()
    {
      new Document("First Document"),
      new Document("Second Document")
    };
  }

  private ObservableCollection<IDocument> documentMainPool;
  public ObservableCollection<IDocument> DocumentMainPool
  {
    get => this.documentMainPool;
    set
    {
      this.documentMainPool = value;
      OnPropertyChanged();
    }
  }

  public ICommand NavigateToNextDocument => new RelayCommand(param => CycleNextDocuments());

  private void CycleNextDocuments()
  {
    // Only one or no document -> nothing to cycle through
    if (this.DocumentMainPool.Count < 2)
    {
      return;
    }

    IDocument currentlySelectedDocument = this.DocumentMainPool.FirstOrDefault(document => document.IsSelected);
    int currentDocumentIndex = this.DocumentMainPool.IndexOf(currentlySelectedDocument);

    // If last document reached, show first again
    if (currentDocumentIndex == this.DocumentMainPool.Count - 1)
    {
      this.DocumentMainPool.FirstOrDefault().IsSelected = true;
      return;
    }

    IDocument nextDocument = this.DocumentMainPool
      .Skip(currentDocumentIndex + 1)
      .Take(1)
      .FirstOrDefault();
    nextDocument.IsSelected = true;
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

IDocument.cs

// Important: IsSelected must raise PropertyChanged
public interface IDocument : INotifyPropertyChanged
{
  string Title { get; set; }
  bool IsSelected { get; set; }
}

Document.cs

public class Document : IDocument
{
  public Document(string title)
  {
    this.Title = title;
  }

  #region Implementation of IDocument

  public string Title { get; set; }

  private bool isSelected;
  public bool IsSelected
  {
    get => this.isSelected;
    set
    {
      this.isSelected = value;
      OnPropertyChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  {
    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  #endregion
}

RelayCommand.cs

Implementation taken from Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern:

public class RelayCommand : ICommand
{
    #region Fields
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;
    #endregion // Fields
    #region Constructors
    public RelayCommand(Action<object> execute) : this(execute, null) { }
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute; _canExecute = canExecute;
    }
    #endregion // Constructors

    #region ICommand Members
    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public void Execute(object parameter) { _execute(parameter); }
    #endregion // ICommand Members
}


问:
Scrapy: spider returns nothing
this is my first time creating a spider and in spite my efforts it continues to return nothing to my csv export. My code is:

```<code>from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector

class Emag(CrawlSpider):
    name = "emag"
    allowed_domains = ["emag.ro"]
    start_urls = [
        "http://www.emag.ro/"]

    rules = (Rule(SgmlLinkExtractor(allow=(r'www.emag.ro')), callback="parse", follow= True))

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//a/@href').extract()
        for site in sites:
            site = str(site)

        for clean_site in site:
            name = clean_site.xpath('//[@id=""]/span').extract()
            return name
</code>```

the thing is that if i print the sites, it bring me a list of the URLs, which is OK. if i search for the name inside one of the URLs in scrapy shell, it will find it. the problem is when i what all the names in all links crawled.I run it with "scrapy crawl emag>emag.csv"

Can you please give me a hint whats wrong?

答:
One problem might be, you have been forbidden by robots.txt for the site
You can check that from the log trace.
If so go to your settings.py and make ROBOTSTXT_OBEY=False
That solved my issue</p>

Title: Scrapy: spider returns nothing

Body:
this is my first time creating a spider and in spite my efforts it continues to return nothing to my csv export. My code is:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector

class Emag(CrawlSpider):
    name = "emag"
    allowed_domains = ["emag.ro"]
    start_urls = [
        "http://www.emag.ro/"]

    rules = (Rule(SgmlLinkExtractor(allow=(r'www.emag.ro')), callback="parse", follow= True))

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//a/@href').extract()
        for site in sites:
            site = str(site)

        for clean_site in site:
            name = clean_site.xpath('//[@id=""]/span').extract()
            return name

the thing is that if i print the sites, it bring me a list of the URLs, which is OK. if i search for the name inside one of the URLs in scrapy shell, it will find it. the problem is when i what all the names in all links crawled.I run it with "scrapy crawl emag>emag.csv"

Can you please give me a hint whats wrong?


问:
Regarding "officer" package and Table function in R
I have the following piece of code where I:
1) populate a data frame and its summary into PPT using officer package
2) Calculate summary from data frame using table function

```<code>library(officer)

df1 <- data.frame(
  Country = c("France", "England", "India", "America", "England", "India"),
  City = c("Paris", "London", "Mumbai", "Los Angeles", "Surrey", "Chennai"),
  Order_No = c("1", "2", "3", "4", "5", "6"),
  State = c("Yes", "No", "Yes", "No", "Yes", "Transit"),
  stringsAsFactors = FALSE
)

my_pres <- read_pptx()
my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "heading", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = df1, location = ph_location_type(type = "body"), header = TRUE)
print(my_pres, target = "first_example.pptx")

table1 <- table(df1$Country, df1$State)

overview.df <- data.frame(Country = rownames(table1),
                          Not.Delivered =table1[,1],
                          In.Transit = table1[,2],
                          Delivered = table1[,3])

my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "Summary", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = overview.df, location = ph_location_type(type = "body"), header = TRUE)
print(my_pres, target = "first_example.pptx")
</code>```

I have 2 questions here which I am unable to solve and need help:

1) I am unable to change the font and font size of the output in PPT. Can someone help me here
2) When I calculate the dataframe "overview.df" from "table1", sometimes the output contains "Yes, "No" and "Transit" for which the above code works. But sometimes, the input data frame only contains "Yes" and "No" for which my code fails. Hence I would like a generic code to replace the following lines:

```<code>table1 <- table(df1$Country, df1$State)

overview.df <- data.frame(Country = rownames(table1),
                          Not.Delivered =table1[,1],
                          In.Transit = table1[,2],
                          Delivered = table1[,3])
</code>```

Thanks all in advance! Awaiting your reply.

答:
Question 1: you need to use fpar and/or block_list to control from R the size, color, etc. of fonts. By default, the font used is the font defined in your template. In your case, you don't provide any template so the default one is used.

Question 2: maybe use flextable::proc_freq:

```<code>library(officer)
library(flextable)

df1 <- data.frame(
  Country = c("France", "England", "India", "America", "England", "India"),
  City = c("Paris", "London", "Mumbai", "Los Angeles", "Surrey", "Chennai"),
  Order_No = c("1", "2", "3", "4", "5", "6"),
  State = c("Yes", "No", "Yes", "No", "Yes", "Transit"),
  stringsAsFactors = FALSE
)

# this is a "proc freq" like ----
pf <- proc_freq(df1, "Country", "State")
pf <- fontsize(pf, size = 11, part = "all")
pf <- padding(pf, padding = 1, part = "all")
pf <- valign(pf, valign = "top", part = "all")
pf <- autofit(pf)

my_pres <- read_pptx()
my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "heading", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = df1, location = ph_location_type(type = "body"), header = TRUE)

my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "Summary", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = pf,
                   location = ph_location_type(type = "body"), header = TRUE)
print(my_pres, target = "first_example.pptx")
</code>```

Body:
I have the following piece of code where I:
1) populate a data frame and its summary into PPT using officer package
2) Calculate summary from data frame using table function

library(officer)

df1 <- data.frame(
  Country = c("France", "England", "India", "America", "England", "India"),
  City = c("Paris", "London", "Mumbai", "Los Angeles", "Surrey", "Chennai"),
  Order_No = c("1", "2", "3", "4", "5", "6"),
  State = c("Yes", "No", "Yes", "No", "Yes", "Transit"),
  stringsAsFactors = FALSE
)

my_pres <- read_pptx()
my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "heading", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = df1, location = ph_location_type(type = "body"), header = TRUE)
print(my_pres, target = "first_example.pptx")

table1 <- table(df1$Country, df1$State)

overview.df <- data.frame(Country = rownames(table1),
                          Not.Delivered =table1[,1],
                          In.Transit = table1[,2],
                          Delivered = table1[,3])

my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "Summary", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = overview.df, location = ph_location_type(type = "body"), header = TRUE)
print(my_pres, target = "first_example.pptx")

I have 2 questions here which I am unable to solve and need help:

1) I am unable to change the font and font size of the output in PPT. Can someone help me here
2) When I calculate the dataframe "overview.df" from "table1", sometimes the output contains "Yes, "No" and "Transit" for which the above code works. But sometimes, the input data frame only contains "Yes" and "No" for which my code fails. Hence I would like a generic code to replace the following lines:

table1 <- table(df1$Country, df1$State)

overview.df <- data.frame(Country = rownames(table1),
                          Not.Delivered =table1[,1],
                          In.Transit = table1[,2],
                          Delivered = table1[,3])

Thanks all in advance! Awaiting your reply.

Body:
Question 1: you need to use fpar and/or block_list to control from R the size, color, etc. of fonts. By default, the font used is the font defined in your template. In your case, you don't provide any template so the default one is used.

Question 2: maybe use flextable::proc_freq:

library(officer)
library(flextable)

df1 <- data.frame(
  Country = c("France", "England", "India", "America", "England", "India"),
  City = c("Paris", "London", "Mumbai", "Los Angeles", "Surrey", "Chennai"),
  Order_No = c("1", "2", "3", "4", "5", "6"),
  State = c("Yes", "No", "Yes", "No", "Yes", "Transit"),
  stringsAsFactors = FALSE
)

# this is a "proc freq" like ----
pf <- proc_freq(df1, "Country", "State")
pf <- fontsize(pf, size = 11, part = "all")
pf <- padding(pf, padding = 1, part = "all")
pf <- valign(pf, valign = "top", part = "all")
pf <- autofit(pf)

my_pres <- read_pptx()
my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "heading", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = df1, location = ph_location_type(type = "body"), header = TRUE)

my_pres <- add_slide(my_pres, layout = "Title and Content", master = "Office Theme")
my_pres <- ph_with(my_pres, value = "Summary", location = ph_location_type(type = "title"))
my_pres <- ph_with(my_pres, value = pf,
                   location = ph_location_type(type = "body"), header = TRUE)
print(my_pres, target = "first_example.pptx")