问:
You must use the http and https protocols for intent filters. Why receive this error message?
When I choosing to upload android Instant App apk-s zip to Google Play Developer Console I receive this error: Upload failed. You must use the http and https protocols for intent filters

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      package="com.example.feature">

<application>
    <meta-data
        android:name="asset_statements"
        android:resource="@string/asset_statements"/>
    <activity android:name=".ui.MainActivity">
        <tools:validation testUrl="https://com.example/"/>

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
        <intent-filter
            android:order="1"
            android:autoVerify="true">
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:scheme="https"
                android:host="com.example"
                android:pathPattern="/.*"/>
        </intent-filter>

        <meta-data
            android:name="default-url"
            android:value="https://com.example"/>
    </activity>
</application>
</code>```

答:
I was using intent-filter to receive dynamic link but also was integrating deep link in navigation graph, for this reason it was also necessary to include "http" and "https" support in the nav_graph.xml document.</p>

```<code><fragment
        android:id="@+id/someFragment"
        android:name="com.apps.example.SomeFragment"
        android:label="fragment_some"
        tools:layout="@layout/fragment_some" >
        <deepLink
            android:id="@+id/deepLink1"
            app:uri="https://example.page.link" />

        <deepLink
            android:id="@+id/deepLink2"
            app:uri="http://example.page.link" />
  </fragment>
</code>```

Body:
When I choosing to upload android Instant App apk-s zip to Google Play Developer Console I receive this error: Upload failed. You must use the http and https protocols for intent filters

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      package="com.example.feature">

<application>
    <meta-data
        android:name="asset_statements"
        android:resource="@string/asset_statements"/>
    <activity android:name=".ui.MainActivity">
        <tools:validation testUrl="https://com.example/"/>

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
        <intent-filter
            android:order="1"
            android:autoVerify="true">
            <action android:name="android.intent.action.VIEW"/>

            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>

            <data
                android:scheme="https"
                android:host="com.example"
                android:pathPattern="/.*"/>
        </intent-filter>

        <meta-data
            android:name="default-url"
            android:value="https://com.example"/>
    </activity>
</application>

Body:
I was using intent-filter to receive dynamic link but also was integrating deep link in navigation graph, for this reason it was also necessary to include "http" and "https" support in the nav_graph.xml document.

<fragment
        android:id="@+id/someFragment"
        android:name="com.apps.example.SomeFragment"
        android:label="fragment_some"
        tools:layout="@layout/fragment_some" >
        <deepLink
            android:id="@+id/deepLink1"
            app:uri="https://example.page.link" />

        <deepLink
            android:id="@+id/deepLink2"
            app:uri="http://example.page.link" />
  </fragment>


来源: stackexchange

问:
Split a string with multiple delimiters in Ruby
Take for instance, I have a string like this:

```<code>options = "Cake or pie, ice cream, or pudding"
</code>```

I want to be able to split the string via or, ,, and , or.

The thing is, is that I have been able to do it, but only by parsing , and , or first, and then splitting each array item at or, flattening the resultant array afterwards as such:

```<code>options = options.split(/(?:\s?or\s)*([^,]+)(?:,\s*)*/).reject(&:empty?);
options.each_index {|index| options[index] = options[index].sub("?","").split(" or "); }
</code>```

The resultant array is as such: ["Cake", "pie", "ice cream", "pudding"]

Is there a more efficient (or easier) way to split my string on those three delimiters?

答:
What about the following:

```<code>options.gsub(/ or /i, ",").split(",").map(&:strip).reject(&:empty?)
</code>```

replaces all delimiters but the ,

splits it at ,

trims each characters, since stuff like  ice cream with a leading space might be left

removes all blank strings

ContentLicense: CC BY-SA 3.0

Body:
Take for instance, I have a string like this:

options = "Cake or pie, ice cream, or pudding"

I want to be able to split the string via or, ,, and , or.

The thing is, is that I have been able to do it, but only by parsing , and , or first, and then splitting each array item at or, flattening the resultant array afterwards as such:

options = options.split(/(?:\s?or\s)*([^,]+)(?:,\s*)*/).reject(&:empty?);
options.each_index {|index| options[index] = options[index].sub("?","").split(" or "); }

The resultant array is as such: ["Cake", "pie", "ice cream", "pudding"]

Is there a more efficient (or easier) way to split my string on those three delimiters?

Body:
What about the following:

options.gsub(/ or /i, ",").split(",").map(&:strip).reject(&:empty?)

replaces all delimiters but the ,

splits it at ,

trims each characters, since stuff like  ice cream with a leading space might be left

removes all blank strings


问:
Unique email address with Sequelize
I'm running ExpressJS with Sequelize/MySQL and trying very hard to get a simple validator check working for unique email address.

Here is my user model. And for the life of me I don't understand why this is allowing records that have duplicate email address. Surely the email.unique=true would be preventing this.

```<code>'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: {
          msg: "Must be a valid email address",
        }
      }
    }
  }, {
    indexes: [{
      fields: ['email'],
      unique: true,
    }]
  });
  return User;
};
</code>```

Any help appreciated.

EDIT:
As requested here is the controller code for create user.

```<code>const User = require('../models').User;

exports.create = (req, res) => {
  User.create( req.body )
  .then( user => {
    res.json( user );
  })
  .catch( errors => {
    res.json({ errors: errors.errors });
  });
};
</code>```

答:
One way to solve this is by using sequelize.sync() to create your table according to the schema specified in the model if the table exists then you should pass {force: true} to the sync method, the table will be dropped and a new one will be created.

though using sequelize.sync() is not highly recommended especially in production due to issues with migration files etc, you can google than for more details.

Title: Unique email address with Sequelize

Body:
I'm running ExpressJS with Sequelize/MySQL and trying very hard to get a simple validator check working for unique email address.

Here is my user model. And for the life of me I don't understand why this is allowing records that have duplicate email address. Surely the email.unique=true would be preventing this.

'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isEmail: {
          msg: "Must be a valid email address",
        }
      }
    }
  }, {
    indexes: [{
      fields: ['email'],
      unique: true,
    }]
  });
  return User;
};

Any help appreciated.

EDIT:
As requested here is the controller code for create user.

const User = require('../models').User;

exports.create = (req, res) => {
  User.create( req.body )
  .then( user => {
    res.json( user );
  })
  .catch( errors => {
    res.json({ errors: errors.errors });
  });
};

ContentLicense: CC BY-SA 4.0


问:
Can't run any container with an entrypoint script
I work with docker on a daily basis, but this morning, when I tried to launch some containers, it failed for every of my containers with an entrypoint script:

```<code>$ docker run postgres:11
bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run mysql:5
/bin/bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run php:7.3-apache
/bin/sh: 0: Can't open /usr/local/bin/docker-php-entrypoint
</code>```

I managed to docker run hello-world without errors.

What happens? I don't think I have changed anything important on my computer since the last time it worked... I am on Ubuntu 20.04.
Thanks for your help.

UPDATE

I still don't know what was going on. I managed to make it work again by removing docker-ce and re-installing it:

```<code>sudo apt-get remove docker-ce
sudo apt install docker-ce
docker run postgres:11
  ==> ok, worked!
</code>```

But, each time I shut down my laptop and then turn it on, I have the same problem again, docker doesn't run any container with an entrypoint.

Any ideas?

答: We had exactly the same problem on Ubuntu 19.04 and docker installed via snap few hours ago. Apparmor was the cause, we follow the solution from the previous answer. Disable apparmor, remove apparmor which also remove snap and also remove docker. Then I installed docker via apt and works. The odd is apparmor and snap are related some how, but apparmor blocks docker which was installed via snap.</p>

Body:
I work with docker on a daily basis, but this morning, when I tried to launch some containers, it failed for every of my containers with an entrypoint script:

$ docker run postgres:11
bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run mysql:5
/bin/bash: /usr/local/bin/docker-entrypoint.sh: Permission denied

$ docker run php:7.3-apache
/bin/sh: 0: Can't open /usr/local/bin/docker-php-entrypoint

I managed to docker run hello-world without errors.

What happens? I don't think I have changed anything important on my computer since the last time it worked... I am on Ubuntu 20.04.
Thanks for your help.

UPDATE

I still don't know what was going on. I managed to make it work again by removing docker-ce and re-installing it:

sudo apt-get remove docker-ce
sudo apt install docker-ce
docker run postgres:11
  ==> ok, worked!

But, each time I shut down my laptop and then turn it on, I have the same problem again, docker doesn't run any container with an entrypoint.

Any ideas?


问:
Unable to Align 2 Cardviews Vertically Inside RecyclerView
I have 2 CardViews and a RecyclerView but i am

unable to align them vertically

unable to slide them independently (both slide if I slide any one in a bugged workaround)

I tried a few workarounds as well as different tutorials like edmt Dev and CodingWithMitch as well as searched for similar problems on stackoverflow but the problem seems to persist. So how do I align both of the cardviews vertically while still being able to slide each of them independently and horizontally.

(Code works fine for single card view)

Main Activity:

```<code>public class MainActivity extends AppCompatActivity {

List<Articles> articlesData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    articlesData = new ArrayList<>();

    //Repeats
    articlesData.add(new Articles("10 Necessary Gadgets","Gadgets","Gadgets You Must Carry",R.drawable.bagchaincustom));
    articlesData.add(new Articles("10 Benefits of Pre-Planning the Day","Self Improvement","Benefits of Planning in Advance",R.drawable.planner1custom));

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
    RecyclerView recyclerView = findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(layoutManager);
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, articlesData);
    recyclerView.setAdapter(adapter);

}
</code>```

Here is activity_main.xml:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerview"
        android:orientation="horizontal">
        </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Here is the RecyclerViewAdapter Class:

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;

@Override
public int getItemViewType(int position)
{
    if(position == LAYOUT_ONE){
        return LAYOUT_TWO;
    }
    else {
        return LAYOUT_ONE;
    }
}

private static final String Tag = "RecyclerViewAdapter";
private Context mContext;
private List<Articles> mData;

public RecyclerViewAdapter(Context mContext, List<Articles> mData) {
    this.mContext = mContext;
    this.mData = mData;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater mInflater = LayoutInflater.from(mContext);
    View view;

    switch (viewType) {
        case 0:
            ViewHolder1 viewHolder1;
            view = mInflater.inflate(R.layout.layout_listitem, parent, false);
            return new ViewHolder1(view);

        case 1:
            ViewHolder2 viewHolder2;
            view = mInflater.inflate(R.layout.layout_listitem2, parent, false);
            return new ViewHolder2(view);

        default:
            return null;
    }

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

    switch (holder.getItemViewType()){
        case 0:
            ViewHolder1 viewHolder1 = (ViewHolder1)holder;
        viewHolder1.tv_article_title.setText(mData.get(position).getTitle());
            viewHolder1.img_article_thumbnail.setImageResource(mData.get(position).getThumbnail());
            viewHolder1.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ArticlesActivity.class);
                intent.putExtra("Title", mData.get(position).getTitle());
                intent.putExtra("Description", mData.get(position).getDescription());
                intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                intent.putExtra("Category", mData.get(position).getCategory());
                mContext.startActivity(intent);
            }
        });
        break;

        case 1:
            ViewHolder2 viewHolder2 = (ViewHolder2)holder;
            viewHolder2.tv_article_title2.setText(mData.get(position).getTitle());
            viewHolder2.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
            viewHolder2.cardView2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ArticlesActivity.class);
                    intent.putExtra("Title", mData.get(position).getTitle());
                    intent.putExtra("Description", mData.get(position).getDescription());
                    intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                    intent.putExtra("Category", mData.get(position).getCategory());
                    mContext.startActivity(intent);
                }
            });
            break;

    }
}

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

public class ViewHolder1 extends RecyclerView.ViewHolder{
    TextView tv_article_title;
    ImageView img_article_thumbnail;
    CardView cardView;

    public ViewHolder1(@NonNull View itemView) {
        super(itemView);
        tv_article_title = (TextView) itemView.findViewById(R.id.article_title_id);
        img_article_thumbnail = (ImageView) itemView.findViewById((R.id.article_image_id));
        cardView = (CardView) itemView.findViewById(R.id.cardview_id);

    }
}

public class ViewHolder2 extends RecyclerView.ViewHolder{
    TextView tv_article_title2;
    ImageView img_article_thumbnail2;
    CardView cardView2;

    public ViewHolder2(@NonNull View itemView) {
        super(itemView);
        tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
        img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
        cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);

    }
}

}
</code>```

Here is the Articles Class:

```<code>public class Articles {

private String Title;
private String Category;
private String Description;
private int Thumbnail;

public Articles(String title, String category, String description, int thumbnail) {
    Title = title;
    Category = category;
    Description = description;
    Thumbnail = thumbnail;
}

public String getTitle() {
    return Title;
}

public String getCategory() {
    return Category;
}

public String getDescription() {
    return Description;
}

public int getThumbnail() {
    return Thumbnail;
}
</code>```

And here is the CardView -> layout_listitem Layout:

```<code>    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_alignParentStart="true"
    android:id="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/cardview_id"
    android:layout_width="120dp"
    android:layout_height="220dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="0dp"
    app:cardElevation="0dp">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/article_image_id"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:background="#2d2d2d"
            android:scaleType="centerCrop"></ImageView>

        <TextView
            android:id="@+id/article_title_id"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:text="Article Name"
            android:textSize="14sp">

        </TextView>

    </LinearLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>
</code>```

And here is the CardView -> layout_listitem2 Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_alignParentStart="true"
    android:id="@+id/rview2"
    android:layout_below="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="300dp">

    <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:card_view="http://schemas.android.com/tools"
        android:id="@+id/cardview_id2"
        android:layout_below="@id/cardview_id"
        android:layout_width="120dp"
        android:layout_height="220dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        app:cardCornerRadius="0dp"
        app:cardElevation="0dp">

        <LinearLayout
            android:layout_marginTop="250dp"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/article_image_id2"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="#2d2d2d"
                android:scaleType="centerCrop"></ImageView>

            <TextView
                android:id="@+id/article_title_id2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:text="Article Name Sec"
                android:textSize="14sp">

            </TextView>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>
</code>```

答:
So I made a few modifications to the above code and it has solved the both problems (Independent sliding and vertical alignment)

I have added another recyclerview in main_activity.xml

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

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerview_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

</androidx.recyclerview.widget.RecyclerView>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_below="@+id/recyclerview_id2"
        android:layout_marginTop="10dp"
        android:id="@+id/recyclerview_id2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="NotSibling">
    </androidx.recyclerview.widget.RecyclerView>

</LinearLayout>
</code>```

I have also created another Adapter for the new recyclerview, seperated classes for both viewholders as well as removed the switch statements and itemViewType  from RecyclerViewAdapter and RecyclerViewAdapter2 class :

```<code>    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view;
    LayoutInflater mInflater = LayoutInflater.from(mContext);
    view = mInflater.inflate(R.layout.layout_listitem2,parent,false);
    return new ViewHolder(view);

}

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

    holder.tv_article_title2.setText(mData.get(position).getTitle());
    holder.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
    holder.cardView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext,ArticlesActivity.class);
            intent.putExtra("Title",mData.get(position).getTitle());
            intent.putExtra("Description",mData.get(position).getDescription());
            intent.putExtra("Thumbnail",mData.get(position).getThumbnail());
            intent.putExtra("Category",mData.get(position).getCategory());
            mContext.startActivity(intent);
        }
    });

}

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

public static class ViewHolder extends RecyclerView.ViewHolder{

    TextView tv_article_title2;
    ImageView img_article_thumbnail2;
    CardView cardView2;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
        img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
        cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);
    }
}
</code>```

I also edited the main_acitivty class by adding the new recyclerview and layout manager at the end:

```<code>LinearLayoutManager layoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
    RecyclerView recyclerView2 = findViewById(R.id.recyclerview_id2);
    recyclerView2.setLayoutManager(layoutManager2);
    RecyclerViewAdapter2 adapter2 = new RecyclerViewAdapter2(this, articlesData);
    recyclerView2.setAdapter(adapter2);
</code>```

Even though this workaround fixes both problems i was facing is there any other better/more refined way of doing this (eg by using single recyclerview) and where did i made the mistake in previous approach?

Body:
I have 2 CardViews and a RecyclerView but i am

unable to align them vertically

unable to slide them independently (both slide if I slide any one in a bugged workaround)

I tried a few workarounds as well as different tutorials like edmt Dev and CodingWithMitch as well as searched for similar problems on stackoverflow but the problem seems to persist. So how do I align both of the cardviews vertically while still being able to slide each of them independently and horizontally.

(Code works fine for single card view)

Main Activity:

public class MainActivity extends AppCompatActivity {

List<Articles> articlesData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    articlesData = new ArrayList<>();

    //Repeats
    articlesData.add(new Articles("10 Necessary Gadgets","Gadgets","Gadgets You Must Carry",R.drawable.bagchaincustom));
    articlesData.add(new Articles("10 Benefits of Pre-Planning the Day","Self Improvement","Benefits of Planning in Advance",R.drawable.planner1custom));

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
    RecyclerView recyclerView = findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(layoutManager);
    RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, articlesData);
    recyclerView.setAdapter(adapter);

}

Here is activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerview"
        android:orientation="horizontal">
        </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

Here is the RecyclerViewAdapter Class:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;

@Override
public int getItemViewType(int position)
{
    if(position == LAYOUT_ONE){
        return LAYOUT_TWO;
    }
    else {
        return LAYOUT_ONE;
    }
}

private static final String Tag = "RecyclerViewAdapter";
private Context mContext;
private List<Articles> mData;

public RecyclerViewAdapter(Context mContext, List<Articles> mData) {
    this.mContext = mContext;
    this.mData = mData;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater mInflater = LayoutInflater.from(mContext);
    View view;

    switch (viewType) {
        case 0:
            ViewHolder1 viewHolder1;
            view = mInflater.inflate(R.layout.layout_listitem, parent, false);
            return new ViewHolder1(view);

        case 1:
            ViewHolder2 viewHolder2;
            view = mInflater.inflate(R.layout.layout_listitem2, parent, false);
            return new ViewHolder2(view);

        default:
            return null;
    }

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

    switch (holder.getItemViewType()){
        case 0:
            ViewHolder1 viewHolder1 = (ViewHolder1)holder;
        viewHolder1.tv_article_title.setText(mData.get(position).getTitle());
            viewHolder1.img_article_thumbnail.setImageResource(mData.get(position).getThumbnail());
            viewHolder1.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ArticlesActivity.class);
                intent.putExtra("Title", mData.get(position).getTitle());
                intent.putExtra("Description", mData.get(position).getDescription());
                intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                intent.putExtra("Category", mData.get(position).getCategory());
                mContext.startActivity(intent);
            }
        });
        break;

        case 1:
            ViewHolder2 viewHolder2 = (ViewHolder2)holder;
            viewHolder2.tv_article_title2.setText(mData.get(position).getTitle());
            viewHolder2.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
            viewHolder2.cardView2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ArticlesActivity.class);
                    intent.putExtra("Title", mData.get(position).getTitle());
                    intent.putExtra("Description", mData.get(position).getDescription());
                    intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
                    intent.putExtra("Category", mData.get(position).getCategory());
                    mContext.startActivity(intent);
                }
            });
            break;

    }
}

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

public class ViewHolder1 extends RecyclerView.ViewHolder{
    TextView tv_article_title;
    ImageView img_article_thumbnail;
    CardView cardView;

    public ViewHolder1(@NonNull View itemView) {
        super(itemView);
        tv_article_title = (TextView) itemView.findViewById(R.id.article_title_id);
        img_article_thumbnail = (ImageView) itemView.findViewById((R.id.article_image_id));
        cardView = (CardView) itemView.findViewById(R.id.cardview_id);

    }
}

public class ViewHolder2 extends RecyclerView.ViewHolder{
    TextView tv_article_title2;
    ImageView img_article_thumbnail2;
    CardView cardView2;

    public ViewHolder2(@NonNull View itemView) {
        super(itemView);
        tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
        img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
        cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);

    }
}

}

Here is the Articles Class:

public class Articles {

private String Title;
private String Category;
private String Description;
private int Thumbnail;

public Articles(String title, String category, String description, int thumbnail) {
    Title = title;
    Category = category;
    Description = description;
    Thumbnail = thumbnail;
}

public String getTitle() {
    return Title;
}

public String getCategory() {
    return Category;
}

public String getDescription() {
    return Description;
}

public int getThumbnail() {
    return Thumbnail;
}

And here is the CardView -> layout_listitem Layout:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_alignParentStart="true"
    android:id="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/cardview_id"
    android:layout_width="120dp"
    android:layout_height="220dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="0dp"
    app:cardElevation="0dp">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/article_image_id"
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:background="#2d2d2d"
            android:scaleType="centerCrop"></ImageView>

        <TextView
            android:id="@+id/article_title_id"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:gravity="center"
            android:text="Article Name"
            android:textSize="14sp">

        </TextView>

    </LinearLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>

And here is the CardView -> layout_listitem2 Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_alignParentStart="true"
    android:id="@+id/rview2"
    android:layout_below="@+id/rview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="300dp">

    <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:card_view="http://schemas.android.com/tools"
        android:id="@+id/cardview_id2"
        android:layout_below="@id/cardview_id"
        android:layout_width="120dp"
        android:layout_height="220dp"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        app:cardCornerRadius="0dp"
        app:cardElevation="0dp">

        <LinearLayout
            android:layout_marginTop="250dp"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/article_image_id2"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="#2d2d2d"
                android:scaleType="centerCrop"></ImageView>

            <TextView
                android:id="@+id/article_title_id2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:text="Article Name Sec"
                android:textSize="14sp">

            </TextView>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

Body:
So I made a few modifications to the above code and it has solved the both problems (Independent sliding and vertical alignment)

I have added another recyclerview in main_activity.xml

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

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerview_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

</androidx.recyclerview.widget.RecyclerView>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_below="@+id/recyclerview_id2"
        android:layout_marginTop="10dp"
        android:id="@+id/recyclerview_id2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="NotSibling">
    </androidx.recyclerview.widget.RecyclerView>

</LinearLayout>

I have also created another Adapter for the new recyclerview, seperated classes for both viewholders as well as removed the switch statements and itemViewType  from RecyclerViewAdapter and RecyclerViewAdapter2 class :

    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view;
    LayoutInflater mInflater = LayoutInflater.from(mContext);
    view = mInflater.inflate(R.layout.layout_listitem2,parent,false);
    return new ViewHolder(view);

}

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

    holder.tv_article_title2.setText(mData.get(position).getTitle());
    holder.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
    holder.cardView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext,ArticlesActivity.class);
            intent.putExtra("Title",mData.get(position).getTitle());
            intent.putExtra("Description",mData.get(position).getDescription());
            intent.putExtra("Thumbnail",mData.get(position).getThumbnail());
            intent.putExtra("Category",mData.get(position).getCategory());
            mContext.startActivity(intent);
        }
    });

}

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

public static class ViewHolder extends RecyclerView.ViewHolder{

    TextView tv_article_title2;
    ImageView img_article_thumbnail2;
    CardView cardView2;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
        img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
        cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);
    }
}

I also edited the main_acitivty class by adding the new recyclerview and layout manager at the end:

LinearLayoutManager layoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
    RecyclerView recyclerView2 = findViewById(R.id.recyclerview_id2);
    recyclerView2.setLayoutManager(layoutManager2);
    RecyclerViewAdapter2 adapter2 = new RecyclerViewAdapter2(this, articlesData);
    recyclerView2.setAdapter(adapter2);

Even though this workaround fixes both problems i was facing is there any other better/more refined way of doing this (eg by using single recyclerview) and where did i made the mistake in previous approach?


问:
Can I get the path of the currently running java executable?
Suppose I want to run a java program from the command line and I use this command:

```<code>myExes\java\java.exe AJavaProgram
</code>```

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.

答:
ProcessHandle.current() returns the current Java process.  You can use that to see the full command in the process handle’s info:</p>

```<code>ProcessHandle.current().info().command().ifPresent(
    cmd -> System.out.println(cmd));
</code>```

Body:
Suppose I want to run a java program from the command line and I use this command:

myExes\java\java.exe AJavaProgram

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.

Body:
ProcessHandle.current() returns the current Java process.  You can use that to see the full command in the process handle’s info:

ProcessHandle.current().info().command().ifPresent(
    cmd -> System.out.println(cmd));


问:
How to distinguish between Digital/Composite AV Cable on iPad?
I am using UIApplication+ScreenMirroring as software support for mirroring display on iPad1.  iPad2 now includes built-in support for mirroring when using the Digital AV Cable.  Currently in my app, I am disabling the software support for mirroring when an iPad2 is detected.  However, if a user is using an iPad2 but connects a Composite AV Cable, I would like to enable software support (i.e., Composite AV Cable on iPad2 behaves likes iPad1).

How can I distinguish between a Digital versus Composite AV cable connection on iPad2?  Currently, the code I'm using receives UIScreenDidConnectNotification, but I can find no clues in this message.

答:
You may be able to use UIScreen's mirroredScreen property added in 4.3 to determine if mirroring is actually happening due to a supported device being connected. Since this is only in 4.3 and all ipad 2s shipped with 4.3 greater, you would just need to do an os level check to ensure the property exists, if it doesn't it must be an ipad 1.

Apple provides more information in this technote.


问:
How to trigger zoom in and zoom out in plotly chart using user created on click buttons?
I am building an angular application. In which we need to create on click buttons for zooming in and zooming out for plotly chart. We can zoom in zoom out in plotly chart using buttons on hoverable mode bar but this is not required for our application. We want to zoom in and zoom out the chart using user created on click buttons. Is there a way to trigger actions of hoverable mode bar zoom in and out using on click buttons? if not then what are the other ways to do? any suggestion is appreciated.

Code in .ts file

```<code>basicChart() {

    var trace1 = {
        x: ['2020-10-04', '2021-11-04', '2023-12-04'],
        y: [90, 40, 60],
        type: 'scatter'
    };

    var data = [trace1];

    var layout = {
        title: 'Chart',
        showlegend: false
    };

    Plotly.newPlot('myDiv', data, layout);
}
</code>```

答:
I had this same problem and ended up just using the DOM to click the modebar.

zoom-functions-example.js

const plot = Plotly.newPlot('myDiv', data, layout)
let zoomIn = function(plot){
  plot.querySelector('a[data-attr="zoom"][data-val="in"]').click()
},
let zoomOut = function(plot){
  plot.querySelector('a[data-attr="zoom"][data-val="out"]').click()
},
let resetView = function(plot){
  plot.querySelector('a[data-attr="zoom"][data-val="reset"]').click()
},
```
<h3>CSS to hide modebar:</h3>
<pre class="lang-css prettyprint-override"><code>.modebar-container{
  display: none;
}
</code>```

Body:
I am building an angular application. In which we need to create on click buttons for zooming in and zooming out for plotly chart. We can zoom in zoom out in plotly chart using buttons on hoverable mode bar but this is not required for our application. We want to zoom in and zoom out the chart using user created on click buttons. Is there a way to trigger actions of hoverable mode bar zoom in and out using on click buttons? if not then what are the other ways to do? any suggestion is appreciated.

Code in .ts file

basicChart() {

    var trace1 = {
        x: ['2020-10-04', '2021-11-04', '2023-12-04'],
        y: [90, 40, 60],
        type: 'scatter'
    };

    var data = [trace1];

    var layout = {
        title: 'Chart',
        showlegend: false
    };

    Plotly.newPlot('myDiv', data, layout);
}

Body:
I had this same problem and ended up just using the DOM to click the modebar.

zoom-functions-example.js

const plot = Plotly.newPlot('myDiv', data, layout)
let zoomIn = function(plot){
  plot.querySelector('a[data-attr="zoom"][data-val="in"]').click()
},
let zoomOut = function(plot){
  plot.querySelector('a[data-attr="zoom"][data-val="out"]').click()
},
let resetView = function(plot){
  plot.querySelector('a[data-attr="zoom"][data-val="reset"]').click()
},

CSS to hide modebar:

.modebar-container{
  display: none;
}


问:
My code throws stackoverflowexception when i execute
I am working on a Windows Application Development in c# language.
I have a template form => Masterpage which is inherited by all my other forms.

It has menustrip to open all other forms as well:

my error reads:

```<code>System.StackOverflowException
  HResult=0x800703E9
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>
</code>```

my Masterpage code is:

```<code>namespace WindowsProject
{
    public partial class Masterpage : Form
    {
        BookEditor bookE;
        StudentEditor studentE;
        ViewBorrowedBooks viewB;
        IssueBook issueBook;

        public Masterpage()
        {
            InitializeComponent();
            bookE = new BookEditor();
            studentE = new StudentEditor();
            viewB = new ViewBorrowedBooks();
            issueBook = new IssueBook();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void showForm(Form f)
        {
            bookE.Hide();
            studentE.Hide();
            viewB.Hide();
            issueBook.Hide();
            this.Hide();
            f.Show();
        }

        private void booksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(bookE);
        }

        private void studentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(studentE);
        }

        private void viewBorrowedBooksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(viewB);
        }

        private void issueBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(issueBook);
        }
    }
}
</code>```

all my other forms inherits from Masterpage

答:
Thank you all for answering my question.
The problem i found on my code was it was looping infinitely since i put a child form inside the parent MDI form and instantiated the child form inside parent form’s constructor.
The problem was solved by instantiating the forms outside the constructor inside a method.</p>

Body:
I am working on a Windows Application Development in c# language.
I have a template form => Masterpage which is inherited by all my other forms.

It has menustrip to open all other forms as well:

my error reads:

System.StackOverflowException
  HResult=0x800703E9
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

my Masterpage code is:

namespace WindowsProject
{
    public partial class Masterpage : Form
    {
        BookEditor bookE;
        StudentEditor studentE;
        ViewBorrowedBooks viewB;
        IssueBook issueBook;

        public Masterpage()
        {
            InitializeComponent();
            bookE = new BookEditor();
            studentE = new StudentEditor();
            viewB = new ViewBorrowedBooks();
            issueBook = new IssueBook();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void showForm(Form f)
        {
            bookE.Hide();
            studentE.Hide();
            viewB.Hide();
            issueBook.Hide();
            this.Hide();
            f.Show();
        }

        private void booksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(bookE);
        }

        private void studentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(studentE);
        }

        private void viewBorrowedBooksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(viewB);
        }

        private void issueBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showForm(issueBook);
        }
    }
}

all my other forms inherits from Masterpage


问:
Flutter show Snackbar inside build
I implemented the BLoC pattern in my app by I have a problem.

Once I have a special event, I need to show a snackbar, but I have this error :

```<code>The following assertion was thrown building InteractWithMorceauPage(dirty, dependencies: [MediaQuery], state: _InteractWithMorceauPageState#25201):
setState() or markNeedsBuild() called during build.

This Scaffold widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: Scaffold
  dependencies: [TickerMode, MediaQuery, _InheritedTheme, _LocalizationsScope-[GlobalKey#dc380], Directionality]
  state: ScaffoldState#8a46b(tickers: tracking 3 tickers)
The widget which was currently being built when the offending call was made was: InteractWithMorceauPage
  dirty
  dependencies: [MediaQuery]
  state: _InteractWithMorceauPageState#25201
</code>```

Here is what I'm doing :

```<code>   else if (widget.state is TickNotPossibleState){
      buttonState = PAUSE;
      Scaffold.of(context).showSnackBar(SnackBar(content: Text("My Snackbar text!")));
    }

    return _generatePage(buttonState);
</code>```

答: Try showsnackbar in bloc listener and make sure  bloc listener define under scaffold.</p>

Title: Flutter show Snackbar inside build

Body:
I implemented the BLoC pattern in my app by I have a problem.

Once I have a special event, I need to show a snackbar, but I have this error :

The following assertion was thrown building InteractWithMorceauPage(dirty, dependencies: [MediaQuery], state: _InteractWithMorceauPageState#25201):
setState() or markNeedsBuild() called during build.

This Scaffold widget cannot be marked as needing to build because the framework is already in the process of building widgets.  A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: Scaffold
  dependencies: [TickerMode, MediaQuery, _InheritedTheme, _LocalizationsScope-[GlobalKey#dc380], Directionality]
  state: ScaffoldState#8a46b(tickers: tracking 3 tickers)
The widget which was currently being built when the offending call was made was: InteractWithMorceauPage
  dirty
  dependencies: [MediaQuery]
  state: _InteractWithMorceauPageState#25201

Here is what I'm doing :

   else if (widget.state is TickNotPossibleState){
      buttonState = PAUSE;
      Scaffold.of(context).showSnackBar(SnackBar(content: Text("My Snackbar text!")));
    }

    return _generatePage(buttonState);


问:
How can class variables be updated automatically in python?
I am trying to automatically update class variables that are in a fix relation. E.g.

```<code>class vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        self.r = (x**2+y**2+z**2)**0.5
        self.theta = tan((x**2+y**2)**0.5/z)
        self.phi = tan(y/x)
</code>```

If I change the value x of an instance of this class, I want to update the radius and the angles automatically. And if I change an angle or the radius, I want to update the x,y,z components automatically. Is there any way to do this?

Edit:
Okay I have the following solution now. Please correct me if there is a mistake or not conventional what I did.

```<code>from math import tan, cos, sin

class Vector:
    def __init__(self, x, y, z):
        self._x = x
        self._y = y
        self._z = z
        self._r = (self._x**2+self._y**2+self._z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, new_x):
        self._x = new_x
        self._r = (self._x**2+self._y**2+self._z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, new_y):
        self._y = new_y
        self._r = (self._x**2+self._y**2+self._z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def z(self):
        return self._z

    @z.setter
    def z(self, new_z):
        self._z = new_z
        self._r = (self.x**2+self.y**2+self.z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def r(self):
        return (self._x**2+self._y**2+self._z**2)**0.5

    @r.setter
    def r(self, new_r):
        self._r = new_r
        self._x = self._r*cos(self._theta)*cos(self._phi)
        self._y = self._r*cos(self._theta)*sin(self._phi)
        self._z = self._r*sin(self._theta)

    @property
    def theta(self):
        return tan((self._x**2+self._y**2)**0.5/self._z)

    @theta.setter
    def theta(self, new_theta):
        self._theta = new_theta
        self._x = self._r*cos(self._theta)*cos(self._phi)
        self._y = self._r*cos(self._theta)*sin(self._phi)
        self._z = self._r*sin(self._theta)

    @property
    def phi(self):
        return tan(self._y/self._x)

    @phi.setter
    def phi(self,new_phi):
        self._phi = new_phi
        self._x = self._r*cos(self._theta)*cos(self._phi)
        self._y = self._r*cos(self._theta)*sin(self._phi)
        self._z = self._r*sin(self._theta)

</code>```

答:
You are looking for the @property decorator, which sets an object's variable via a function statement.

from math import tan

class Vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    @property
    def r(self):
        return (self.x**2+self.y**2+self.z**2)**0.5

    @property
    def theta(self):
        return tan((self.x**2+self.y**2)**0.5/self.z)

    @property
    def phi(self):
        return tan(self.y/self.x)
```

<p>Therefore,</p>

```v = Vector(1, 2, 3)
v.phi # -2.185039863261519
```

Body:
I am trying to automatically update class variables that are in a fix relation. E.g.

class vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        self.r = (x**2+y**2+z**2)**0.5
        self.theta = tan((x**2+y**2)**0.5/z)
        self.phi = tan(y/x)

If I change the value x of an instance of this class, I want to update the radius and the angles automatically. And if I change an angle or the radius, I want to update the x,y,z components automatically. Is there any way to do this?

Edit:
Okay I have the following solution now. Please correct me if there is a mistake or not conventional what I did.

from math import tan, cos, sin

class Vector:
    def __init__(self, x, y, z):
        self._x = x
        self._y = y
        self._z = z
        self._r = (self._x**2+self._y**2+self._z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, new_x):
        self._x = new_x
        self._r = (self._x**2+self._y**2+self._z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, new_y):
        self._y = new_y
        self._r = (self._x**2+self._y**2+self._z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def z(self):
        return self._z

    @z.setter
    def z(self, new_z):
        self._z = new_z
        self._r = (self.x**2+self.y**2+self.z**2)**0.5
        self._theta = tan((self._x**2+self._y**2)**0.5/self._z)
        self._phi = tan(self._y/self._x)

    @property
    def r(self):
        return (self._x**2+self._y**2+self._z**2)**0.5

    @r.setter
    def r(self, new_r):
        self._r = new_r
        self._x = self._r*cos(self._theta)*cos(self._phi)
        self._y = self._r*cos(self._theta)*sin(self._phi)
        self._z = self._r*sin(self._theta)

    @property
    def theta(self):
        return tan((self._x**2+self._y**2)**0.5/self._z)

    @theta.setter
    def theta(self, new_theta):
        self._theta = new_theta
        self._x = self._r*cos(self._theta)*cos(self._phi)
        self._y = self._r*cos(self._theta)*sin(self._phi)
        self._z = self._r*sin(self._theta)

    @property
    def phi(self):
        return tan(self._y/self._x)

    @phi.setter
    def phi(self,new_phi):
        self._phi = new_phi
        self._x = self._r*cos(self._theta)*cos(self._phi)
        self._y = self._r*cos(self._theta)*sin(self._phi)
        self._z = self._r*sin(self._theta)

Body:
You are looking for the @property decorator, which sets an object's variable via a function statement.

from math import tan

class Vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    @property
    def r(self):
        return (self.x**2+self.y**2+self.z**2)**0.5

    @property
    def theta(self):
        return tan((self.x**2+self.y**2)**0.5/self.z)

    @property
    def phi(self):
        return tan(self.y/self.x)

Therefore,

v = Vector(1, 2, 3)
v.phi # -2.185039863261519


问:
Validating forms Ajax PHP
The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.

contact form index.html

```<code> <div class="form">
                    <div id="sendmessage">Your message has been sent. Thank you!</div>
                    <div id="errormessage"></div>
                    <form action="contactform/contactform.php" method="POST" role="form" class="contactForm">
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
                                <div class="validation"></div>
                            </div>
                            <div class="form-group col-md-6">
                                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
                                <div class="validation"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />
                            <div class="validation"></div>
                        </div>
                        <div class="form-group">
                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
                            <div class="validation"></div>
                        </div>
                        <div class="text-center"><button type="submit">Send Message</button></div>
                    </form>
                </div>
</code>```

contactform.js

```<code>jQuery(document).ready(function($) {
  "use strict";

  //Contact
  $('form.contactForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

    f.children('input').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
            }
            break;

          case 'checked':
            if (! i.is(':checked')) {
              ferror = ierror = true;
            }
            break;

          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    f.children('textarea').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    if (ferror) return false;
    else var str = $(this).serialize();
    var action = $(this).attr('action');
    if( ! action ) {
      action = 'contactform/contactform.php';
    }
    $.ajax({
      type: "POST",
      url: action,
      data: str,
      success: function(msg) {
         //alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, textarea").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});

</code>```

contactform.php

```<code><?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');

//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;

//Add new message
if (isset($_POST['name'])){

        //Get values
        $contactFormName = $_POST['name'];
        $contactFormEmail = $_POST['email'];
        $contactFormSubject = $_POST['subject'];
        $contactFormMessage = $_POST['message'];

        // 1. check name form field
        if($checkStep == 1){
            if($contactFormName === $_POST['name']){
                $contactFormName = filterName($contactFormName);
                $checkStep++;

            }else{
                echo "No its not working";
            }
        }
            // 2. check email field
            if($checkStep == 2){
                if($contactFormEmail === $_POST['email']){
                    $contactFormEmail = filterEmail($contactFormEmail);
                    $checkStep++;
                }else{
                        echo "Uh Oh! Something went wrong with your email please try again!";
                    }
                }

            // 3. check subject
            if($checkStep == 3){
                if($contactFormSubject === $_POST['subject']){
                    $contactFormSubject = filterSubject($contactFormSubject);
                    $checkStep++;
                }else{
                    echo "Uh Oh! Whats up with your subject";
                }
            }
            // 4. check message
            if($checkStep == 4){
                 if($contactFormMessage === $_POST['message']){
                    $contactFormMessage = filterMessage($contactFormMessage);
                     $checkStep++;
                }else{
                    echo "Uh ho!  Please write us a message";
                }
            }
            // 5. insert message
            if($checkStep == 5){
                $sqlAddMessage = "
                    INSERT INTO contact_form(
                        name,
                        email,
                        subject,
                        message
                    ) VALUES(
                        '$contactFormName',
                        '$contactFormEmail',
                        '$contactFormSubject',
                        '$contactFormMessage'
                    )
                ";
                $queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);

                if($queryAddMessage){

                //code goes here
                }

            }else{
                echo "Uh Oh! NO No No. Check step 5";
            }
        }

?>

</code>```

答:
You should echo msg checked by js in php as OK</p>

```<code>if($queryAddMessage){

                //code goes here
                echo 'OK';
 }
</code>```

Title: Validating forms Ajax PHP

Body:
The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.

contact form index.html

Your message has been sent. Thank you!

                    <form action="contactform/contactform.php" method="POST" role="form" class="contactForm">

                                <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />

                                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />

                            <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />

                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>

<button type="submit">Send Message</button>

                    </form>

contactform.js

jQuery(document).ready(function($) {
  "use strict";

  //Contact
  $('form.contactForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;

    f.children('input').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
            }
            break;

          case 'checked':
            if (! i.is(':checked')) {
              ferror = ierror = true;
            }
            break;

          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    f.children('textarea').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    if (ferror) return false;
    else var str = $(this).serialize();
    var action = $(this).attr('action');
    if( ! action ) {
      action = 'contactform/contactform.php';
    }
    $.ajax({
      type: "POST",
      url: action,
      data: str,
      success: function(msg) {
         //alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, textarea").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});

contactform.php

<?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');

//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;

//Add new message
if (isset($_POST['name'])){

        //Get values
        $contactFormName = $_POST['name'];
        $contactFormEmail = $_POST['email'];
        $contactFormSubject = $_POST['subject'];
        $contactFormMessage = $_POST['message'];

        // 1. check name form field
        if($checkStep == 1){
            if($contactFormName === $_POST['name']){
                $contactFormName = filterName($contactFormName);
                $checkStep++;

            }else{
                echo "No its not working";
            }
        }
            // 2. check email field
            if($checkStep == 2){
                if($contactFormEmail === $_POST['email']){
                    $contactFormEmail = filterEmail($contactFormEmail);
                    $checkStep++;
                }else{
                        echo "Uh Oh! Something went wrong with your email please try again!";
                    }
                }

            // 3. check subject
            if($checkStep == 3){
                if($contactFormSubject === $_POST['subject']){
                    $contactFormSubject = filterSubject($contactFormSubject);
                    $checkStep++;
                }else{
                    echo "Uh Oh! Whats up with your subject";
                }
            }
            // 4. check message
            if($checkStep == 4){
                 if($contactFormMessage === $_POST['message']){
                    $contactFormMessage = filterMessage($contactFormMessage);
                     $checkStep++;
                }else{
                    echo "Uh ho!  Please write us a message";
                }
            }
            // 5. insert message
            if($checkStep == 5){
                $sqlAddMessage = "
                    INSERT INTO contact_form(
                        name,
                        email,
                        subject,
                        message
                    ) VALUES(
                        '$contactFormName',
                        '$contactFormEmail',
                        '$contactFormSubject',
                        '$contactFormMessage'
                    )
                ";
                $queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);

                if($queryAddMessage){

                //code goes here
                }

            }else{
                echo "Uh Oh! NO No No. Check step 5";
            }
        }

?>

Body:
You should echo msg checked by js in php as OK

if($queryAddMessage){

                //code goes here
                echo 'OK';
 }


问:
I need an XMPP library for PHP
And I can't use composer (the server is behind a firewall, and PHP-download.com does not work)

In particular, I need to export the user list with their groups

I have tried https://code.google.com/archive/p/xmpphp/ but it is not compatible with PHP 7

答:
```<code>$server   = "SERVER NAME HERE";
$username = "USER NAME HERE";
$password = "PASSWORD HERE";
$resource = "globe";
$streamid = "";

function vardump($data, $title = false){
    if($title){
        echo '<H2>' . $title . '</H2>';
    }
    echo '<PRE>';
    var_dump($data);
    echo '</PRE>';
}

function open_connection($server) {
    $connection = fsockopen($server, 5222, $errno, $errstr);
    if (!$connection) {
        print "$errstr ($errno)<br>";
        return false;
    }
    return $connection;
}

function send_xml($connection, $xml) {
    fwrite($connection, $xml);
}

function textcontains($text, $searchfor, $or = false){
    return stripos($text, $searchfor) !== false;
}

function send_recv_xml($connection, $xml, $size = 4096) {
    send_xml($connection, $xml);
    $data = recv_xml($connection, $size);
    $data["sent_xml"] = $xml;
    $data["sent_html"] = htmlspecialchars($xml);
    return $data;
}

function fread_untildone($connection, $size = 4096){
    $content = '';
    if($size < 0){
        while(!textcontains($content, '</iq>')){
            $content .= fread($connection, abs($size));
        }
    } else {
        $content = fread($connection, $size);
    }
    /*while(!feof($connection)){//did not work
        $content .= fread($connection, $size);
    }*/
    return $content;
}

function recv_xml($connection, $size = 4096) {
    $xml = fread_untildone($connection, $size);
    if ($xml === "") {
         return null;
    }
    // parses xml
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $xml, $val, $index);
    xml_parser_free($xml_parser);
    $RET = array($val, $index);
    $RET["originaldata"] = $xml;
    $RET["specialdata"] = htmlspecialchars($xml);
    $RET["time"] = time();
    return $RET;
}

function find_xmpp($connection, $tag, $value=null, &$ret=null) {
    static $val = null, $index = null;
    do {
        if ($val === null && $index === null) {
            list($val, $index) = recv_xml($connection);
            if ($val === null || $index === null) {
                return false;
            }
        }
        foreach ($index as $tag_key => $tag_array) {
            if ($tag_key === $tag) {
                if ($value === null) {
                    if (isset($val[$tag_array[0]]['value'])) {
                        $ret = $val[$tag_array[0]]['value'];
                    }
                    return true;
                }
                foreach ($tag_array as $i => $pos) {
                    if ($val[$pos]['tag'] === $tag && isset($val[$pos]['value']) &&
                        $val[$pos]['value'] === $value) {
                            $ret = $val[$pos]['value'];
                            return true;
                    }
                }
            }
        }
        $val = $index = null;
    } while (!feof($connection));

    return false;
}

function xmpp_connect($server, $username, $password, $resource = "globe") {
    global $streamid;
    $connection = open_connection($server);
    if (!$connection) {
        return false;
    }
    send_xml($connection, '<stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xmlns="jabber:client" to="' . $server . '" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">');
    $data = recv_xml($connection);
    $streamid = $data[0][0]["attributes"]["ID"];
    //vardump($streamid, "stream id:");

    send_xml($connection, '<iq type="get" to="' . $server . '" id="auth1"><query xmlns="jabber:iq:auth"><username>' . $username . '</username></query></iq>');
    $data = recv_xml($connection);

    $XML = '<iq type="set" id="auth2"><query xmlns="jabber:iq:auth">';
    $fields = [];
    foreach($data[1] as $KEY => $VALUE){
        $KEY = strtolower($KEY);
        switch($KEY){
            case "username":    $VALUE = $username; break;
            case "password":    $VALUE = $password; break;
            case "digest":      $VALUE = strtolower(sha1($streamid . $password)); break;
            case "resource":    $VALUE = $resource; break;
            default: $VALUE = "";
        }
        $fields[ $KEY ] = $VALUE;
        if($VALUE){
            $XML .= '<' . $KEY . '>' . $VALUE . '</' . $KEY . '>';
        }
    }
    $XML .= '</query></iq>';
    //vardump($fields, "auth");

    $data = send_recv_xml($connection, $XML);
    //vardump($data, 'login');

    return $connection;
}

function xmpp_enum_users($connection, $server, $username, $resource = "globe"){
    //$XML = '<iq from="' . $username . '@' . $server . '/' . $resource . '" id="get-registered-users-list-1" to="' . $server . '" type="set" xml:lang="en">';
    //$XML .= '<command xmlns="http://jabber.org/protocol/commands" action="execute" node="http://jabber.org/protocol/admin#get-registered-users-list"/></iq>';

    /*$XML = '<iq from="' . $username . '" type="result" to="' . $username . '@' . $server . '/' .  $resource . '" id="123">
    <query xmlns="http://jabber.org/protocol/disco#items">
        <item jid="conference.localhost" />
        <item jid="pubsub.localhost" />
        <item jid="riot.localhost" />
        <item jid="vjud.localhost" />
        <item node="announce" name="Announcements" jid="localhost" />
        <item node="config" name="Configuration" jid="localhost" />
        <item node="user" name="User Management" jid="localhost" />
        <item node="online users" name="Online Users" jid="localhost" />
        <item node="all users" name="All Users" jid="localhost" />
        <item node="outgoing s2s" name="Outgoing s2s Connections" jid="localhost" />
        <item node="running nodes" name="Running Nodes" jid="localhost" />
        <item node="stopped nodes" name="Stopped Nodes" jid="localhost" />
    </query></iq>';*/
    global $streamid;
    $XML = '<iq from="' . $username . '@' . $server . '/' .  $resource . '" id="' . $streamid . '" type="get"><query xmlns="jabber:iq:roster"/></iq>';
    return send_recv_xml($connection, $XML, -4096);
}

function xmpp_disconnect($connection){
    fclose($connection);
}

$connection = xmpp_connect($server, $username, $password, $resource);
$data = xmpp_enum_users($connection, $server, $username, $resource);
$xml = simplexml_load_string($data["originaldata"]);
$users = [];
foreach($xml->query->item as $user){
    $username = $user->attributes()->name;
    $group = $user->group[0];
    $users[$username] = $group;
}

vardump($users, "users");
echo '<HR>' . json_encode($users);
echo '<HR>';
foreach($users as $username => $group){
    echo $username . '=' . $group . '<BR>';
}

xmpp_disconnect($connection);
</code>```

This is the start of an XMPP client. It took a while to find the base code to connect, and I noticed other people asking for this but not getting it.

Title: I need an XMPP library for PHP

Body:
$server   = "SERVER NAME HERE";
$username = "USER NAME HERE";
$password = "PASSWORD HERE";
$resource = "globe";
$streamid = "";

function vardump($data, $title = false){
    if($title){
        echo '<H2>' . $title . '</H2>';
    }
    echo '<PRE>';
    var_dump($data);
    echo '</PRE>';
}

function open_connection($server) {
    $connection = fsockopen($server, 5222, $errno, $errstr);
    if (!$connection) {
        print "$errstr ($errno)<br>";
        return false;
    }
    return $connection;
}

function send_xml($connection, $xml) {
    fwrite($connection, $xml);
}

function textcontains($text, $searchfor, $or = false){
    return stripos($text, $searchfor) !== false;
}

function send_recv_xml($connection, $xml, $size = 4096) {
    send_xml($connection, $xml);
    $data = recv_xml($connection, $size);
    $data["sent_xml"] = $xml;
    $data["sent_html"] = htmlspecialchars($xml);
    return $data;
}

function fread_untildone($connection, $size = 4096){
    $content = '';
    if($size < 0){
        while(!textcontains($content, '</iq>')){
            $content .= fread($connection, abs($size));
        }
    } else {
        $content = fread($connection, $size);
    }
    /*while(!feof($connection)){//did not work
        $content .= fread($connection, $size);
    }*/
    return $content;
}

function recv_xml($connection, $size = 4096) {
    $xml = fread_untildone($connection, $size);
    if ($xml === "") {
         return null;
    }
    // parses xml
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $xml, $val, $index);
    xml_parser_free($xml_parser);
    $RET = array($val, $index);
    $RET["originaldata"] = $xml;
    $RET["specialdata"] = htmlspecialchars($xml);
    $RET["time"] = time();
    return $RET;
}

function find_xmpp($connection, $tag, $value=null, &$ret=null) {
    static $val = null, $index = null;
    do {
        if ($val === null && $index === null) {
            list($val, $index) = recv_xml($connection);
            if ($val === null || $index === null) {
                return false;
            }
        }
        foreach ($index as $tag_key => $tag_array) {
            if ($tag_key === $tag) {
                if ($value === null) {
                    if (isset($val[$tag_array[0]]['value'])) {
                        $ret = $val[$tag_array[0]]['value'];
                    }
                    return true;
                }
                foreach ($tag_array as $i => $pos) {
                    if ($val[$pos]['tag'] === $tag && isset($val[$pos]['value']) &&
                        $val[$pos]['value'] === $value) {
                            $ret = $val[$pos]['value'];
                            return true;
                    }
                }
            }
        }
        $val = $index = null;
    } while (!feof($connection));

    return false;
}

function xmpp_connect($server, $username, $password, $resource = "globe") {
    global $streamid;
    $connection = open_connection($server);
    if (!$connection) {
        return false;
    }
    send_xml($connection, '<stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xmlns="jabber:client" to="' . $server . '" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">');
    $data = recv_xml($connection);
    $streamid = $data[0][0]["attributes"]["ID"];
    //vardump($streamid, "stream id:");

    send_xml($connection, '<iq type="get" to="' . $server . '" id="auth1"><query xmlns="jabber:iq:auth"><username>' . $username . '</username></query></iq>');
    $data = recv_xml($connection);

    $XML = '<iq type="set" id="auth2"><query xmlns="jabber:iq:auth">';
    $fields = [];
    foreach($data[1] as $KEY => $VALUE){
        $KEY = strtolower($KEY);
        switch($KEY){
            case "username":    $VALUE = $username; break;
            case "password":    $VALUE = $password; break;
            case "digest":      $VALUE = strtolower(sha1($streamid . $password)); break;
            case "resource":    $VALUE = $resource; break;
            default: $VALUE = "";
        }
        $fields[ $KEY ] = $VALUE;
        if($VALUE){
            $XML .= '<' . $KEY . '>' . $VALUE . '</' . $KEY . '>';
        }
    }
    $XML .= '</query></iq>';
    //vardump($fields, "auth");

    $data = send_recv_xml($connection, $XML);
    //vardump($data, 'login');

    return $connection;
}

function xmpp_enum_users($connection, $server, $username, $resource = "globe"){
    //$XML = '<iq from="' . $username . '@' . $server . '/' . $resource . '" id="get-registered-users-list-1" to="' . $server . '" type="set" xml:lang="en">';
    //$XML .= '<command xmlns="http://jabber.org/protocol/commands" action="execute" node="http://jabber.org/protocol/admin#get-registered-users-list"/></iq>';

    /*$XML = '<iq from="' . $username . '" type="result" to="' . $username . '@' . $server . '/' .  $resource . '" id="123">
    <query xmlns="http://jabber.org/protocol/disco#items">
        <item jid="conference.localhost" />
        <item jid="pubsub.localhost" />
        <item jid="riot.localhost" />
        <item jid="vjud.localhost" />
        <item node="announce" name="Announcements" jid="localhost" />
        <item node="config" name="Configuration" jid="localhost" />
        <item node="user" name="User Management" jid="localhost" />
        <item node="online users" name="Online Users" jid="localhost" />
        <item node="all users" name="All Users" jid="localhost" />
        <item node="outgoing s2s" name="Outgoing s2s Connections" jid="localhost" />
        <item node="running nodes" name="Running Nodes" jid="localhost" />
        <item node="stopped nodes" name="Stopped Nodes" jid="localhost" />
    </query></iq>';*/
    global $streamid;
    $XML = '<iq from="' . $username . '@' . $server . '/' .  $resource . '" id="' . $streamid . '" type="get"><query xmlns="jabber:iq:roster"/></iq>';
    return send_recv_xml($connection, $XML, -4096);
}

function xmpp_disconnect($connection){
    fclose($connection);
}

$connection = xmpp_connect($server, $username, $password, $resource);
$data = xmpp_enum_users($connection, $server, $username, $resource);
$xml = simplexml_load_string($data["originaldata"]);
$users = [];
foreach($xml->query->item as $user){
    $username = $user->attributes()->name;
    $group = $user->group[0];
    $users[$username] = $group;
}

vardump($users, "users");
echo '<HR>' . json_encode($users);
echo '<HR>';
foreach($users as $username => $group){
    echo $username . '=' . $group . '<BR>';
}

xmpp_disconnect($connection);

This is the start of an XMPP client. It took a while to find the base code to connect, and I noticed other people asking for this but not getting it.


问:
Flutter: How to securely share data among two separate android apps?
I need to share some particular data among two separate apps on android,
preferably make some kind of shared folder which can be accessed by both the apps only.

Why? I need a single sign on functionality between two separate apps.

Till now I have been authenticating users using JWT tokens by storing them in sharedpreferences (storing them to maintain the signin) and clearing the shared prefs when the user logs out (along with hitting the api which changes the token).

Now I have another app which works with the same token.

What's required: you sign into one and another one automatically signs in. So, my plan is to store the token on the device which in turn can be accessed by both the apps.

I know I will need an active directory for a secure SSO but I am okay with not having a 100% security as of now, the question still remains about how to share data among apps.

答:
I'm just giving you an idea, and not to mention this ONLY works in Android.

From your 1st app (primary), create a file (for now, I am creating a .txt file) in device external storage using path_provider,

```<code>Future<void> _createAndWrite() async {
  // Get external directory
  final directory = (await Directory('storage/emulated/0/Sharing Folder').create()).path;

  // Create your file
  final file = File('$directory/any_file.txt');
  await file.create();

  // Write to the file
  await file.writeAsString('Content to write');
}
</code>```

In your 2nd app, you can read the contents of the file with something like:

```<code>Future<void> _readFile() async {
  // Get external directory
  final directory = (await Directory('storage/emulated/0/Sharing Folder').create()).path;

  // Get the file
  final file = File('$directory/any_file.txt');

  // Read it
  final content = await file.readAsString();
}
</code>```

Make sure in both apps you have declared the following permission:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Body:
I'm just giving you an idea, and not to mention this ONLY works in Android.

From your 1st app (primary), create a file (for now, I am creating a .txt file) in device external storage using path_provider,

Future<void> _createAndWrite() async {
  // Get external directory
  final directory = (await Directory('storage/emulated/0/Sharing Folder').create()).path;

  // Create your file
  final file = File('$directory/any_file.txt');
  await file.create();

  // Write to the file
  await file.writeAsString('Content to write');
}

In your 2nd app, you can read the contents of the file with something like:

Future<void> _readFile() async {
  // Get external directory
  final directory = (await Directory('storage/emulated/0/Sharing Folder').create()).path;

  // Get the file
  final file = File('$directory/any_file.txt');

  // Read it
  final content = await file.readAsString();
}

Make sure in both apps you have declared the following permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


答:
You could rewrite your class as below</p>

```<code>import math

class Vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    @property
    def radius(self):
        return (self.x**2+self.y**2+self.z**2)**0.5

    @property
    def theta(self):
        return math.tan((self.x**2+self.y**2)**0.5/self.z)

    @property
    def phi(self):
        return math.tan(self.y/self.x)

</code>```

Title: How can class variables be updated automatically in python?

Body:
You could rewrite your class as below

import math

class Vector:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    @property
    def radius(self):
        return (self.x**2+self.y**2+self.z**2)**0.5

    @property
    def theta(self):
        return math.tan((self.x**2+self.y**2)**0.5/self.z)

    @property
    def phi(self):
        return math.tan(self.y/self.x)


问:
GDB Unknown Load Command
I compiled a project for debugging, but when I try to run it through GDB I get this message:
Reading symbols from FSOP...

BFD: /usr/lib/dyld(i386:x86-64): unknown load command 0x34

BFD: /usr/lib/dyld(i386:x86-64): unknown load command 0x34

BFD: /usr/lib/dyld(i386:x86-64): unknown load command 0x34

I am using GDB 9.1 and am on Mac OS Catilina. Anyone know what is going wrong?

答:
BFD is complaining because there is a mach-o load command in dyld that it doesn't understand.  The load commands are the directives the linker uses to describe the contents of a mach-o executable.

You can find all the mach-o load commands in usr/include/mach-o/loader.h.  0x34 is LC_DYLD_CHAINED_FIXUPS.  Looks like it was added at the end of 2019.

lldb doesn't have to do anything with this load command (other than not complain about it).  So gdb shouldn't need to handle this either, and provided this is just a warning and not an error from BFD, you can ignore it.

I don't remember whether gdb uses its own copy of the loader.h defines or uses the one from the system includes.  If the latter, you probably just need to rebuild gdb against a Catalina SDK.

Title: GDB Unknown Load Command


问:
Pandas read_excel doesn't parse dates correctly - returns a constant date instead
I've read a .xlsb file and parsed date columns using a code below:

```<code>dateparser = lambda x: pd.to_datetime(x)

data = pd.read_excel(r"test.xlsb", engine="pyxlsb",
                 parse_dates=["start_date","end_date"],
                 date_parser=dateparser
                 )
</code>```

My input columns in the .xlsb file have format DD/MM/YYYY (e.g. 26/01/2008). As an output of the above-mentioned code I get, for example: 1970-01-01 00:00:00.000038840. Only the last 5 digits changes.

If I read the same file without parsing dates, the same columns are of float64 type and containing only the last 5 digits of output before (e.g. 38840.0).

I assume this is a problem associated with date encoding itself. Does anyone know how to fix this issue?

答:
I am not sure if you were able to figure out the answer to this problem. But, below is how I resolved it:

```<code>from pyxlsb import convert_date

self.data: pd.DataFrame = pd.read_excel(self.file, sheet_name=self.sheet, engine='pyxlsb', header=0)
self.data["test"] = self.data.apply(lambda x: convert_date(x.SomeStupidDate), axis=1)
</code>```

More details can be found here: https://pypi.org/project/pyxlsb/ by doing ctrl+F for "convert_date".

Body:
I've read a .xlsb file and parsed date columns using a code below:

dateparser = lambda x: pd.to_datetime(x)

data = pd.read_excel(r"test.xlsb", engine="pyxlsb",
                 parse_dates=["start_date","end_date"],
                 date_parser=dateparser
                 )

My input columns in the .xlsb file have format DD/MM/YYYY (e.g. 26/01/2008). As an output of the above-mentioned code I get, for example: 1970-01-01 00:00:00.000038840. Only the last 5 digits changes.

If I read the same file without parsing dates, the same columns are of float64 type and containing only the last 5 digits of output before (e.g. 38840.0).

I assume this is a problem associated with date encoding itself. Does anyone know how to fix this issue?

Body:
I am not sure if you were able to figure out the answer to this problem. But, below is how I resolved it:

from pyxlsb import convert_date

self.data: pd.DataFrame = pd.read_excel(self.file, sheet_name=self.sheet, engine='pyxlsb', header=0)
self.data["test"] = self.data.apply(lambda x: convert_date(x.SomeStupidDate), axis=1)

More details can be found here: https://pypi.org/project/pyxlsb/ by doing ctrl+F for "convert_date".