问:
creating volume point on candle
I want to point out the highest volume on a candlestick with a vertical line. Now I only see this point inside the body of the candlestick (without seeing this point in the wick). I would include the wicks in this. Could someone help?

```<code>//@version=4
study("Name", overlay=true)
i = input(1, title="Volume Periods")
Name = barssince(volume == max(highest(volume, i), 0))
plot(close[Name], color=color.black, title="Name", style=plot.style_circles)
</code>```

enter image description here

The length of the horizontal line should be shorter.

答:
Drawing vertical lines in PineScript is tricky and can cause scaling problems.

Some examples can be found here.

It might be better to just highlight the background when your condition occurs.

```<code>//@version=4
study("Name", overlay=true)
i = input(20, title="Volume Periods")
bgcolor(volume == highest(volume,i) ? color.yellow : na)
</code>```

Which yields

Title: creating volume point on candle

Body:
I want to point out the highest volume on a candlestick with a vertical line. Now I only see this point inside the body of the candlestick (without seeing this point in the wick). I would include the wicks in this. Could someone help?

//@version=4
study("Name", overlay=true)
i = input(1, title="Volume Periods")
Name = barssince(volume == max(highest(volume, i), 0))
plot(close[Name], color=color.black, title="Name", style=plot.style_circles)

enter image description here

The length of the horizontal line should be shorter.

Body:
Drawing vertical lines in PineScript is tricky and can cause scaling problems.

Some examples can be found here.

It might be better to just highlight the background when your condition occurs.

//@version=4
study("Name", overlay=true)
i = input(20, title="Volume Periods")
bgcolor(volume == highest(volume,i) ? color.yellow : na)

Which yields


来源: stackexchange

问:
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit
When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?

I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.

答:
You don't need to commit, you just need to flush.  Here's some sample code.  After the call to flush you can access the primary key that was assigned.  Note this is with SQLAlchemy v1.3.6 and Python 3.7.4.

```<code>from sqlalchemy import *
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class User(Base):
    __tablename__ = 'user'
    user_id = Column('user_id', Integer, primary_key=True)
    name = Column('name', String)

if __name__ == '__main__':
    import unittest
    from sqlalchemy.orm import *
    import datetime

    class Blah(unittest.TestCase):
        def setUp(self):
            self.engine = create_engine('sqlite:///:memory:', echo=True)
            self.sessionmaker = scoped_session(sessionmaker(bind=self.engine))
            Base.metadata.bind = self.engine
            Base.metadata.create_all()
            self.now = datetime.datetime.now()

        def test_pkid(self):
            user = User(name="Joe")
            session = self.sessionmaker()
            session.add(user)
            session.flush()
            print('user_id', user.user_id)
            session.commit()
            session.close()

    unittest.main()
</code>```

OwnerDisplayName: Sean

LastEditorDisplayName: Jacob Gabrielson

ContentLicense: CC BY-SA 2.5

Body:
You don't need to commit, you just need to flush.  Here's some sample code.  After the call to flush you can access the primary key that was assigned.  Note this is with SQLAlchemy v1.3.6 and Python 3.7.4.

from sqlalchemy import *
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class User(Base):
    __tablename__ = 'user'
    user_id = Column('user_id', Integer, primary_key=True)
    name = Column('name', String)

if __name__ == '__main__':
    import unittest
    from sqlalchemy.orm import *
    import datetime

    class Blah(unittest.TestCase):
        def setUp(self):
            self.engine = create_engine('sqlite:///:memory:', echo=True)
            self.sessionmaker = scoped_session(sessionmaker(bind=self.engine))
            Base.metadata.bind = self.engine
            Base.metadata.create_all()
            self.now = datetime.datetime.now()

        def test_pkid(self):
            user = User(name="Joe")
            session = self.sessionmaker()
            session.add(user)
            session.flush()
            print('user_id', user.user_id)
            session.commit()
            session.close()

    unittest.main()

OwnerDisplayName: Jacob Gabrielson

ContentLicense: CC BY-SA 4.0


问:
Reindexing using lucene/ deleting term from index
I hope you can help me, here is my problem:

edit: Now that I re-thought, if there is a way to delete a term from the index, it would work anyway. Is there a way to do that? if there is, there is no need to read the rest of the question. thanks!

Here is what I intend to do:
1 - I have to index some files while removing the standard stopwords.
2 - Afterwards, I must count the document frequency of every term, and remove those terms that have df < 2

How I'm doing it:

1 - I index the files using indexwriter, while removing the std stopwords.
2 - I count the df of every term, and add to the stopwords list.
3 - And then, I index again the texts using indexwriter, but with the new stopwords list

What's really happening:

The first time I index it goes as planned. The problem is when I try to index for a second time. The result becomes pretty unpredictable:

1) if i run the program one time, even though the stopwords has new words,only the std stopwords are removed.

2) if i run the program a second time, then the terms with df < 2 are removed.

I print the terms in the index twice, one after indexing for the first time, and one after indexing for the second time.

When i run for a second time, the terms with df < 2 appear removed in the first print(notice that I add the terms with df < 2 when indexing for the second time, It shouldn't) appear removed in the first print.

Maybe the way I explained was a bit confusing, I ask you to tell me if something couldn't be understood.

I hope you guys can help me.
Thank you very much!

答:
When indexing documents for the second time, make sure to delete the first instance of the document, otherwise you will inflate the dfs for all terms. You can delete documents by the external id field: create a Term with field=idfield & value=externalId, and then use deleteDocument(Term) of IndexWriter to remove the old instance; then add the new one. I don't think there is a way to delete terms explicitly; they are derived from the documents.

As an optimization, you might consider the following:
1. Index all documents
2. Find all terms with df = 1
3. Remove all documents with each such term, keeping track of their external document ids
4. Add the terms to your stop list
5. Re-index only the previously-removed documents.

Of course first you have to think carefully about the use case for removing these terms.
1. Why does it matter if they occur in the index?
2. What happens if you update the index later, and add a new document that causes some term that previously had df=1 now to have df=2. You wouldn't be able to index on that term since it would have been already in the stop list.

ContentLicense: CC BY-SA 3.0


问:
delete item from recyclerview and firebase database showing error
When i click the delete button it removes the child. After removing child its its showing error.
What can be the solution? I have tried various option, but same issue showing again and again. can anyone help me to solve this problem?

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

    public Context mContext;
    private List <Post>mPost;
    private FirebaseUser firebaseUser;
    ProgressBar progressBar;

    public PostAdapter(Context mContext, List<Post> mPost) {
        this.mContext = mContext;
        this.mPost = mPost;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);

        return new PostAdapter.ViewHolder(view);
    }

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

        firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
        final Post post=mPost.get(position);

        try {
            Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(holder.post_image);

        }catch (Exception e)
        {

        }

        //holder.time.setText(post.getTime());
        Get_Time_ago getTimeAgo=new Get_Time_ago();

        long lastTime=Long.parseLong(String.valueOf(post.timestamp));
        String last_seen_time=getTimeAgo.getTimeAgo(lastTime,mContext);
       holder. time.setText(last_seen_time);
                   /*SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                   String time=sfd.format(new Date(lastseenonline));
                   mLast_seenview.setText(time);*/

        if(post.getDescription().equals("")){
            holder.description.setVisibility(View.GONE);

        }else {
            holder.description.setVisibility(View.VISIBLE);
            holder.description.setText(post.getDescription());

        }

        publisherInfo(holder.image_profile,holder.username,holder.blood,holder.publisher,post.getPublisher());

        if(post.getPublisher().equals(firebaseUser.getUid())){
            holder.delete.setVisibility(View.VISIBLE);

        }else {
            holder.delete.setVisibility(View.GONE);

        }

        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                    alertDialog.setTitle("Confirm Delete?");
                    alertDialog.setMessage("Do you want to delete your post?");
                    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
                            notify();

                        }
                    });
                    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    alertDialog.show();
                }

        });

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView image_profile,post_image,like,dislike,comment,save,delete;
        public TextView username,blood,likes,dislikes,comments, description,publisher,time;

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

            image_profile=itemView.findViewById(R.id.image_profile);
            post_image=itemView.findViewById(R.id.post_image);
            like=itemView.findViewById(R.id.like);
            comment=itemView.findViewById(R.id.comment);
            save=itemView.findViewById(R.id.save);
            delete=itemView.findViewById(R.id.delete);

            username=itemView.findViewById(R.id.username);
            blood=itemView.findViewById(R.id.blood);
            time=itemView.findViewById(R.id.time);

            likes=itemView.findViewById(R.id.likes);
            dislikes=itemView.findViewById(R.id.dislikes);
            dislike=itemView.findViewById(R.id.dislike);
            comments=itemView.findViewById(R.id.comments);
            description=itemView.findViewById(R.id.description);
            publisher=itemView.findViewById(R.id.publisher);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);

        }
    }

    private void publisherInfo (final ImageView image_profile, final TextView username,final  TextView blood, final TextView publisher, final String userId ){
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                try {
                    User user=dataSnapshot.getValue(User.class);
                    Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(image_profile);

                    username.setText(user.getUsername());
                    blood.setText(user.getBlood());

                    publisher.setText(user.getUsername());

                }catch (Exception e){

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

}
</code>```

Error

```<code>java.lang.NullPointerException: Attempt to read from field 'long com.example.mfree.Model.Post.timestamp' on a null object reference
        at com.example.mfree.Adapter.PostAdapter.onBindViewHolder(PostAdapter.java:116)
        at com.example.mfree.Adapter.PostAdapter.onBindViewHolder(PostAdapter.java:51)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3540)
        at android.view.View.measure(View.java:23169)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2718)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1572)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1855)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
2020-05-29 06:45:07.599 9312-9312/com.example.mfree E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

答:
In the setPositiveButton onClick:

Instead of this:

```<code>......
......
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
notify();
............
</code>```

Try this:

```<code>......
......
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
mPost.remove(position);
notifyDataSetChanged();
............
</code>```

Body:
When i click the delete button it removes the child. After removing child its its showing error.
What can be the solution? I have tried various option, but same issue showing again and again. can anyone help me to solve this problem?

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

    public Context mContext;
    private List <Post>mPost;
    private FirebaseUser firebaseUser;
    ProgressBar progressBar;

    public PostAdapter(Context mContext, List<Post> mPost) {
        this.mContext = mContext;
        this.mPost = mPost;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);

        return new PostAdapter.ViewHolder(view);
    }

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

        firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
        final Post post=mPost.get(position);

        try {
            Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(holder.post_image);

        }catch (Exception e)
        {

        }

        //holder.time.setText(post.getTime());
        Get_Time_ago getTimeAgo=new Get_Time_ago();

        long lastTime=Long.parseLong(String.valueOf(post.timestamp));
        String last_seen_time=getTimeAgo.getTimeAgo(lastTime,mContext);
       holder. time.setText(last_seen_time);
                   /*SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                   String time=sfd.format(new Date(lastseenonline));
                   mLast_seenview.setText(time);*/

        if(post.getDescription().equals("")){
            holder.description.setVisibility(View.GONE);

        }else {
            holder.description.setVisibility(View.VISIBLE);
            holder.description.setText(post.getDescription());

        }

        publisherInfo(holder.image_profile,holder.username,holder.blood,holder.publisher,post.getPublisher());

        if(post.getPublisher().equals(firebaseUser.getUid())){
            holder.delete.setVisibility(View.VISIBLE);

        }else {
            holder.delete.setVisibility(View.GONE);

        }

        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                    alertDialog.setTitle("Confirm Delete?");
                    alertDialog.setMessage("Do you want to delete your post?");
                    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
                            notify();

                        }
                    });
                    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    alertDialog.show();
                }

        });

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView image_profile,post_image,like,dislike,comment,save,delete;
        public TextView username,blood,likes,dislikes,comments, description,publisher,time;

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

            image_profile=itemView.findViewById(R.id.image_profile);
            post_image=itemView.findViewById(R.id.post_image);
            like=itemView.findViewById(R.id.like);
            comment=itemView.findViewById(R.id.comment);
            save=itemView.findViewById(R.id.save);
            delete=itemView.findViewById(R.id.delete);

            username=itemView.findViewById(R.id.username);
            blood=itemView.findViewById(R.id.blood);
            time=itemView.findViewById(R.id.time);

            likes=itemView.findViewById(R.id.likes);
            dislikes=itemView.findViewById(R.id.dislikes);
            dislike=itemView.findViewById(R.id.dislike);
            comments=itemView.findViewById(R.id.comments);
            description=itemView.findViewById(R.id.description);
            publisher=itemView.findViewById(R.id.publisher);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);

        }
    }

    private void publisherInfo (final ImageView image_profile, final TextView username,final  TextView blood, final TextView publisher, final String userId ){
        DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                try {
                    User user=dataSnapshot.getValue(User.class);
                    Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(image_profile);

                    username.setText(user.getUsername());
                    blood.setText(user.getBlood());

                    publisher.setText(user.getUsername());

                }catch (Exception e){

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

}

Error

java.lang.NullPointerException: Attempt to read from field 'long com.example.mfree.Model.Post.timestamp' on a null object reference
        at com.example.mfree.Adapter.PostAdapter.onBindViewHolder(PostAdapter.java:116)
        at com.example.mfree.Adapter.PostAdapter.onBindViewHolder(PostAdapter.java:51)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3540)
        at android.view.View.measure(View.java:23169)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2718)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1572)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1855)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
2020-05-29 06:45:07.599 9312-9312/com.example.mfree E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Body:
In the setPositiveButton onClick:

Instead of this:

......
......
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
notify();
............

Try this:

......
......
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

dialog.cancel();
FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
mPost.remove(position);
notifyDataSetChanged();
............


问:
Unable to load QML plugin: cannot protect module as it was never registered
I am unable to load a qml file from C++:

```<code>QQmlComponent component(&engine, QUrl("qrc:/qml/Singletons.qml"));
</code>```

At the top of this file we have

```<code>import My.Module 1.0
</code>```

The error is (component.errorString()):

```<code>plugin cannot be loaded for module "My.Module": Cannot protect module My.Module 1 as it was never registered
</code>```

My.Module is a plugin containing qml only. It has been successfully loaded using QQmlEngine::importPlugin. The qml components are in a qrc and are compiled. I don't register any types in the plugin itself. This worked for Qt 5.14.1 but doesn't work for Qt 5.15.0

答:
The reason is that I didn't register any types, in this case it turns out you need to call qmlRegisterModule:

```<code>void MyModulePlugin::registerTypes(const char *uri)
{
    Q_ASSERT(uri == QLatin1String("My.Module"));
    qmlRegisterModule(uri, 1, 0);
}
</code>```

Body:
I am unable to load a qml file from C++:

QQmlComponent component(&engine, QUrl("qrc:/qml/Singletons.qml"));

At the top of this file we have

import My.Module 1.0

The error is (component.errorString()):

plugin cannot be loaded for module "My.Module": Cannot protect module My.Module 1 as it was never registered

My.Module is a plugin containing qml only. It has been successfully loaded using QQmlEngine::importPlugin. The qml components are in a qrc and are compiled. I don't register any types in the plugin itself. This worked for Qt 5.14.1 but doesn't work for Qt 5.15.0

Body:
The reason is that I didn't register any types, in this case it turns out you need to call qmlRegisterModule:

void MyModulePlugin::registerTypes(const char *uri)
{
    Q_ASSERT(uri == QLatin1String("My.Module"));
    qmlRegisterModule(uri, 1, 0);
}


问:
Smooth circular data
I have an array of data Y such that Y is a function of an independent variable X (another array).

The values in X vary from 0 to 360, with wraparound.

The values in Y vary from -180 to 180, also with wraparound.

(That is, these values are angles in degrees around a circle.)

Does anyone know of any function in Python (in numpy, scipy, etc.) capable of low-pass filtering my Y values as a function of X?

In case this is at all confusing, here's a plot of example data:

答:
You can use convolve2D from scipy.signal. Here is a function, which applies smoothing to a numpy array a. If a has more than one dimension smoothing is applied to the innermost (fastest) dimension.

```<code>import numpy as np
from scipy import signal

def cyclic_moving_av( a, n= 3, win_type= 'boxcar' ):
  window= signal.get_window( win_type, n, fftbins=False ).reshape( (1,n) )
  shp_a= a.shape
  b= signal.convolve2d( a.reshape( ( np.prod( shp_a[:-1], dtype=int ), shp_a[-1] ) ),
                        window, boundary='wrap', mode='same' )
  return ( b / np.sum( window ) ).reshape( shp_a )
</code>```

For instance it can be used like

```<code>import matplotlib.pyplot as plt

x = np.linspace(0, 360, 360)
y1 = 5 * np.sin(x / 90. * 3.14) + 0.5 * np.random.randn(360)
y2 = 5 * np.cos(0.8 * x / 90. * 3.14) + 0.5 * np.random.randn(360)

y_av=  cyclic_moving_av( np.stack((y1,y2)), n=10 )  #1

plt.plot(x, y1, '+')
plt.plot(x, y2, '+')
plt.plot(x, y_av[0])
plt.plot(x, y_av[1])
plt.show()
</code>```

This results in

Line #1 is equivalent to

```<code>y_av[0]=  cyclic_moving_av( y1, n=10 )
y_av[1]=  cyclic_moving_av( y2, n=10 )
</code>```

win_type= 'boxcar' results in averaging over neighbors with equal weights. See signal.get_window for other options.

Title: Smooth circular data

Body:
You can use convolve2D from scipy.signal. Here is a function, which applies smoothing to a numpy array a. If a has more than one dimension smoothing is applied to the innermost (fastest) dimension.

import numpy as np
from scipy import signal

def cyclic_moving_av( a, n= 3, win_type= 'boxcar' ):
  window= signal.get_window( win_type, n, fftbins=False ).reshape( (1,n) )
  shp_a= a.shape
  b= signal.convolve2d( a.reshape( ( np.prod( shp_a[:-1], dtype=int ), shp_a[-1] ) ),
                        window, boundary='wrap', mode='same' )
  return ( b / np.sum( window ) ).reshape( shp_a )

For instance it can be used like

import matplotlib.pyplot as plt

x = np.linspace(0, 360, 360)
y1 = 5 * np.sin(x / 90. * 3.14) + 0.5 * np.random.randn(360)
y2 = 5 * np.cos(0.8 * x / 90. * 3.14) + 0.5 * np.random.randn(360)

y_av=  cyclic_moving_av( np.stack((y1,y2)), n=10 )  #1

plt.plot(x, y1, '+')
plt.plot(x, y2, '+')
plt.plot(x, y_av[0])
plt.plot(x, y_av[1])
plt.show()

This results in

Line #1 is equivalent to

y_av[0]=  cyclic_moving_av( y1, n=10 )
y_av[1]=  cyclic_moving_av( y2, n=10 )

win_type= 'boxcar' results in averaging over neighbors with equal weights. See signal.get_window for other options.


问:
How to destroy slider vue-awesome-swiper in vue.js?
I need to destroy vue-awesome-swiper on desktop and leave on tablet screen. exactly destroy, and not disable swipe. But can I destroy swiper? In directive :options I pass params and component-tag swiper will be worked in any case. Only without passed params</p>

```<code>   <template lang="pug">
    .app
      swiper(:options="swiperOptions")
        swiper-slide(
          v-for="(slide, idx) in slides"
          :key="idx"
          )

    <script>

    import { swiper, swiperSlide } from 'vue-awesome-swiper'

    export default {
      name: 'MySlider',
      components: {
        swiper,
        swiperSlide
      },
      data() {
        return {
          slides: [
            {
              title: 'Заголовок 1',
              img: 'title.jpg',
            },
            {
              title: 'title2',
              img: 'slide2.jpg',
            },
            {
              title: 'title3',
              img: 'slide3.jpg',
            }
        ],
          swiperOptions: {
            slidesPerView: 5,
            spaceBetween: 21,
            // allowTouchMove: false,
            breakpoints: {
              992: {
                slidesPerView: 3,
                spaceBetween: 25,
              },
              768: {
                slidesPerView: 3.7,
                spaceBetween: 22,
              },
              640: {
                slidesPerView: 2.2,
                spaceBetween: 15,
                initialSlide: 0,
                centeredSlides: false,
              }
            },
          },
        }
      },
</code>```

答:
What about using v-if on swiper element so it won't be rendered when viewed on desktop?

You would create a method that detects if the client is desktop or tablet and pass the result to the v-if attribute.

Body:
I need to destroy vue-awesome-swiper on desktop and leave on tablet screen. exactly destroy, and not disable swipe. But can I destroy swiper? In directive :options I pass params and component-tag swiper will be worked in any case. Only without passed params

   <template lang="pug">
    .app
      swiper(:options="swiperOptions")
        swiper-slide(
          v-for="(slide, idx) in slides"
          :key="idx"
          )


问:
Edge Chromium giving Failed to read the 'localStorage' property from 'Window': Access is denied for this document
I am trying to embed a Google Data Studio report in an iframe for a static site.
When opening that static site, in Edge Chromium 83.0.478.37 I recieve this error and the data studio report does not appear. It is a clean default install of Edge Chromium, with no settings modified.

```<code>Tracking Prevention blocked access to storage for https://datastudio.google.com/embed/reporting/<urlofreport>.

error:
datastudio__en.js?cb=312620414:3587 ERROR DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
</code>```

I've found this information, but in my Edge Chromium, that setting is disabled:
Disabled block third-party cookies.
The thing that seems to work is to add an Exception in the "Privacy and services" tab in Edge Settings for the domain embedding the iframe. This seems unneccessary, especially when the same static site works on newest versions on both Chrome, Safari, Opera and Firefox. It also seems unnecessary when Data Studio support suggests to use newest Edge. I don't recieve this error when opening the Data Studio report directly in a tab

答:
I have tested the simple example on my side using Microsoft Edge Chromium 83.0.478.37 version. If we use F12 developer tools to check it, we can see in the Console tab, it contains multiple Tracking prevention blocked Warning and the error message.

After adding the url "https://storage.googleapis.com" in the Edge Tracking Prevention Exception, the warning and the error message will disappear.

So, the issue might be related to the Google Data Studio or Edge Tracking Prevention, I suggest you could feedback this issue to the Google Data Studio and Edge browser (click the Send feedback button on the right corner of the Edge browser).

As a workaround, you could add the domain or URL in Edge Tracking Prevention Exception to prevent tracking prevention for that site

Body:
I am trying to embed a Google Data Studio report in an iframe for a static site.
When opening that static site, in Edge Chromium 83.0.478.37 I recieve this error and the data studio report does not appear. It is a clean default install of Edge Chromium, with no settings modified.

Tracking Prevention blocked access to storage for https://datastudio.google.com/embed/reporting/<urlofreport>.

error:
datastudio__en.js?cb=312620414:3587 ERROR DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

I've found this information, but in my Edge Chromium, that setting is disabled:
Disabled block third-party cookies.
The thing that seems to work is to add an Exception in the "Privacy and services" tab in Edge Settings for the domain embedding the iframe. This seems unneccessary, especially when the same static site works on newest versions on both Chrome, Safari, Opera and Firefox. It also seems unnecessary when Data Studio support suggests to use newest Edge. I don't recieve this error when opening the Data Studio report directly in a tab


问:
Re-use variable outside of function?
How can I use return the $row array in the below example, so that I can re-use the variable outside of this function?

I manage to echo the information inside the function using $row['columnName'], but various combinations of global and $GLOBALS, return $xyz and getting variable scope to work for me has me a bit out of my depth. Any answers please?

```<code><?php
function getInfo() {

    $query = /* Some SQL Query */;

    $result = mysql_query($query);

    if($result == false)
    {
       user_error("Query failed: " . mysql_error() . "<br />\n$query");
    }
    elseif(mysql_num_rows($result) == 0)
    {
       echo "<p>Sorry, no rows were returned by your query.</p>\n";
    }
    else
    {
    while ($row = mysql_fetch_assoc($result)) {
        /* What goes here? */
        }
    }

}
?>
</code>```

答:
Just return it from your function:

```<code>$results = array();
while ($row = mysql_fetch_assoc($result)) {
    $results[] = $row;    // or do something more with the row
}
return $results;
</code>```

and call your function like:

```<code>$query_results = getInfo();
</code>```

Title: Re-use variable outside of function?

Body:
How can I use return the $row array in the below example, so that I can re-use the variable outside of this function?

I manage to echo the information inside the function using $row['columnName'], but various combinations of global and $GLOBALS, return $xyz and getting variable scope to work for me has me a bit out of my depth. Any answers please?

<?php
function getInfo() {

    $query = /* Some SQL Query */;

    $result = mysql_query($query);

    if($result == false)
    {
       user_error("Query failed: " . mysql_error() . "
\n$query");
    }
    elseif(mysql_num_rows($result) == 0)
    {
       echo "
Sorry, no rows were returned by your query.
\n";
    }
    else
    {
    while ($row = mysql_fetch_assoc($result)) {
        /* What goes here? */
        }
    }

}
?>

Body:
Just return it from your function:

$results = array();
while ($row = mysql_fetch_assoc($result)) {
    $results[] = $row;    // or do something more with the row
}
return $results;

and call your function like:

$query_results = getInfo();


问:
Getting error while running a script which uses pywinauto
Whenever I import pywinauto I am getting below error
"
Traceback (most recent call last):
File "D:\Python\Python38\lib\ctypes_init_.py", line 123, in WINFUNCTYPE
return _win_functype_cache[(restype, argtypes, flags)]
KeyError: (, (, , ), 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Users/tejaw/PycharmProjects/xxxxxxxx/Sample.py", line 3, in
import pywinauto
File "D:\Python\Python38\lib\site-packages\pywinauto_init_.py", line 89, in
from . import findwindows
File "D:\Python\Python38\lib\site-packages\pywinauto\findwindows.py", line 42, in
from . import controls
File "D:\Python\Python38\lib\site-packages\pywinauto\controls_init_.py", line 36, in
from . import uiawrapper # register "uia" back-end (at the end of uiawrapper module)
File "D:\Python\Python38\lib\site-packages\pywinauto\controls\uiawrapper.py", line 47, in
from ..uia_defines import IUIA
File "D:\Python\Python38\lib\site-packages\pywinauto\uia_defines.py", line 181, in
pattern_ids = _build_pattern_ids_dic()
File "D:\Python\Python38\lib\site-packages\pywinauto\uia_defines.py", line 169, in _build_pattern_ids_dic
if hasattr(IUIA().ui_automation_client, cls_name):
File "D:\Python\Python38\lib\site-packages\pywinauto\uia_defines.py", line 50, in call
cls._instances[cls] = super(_Singleton, cls).call(*args, **kwargs)
File "D:\Python\Python38\lib\site-packages\pywinauto\uia_defines.py", line 60, in init
self.UIA_dll = comtypes.client.GetModule('UIAutomationCore.dll')
File "D:\Python\Python38\lib\site-packages\comtypes\client_generate.py", line 110, in GetModule
mod = _CreateWrapper(tlib, pathname)
File "D:\Python\Python38\lib\site-packages\comtypes\client_generate.py", line 184, in _CreateWrapper
mod = _my_import(fullname)
File "D:\Python\Python38\lib\site-packages\comtypes\client_generate.py", line 24, in my_import
return import(fullname, globals(), locals(), ['DUMMY'])
File "D:\Python\Python38\lib\site-packages\comtypes\gen_944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py", line 1931, in
IUIAutomation.methods = [
File "D:\Python\Python38\lib\site-packages\comtypes_init.py", line 329, in setattr
self.make_methods(value)
File "D:\Python\Python38\lib\site-packages\comtypes_init.py", line 698, in make_methods
prototype = WINFUNCTYPE(restype, *argtypes)
File "D:\Python\Python38\lib\ctypes_init.py", line 125, in WINFUNCTYPE
class WinFunctionType(_CFuncPtr):
TypeError: item 2 in argtypes passes a union by value, which is unsupported.
"

Please do help me in this.

答:
This is Python bug in Python 2.7.6 and 3.8.1. Please do clean install of Python 3.7.7+ or 3.8.2+.

Full history of the issue is here: https://github.com/pywinauto/pywinauto/issues/868

This is a missing feature in libffi for passing union by value. libffi is used by ctypes for resolving calling convention at runtime. Python Core developers decided to prohibit this option due to missing feature. But it was wrong decision that broke a lot of users on Windows. So the wrong patch was reverted in Python 3.7.7 / 3.8.2.


问:
R Plot Numeric Variable vs Days of the Week
I have a dataframe with two columns, Global Active Power is a numeric column and DateTime is a datetime type column. When I execute the command plot(DateTime,Global Active Power), I automatically get the days of the week as ticks on the x axis.

1. Can someone explain how this is happening?

2. Also, when I run plot(as.factor(weekdays(DateTime)),Global Active Power), I do not get the same plot, instead I get a boxplot.

答:
Your DateTime column has its dates and times all within a 48-hour period, so R chooses the day of the week as the most appropriate x axis labels for you. You can change this formatting to whatever you like.

Since your example did not include any data, I've had to create some dummy data to show how this works:

set.seed(69)
x  <- (as.POSIXct("2020-05-29 10:30:00") + 1:(24 * 60) * 300)[1:1000]
y  <- rpois(1000, 50 * sin(seq(0, 12, length.out = 1000))^2) / 10
df <- data.frame(DateTime = x, `Global Active Power` = y)
```

<p>So plotting this data, we get a similar layout to the plot in your question:</p>

```plot(df$DateTime, df$Global.Active.Power, type ="l", xlab ="Date", ylab ="Power")
```

<p><img src="https://i.imgur.com/k4spzgH.png" alt=""></p>

<p>Now, if I want to format with, say, the date, then I would draw the plot without an x axis then add a formatted axis like this:</p>

<pre class="lang-r prettyprint-override"><code>plot(df$DateTime, df$Global.Active.Power,
     type = "l", xaxt = "n", xlab = "Date", ylab = "Power")

axis.POSIXct(1, df$DateTime, format = "%d %b")
</code>```

As for why your plot changes to a boxplot when you change the x axis to a factor variable according to the day of the week, you have transformed your time variable from a continuous to a discrete variable. There are only two weekdays in your data, so you will only have two points on your x axis where data can appear. R chooses a boxplot here because otherwise your plot would just be a mess, as you can see if I change the date-times to just dates:

```<code>plot(as.Date(df$DateTime),df$Global.Active.Power)
</code>```

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
Your DateTime column has its dates and times all within a 48-hour period, so R chooses the day of the week as the most appropriate x axis labels for you. You can change this formatting to whatever you like.

Since your example did not include any data, I've had to create some dummy data to show how this works:

set.seed(69)
x  <- (as.POSIXct("2020-05-29 10:30:00") + 1:(24 * 60) * 300)[1:1000]
y  <- rpois(1000, 50 * sin(seq(0, 12, length.out = 1000))^2) / 10
df <- data.frame(DateTime = x, `Global Active Power` = y)

So plotting this data, we get a similar layout to the plot in your question:

plot(df$DateTime, df$Global.Active.Power, type ="l", xlab ="Date", ylab ="Power")

Now, if I want to format with, say, the date, then I would draw the plot without an x axis then add a formatted axis like this:

plot(df$DateTime, df$Global.Active.Power,
     type = "l", xaxt = "n", xlab = "Date", ylab = "Power")

axis.POSIXct(1, df$DateTime, format = "%d %b")

As for why your plot changes to a boxplot when you change the x axis to a factor variable according to the day of the week, you have transformed your time variable from a continuous to a discrete variable. There are only two weekdays in your data, so you will only have two points on your x axis where data can appear. R chooses a boxplot here because otherwise your plot would just be a mess, as you can see if I change the date-times to just dates:

plot(as.Date(df$DateTime),df$Global.Active.Power)

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
How to get/print resolved dependencies group, name and version from Maven using Gradle?
Suppose we have a task in Gradle, that prints artifact group, name and version like this:

```<code>task printDependencies {
project.configurations.each { conf ->
    conf.dependencies.each { dep ->
        println "${dep.group}:${dep.name}:${dep.version}"
        }
    }
}
</code>```

But what I would to do, is to print/get this information not only for declared dependencies, but to all resolved dependencies too. How to do this in Gradle?

答:
One solution is to define task like this:

```<code>task printDependencies {
    project.configurations.compile.resolvedConfiguration.resolvedArtifacts.each { id->
        println id
    }
}
</code>```

The line format that will be printed will be like e.g:

```<code>play-services-ads-16.0.0.aar (com.google.android.gms:play-services-ads:16.0.0)
</code>```

Which contains all needed info (file, group:name:version)

Body:
Suppose we have a task in Gradle, that prints artifact group, name and version like this:

task printDependencies {
project.configurations.each { conf ->
    conf.dependencies.each { dep ->
        println "${dep.group}:${dep.name}:${dep.version}"
        }
    }
}

But what I would to do, is to print/get this information not only for declared dependencies, but to all resolved dependencies too. How to do this in Gradle?

Body:
One solution is to define task like this:

task printDependencies {
    project.configurations.compile.resolvedConfiguration.resolvedArtifacts.each { id->
        println id
    }
}

The line format that will be printed will be like e.g:

play-services-ads-16.0.0.aar (com.google.android.gms:play-services-ads:16.0.0)

Which contains all needed info (file, group:name:version)


问:
How to use a makefile with Gtk
My code is supposed to be divided into client, server, and header files. This is the makefile when it's all in one file -

```<code># change application name here (executable output name)
TARGET=BugTrack

# compiler
CC=gcc
# debug
DEBUG=-g
# optimisation
OPT=-O0
# warnings
WARN=-Wall

PTHREAD=-pthread

CCFLAGS=$(DEBUG) $(OPT) $(WARN) $(PTHREAD) -pipe

GTKLIB=`pkg-config --cflags --libs gtk+-3.0`

# linker
LD=gcc
LDFLAGS=$(PTHREAD) $(GTKLIB) -export-dynamic

OBJS= client.o

all: $(OBJS)
    $(LD) -o $(TARGET) $(OBJS) $(LDFLAGS)

client.o: client.c
    $(CC) -c $(CCFLAGS) client.c  $(GTKLIB) -o client.o

clean:
    rm -f *.o $(TARGET)
</code>```

And this works. But changing the last part to this -

```<code>OBJS= client.o server.o

all: $(OBJS)
    $(LD) -o $(TARGET) $(OBJS) $(LDFLAGS)

client.o: client.c
    $(CC) -c $(CCFLAGS) client.c header.h $(GTKLIB) -o client.o

server.o: server.c
    $(CC) -c $(CCFLAGS) server.c header.h $(GTKLIB) -o server.o

clean:
    rm -f *.o $(TARGET)
</code>```

Gives me an error that says fatal error: cannot specify -o with -c, -S or -E with multiple files.
How do I fix it?

答:
You do not need to put the header files into your compile lines, so just do:

```<code>OBJS= client.o server.o

all: $(OBJS)
    $(LD) -o $(TARGET) $(OBJS) $(LDFLAGS)

client.o: client.c
    $(CC) -c $(CCFLAGS) client.c $(GTKLIB) -o client.o

server.o: server.c
    $(CC) -c $(CCFLAGS) server.c $(GTKLIB) -o server.o

clean:
    rm -f *.o $(TARGET)
</code>```

If you need to add header include paths then you can add -I<path>

Title: How to use a makefile with Gtk

Body:
My code is supposed to be divided into client, server, and header files. This is the makefile when it's all in one file -

# change application name here (executable output name)
TARGET=BugTrack

# compiler
CC=gcc
# debug
DEBUG=-g
# optimisation
OPT=-O0
# warnings
WARN=-Wall

PTHREAD=-pthread

CCFLAGS=$(DEBUG) $(OPT) $(WARN) $(PTHREAD) -pipe

GTKLIB=`pkg-config --cflags --libs gtk+-3.0`

# linker
LD=gcc
LDFLAGS=$(PTHREAD) $(GTKLIB) -export-dynamic

OBJS= client.o

all: $(OBJS)
    $(LD) -o $(TARGET) $(OBJS) $(LDFLAGS)

client.o: client.c
    $(CC) -c $(CCFLAGS) client.c  $(GTKLIB) -o client.o

clean:
    rm -f *.o $(TARGET)

And this works. But changing the last part to this -

OBJS= client.o server.o

all: $(OBJS)
    $(LD) -o $(TARGET) $(OBJS) $(LDFLAGS)

client.o: client.c
    $(CC) -c $(CCFLAGS) client.c header.h $(GTKLIB) -o client.o

server.o: server.c
    $(CC) -c $(CCFLAGS) server.c header.h $(GTKLIB) -o server.o

clean:
    rm -f *.o $(TARGET)

Gives me an error that says fatal error: cannot specify -o with -c, -S or -E with multiple files.
How do I fix it?

Body:
You do not need to put the header files into your compile lines, so just do:

OBJS= client.o server.o

all: $(OBJS)
    $(LD) -o $(TARGET) $(OBJS) $(LDFLAGS)

client.o: client.c
    $(CC) -c $(CCFLAGS) client.c $(GTKLIB) -o client.o

server.o: server.c
    $(CC) -c $(CCFLAGS) server.c $(GTKLIB) -o server.o

clean:
    rm -f *.o $(TARGET)

If you need to add header include paths then you can add -I<path>


问:
Cronjob Javascript, how to fire job limited times? ( set counter and max limit )
I'm new to Cronjob and looking for a way to fire it with interval but only 5 times.
Im firing an API call with cron and do not want to loop it.
Is it possible to set a counter and max limit of how many times cron has been executed?
or is there another better way of making delayed API calls with nodejs 5 times during 5 min ?</p>

答: I am not sure if crontab allows to have count. Rather you can write a wrapper program which will be called by the cron job. The wrapper can store the count of how many times the api is called.(save count to a file/database). Based on the count, wrapper can decide whether to call api or not.Then schedule your wrapper cron to run every 5 mins(whatever the interval that you need). </p>


问:
No digraphs available in vim
I can't get digraphs to work in vim.

When I type:

```<code>:digraphs
</code>```

it gives me an error message: E196: No digraphs in this version.

Do I need to install any plugins or packages? If I type:

```<code>:scriptnames
</code>```

it doesn't seem to return i.e. just seems to block.

I am using vim 8.2.587 in Fedora 30, running as a guest inside Virtual Box.

When using vim 8.2.158 running on a native Fedora 31 machine, the digraphs work fine.

Update:

```<code>vi --version | grep digraph
</code>```

shows that vim  was built with digraph support. The full output is below.

```<code>> vi --version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Apr 17 2020 05:09:15)
Included patches: 1-587
Modified by <bugzilla@redhat.com>
Compiled by <bugzilla@redhat.com>
Small version without GUI.  Features included (+) or not (-):
+acl               -farsi             +mouse_sgr         -tag_old_static
-arabic            -file_in_path      -mouse_sysmouse    -tag_any_white
+autocmd           -find_in_path      -mouse_urxvt       -tcl
-autochdir         -float             +mouse_xterm       -termguicolors
-autoservername    -folding           +multi_byte        -terminal
-balloon_eval      -footer            -multi_lang        +terminfo
-balloon_eval_term +fork()            -mzscheme          +termresponse
-browse            -gettext           -netbeans_intg     -textobjects
+builtin_terms     -hangul_input      +num64             -textprop
-byte_offset       +iconv             -packages          -timers
-channel           +insert_expand     -path_extra        -title
-cindent           -ipv6              -perl              -toolbar
-clientserver      -job               -persistent_undo   +user_commands
-clipboard         +jumplist          -popupwin          -vartabs
+cmdline_compl     -keymap            -printer           +vertsplit
+cmdline_hist      -lambda            -profile           +virtualedit
-cmdline_info      -langmap           -python            +visual
+comments          -libcall           -python3           +visualextra
-conceal           -linebreak         -quickfix          -viminfo
-cryptv            -lispindent        -reltime           +vreplace
-cscope            +listcmds          -rightleft         +wildignore
+cursorbind        +localmap          -ruby              -wildmenu
-cursorshape       -lua               +scrollbind        +windows
-dialog            -menu              -signs             +writebackup
-diff              -mksession         -smartindent       -X11
-digraphs          +modify_fname      -sound             -xfontset
-dnd               +mouse             -spell             -xim
-ebcdic            -mouseshape        -startuptime       -xpm
-emacs_tags        -mouse_dec         -statusline        -xsmp
-eval              -mouse_gpm         -sun_workshop      -xterm_clipboard
+ex_extra          -mouse_jsbterm     -syntax            -xterm_save
-extra_search      -mouse_netterm     +tag_binary
   system vimrc file: "/etc/virc"
     user vimrc file: "$HOME/.virc"
 2nd user vimrc file: "~/.vim/virc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/etc"
 f-b for $VIMRUNTIME: "/usr/share/vim/vim82"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H     -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc   -Wl,-z,relro  -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -L/usr/local/lib -Wl,--as-needed -o vim        -lm  -lselinux -lncurses -lacl -lattr -ldl
</code>```

答: Small version without GUI and -digraphs speak a clear language here. Many Linux distributions just ship with a minimal, stripped-down version of Vim to provide vi compatibility. If you want to use the full Vim capabilities, you typically can install a separate package (usually named vim, or vim-full vs. the default vim-tiny). And that would then be invoked as vim, not vi.

Title: No digraphs available in vim

Body:
I can't get digraphs to work in vim.

When I type:

:digraphs

it gives me an error message: E196: No digraphs in this version.

Do I need to install any plugins or packages? If I type:

:scriptnames

it doesn't seem to return i.e. just seems to block.

I am using vim 8.2.587 in Fedora 30, running as a guest inside Virtual Box.

When using vim 8.2.158 running on a native Fedora 31 machine, the digraphs work fine.

Update:

vi --version | grep digraph

shows that vim  was built with digraph support. The full output is below.

> vi --version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Apr 17 2020 05:09:15)
Included patches: 1-587
Modified by <bugzilla@redhat.com>
Compiled by <bugzilla@redhat.com>
Small version without GUI.  Features included (+) or not (-):
+acl               -farsi             +mouse_sgr         -tag_old_static
-arabic            -file_in_path      -mouse_sysmouse    -tag_any_white
+autocmd           -find_in_path      -mouse_urxvt       -tcl
-autochdir         -float             +mouse_xterm       -termguicolors
-autoservername    -folding           +multi_byte        -terminal
-balloon_eval      -footer            -multi_lang        +terminfo
-balloon_eval_term +fork()            -mzscheme          +termresponse
-browse            -gettext           -netbeans_intg     -textobjects
+builtin_terms     -hangul_input      +num64             -textprop
-byte_offset       +iconv             -packages          -timers
-channel           +insert_expand     -path_extra        -title
-cindent           -ipv6              -perl              -toolbar
-clientserver      -job               -persistent_undo   +user_commands
-clipboard         +jumplist          -popupwin          -vartabs
+cmdline_compl     -keymap            -printer           +vertsplit
+cmdline_hist      -lambda            -profile           +virtualedit
-cmdline_info      -langmap           -python            +visual
+comments          -libcall           -python3           +visualextra
-conceal           -linebreak         -quickfix          -viminfo
-cryptv            -lispindent        -reltime           +vreplace
-cscope            +listcmds          -rightleft         +wildignore
+cursorbind        +localmap          -ruby              -wildmenu
-cursorshape       -lua               +scrollbind        +windows
-dialog            -menu              -signs             +writebackup
-diff              -mksession         -smartindent       -X11
-digraphs          +modify_fname      -sound             -xfontset
-dnd               +mouse             -spell             -xim
-ebcdic            -mouseshape        -startuptime       -xpm
-emacs_tags        -mouse_dec         -statusline        -xsmp
-eval              -mouse_gpm         -sun_workshop      -xterm_clipboard
+ex_extra          -mouse_jsbterm     -syntax            -xterm_save
-extra_search      -mouse_netterm     +tag_binary
   system vimrc file: "/etc/virc"
     user vimrc file: "$HOME/.virc"
 2nd user vimrc file: "~/.vim/virc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/etc"
 f-b for $VIMRUNTIME: "/usr/share/vim/vim82"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H     -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc   -Wl,-z,relro  -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -L/usr/local/lib -Wl,--as-needed -o vim        -lm  -lselinux -lncurses -lacl -lattr -ldl


问:
increment counter in a column based on certain condition pandas
```<code>col1     col2
 -        -
 -        -
 no       1
 -        -
 no       2
 no       3
</code>```

I have 2 columns in a dataframe. Whenever 'no' is encountered in col1, need to increment the counter in col2 as shown above

答:
Campare values by Series.eq for ==, then use cumulative sum and replace non no values to - by Series.where:

```<code>m = df['col1'].eq('no')
df['col2'] = m.cumsum().where(m, '-')
print (df)
  col1 col2
0    -    -
1    -    -
2   no    1
3    -    -
4   no    2
5   no    3
</code>```

Body:
col1     col2
 -        -
 -        -
 no       1
 -        -
 no       2
 no       3

I have 2 columns in a dataframe. Whenever 'no' is encountered in col1, need to increment the counter in col2 as shown above

Body:
Campare values by Series.eq for ==, then use cumulative sum and replace non no values to - by Series.where:

m = df['col1'].eq('no')
df['col2'] = m.cumsum().where(m, '-')
print (df)
  col1 col2
0    -    -
1    -    -
2   no    1
3    -    -
4   no    2
5   no    3


问:
vue emit parent not listening to custom event
i am trying to do a emit to do a function call from child to parent.
CodeSandbox of my try.

i dont get why my custom-event is not get listening on parent:
https://codesandbox.io/s/broken-bash-ryq26?file=/src/App.vue

答:
You need to put the listener on the component where its come from, not on some div</p>

```<code><HelloWorld @whats-up="notMuch" msg="Hello Vue in CodeSandbox!"/>
</code>```

Body:
You need to put the listener on the component where its come from, not on some div

<HelloWorld @whats-up="notMuch" msg="Hello Vue in CodeSandbox!"/>


问:
Failed to find GeneratedAppGlideModule
Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored

In Gradle

```<code>compile 'com.github.bumptech.glide:glide:4.1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.1.1'
</code>```

答:
Remove apply plugin: 'kotlin-kapt' in build.gradle.

It solved my problem!

And if your project is kotlin,try replace "annotationProcessor" to "kapt"

Title: Failed to find GeneratedAppGlideModule

Body:
Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored

In Gradle

compile 'com.github.bumptech.glide:glide:4.1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.1.1'


问:
django dynamic query set filtering with using string from URL
is there any way we can filter the queryset dynamically i.e we have a two string value from the url and search the model where first string is an  attribute of the model and get all the objects containing second string in that particular attribute

答:
Hi you just need to follow this solution and adapt it to your case

```<code>Model.objects.values('attribute', 'id') # using '.values'
[{'attribute': 'some attribute', 'id': 1 }, {'attribute': 'some 3', 'id': 2}, {'attribute': 'something', 'id': 3}, {'attribute': 'some some', 'id': 4}] # returns list of dictionaries
</code>```

Filter or search the list of dictionaries with your "second string" and make a new query with the ids.
You can adapt this one

```<code>Model.objects.filter(id__in=object_ids)
</code>```

or use this solution

```<code>filterExpresion = attribute+'__contains'
dynamicFilter = {filterExpresion: secondString}
Model.objects.filter(**dynamicFilter)
</code>```

Body:
Hi you just need to follow this solution and adapt it to your case

Model.objects.values('attribute', 'id') # using '.values'
[{'attribute': 'some attribute', 'id': 1 }, {'attribute': 'some 3', 'id': 2}, {'attribute': 'something', 'id': 3}, {'attribute': 'some some', 'id': 4}] # returns list of dictionaries

Filter or search the list of dictionaries with your "second string" and make a new query with the ids.
You can adapt this one

Model.objects.filter(id__in=object_ids)

or use this solution

filterExpresion = attribute+'__contains'
dynamicFilter = {filterExpresion: secondString}
Model.objects.filter(**dynamicFilter)


答:
You should listen to whats-up event in HelloWorld component. Code Should be like it

```<code><HelloWorld @whats-up="notMuch" msg="Hello Vue in CodeSandbox!"/>
</code>```

Title: vue emit parent not listening to custom event

Body:
i am trying to do a emit to do a function call from child to parent.
CodeSandbox of my try.

i dont get why my custom-event is not get listening on parent:
https://codesandbox.io/s/broken-bash-ryq26?file=/src/App.vue

Body:
You should listen to whats-up event in HelloWorld component. Code Should be like it

<HelloWorld @whats-up="notMuch" msg="Hello Vue in CodeSandbox!"/>


问:
Beginner Python programmer here, struggling to use the logical OR operator
Wrote the code snippet below on the Python IDLE and got the proper answer below:

```<code>>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" in car:
        print(car.title())
    else:
        print(car.upper())
</code>```

RESULT:

```<code>Audi
BMW
Daimler
Toyota
VW
</code>```

Then I changed the code so I could print the cars with no vowel UPPER and the rest Title as shown below but I got all cars printed Title:

```<code>>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" or "e" in car:
        print(car.title())
    else:
        print(car.upper())
</code>```

RESULT:

```<code>Audi
Bmw
Daimler
Toyota
Vw
</code>```

Can someone kindly help tell what is wrong with the last block of code, the goal is to print all cars without vowel fully uppercase and the rest as Title.

Thank you.

答:
TBH you are not very clear with or statements no problem but this is the desired way of passing the or in if statement i have made the code for you.

```<code>cars = ["audi", "bmw", "daimler", "toyota", "vw"]
for car in cars:
    if "a" in car or 'e' in car or 'i' in car or 'o' in car or 'u' in car:
        print(car.title())
    else:
        print(car.upper())
</code>```

The output is:

```<code>Audi
BMW
Daimler
Toyota
VW

Process finished with exit code 0
</code>```

Hope you find this helpful

Body:
Wrote the code snippet below on the Python IDLE and got the proper answer below:

>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" in car:
        print(car.title())
    else:
        print(car.upper())

RESULT:

Audi
BMW
Daimler
Toyota
VW

Then I changed the code so I could print the cars with no vowel UPPER and the rest Title as shown below but I got all cars printed Title:

>>> cars = ["audi", "bmw", "daimler", "toyota", "vw"]
>>> for car in cars:
    if "a" or "e" in car:
        print(car.title())
    else:
        print(car.upper())

RESULT:

Audi
Bmw
Daimler
Toyota
Vw

Can someone kindly help tell what is wrong with the last block of code, the goal is to print all cars without vowel fully uppercase and the rest as Title.

Thank you.

Body:
TBH you are not very clear with or statements no problem but this is the desired way of passing the or in if statement i have made the code for you.

cars = ["audi", "bmw", "daimler", "toyota", "vw"]
for car in cars:
    if "a" in car or 'e' in car or 'i' in car or 'o' in car or 'u' in car:
        print(car.title())
    else:
        print(car.upper())

The output is:

Audi
BMW
Daimler
Toyota
VW

Process finished with exit code 0

Hope you find this helpful


问:
Distribute data from `tf.data.Dataset` to multiple workers (e.g. for Horovod)
With Horovod, you basically run N independent instances (so it is a form of between-graph replication), and they communicate via special Horovod ops (basically broadcast + reduce).

Now let's say either instance 0, or some other external instance loads your data (via tf.data.Dataset). How would you distribute the iterator.get_next() to each instance? Using Horovod broadcast would be inefficient, as you would copy all the data to all instances.

Having the dataset in every instance, and doing all the loading in there, and then using shard on the dataset would also be inefficient, as you would load the data everywhere, and then throw away (N-1)/N of it.
So that's why you would also not want sharding, and instead have the dataset loading only in a single (producer/dataset worker) instance, which then distributes the batches on all the train workers.

I guess the TF MultiDeviceIterator provides some similar functionality (or basically exactly that) but I'm not sure whether that works together with Horovod, and how you would set it up?

Or maybe you can make the distribution somehow via TF workers (guide)? (Maybe that is how you would configure MultiDeviceIterator as well?)

If possible, this should be via TensorFlow operations / functions (there are many related functions which might already give me this, but I might not know about them, or have misunderstood how it works).
Or maybe the answer is that TensorFlow does not provide any such functionality yet? (This would still be useful to know. Then I would implement my own solution in C++, wrapped as a TensorFlow op. But before doing so, it would be good to know whether this is really necessary.)

(Related is also this Horovod issue.)

(This question is actually a bit more generic than just Horovod, although Horovod might be a good example. You might have this problem always for distributed TensorFlow?)

(I collected an overview of all the distributed TensorFlow terminology and aspects here, mostly for clarification.)

(Related are (maybe?) also this, this, this, this or this questions.)

答:
As you said, copying the data in each instance and sharding the data for each instance would be impractical.

One solution would then be to separate the data in a data process and have each instance pull data from the data process as shown in the figure below. For example, this communication can be established using a queue.

In such a system, the data process would load the dataset, preprocess it into batches and push the batches into a queue. Each training instance would then pull batches from this queue. For example, you could pass the queue as a generator into the dataset API (see tf.data.Dataset.from_generator).
Also, if batches are not produced fast enough, it is possible to create more data processes to increase the batches throughput.

Depending on your use case, the implementation specifics will vary. For more information, you can look up Networking and Interprocess communication and Multiprocessing pipes and queues.

                                                             Training
                                                         +--------------+  ++
                                                         |              |   |
                                                    +----+  Instance 1  |   |
                                                    |    |              |   |
                                                    |    +--------------+   |
                                                    |                       |
                      Preprocessing                 |                       |
                  +--------------------+            +---->      X           |
                  |                    |            |                       |
             Load |                    | Batches    +           X           |
    Dataset+------>    Data Process    +--------->Queue                     |  N instances
                  |                    |            +           X           |  Distributed training
                  |                    |            |                       |  For example, using
                  +--------------------+            +---->      X           |  Horovod broadcast + reduce
                                                    |                       |
                                                    |        Training       |
                                                    |    +--------------+   |
                                                    |    |              |   |
                                                    +----+  Instance N  |   |
                                                         |              |   |
                                                         +--------------+  ++
```

<p>For a tensorflow implementation, you could use <code>tf.data.Dataset.shard</code> with <code>tf.data.TFRecordDataset</code>. </p>

<p>The documentation addresses your inefficiency concern using TFRecords:</p>

<blockquote>
  <p>Important caveats:</p>

  <ul>
  <li><p>Be sure to shard before you use any randomizing operator (such as shuffle).</p></li>
  <li><p>Generally it is best if the shard operator is used early in the dataset  pipeline. For example, when reading from a set of TFRecord files, shard before converting the dataset to input samples. This avoids reading every file on every worker. The following is an example of an efficient sharding strategy within a complete pipeline:</p></li>
  </ul>

  <p></p>

```d = Dataset.list_files(pattern)
d = d.shard(num_workers, worker_index)
d = d.repeat(num_epochs)
d = d.shuffle(shuffle_buffer_size)
d = d.interleave(tf.data.TFRecordDataset,
                 cycle_length=num_readers, block_length=1)
d = d.map(parser_fn, num_parallel_calls=num_map_threads)
```

Body:
As you said, copying the data in each instance and sharding the data for each instance would be impractical.

One solution would then be to separate the data in a data process and have each instance pull data from the data process as shown in the figure below. For example, this communication can be established using a queue.

In such a system, the data process would load the dataset, preprocess it into batches and push the batches into a queue. Each training instance would then pull batches from this queue. For example, you could pass the queue as a generator into the dataset API (see tf.data.Dataset.from_generator).
Also, if batches are not produced fast enough, it is possible to create more data processes to increase the batches throughput.

Depending on your use case, the implementation specifics will vary. For more information, you can look up Networking and Interprocess communication and Multiprocessing pipes and queues.

                                                             Training
                                                         +--------------+  ++
                                                         |              |   |
                                                    +----+  Instance 1  |   |
                                                    |    |              |   |
                                                    |    +--------------+   |
                                                    |                       |
                      Preprocessing                 |                       |
                  +--------------------+            +---->      X           |
                  |                    |            |                       |
             Load |                    | Batches    +           X           |
    Dataset+------>    Data Process    +--------->Queue                     |  N instances
                  |                    |            +           X           |  Distributed training
                  |                    |            |                       |  For example, using
                  +--------------------+            +---->      X           |  Horovod broadcast + reduce
                                                    |                       |
                                                    |        Training       |
                                                    |    +--------------+   |
                                                    |    |              |   |
                                                    +----+  Instance N  |   |
                                                         |              |   |
                                                         +--------------+  ++

For a tensorflow implementation, you could use tf.data.Dataset.shard with tf.data.TFRecordDataset.

The documentation addresses your inefficiency concern using TFRecords:

Important caveats:

Be sure to shard before you use any randomizing operator (such as shuffle).

Generally it is best if the shard operator is used early in the dataset  pipeline. For example, when reading from a set of TFRecord files, shard before converting the dataset to input samples. This avoids reading every file on every worker. The following is an example of an efficient sharding strategy within a complete pipeline:

d = Dataset.list_files(pattern)
d = d.shard(num_workers, worker_index)
d = d.repeat(num_epochs)
d = d.shuffle(shuffle_buffer_size)
d = d.interleave(tf.data.TFRecordDataset,
                 cycle_length=num_readers, block_length=1)
d = d.map(parser_fn, num_parallel_calls=num_map_threads)


问:
not able to get SQLite database in python
1) I am new to python and I am using SQLITE database. While setting up the connection I am not able to get the database(Which I already made in SQLite and tables as well)

2) While executing the insert query I am getting the following error :
    "sqlite3.OperationalError: no such table: MemberDetails"

HERE IS THE CODE:

```<code>import sqlite3
my_cursor = ""
conn = ""

# setting the connection with database
# def con_database_connection():
# try:
globals()
conn = sqlite3.connect('CareForNation.db')
# new_con = sqlite3.connect('CareForNation.db')
print("connection established successfully")
my_cursor = conn.cursor()
# except sqlite3 as error
# print("Connection failed")

# Login Admin Control
user_name = input("Enter user name")
user_password = input("Enter Password")
if user_name == "123" and user_password == "123":
    print("Login successful")
else:
    print("Invalid user name or password")

# Inserting member information
# con_database_connection()
mid = input("Enter Member ID")
member_name = input("Enter member name")
member_phone_number = input("enter phone number")
member_address = input("Enter address")

insert_data = my_cursor.execute("insert into MemberDetails(Member_ID, Member_Name, Phone_Number, address) "
                                "values('mid', 'member_name', 'member_phone_number', member_address)")

# abc = conn.executescript("select * from MemberDetails")

print("New data entered to Member details module")
conn.close()
</code>```

答:
[Updated]

I've made some change in your code it works perfectly now!

import sqlite3
my_cursor = ""
conn = ""

# setting the connection with database
# def con_database_connection():
# try:
globals()
conn = sqlite3.connect('CareForNation.db')
# new_con = sqlite3.connect('CareForNation.db')
print("connection established successfully")
my_cursor = conn.cursor()
# except sqlite3 as error
# print("Connection failed")

# Login Admin Control
user_name = input("Enter user name")
user_password = input("Enter Password")
if user_name == "123" and user_password == "123":
    print("Login successful")
else:
    print("Invalid user name or password")

# Inserting member information
# con_database_connection()
mid = input("Enter Member ID")
member_name = input("Enter member name")
member_phone_number = input("enter phone number")
member_address = input("Enter address")

my_cursor.execute("create table if not exists MemberDetails(Member_ID, Member_Name, Phone_Number, address)")
insert_data = my_cursor.execute("insert into MemberDetails (Member_ID, Member_Name, Phone_Number, address) values (?, ?, ?, ?)", (mid, member_name, member_phone_number, member_address))
# abc = conn.executescript("select * from MemberDetails")

print("New data entered to Member details module")
conn.close()
~             ```

Body:
1) I am new to python and I am using SQLITE database. While setting up the connection I am not able to get the database(Which I already made in SQLite and tables as well)

2) While executing the insert query I am getting the following error :
    "sqlite3.OperationalError: no such table: MemberDetails"

HERE IS THE CODE:

import sqlite3
my_cursor = ""
conn = ""

# setting the connection with database
# def con_database_connection():
# try:
globals()
conn = sqlite3.connect('CareForNation.db')
# new_con = sqlite3.connect('CareForNation.db')
print("connection established successfully")
my_cursor = conn.cursor()
# except sqlite3 as error
# print("Connection failed")

# Login Admin Control
user_name = input("Enter user name")
user_password = input("Enter Password")
if user_name == "123" and user_password == "123":
    print("Login successful")
else:
    print("Invalid user name or password")

# Inserting member information
# con_database_connection()
mid = input("Enter Member ID")
member_name = input("Enter member name")
member_phone_number = input("enter phone number")
member_address = input("Enter address")

insert_data = my_cursor.execute("insert into MemberDetails(Member_ID, Member_Name, Phone_Number, address) "
                                "values('mid', 'member_name', 'member_phone_number', member_address)")

# abc = conn.executescript("select * from MemberDetails")

print("New data entered to Member details module")
conn.close()


问:
Not able to assign data value returned from api to class variable in Angular 8
I am calling api to get data on ngOnInit. However I am not able to assign the data class variable.
Below is the related code

```<code>  tasks: Task[];

  ngOnInit() {

    this.apiService.getTasks()
      .subscribe( data => {
        Object.keys(data).map((index) => {
          this.tasks.push(data[index]);
       });
      });

  }
</code>```

I get error saying 'TypeError: Cannot read property 'push' of undefined' for statement

```<code>this.tasks.push(data[index]);
</code>```

But the tasks is already defined as array.

Can anyone help me here, the scope really confuses me

答:
If all you do in the map is to return the value of the property, you could use Object.values().

this.apiService.getTasks().subscribe(data => {
  this.tasks = Object.values(data);
});
```

Body:
I am calling api to get data on ngOnInit. However I am not able to assign the data class variable.
Below is the related code

  tasks: Task[];

  ngOnInit() {

    this.apiService.getTasks()
      .subscribe( data => {
        Object.keys(data).map((index) => {
          this.tasks.push(data[index]);
       });
      });

  }

I get error saying 'TypeError: Cannot read property 'push' of undefined' for statement

this.tasks.push(data[index]);

But the tasks is already defined as array.

Can anyone help me here, the scope really confuses me


问:
Declare and initialize variable for assigning list of anonymous types
I try to join two tables:

```<code>var data = from request in context.Requests
                        join account in context.AutolineAccts
                            on request.PkRequest.ToString() equals account.AccountCode
                        select new
                        {
                            ID = request.PkRequest.ToString(),
                            Location = request.FkLocation,
                            RequestDate = request.RequestDate.Value,
                            Requestor = request.FkRequestor,
                            DebitorNr = request.FkDebitor.ToString(),
                            NewDebit = request.Debit.ToString(),
                            ApprovalStatus = request.ApprovalStatus.ToString(),
                            RecommendationStatus = request.RecommendationStatus.ToString(),
                            DebitorName = account.CustomerSname,
                            Limit = account.CreditLimit
                        };
</code>```

Now I want to filter the result set depending on the status of the user:

```<code>// Accounting user
if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.ACCOUNTING) )

    req = data.Where(x => x.RecommendationStatus == null).ToList();

// After sales manager
else if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.SAV_LEADERS))
    req = data.OrderByDescending(x => x.ID).ToList();

// Everybody else
else
    req = data.OrderByDescending(x => x.PkRequest).ToList();
</code>```

And that's where I'm stuck. When I don't have the join and only retrieve a "Request" type, I can just declare a list of Requests

```<code>List<Requests> req;
</code>```

But with that combination of Requests and AutolineAccts I would have to declare and initialize a list of "items" (req) to assign the result set to in the if-else segments. But I don't know how that anonymous variable should look like.

Later on I have to map the result set to a list of my IndexViewModels:

```<code>foreach (var item in req)
                viewModel.CLModels.Add(new IndexViewModel
                {
                    ID = item .PkRequest.ToString(),
                    Location = item .FkLocation,
                    RequestDate = item .RequestDate.Value,
                    Requestor = item .FkRequestor,
                    DebitorNr = item .FkDebitor.ToString(),
                    NewDebit = item .Debit.ToString(),
                    ApprovalStatus = item .ApprovalStatus.ToString(),
                    RecommendationStatus = item .RecommendationStatus.ToString(),
                    DebitorName = item.CustomerSname,
                    Limit = item.CreditLimit
                });
</code>```

Any idea to solve this issue?

答:
```<code>IEnumerable<dynamic> result = from request in requests
                    join account in accounts
                        on request.id equals account.id
                        select new {id=request.id, name=account.name};
</code>```

Keeps the accessors, can further be queried and be return type of a method.

Body:
I try to join two tables:

var data = from request in context.Requests
                        join account in context.AutolineAccts
                            on request.PkRequest.ToString() equals account.AccountCode
                        select new
                        {
                            ID = request.PkRequest.ToString(),
                            Location = request.FkLocation,
                            RequestDate = request.RequestDate.Value,
                            Requestor = request.FkRequestor,
                            DebitorNr = request.FkDebitor.ToString(),
                            NewDebit = request.Debit.ToString(),
                            ApprovalStatus = request.ApprovalStatus.ToString(),
                            RecommendationStatus = request.RecommendationStatus.ToString(),
                            DebitorName = account.CustomerSname,
                            Limit = account.CreditLimit
                        };

Now I want to filter the result set depending on the status of the user:

// Accounting user
if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.ACCOUNTING) )

    req = data.Where(x => x.RecommendationStatus == null).ToList();

// After sales manager
else if (ActiveDirectoryHelper.CheckIfUserIsInADGroup(userLogin, AdGroups.SAV_LEADERS))
    req = data.OrderByDescending(x => x.ID).ToList();

// Everybody else
else
    req = data.OrderByDescending(x => x.PkRequest).ToList();

And that's where I'm stuck. When I don't have the join and only retrieve a "Request" type, I can just declare a list of Requests

List<Requests> req;

But with that combination of Requests and AutolineAccts I would have to declare and initialize a list of "items" (req) to assign the result set to in the if-else segments. But I don't know how that anonymous variable should look like.

Later on I have to map the result set to a list of my IndexViewModels:

foreach (var item in req)
                viewModel.CLModels.Add(new IndexViewModel
                {
                    ID = item .PkRequest.ToString(),
                    Location = item .FkLocation,
                    RequestDate = item .RequestDate.Value,
                    Requestor = item .FkRequestor,
                    DebitorNr = item .FkDebitor.ToString(),
                    NewDebit = item .Debit.ToString(),
                    ApprovalStatus = item .ApprovalStatus.ToString(),
                    RecommendationStatus = item .RecommendationStatus.ToString(),
                    DebitorName = item.CustomerSname,
                    Limit = item.CreditLimit
                });

Any idea to solve this issue?

Body:
IEnumerable<dynamic> result = from request in requests
                    join account in accounts
                        on request.id equals account.id
                        select new {id=request.id, name=account.name};

Keeps the accessors, can further be queried and be return type of a method.


问:
How to setup a workflow to be used with Infopath
How would I go about creating a workflow in SPD (to work also with a form in Infopath) that would allow me to make a selection from a drop down menu, prepare an email to be sent and CC additional email addresses that have been selected from a list box within infopath?

I'm quite new to this and would greatly appreciate some guidance. Thanks!

答:
SharePoint workflow is designed for list item. So you could customize your list in Infopath form.

Make sure you have columns created for the list because sharepoint worfklow can only get infomation from colums


问:
c# dialog opened from dialog closes the entire chain
oi. i have a generic form that creates its own controls dependent on the class passed it. in the interim before conversion to wpf, i have this problem:

this generic record edit form opens as dialog for a child record listed on a master record form. it opens as dialog because i want the user to focus only on that. if a child record attribute requires access to OpenFileDialog, closing OpenFileDialog closes the child record dialog as well.

any advice on how to stop this?

答: This should help You - http://bytes.com/topic/net/answers/769433-c-showdialog-inside-showdialog-closing-both-return</p>


问:
Android Studio does not have write access
I am using android studio 3.4.2. When I try to update
the android studio it says

"Studio does not have write access to /app/extra. Please Run it by a privileged user to update"

How to solve it?

答:
I would suggest to set your current user as owner of /usr/bin/android-studio

This will resolve the issue in long term:

```<code>sudo chown -R $USER:$USER /usr/bin/android-studio
</code>```

Body:
I would suggest to set your current user as owner of /usr/bin/android-studio

This will resolve the issue in long term:

sudo chown -R $USER:$USER /usr/bin/android-studio


问:
Ruby: How to pluralize/singularize a word in Active Admin panel according to variable quantity (Active Admin, rails 3.2, ruby)
I'ma newbie in Ruby on Rails and I don't manage to change the end of a word according to the quantity it has.

Near top of the code below, you'll see that I write

```<code>h3 "The deal has #{deal.prizes.where(:prize_type => u).count} #{u}
</code>```

The "u" here takes one of the value inside an array called PRIZE_TYPE.
How can I do so that

if count= 1, it displays "the deal has 1 jackpot prize"

if count=4, it displays "the deal has 4 jackpot prizeS

Note: The count can't be = 0 or <  0

Here is my code:

```<code>panel "Details of Prizes" do

      PRIZE_TYPES.each do |u|

        table_for deal.prizes.where(:prize_type => u) do |t|
          h3 "The deal has #{deal.prizes.where(:prize_type => u).count} #{u}s
          initially set in the campaign for a total value of #{custom_number_to_currency (deal.category_prizes_total_initial_value(u)) }", class: 'title-within-table'
          if deal.prizes.where(:prize_type => u).count > 0 # if there is at least one record of 'jackpot prize'
            t.column("Prize")             { |prize| link_to( image_tag( prize.prize_image_url, class: 'main_img_in_admin_interface' ), admin_prize_path(prize), target: :blank ) }
            t.column("Name")              { |prize| link_to prize.prize_name, admin_prize_path(prize), target: :blank }
            t.column("Category")          { |prize| prize.prize_category }
            t.column("Initial quantity")  { |prize| prize.prize_initial_stock_quantity }

      end # end of Prize.each...

    end # end of panel "details of prizes"
</code>```

And the PRIZE_TYPE constant:

```<code>PRIZE_TYPES = ["Jackpot prize","Consolation prize", "awesome prize"]
</code>```

答:
According to pluralize

you can just do

```<code>pluralize(1, 'person')
# => 1 person

pluralize(2, 'person')
# => 2 people

pluralize(3, 'person', plural: 'users')
# => 3 users

pluralize(0, 'person')
# => 0 people

pluralize(2, 'Person', locale: :de)
# => 2 Personen
</code>```

Body:
I'ma newbie in Ruby on Rails and I don't manage to change the end of a word according to the quantity it has.

Near top of the code below, you'll see that I write

h3 "The deal has #{deal.prizes.where(:prize_type => u).count} #{u}

The "u" here takes one of the value inside an array called PRIZE_TYPE.
How can I do so that

if count= 1, it displays "the deal has 1 jackpot prize"

if count=4, it displays "the deal has 4 jackpot prizeS

Note: The count can't be = 0 or <  0

Here is my code:

panel "Details of Prizes" do

      PRIZE_TYPES.each do |u|

        table_for deal.prizes.where(:prize_type => u) do |t|
          h3 "The deal has #{deal.prizes.where(:prize_type => u).count} #{u}s
          initially set in the campaign for a total value of #{custom_number_to_currency (deal.category_prizes_total_initial_value(u)) }", class: 'title-within-table'
          if deal.prizes.where(:prize_type => u).count > 0 # if there is at least one record of 'jackpot prize'
            t.column("Prize")             { |prize| link_to( image_tag( prize.prize_image_url, class: 'main_img_in_admin_interface' ), admin_prize_path(prize), target: :blank ) }
            t.column("Name")              { |prize| link_to prize.prize_name, admin_prize_path(prize), target: :blank }
            t.column("Category")          { |prize| prize.prize_category }
            t.column("Initial quantity")  { |prize| prize.prize_initial_stock_quantity }

      end # end of Prize.each...

    end # end of panel "details of prizes"

And the PRIZE_TYPE constant:

PRIZE_TYPES = ["Jackpot prize","Consolation prize", "awesome prize"]

Body:
According to pluralize

you can just do

pluralize(1, 'person')
# => 1 person

pluralize(2, 'person')
# => 2 people

pluralize(3, 'person', plural: 'users')
# => 3 users

pluralize(0, 'person')
# => 0 people

pluralize(2, 'Person', locale: :de)
# => 2 Personen