问:
Dynamically adding views to CardView without duplicating
I have a layout for CardView with 2 TextViews and 2 Buttons initially. Based on the #options in poll.getOptions(), a Cardview can have up to 5 buttons. So I want to add dynamically those buttons... If I add them in onBindViewHolder, after clicking a button, it adds duplicates of these buttons. I tried to add it in onCreateViewHolder but when I try to create a new button it gives me a NullPointerException. I tried in many ways but can't find solution. What is the true way of adding dynamic views in cardview or why it gives me that error?

Layout for CardView:

```<code><?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto">

        <data>
            <variable
                name = "poll"
                type = "mattoncino.pollo.Poll" />
        </data>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            card_view:cardCornerRadius="@dimen/cardview_default_radius"
            card_view:cardElevation="@dimen/cardview_default_elevation">

            <LinearLayout
                android:id="@+id/listItemLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="5dp">

                <TextView
                    android:id="@+id/nameTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="30sp"
                    android:textAllCaps="false"
                    android:text="@{poll.name}"/>

                <TextView
                    android:id="@+id/questionTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="20sp"
                    android:text="@{poll.question}"/>

                <Button
                    android:id="@+id/opt1Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(1)}"
                    android:enabled="@{!poll.disabled}"/>

                <Button
                    android:id="@+id/opt2Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(2)}"
                    android:enabled="@{!poll.disabled}"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>
    </layout>
</code>```

My CardViewAdapter class:

```<code>public class PollsCardViewAdapter extends RecyclerView.Adapter<PollsCardViewAdapter.CardViewHolder> {

        private List<Poll> activePolls;
        private final static String TAG = "CARDVIEW_ADAPTER";

        public PollsCardViewAdapter(List<Poll> polls){
            activePolls = polls;
        }

        public static class CardViewHolder extends RecyclerView.ViewHolder {

            private ActivePollsListItemBinding listItemBinding;

            public CardViewHolder(View v) {
                super(v);
                listItemBinding = DataBindingUtil.bind(v);
            }

            public ActivePollsListItemBinding getBinding(){
                return listItemBinding;
            }
        }

        // Create new views (invoked by the layout manager)
        @Override
        public PollsCardViewAdapter.CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.active_polls_list_item, parent, false);

            CardViewHolder holder = new CardViewHolder(v);
            Context context = holder.getBinding().nameTextView.getContext();

            Poll poll = activePolls.get(viewType);

            for (int i = 2; i < poll.getOptions().size(); i++) {
                int opt = i + 1;
                Button button = createNewOptionButton(context, poll.getText(opt));
                if(poll.isDisabled()) {
                    button.setEnabled(false);
                }
                else button.setText(poll.getText(opt));
                parent.addView(button);
            }

            return holder;
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(final PollsCardViewAdapter.CardViewHolder holder, final int position) {
            final Poll poll = activePolls.get(position);
            final LinearLayout rLayout = holder.getBinding().listItemLayout;

            if(!poll.isDisabled()){
                for (int i = 2; i < rLayout.getChildCount(); i++){
                    final View view = rLayout.getChildAt(i);
                    final int opt = i - 1;

                    if(view instanceof Button){
                        final Button button = (Button) view;
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                button.setText(button.getText().toString() + "    " + "\u2713");
                             setCardDetails(holder.getBinding().nameTextView.getContext(), rLayout, poll, opt);
                            }
                        });
                    }
                }
            }

            holder.getBinding().setVariable(BR.poll, poll);
            holder.getBinding().executePendingBindings();
        }

        private void setCardDetails(final Context context, final LinearLayout rLayout, final Poll poll, final int opt){
            poll.setDisabled(true);
            disableOptionButtons(rLayout);
            rLayout.addView(addMessageView(context));

            Handler handler = new Handler();
            final Runnable r = new Runnable(){
                @Override
                public void run() {
                    poll.addVote(opt);
                    notifyDataSetChanged();
                }
            };
            handler.post(r);
        }

        private void disableOptionButtons(ViewGroup layout){
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                if(child.hasOnClickListeners())
                    child.setEnabled(false);
            }
        }

        private TextView addMessageView(Context context){
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            TextView textView = new TextView(context);
            textView.setLayoutParams(lparams);
            textView.setId(View.generateViewId());
            textView.setText("Thanks for voting! Wait for results...");
            textView.setTextSize(20);
            textView.setTypeface(null, Typeface.BOLD_ITALIC);

            return textView;
        }

        private static Button createNewOptionButton(Context context, String option) {
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            final Button button = new Button(context);
            button.setLayoutParams(lparams);
            button.setId(View.generateViewId());
            button.setTextSize(18);
            button.setText(option);
            //button.setBackgroundColor(Color.TRANSPARENT);
            return button;

        }

        @Override
        public int getItemCount() {
            return activePolls.size();
        }
    }
</code>```

The exception that I get, inside the createNewOptionButton()

```<code>mattoncino.pollo E/AndroidRuntime: FATAL EXCEPTION: main
        Process: mattoncino.pollo, PID: 4684
        java.lang.NullPointerException
        at android.support.v7.widget.RecyclerView$LayoutParams.getViewLayoutPosition(RecyclerView.java:10862)
        at android.support.v7.widget.RecyclerView$LayoutManager.getPosition(RecyclerView.java:7949)
        at android.support.v7.widget.LinearLayoutManager.updateLayoutState(LinearLayoutManager.java:1184)
        at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1323)
        at android.support.v7.widget.LinearLayoutManager.fixLayoutEndGap(LinearLayoutManager.java:894)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:636)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1160)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1651)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5333)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
You can add the buttons dynamically.

Set the poll option with the onclicklistener and inside the onclicklistener's onclick method..

Create 5 new Buttons and add it to the cardView .

```<code>Button btn1 = new Button(context);
BUtton btn2 = new Button(context);
Button btn3 = new Button(context);

cardView.addView (btn1);
</code>```

Repeat this.

To get the cardView of particular item ..

define the onclicklistener in the viewHolder and to get the position use the getAdapterPosition() method.

By this way you can add it

Body:
I have a layout for CardView with 2 TextViews and 2 Buttons initially. Based on the #options in poll.getOptions(), a Cardview can have up to 5 buttons. So I want to add dynamically those buttons... If I add them in onBindViewHolder, after clicking a button, it adds duplicates of these buttons. I tried to add it in onCreateViewHolder but when I try to create a new button it gives me a NullPointerException. I tried in many ways but can't find solution. What is the true way of adding dynamic views in cardview or why it gives me that error?

Layout for CardView:

<?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto">

        <data>
            <variable
                name = "poll"
                type = "mattoncino.pollo.Poll" />
        </data>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            card_view:cardCornerRadius="@dimen/cardview_default_radius"
            card_view:cardElevation="@dimen/cardview_default_elevation">

            <LinearLayout
                android:id="@+id/listItemLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="5dp">

                <TextView
                    android:id="@+id/nameTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="30sp"
                    android:textAllCaps="false"
                    android:text="@{poll.name}"/>

                <TextView
                    android:id="@+id/questionTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="20sp"
                    android:text="@{poll.question}"/>

                <Button
                    android:id="@+id/opt1Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(1)}"
                    android:enabled="@{!poll.disabled}"/>

                <Button
                    android:id="@+id/opt2Button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textSize="18sp"
                    android:textAllCaps="false"
                    android:text="@{poll.getText(2)}"
                    android:enabled="@{!poll.disabled}"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>
    </layout>

My CardViewAdapter class:

public class PollsCardViewAdapter extends RecyclerView.Adapter<PollsCardViewAdapter.CardViewHolder> {

        private List<Poll> activePolls;
        private final static String TAG = "CARDVIEW_ADAPTER";

        public PollsCardViewAdapter(List<Poll> polls){
            activePolls = polls;
        }

        public static class CardViewHolder extends RecyclerView.ViewHolder {

            private ActivePollsListItemBinding listItemBinding;

            public CardViewHolder(View v) {
                super(v);
                listItemBinding = DataBindingUtil.bind(v);
            }

            public ActivePollsListItemBinding getBinding(){
                return listItemBinding;
            }
        }

        // Create new views (invoked by the layout manager)
        @Override
        public PollsCardViewAdapter.CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.active_polls_list_item, parent, false);

            CardViewHolder holder = new CardViewHolder(v);
            Context context = holder.getBinding().nameTextView.getContext();

            Poll poll = activePolls.get(viewType);

            for (int i = 2; i < poll.getOptions().size(); i++) {
                int opt = i + 1;
                Button button = createNewOptionButton(context, poll.getText(opt));
                if(poll.isDisabled()) {
                    button.setEnabled(false);
                }
                else button.setText(poll.getText(opt));
                parent.addView(button);
            }

            return holder;
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        public void onBindViewHolder(final PollsCardViewAdapter.CardViewHolder holder, final int position) {
            final Poll poll = activePolls.get(position);
            final LinearLayout rLayout = holder.getBinding().listItemLayout;

            if(!poll.isDisabled()){
                for (int i = 2; i < rLayout.getChildCount(); i++){
                    final View view = rLayout.getChildAt(i);
                    final int opt = i - 1;

                    if(view instanceof Button){
                        final Button button = (Button) view;
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                button.setText(button.getText().toString() + "    " + "\u2713");
                             setCardDetails(holder.getBinding().nameTextView.getContext(), rLayout, poll, opt);
                            }
                        });
                    }
                }
            }

            holder.getBinding().setVariable(BR.poll, poll);
            holder.getBinding().executePendingBindings();
        }

        private void setCardDetails(final Context context, final LinearLayout rLayout, final Poll poll, final int opt){
            poll.setDisabled(true);
            disableOptionButtons(rLayout);
            rLayout.addView(addMessageView(context));

            Handler handler = new Handler();
            final Runnable r = new Runnable(){
                @Override
                public void run() {
                    poll.addVote(opt);
                    notifyDataSetChanged();
                }
            };
            handler.post(r);
        }

        private void disableOptionButtons(ViewGroup layout){
            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                if(child.hasOnClickListeners())
                    child.setEnabled(false);
            }
        }

        private TextView addMessageView(Context context){
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            TextView textView = new TextView(context);
            textView.setLayoutParams(lparams);
            textView.setId(View.generateViewId());
            textView.setText("Thanks for voting! Wait for results...");
            textView.setTextSize(20);
            textView.setTypeface(null, Typeface.BOLD_ITALIC);

            return textView;
        }

        private static Button createNewOptionButton(Context context, String option) {
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

            final Button button = new Button(context);
            button.setLayoutParams(lparams);
            button.setId(View.generateViewId());
            button.setTextSize(18);
            button.setText(option);
            //button.setBackgroundColor(Color.TRANSPARENT);
            return button;

        }

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

The exception that I get, inside the createNewOptionButton()

mattoncino.pollo E/AndroidRuntime: FATAL EXCEPTION: main
        Process: mattoncino.pollo, PID: 4684
        java.lang.NullPointerException
        at android.support.v7.widget.RecyclerView$LayoutParams.getViewLayoutPosition(RecyclerView.java:10862)
        at android.support.v7.widget.RecyclerView$LayoutManager.getPosition(RecyclerView.java:7949)
        at android.support.v7.widget.LinearLayoutManager.updateLayoutState(LinearLayoutManager.java:1184)
        at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1323)
        at android.support.v7.widget.LinearLayoutManager.fixLayoutEndGap(LinearLayoutManager.java:894)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:636)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1160)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1651)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4867)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5333)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)

Body:
You can add the buttons dynamically.

Set the poll option with the onclicklistener and inside the onclicklistener's onclick method..

Create 5 new Buttons and add it to the cardView .

Button btn1 = new Button(context);
BUtton btn2 = new Button(context);
Button btn3 = new Button(context);

cardView.addView (btn1);

Repeat this.

To get the cardView of particular item ..

define the onclicklistener in the viewHolder and to get the position use the getAdapterPosition() method.

By this way you can add it


来源: stackexchange

问:
Using an image caption in Markdown Jekyll
I am hosting a Jekyll Blog on Github and write my posts with Markdown. When I am adding images, I do it the following way:

![name of the image](http://link.com/image.jpg)

This then shows the image in the text.

However, how can I tell Markdown to add a caption which is presented below or above the image?

答:
The correct HTML to use for images with captions, is
 with
.

There's no Markdown equivalent for this, so if you're only adding the occasional caption, I'd encourage you to just add that html into your Markdown document:

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit...

<figure>
  <img src="{{site.url}}/assets/image.jpg" alt="my alt text"/>
  <figcaption>This is my caption text.</figcaption>
</figure>

Vestibulum eu vulputate magna...
</code>```

The Markdown spec encourages you to embed HTML in cases like this, so it will display just fine. It's also a lot simpler than messing with plugins.

If you're trying to use other Markdown-y features (like tables, asterisks, etc) to produce captions, then you're just hacking around how Markdown was intended to be used.

ContentLicense: CC BY-SA 3.0

Body:
The correct HTML to use for images with captions, is <figure> with <figcaption>.

There's no Markdown equivalent for this, so if you're only adding the occasional caption, I'd encourage you to just add that html into your Markdown document:

Lorem ipsum dolor sit amet, consectetur adipiscing elit...

<figure>
  <img src="{{site.url}}/assets/image.jpg" alt="my alt text"/>
  <figcaption>This is my caption text.</figcaption>
</figure>

Vestibulum eu vulputate magna...

The Markdown spec encourages you to embed HTML in cases like this, so it will display just fine. It's also a lot simpler than messing with plugins.

If you're trying to use other Markdown-y features (like tables, asterisks, etc) to produce captions, then you're just hacking around how Markdown was intended to be used.

ContentLicense: CC BY-SA 4.0


问:
PowerPivot Calculated Column Circular Dependency
I'm really spinning my wheels on this one. I'm trying to add 2 calculated columns in a Power Pivot table (in Excel 2013) to a loaded single column.

Setup (just first row shown):

```<code>Prd | Beg                                                      | End
1   | =CALCULATE(SUM([End]),Table[Prd]=EARLIER([Prd])-1)       | =[Beg]+[Prd]
</code>```

I want it to calculate like this:

```<code>Prd | Beg | End
1   | 1   | 2
2   | 2   | 4
3   | 4   | 7
</code>```

But no matter what I do, I get a circular reference error because the [End] calculation is pointing to the [Beg] calculation and vice versa. I'm trying to get it to perform a rolling calculation where the [Beg] amount always equals the [End] amount from the prior [Prd].

I tried various calculations using SUMX and ALLEXCEPT, but I'm not getting this one right. I even tried designating the Row Identifier in the Table Behavior tab based on this but it's not working with that either.

Appreciate any suggestions!

答:
I would suggest you to base your formula for [Beg] column on previous values of [Prd] column. Therefore

```<code>Beg=SUMX(
         FILTER(
                ALL(Table[Prd]),
                Table[Prd] < EARLIER(Table[Prd])
               ),
         Table[Prd]
        ) + 1
</code>```

Explanation:

It sums up all the previous values for [Prd] column and adds 1 (if you take a look at the generated values, you'll see the pattern).

But the formula for [End] should also be fixed so you won't run into the same exception. So you'll have the following (this will sum values from current row for [Beg] and [Prd]):

```<code>End=SUMX(
         FILTER(
                ALL(Table[Beg], Table[Prd]),
                Table[Prd]=EARLIER(Table[Prd])),Table[Beg]
        ) + Table[Prd]
</code>```

Explanation:

In your case, avoiding to use CALCULATE and using instead just SUMX and EARLIER for [End] will help you to get rid of circular dependency.

Body:
I'm really spinning my wheels on this one. I'm trying to add 2 calculated columns in a Power Pivot table (in Excel 2013) to a loaded single column.

Setup (just first row shown):

Prd | Beg                                                      | End
1   | =CALCULATE(SUM([End]),Table[Prd]=EARLIER([Prd])-1)       | =[Beg]+[Prd]

I want it to calculate like this:

Prd | Beg | End
1   | 1   | 2
2   | 2   | 4
3   | 4   | 7

But no matter what I do, I get a circular reference error because the [End] calculation is pointing to the [Beg] calculation and vice versa. I'm trying to get it to perform a rolling calculation where the [Beg] amount always equals the [End] amount from the prior [Prd].

I tried various calculations using SUMX and ALLEXCEPT, but I'm not getting this one right. I even tried designating the Row Identifier in the Table Behavior tab based on this but it's not working with that either.

Appreciate any suggestions!

Body:
I would suggest you to base your formula for [Beg] column on previous values of [Prd] column. Therefore

Beg=SUMX(
         FILTER(
                ALL(Table[Prd]),
                Table[Prd] < EARLIER(Table[Prd])
               ),
         Table[Prd]
        ) + 1

Explanation:

It sums up all the previous values for [Prd] column and adds 1 (if you take a look at the generated values, you'll see the pattern).

But the formula for [End] should also be fixed so you won't run into the same exception. So you'll have the following (this will sum values from current row for [Beg] and [Prd]):

End=SUMX(
         FILTER(
                ALL(Table[Beg], Table[Prd]),
                Table[Prd]=EARLIER(Table[Prd])),Table[Beg]
        ) + Table[Prd]

Explanation:

In your case, avoiding to use CALCULATE and using instead just SUMX and EARLIER for [End] will help you to get rid of circular dependency.


问:
python : the selenium webscraping script not working through module
whenever I am running the following script through shell its working but whenever i am running the same script through python module or pycharm its not working, its not fetching the data. Can anyone please help in that ?</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
site = browser.get("https://www.flipkart.com/")
searchInput = browser.find_element_by_class_name("LM6RPg")
searchInput.send_keys('Laptop')
searchInput.send_keys(Keys.ENTER)
titleResults = browser.find_elements_by_xpath("//div[@class='_3wU53n']")
for title in titleResults:
    print(title.text)
</code>```

答:
Here is the Answer to your Question:

```<code>    from selenium import webdriver
    from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait

    binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')
    caps = DesiredCapabilities().FIREFOX
    caps["marionette"] = True
    browser = webdriver.Firefox(capabilities=caps, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")

    site = browser.get("https://www.flipkart.com/")
    searchInput = browser.find_element_by_xpath("//input[@class='LM6RPg']")
    searchInput.send_keys('Laptop')
    searchInput.send_keys(Keys.ENTER)
    WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='container']//div[text()='Dell Inspiron Core i3 6th Gen - (4 GB/1 TB HDD/Windows 10 Home) 3467 Notebook']")))
    titleResults = browser.find_elements_by_xpath("//div[@class='_3wU53n']")
    for title in titleResults:
        print(title.text)
</code>```

Let me know if this Answers your Question.

Body:
whenever I am running the following script through shell its working but whenever i am running the same script through python module or pycharm its not working, its not fetching the data. Can anyone please help in that ?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
site = browser.get("https://www.flipkart.com/")
searchInput = browser.find_element_by_class_name("LM6RPg")
searchInput.send_keys('Laptop')
searchInput.send_keys(Keys.ENTER)
titleResults = browser.find_elements_by_xpath("//div[@class='_3wU53n']")
for title in titleResults:
    print(title.text)

Body:
Here is the Answer to your Question:

    from selenium import webdriver
    from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait

    binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')
    caps = DesiredCapabilities().FIREFOX
    caps["marionette"] = True
    browser = webdriver.Firefox(capabilities=caps, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")

    site = browser.get("https://www.flipkart.com/")
    searchInput = browser.find_element_by_xpath("//input[@class='LM6RPg']")
    searchInput.send_keys('Laptop')
    searchInput.send_keys(Keys.ENTER)
    WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='container']//div[text()='Dell Inspiron Core i3 6th Gen - (4 GB/1 TB HDD/Windows 10 Home) 3467 Notebook']")))
    titleResults = browser.find_elements_by_xpath("//div[@class='_3wU53n']")
    for title in titleResults:
        print(title.text)

Let me know if this Answers your Question.


问:
Panorama control truncating long titles
I'm trying to create a simple Windows Phone 7 app in which one of the pages uses a Panorama control. My control has five PanoramaItem children. Using the code below, the title is truncated on the fourth screen in the middle of the word "anyone." How can I make the Panorama control display the full title?

```<code><controls:Panorama Title="This is the longest title anyone has ever seen" >
</code>```

答: I believe panorama page title has to fit within 1000 px.</p>

ContentLicense: CC BY-SA 2.5

Title: Panorama control truncating long titles

Body:
I'm trying to create a simple Windows Phone 7 app in which one of the pages uses a Panorama control. My control has five PanoramaItem children. Using the code below, the title is truncated on the fourth screen in the middle of the word "anyone." How can I make the Panorama control display the full title?

<controls:Panorama Title="This is the longest title anyone has ever seen" >


问:
Getting all branches from bitbucket
I need to hand off a visual studio project that has multiple branches. Bitbucket is being used as the repo. I am trying to find a way to download the entire repo with every branch. I'm not sure if there is a solution using GIT or some feature in bitbucket that I can't find. When I try to download directly from Bitbucket I only get the master branch</p>

答:
Is there some reason why you can't just git fetch from the repository:

```<code>git fetch origin
</code>```

This should pull in every remote branch to whatever local machine from which you issue this command.  If you need to access a particular branch, you could just check it out via:

```<code>git checkout some_branch
</code>```

Title: Getting all branches from bitbucket

Body:
Is there some reason why you can't just git fetch from the repository:

git fetch origin

This should pull in every remote branch to whatever local machine from which you issue this command.  If you need to access a particular branch, you could just check it out via:

git checkout some_branch


问:
Parsing through dataset
Using the Wordpress function wp_load_alloptions() I get a large array with all my sites option data. I selected a single portion of it that I need to globally get data from.

```<code>$all_options = wp_load_alloptions();
$my_options = array();
foreach( $all_options as $name => $value ) {
   if(stristr($name, 'options')) $my_options[$name] = $value;
}

echo '```';
   print_r($my_options['sl_options_options']);
echo '```';
</code>```

This returns:

```<code>s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";}
</code>```

Is there a way I can parse through this data set to break out each individual part. Example of individual parts that go together:

```<code>s:12:"optim_toggle";s:2:"On";
</code>```

Title: Parsing through dataset

Body:
Using the Wordpress function wp_load_alloptions() I get a large array with all my sites option data. I selected a single portion of it that I need to globally get data from.

$all_options = wp_load_alloptions();
$my_options = array();
foreach( $all_options as $name => $value ) {
   if(stristr($name, 'options')) $my_options[$name] = $value;
}

echo '
';
   print_r($my_options['sl_options_options']);
echo '
';

This returns:

s:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";}

Is there a way I can parse through this data set to break out each individual part. Example of individual parts that go together:

s:12:"optim_toggle";s:2:"On";

Body:
You want something like this ? :

preg_split('/;|,/', 's:15:"popup_form_text";s:0:"";s:14:"popup_form_URL";s:124:"url";s:15:"popup_form_open";s:2:"14";s:16:"popup_form_close";s:2:"23";s:15:"evergage_toggle";s:2:"On";s:12:"optim_toggle";s:2:"On";s:13:"soasta_toggle";s:3:"Off";}');

Output :

array(15) {
  [0] =>
  string(22) "s:15:"popup_form_text""
  [1] =>
  string(6) "s:0:"""
  [2] =>
  string(21) "s:14:"popup_form_URL""
  [3] =>
  string(11) "s:124:"url""
  [4] =>
  string(22) "s:15:"popup_form_open""
  [5] =>
  string(8) "s:2:"14""
  [6] =>
  string(23) "s:16:"popup_form_close""
  [7] =>
  string(8) "s:2:"23""
  [8] =>
  string(22) "s:15:"evergage_toggle""
  [9] =>
  string(8) "s:2:"On""
  [10] =>
  string(19) "s:12:"optim_toggle""
  [11] =>
  string(8) "s:2:"On""
  [12] =>
  string(20) "s:13:"soasta_toggle""
  [13] =>
  string(9) "s:3:"Off""
  [14] =>
  string(1) "}"
}

You can optimize it easily.


问:
how to copy .htaccess to all 0777 folders
The following command attempts to copy /.htaccess to all folders permission 0777

```<code>find /home/*/www/ -type d -perm 0777 \
| xargs -r -d '\n'  cp -rf /.htaccess
</code>```

am looking to run it with terminal ssh command

i search for all folders have 0777 and copy htaccess to all at once

答:
find /home/*/www -type d -perm /0777 -print0 | xargs -0 -I{} -r -P4 -n1 cp /.htaccess '{}'

You want to use print0 combined with xargs -0 so that it can handle IFS characters.

Use xargs -n1 so that it only tries to copy to one directory at a time.

I use xargs -I{} to be more explicit in what I'm doing.

xargs -P4 will parallelize it 4 times to increased speed.

Body:
The following command attempts to copy /.htaccess to all folders permission 0777

find /home/*/www/ -type d -perm 0777 \
| xargs -r -d '\n'  cp -rf /.htaccess

am looking to run it with terminal ssh command

i search for all folders have 0777 and copy htaccess to all at once


问:
EntityManager#getResultList() returns an empty list
I'm working on my first web shop and have trouble to retrieve objects when searching for them. Searching for an existing product results in that the list productHits remains empty.

(To read the whole project please see https://github.com/gitsjogren/TareaWebShop)

Here's the product catalogue:

```<code>public final class ProductCatalogue extends AbstractDAO<Product, Long> implements IProductCatalogue {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("shop_pu");
    private static Product p1;
    private static Customer c1;

@Override
    public List<Product> search(String searchWord){
        EntityManager em = emf.createEntityManager();
        List<Product> prodHits = new ArrayList<>();
        try {
            String sqlQuery = "SELECT p FROM Product p WHERE p.name LIKE :theSearch";
            TypedQuery<Product> q = em.createQuery(sqlQuery, Product.class);
            String searchQuery = "%" + searchWord + "%";
            q.setParameter("theSearch", searchQuery);
            prodHits = (List<Product>) q.getResultList();
        } catch (Exception e) {
            System.out.print(e);
        }
        em.close();
        return prodHits;
}
</code>```

I have also tried using a NativeQuery instead of a TypedQuery, with no luck.

```<code>Query q = em.createNativeQuery(sqlQuery, Product.class);
</code>```

答:
If you're didn't get your answer yet:

it can happen when you have something uncommitted on that table in DB. In that case, if you run the same query in DB you'd get the real answer, but if you run it from the code, it may return empty list.

Body:
I'm working on my first web shop and have trouble to retrieve objects when searching for them. Searching for an existing product results in that the list productHits remains empty.

(To read the whole project please see https://github.com/gitsjogren/TareaWebShop)

Here's the product catalogue:

public final class ProductCatalogue extends AbstractDAO<Product, Long> implements IProductCatalogue {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("shop_pu");
    private static Product p1;
    private static Customer c1;

@Override
    public List<Product> search(String searchWord){
        EntityManager em = emf.createEntityManager();
        List<Product> prodHits = new ArrayList<>();
        try {
            String sqlQuery = "SELECT p FROM Product p WHERE p.name LIKE :theSearch";
            TypedQuery<Product> q = em.createQuery(sqlQuery, Product.class);
            String searchQuery = "%" + searchWord + "%";
            q.setParameter("theSearch", searchQuery);
            prodHits = (List<Product>) q.getResultList();
        } catch (Exception e) {
            System.out.print(e);
        }
        em.close();
        return prodHits;
}

I have also tried using a NativeQuery instead of a TypedQuery, with no luck.

Query q = em.createNativeQuery(sqlQuery, Product.class);


问:
React autofocus input after enabling a disabled input
I'm trying to autofocus a text input (the input is enabled upon selecting a relevant radio option).

The autofocus works when toggling between options that will enable the text input. However, autofocus fails when switching from an option that disables the text input to an option that enables the text input.

In the sample link below:

option 1, option 2: disable the text input

option 3, option 4: enable the text input

Failure case:

option 1 is default

choose option 3 or option 4

input gets enabled

autofocus fails (looking for pointer to fix this behaviour)

Success case:

choose option 3

input is enabled

switch to option 4

input is autoFocussed

sample code for the problem on codesandbox

答: Just a little extra to add, autoFocus only works on the initial render of the element (basically only when componentDidMount runs). So that's why it's not automatically focusing when you re-enable the input, it's not being unmounted and then re-mounted. To make autoFocus work, you'd need to move the input and disabled input into separate components and conditionally render them based on state.


问:
CSS Copy and paste problem
I've developed a system in my application where emails are picked up with a regex, and then reversed in the source (to thwart bots). I then add the span class 'obfuscate email'. I then use CSS to reverse the the text back to be displayed and Javascript make sure that mailto: links still work.

I was pretty happy with my solution until I realised that copying and pasting the email puts it in the clipboard backwards. I was wondering if there was any way I could remedy this? I've been testing in Firefox 3 for OS X.

The page in question is available here: http://www.leaklocations.com.au/contact-us/

To see the problem, simply copy and paste the email on that site.

答:
I personally think it's going a bit over the top, but if you really want to obfuscate the address, why not obfuscate it in a human readable way? Instead of reversing the address, make the server output "info at leaklocations dot com dot au" and get javascript to fix it up?

If you wanted to stick to using the RTL CSS method, you could try playing around with the unicode character to reverse text: \u202E I'm not sure if that will help, but it's worth looking at

To see how this works, run this javascript:

```<code>alert("one \u202E two \u202E three")
</code>```

and it'll output "one owt three"

OwnerDisplayName: alex

Title: CSS Copy and paste problem

Body:
I personally think it's going a bit over the top, but if you really want to obfuscate the address, why not obfuscate it in a human readable way? Instead of reversing the address, make the server output "info at leaklocations dot com dot au" and get javascript to fix it up?

If you wanted to stick to using the RTL CSS method, you could try playing around with the unicode character to reverse text: \u202E I'm not sure if that will help, but it's worth looking at

To see how this works, run this javascript:

alert("one \u202E two \u202E three")

and it'll output "one owt three"

OwnerDisplayName: nickf


问:
PHP: is_array on $arr['key'] with non existing 'key'
One of my colleges seem to have an 'undefined index' error on a code I wrote

This code of mine looks like this:

```<code>if ( is_array ($arr['key']))
</code>```

My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?

Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?

Thank you

答:
Yes, use isset, then is_array.

```<code>if(isset($arr['key']) && is_array($arr['key'])) {
    // ...
}
</code>```

Because PHP uses short-circuit logic evaluation, it will stop before it gets to is_array(), so you'll never get an error.

Body:
One of my colleges seem to have an 'undefined index' error on a code I wrote

This code of mine looks like this:

if ( is_array ($arr['key']))

My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?

Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?

Thank you

Body:
Yes, use isset, then is_array.

if(isset($arr['key']) && is_array($arr['key'])) {
    // ...
}

Because PHP uses short-circuit logic evaluation, it will stop before it gets to is_array(), so you'll never get an error.


问:
Restricting stripe shipping address by country
I am selling a physical product through Stripe Checkout (the native stripe version) and I'm looking to lock the shipping address to UK.

Has anyone any info on how this can be configured? Can't find it in docs.

答: This is not something supported by Stripe Checkout at the moment. The best solution here would be to collect the shipping address in your own form before opening Stripe Checkout and only collect billing address in Checkout (or no address at all).</p>


问:
Can't resolve getProofOfPayment Paypal
I'm a newbie in coding. I am trying to add Paypal Payments to my app and found a tutorialvideo for that but in I get an error:

getProofOfPayment method can't be resolved.

Do you have any idea why? I did everything like in the tutorial so far and there was no error.

Here is my code:

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

    TextView m_response;

    PayPalConfiguration m_configuration;

    String m_paypalClientid;

    Intent m_service;

    int m_paypalRequestCode = 999;

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

        m_response = (TextView) findViewById(R.id.response);

        m_configuration = new PayPalConfiguration().environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
        .clientId(m_paypalClientid);

        m_service = new Intent(this, PayPalService.class);
        m_service.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, m_configuration);
        startService(m_service);
    }

    void pay (View view){
        PayPalPayment payment = new PayPalPayment(new BigDecimal(10), "EUR", "Tes payment for Paypal",
                PayPalPayment.PAYMENT_INTENT_SALE);

        Intent intent = new Intent(this, PayPalPayment.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, m_configuration);
        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
        startActivityForResult(intent, m_paypalRequestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == m_paypalRequestCode)

        {
            if (resultCode == Activity.RESULT_OK)
            {
                PayPalConfiguration confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);

                if (confirmation != null)
                {
                    String state = confirmation.getProofOfPayment().getState();

                    if (state.equals("approved"))
                        m_response.setText("Payment approved");
                    else
                        m_response.setText("Error in the payment");

                }
                else
                    m_response.setText("confirmation is null");

            }

        }
    }
}
</code>```

答:
I think you want an object of Type PaymentConfirmation instead of your PayPalConfiguration in Method onActivityResult

Just replace it and it should work.

Title: Can't resolve getProofOfPayment Paypal

Body:
I'm a newbie in coding. I am trying to add Paypal Payments to my app and found a tutorialvideo for that but in I get an error:

getProofOfPayment method can't be resolved.

Do you have any idea why? I did everything like in the tutorial so far and there was no error.

Here is my code:

public class MainActivity extends AppCompatActivity {

    TextView m_response;

    PayPalConfiguration m_configuration;

    String m_paypalClientid;

    Intent m_service;

    int m_paypalRequestCode = 999;

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

        m_response = (TextView) findViewById(R.id.response);

        m_configuration = new PayPalConfiguration().environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
        .clientId(m_paypalClientid);

        m_service = new Intent(this, PayPalService.class);
        m_service.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, m_configuration);
        startService(m_service);
    }

    void pay (View view){
        PayPalPayment payment = new PayPalPayment(new BigDecimal(10), "EUR", "Tes payment for Paypal",
                PayPalPayment.PAYMENT_INTENT_SALE);

        Intent intent = new Intent(this, PayPalPayment.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, m_configuration);
        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
        startActivityForResult(intent, m_paypalRequestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == m_paypalRequestCode)

        {
            if (resultCode == Activity.RESULT_OK)
            {
                PayPalConfiguration confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);

                if (confirmation != null)
                {
                    String state = confirmation.getProofOfPayment().getState();

                    if (state.equals("approved"))
                        m_response.setText("Payment approved");
                    else
                        m_response.setText("Error in the payment");

                }
                else
                    m_response.setText("confirmation is null");

            }

        }
    }
}


问:
How to send a message from a Telegram bot in case of python script exception?
I'm working on my wetherstation which collects temperature and humidity every minute. To this project I would like to add a Telegram bot which sends me a message if the data record gets stopped.

I downloaded the Telegram bot library and made some tests with my Telegram bot.

For now, my bot is able to answer if I request, for example, the current humidity by sending /humidity to my bot.

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.

"""
This Bot uses the Updater class to handle the bot.

First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.

Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import read_from_database

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
    update.message.reply_text('Hi!')

def status(bot, update):
    zeitstempel = read_from_database.get_timestamp()
    update.message.reply_text('letzter Eintrag: {:%d.%m.%Y %H:%M}'.format(zeitste$

def temperatur(bot, update):
    temperatur = read_from_database.get_temperature()
#    update.message.reply_text('letzter Temperatureintrag: %s ' % temperatur + u'$
    update.message.reply_text('letzter Temperatureintrag: %s C' % temperatur)

def feuchtigkeit(bot, update):
    feuchtigkeit = read_from_database.get_humidity()
    update.message.reply_text('letzter Feuchtigkeitseintrag: %s %%' % feuchtigkei$

def echo(bot, update):
    update.message.reply_text(update.message.text)

def error(bot, update, error):
    logger.warn('Update "%s" caused error "%s"' % (update, error))

def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater("TOKEN")

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("status", status))
    dp.add_handler(CommandHandler("feuchtigkeit", feuchtigkeit))
    dp.add_handler(CommandHandler("temperatur", temperatur))

    # on noncommand i.e message - echo the message on Telegram
    #dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()
</code>```

But I have no idea how to send out an alarm when my python script runs into an exception during the record. Is there a possibility to send a message from my python script without sending a request to my Telegram bot?

答: use updater.bot.send_message to send message</p>

Body:
I'm working on my wetherstation which collects temperature and humidity every minute. To this project I would like to add a Telegram bot which sends me a message if the data record gets stopped.

I downloaded the Telegram bot library and made some tests with my Telegram bot.

For now, my bot is able to answer if I request, for example, the current humidity by sending /humidity to my bot.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.

"""
This Bot uses the Updater class to handle the bot.

First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.

Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import read_from_database

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
    update.message.reply_text('Hi!')

def status(bot, update):
    zeitstempel = read_from_database.get_timestamp()
    update.message.reply_text('letzter Eintrag: {:%d.%m.%Y %H:%M}'.format(zeitste$

def temperatur(bot, update):
    temperatur = read_from_database.get_temperature()
#    update.message.reply_text('letzter Temperatureintrag: %s ' % temperatur + u'$
    update.message.reply_text('letzter Temperatureintrag: %s C' % temperatur)

def feuchtigkeit(bot, update):
    feuchtigkeit = read_from_database.get_humidity()
    update.message.reply_text('letzter Feuchtigkeitseintrag: %s %%' % feuchtigkei$

def echo(bot, update):
    update.message.reply_text(update.message.text)

def error(bot, update, error):
    logger.warn('Update "%s" caused error "%s"' % (update, error))

def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater("TOKEN")

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("status", status))
    dp.add_handler(CommandHandler("feuchtigkeit", feuchtigkeit))
    dp.add_handler(CommandHandler("temperatur", temperatur))

    # on noncommand i.e message - echo the message on Telegram
    #dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

But I have no idea how to send out an alarm when my python script runs into an exception during the record. Is there a possibility to send a message from my python script without sending a request to my Telegram bot?


问:
How to split the last commit into two in Git?
I have two branches, master and forum, and I've just made some modifications in forum that I'd like to cherry-pick into master. But unfortunately, the commit I want to cherry-pick also contains some modifications that I don't want.

The solution would probably be to somehow delete the wrong commit and replace it with two separate commits, one with changes I want to pick in master, the other with the remaining changes.

I've tried doing

```<code>git reset --hard HEAD^
</code>```

which deleted all changes, so I had to go back with

```<code>git reset ORIG_HEAD
</code>```

So my question is, what is the best way to split the last commit into two separate commits?

答:
The double-revert-squash method

Make another commit that removes the unwanted changes. (If it's per file, this is really easy: git checkout HEAD~1 -- files with unwanted changes and git commit. If not, files with mixed changes can be partially staged git reset file and git add -p file as an intermediate step.) Call this the revert.

git revert HEAD – Make yet another commit, that adds back the unwanted changes. This is the double-revert

Of the 2 commits you now made, squash the first onto the commit to split (git rebase -i HEAD~3). This commit now becomes free of the unwanted changes, for those are in the second commit.

Benefits

Preserves the commit message

Works even if the commit to split is not the last one. It only requires that the unwanted changes do not conflict with later commits

Body:
I have two branches, master and forum, and I've just made some modifications in forum that I'd like to cherry-pick into master. But unfortunately, the commit I want to cherry-pick also contains some modifications that I don't want.

The solution would probably be to somehow delete the wrong commit and replace it with two separate commits, one with changes I want to pick in master, the other with the remaining changes.

I've tried doing

git reset --hard HEAD^

which deleted all changes, so I had to go back with

git reset ORIG_HEAD

So my question is, what is the best way to split the last commit into two separate commits?


问:
Outer merging two data frames in place in pandas
How can I outer merge two data frames in place in pandas?

For example, assume we have these two data frames:

```<code>import pandas as pd

s1 = pd.DataFrame({
    'time':[1234567000,1234567005,1234567009],
    'X1':[96.32,96.01,96.05]
},columns=['time','X1'])  # to keep columns order

s2 = pd.DataFrame({
    'time':[1234567001,1234567005],
    'X2':[23.88,23.96]
},columns=['time','X2'])  # to keep columns order
</code>```

They could be merged with pandas.DataFrame.merge (s3 = pd.merge(s1,s2,how='outer')) or with  pandas.merge (s3=s1.merge(s2,how='outer')), but it isn't in place. Instead, I'd like the merged data frame to replace s1 in memory.

答:
Since there is not inplace parameter in pandas.merge i think the most you can do is:

```<code>s1 = pd.merge(s1,s2,how='outer')
</code>```

other than that, i don't think there's much left to do.

Hope that was helpful somehow.

Body:
How can I outer merge two data frames in place in pandas?

For example, assume we have these two data frames:

import pandas as pd

s1 = pd.DataFrame({
    'time':[1234567000,1234567005,1234567009],
    'X1':[96.32,96.01,96.05]
},columns=['time','X1'])  # to keep columns order

s2 = pd.DataFrame({
    'time':[1234567001,1234567005],
    'X2':[23.88,23.96]
},columns=['time','X2'])  # to keep columns order

They could be merged with pandas.DataFrame.merge (s3 = pd.merge(s1,s2,how='outer')) or with  pandas.merge (s3=s1.merge(s2,how='outer')), but it isn't in place. Instead, I'd like the merged data frame to replace s1 in memory.

Body:
Since there is not inplace parameter in pandas.merge i think the most you can do is:

s1 = pd.merge(s1,s2,how='outer')

other than that, i don't think there's much left to do.

Hope that was helpful somehow.


问:
Is there a solution for getting the default value of the parameters of a given stored procedure?
I use INFORMATION_SCHEMA.PARAMETERS for getting information about a stored procedure parameter now. I need to know the default values of parameters. Is there a solution for getting the default value of the parameters of a given stored procedure?

答:
```<code>Declare @pSProcName NVARCHAR(MAX)='ProcedureName'

DECLARE @SQLTEXT NVARCHAR(MAX),@start int ,@end int,@SearchCode NVARCHAR(MAX)
SELECT @SQLTEXT =OBJECT_DEFINITION(OBJECT_ID(@pSProcName))
SELECT @start=CHARINDEX('@',@SQLTEXT,1)
SELECT @end =min(val) FROM (
SELECT PATINDEX('%'+CHAR(10)+'AS'+CHAR(10)+'%',@SQLTEXT ) AS val
UNION ALL SELECT PATINDEX('%'+CHAR(10)+'AS'+CHAR(13)+'%',@SQLTEXT )
UNION ALL SELECT PATINDEX('%'+CHAR(13)+'AS'+CHAR(10)+'%',@SQLTEXT )
UNION ALL SELECT PATINDEX('%'+CHAR(13)+'AS'+CHAR(13)+'%',@SQLTEXT )
UNION ALL SELECT PATINDEX('%'+CHAR(10)+'AS'+CHAR(32)+'%',@SQLTEXT )
UNION ALL SELECT PATINDEX('%'+CHAR(32)+'AS'+CHAR(10)+'%',@SQLTEXT )
UNION ALL SELECT PATINDEX('%'+CHAR(32)+'AS'+CHAR(32)+'%',@SQLTEXT )
UNION ALL SELECT PATINDEX('%'+CHAR(13)+'AS'+CHAR(32)+'%',@SQLTEXT )
UNION ALL SELECT PATINDEX('%'+CHAR(32)+'AS'+CHAR(13)+'%',@SQLTEXT )
) S
Where s.val <> 0

SELECT @SearchCode=SUBSTRING(@sqltext,@start,@end - @start)
SELECT S2.parameter_id,S2.ParameterName,S2.DataType,S1.Default_Value FROM
(
SELECT CASE WHEN Data like '%=%' then RIGHT(Data,len(Data)-CHARINDEX('=',Data,1)) ELSE '' END as Default_Value,
CASE WHEN Data like '%=%' then 1 ELSE 0 END as Has_default_Value
,Data FROM(
SELECT LTRIM(RTRIM(Split.a.value('.', 'VARCHAR(100)'))) AS Data
 FROM
 (
     SELECT  CAST ('<M>' + REPLACE(@SearchCode, ',', '</M><M>') + '</M>' AS XML) AS Data

 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a))s
 )S1

INNER JOIN
(
Select p.parameter_id,p.name as ParameterName,UPPER(t.name) AS DataType from sys.all_parameters p
Inner JOIN sys.types t
on t.user_type_id = p.user_type_id
where Object_name(OBJECT_ID) = @pSProcName
) S2
ON S1.Data LIKE '%'+S2.ParameterName+'%'+S2.DataType+'%'
</code>```


问:
T-SQL - Help with MAX Operation Over Many-to-Many
This is closely related to a previous question i asked.

I have a many-to-many relationship between Post and Location.

The join table is called PostLocations, and has nothing but the FK's. (LocationId, PostId)

I'm trying to pull back the top post for each location.

This is the query i have (which was given in the answer to my previous question):

```<code>SELECT pl.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by pl.locationid, p.postid, p.UniqueUri, p.Content
</code>```

But the problem is, because PostLocations could have entries like this:

```<code>LocationId   PostId
1            213213
2            498324
1            230943
</code>```

So my above query is returning LocationId 1 twice, because it has two records in the join table. I only want 1 record per location - the top post per locationid.

I've also tried this:

```<code>SELECT l.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.Locations l on pl.LocationId = l.LocationId
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by l.locationid, p.postid, p.UniqueUri, p.Content
</code>```

Same result - this is what comes back:

```<code>LocationId   PostId   UniqueUri   Content   TopScore
1            213213   some-post   pew pew   2.00
2            498324   anot-post   blah bl   4.50
1            230943   sadjsa-as   asijd a   3.5
</code>```

This is what should come back:

```<code>LocationId   PostId   UniqueUri   Content   TopScore
1            230943   sadjsa-as   asijd a   3.5
2            498324   anot-post   blah bl   4.50
</code>```

Because LocationId 1 has 2 posts, but PostId 230943 has the highest score so that is the one returned.

Any ideas on what i'm missing?

答:
As you're grouping on postID which is unique every single post falls into its own group of one.

I'm not sure if there is a better way to do this however what I've done in the past runs along these lines

```<code>Select l.LocationId, p.postid, p.UniqueUri, p.Content, s.basescore as topscore
from
    dbo.Locations l inner join
    (select
        pl.locationid, max(s.BaseScore) as topscore
    from
        dbo.postlocations pl
        inner join dbo.posts p on pl.PostId = p.PostId
        inner join dbo.reviews r on p.postid = r.postid
        inner join dbo.scores s on r.scoreid = s.scoreid
    group by
        pl.locationid) as topPost on l.locationid = topPost.locationid
    inner join dbo.postlocations pl on pl.locationid = l.locationid
    inner join dbo.posts p on pl.PostId = p.PostId
    inner join dbo.reviews r on p.postid = r.postid
    inner join dbo.scores s on r.scoreid = s.scoreid and s.basescore = toppost.topscore
</code>```

We make a subquery to find the top score for a given location then do our joins as before and on the last join ensure that the basescore is the topscore we found earlier.

This means that if we have two equal top scores for a given location we will return both rows, however in all other cases we will return a single row per location, it can be modified to pick an arbitrary post given two equal top scores but I haven't done so.

I'm interested to see if there are any other solutions to this problem as with the number of extra joins this is quite a computationally expensive solution to the problem.

Edit - in response to your comment as postid is the primary key we can rely on it to be greatest for the latest post.

```<code>Select l.LocationId, p.postid, p.UniqueUri, p.Content, bar.basescore as topscore
from
    dbo.Locations l inner join
    (select
        l.LocationId, max(p.postid) as postid ,max(s.basescore) as basescore
    from
        (select
            pl.locationid, max(s.BaseScore) as topscore
        from
            dbo.postlocations pl
            inner join dbo.posts p on pl.PostId = p.PostId
            inner join dbo.reviews r on p.postid = r.postid
            inner join dbo.scores s on r.scoreid = s.scoreid

        group by
            pl.locationid) as topPost on l.locationid = topPost.locationid
        inner join dbo.postlocations pl on pl.locationid = l.locationid
        inner join dbo.posts p on pl.PostId = p.PostId
        inner join dbo.reviews r on p.postid = r.postid
        inner join dbo.scores s on r.scoreid = s.scoreid and s.basescore = toppost.topscore
    group by l.locationid) as bar on l.locationid = bar.locationid
    inner join posts p on bar.postid = p.postid
</code>```

Body:
This is closely related to a previous question i asked.

I have a many-to-many relationship between Post and Location.

The join table is called PostLocations, and has nothing but the FK's. (LocationId, PostId)

I'm trying to pull back the top post for each location.

This is the query i have (which was given in the answer to my previous question):

SELECT pl.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by pl.locationid, p.postid, p.UniqueUri, p.Content

But the problem is, because PostLocations could have entries like this:

LocationId   PostId
1            213213
2            498324
1            230943

So my above query is returning LocationId 1 twice, because it has two records in the join table. I only want 1 record per location - the top post per locationid.

I've also tried this:

SELECT l.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.Locations l on pl.LocationId = l.LocationId
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by l.locationid, p.postid, p.UniqueUri, p.Content

Same result - this is what comes back:

LocationId   PostId   UniqueUri   Content   TopScore
1            213213   some-post   pew pew   2.00
2            498324   anot-post   blah bl   4.50
1            230943   sadjsa-as   asijd a   3.5

This is what should come back:

LocationId   PostId   UniqueUri   Content   TopScore
1            230943   sadjsa-as   asijd a   3.5
2            498324   anot-post   blah bl   4.50

Because LocationId 1 has 2 posts, but PostId 230943 has the highest score so that is the one returned.

Any ideas on what i'm missing?

Body:
As you're grouping on postID which is unique every single post falls into its own group of one.

I'm not sure if there is a better way to do this however what I've done in the past runs along these lines

Select l.LocationId, p.postid, p.UniqueUri, p.Content, s.basescore as topscore
from
    dbo.Locations l inner join
    (select
        pl.locationid, max(s.BaseScore) as topscore
    from
        dbo.postlocations pl
        inner join dbo.posts p on pl.PostId = p.PostId
        inner join dbo.reviews r on p.postid = r.postid
        inner join dbo.scores s on r.scoreid = s.scoreid
    group by
        pl.locationid) as topPost on l.locationid = topPost.locationid
    inner join dbo.postlocations pl on pl.locationid = l.locationid
    inner join dbo.posts p on pl.PostId = p.PostId
    inner join dbo.reviews r on p.postid = r.postid
    inner join dbo.scores s on r.scoreid = s.scoreid and s.basescore = toppost.topscore

We make a subquery to find the top score for a given location then do our joins as before and on the last join ensure that the basescore is the topscore we found earlier.

This means that if we have two equal top scores for a given location we will return both rows, however in all other cases we will return a single row per location, it can be modified to pick an arbitrary post given two equal top scores but I haven't done so.

I'm interested to see if there are any other solutions to this problem as with the number of extra joins this is quite a computationally expensive solution to the problem.

Edit - in response to your comment as postid is the primary key we can rely on it to be greatest for the latest post.

Select l.LocationId, p.postid, p.UniqueUri, p.Content, bar.basescore as topscore
from
    dbo.Locations l inner join
    (select
        l.LocationId, max(p.postid) as postid ,max(s.basescore) as basescore
    from
        (select
            pl.locationid, max(s.BaseScore) as topscore
        from
            dbo.postlocations pl
            inner join dbo.posts p on pl.PostId = p.PostId
            inner join dbo.reviews r on p.postid = r.postid
            inner join dbo.scores s on r.scoreid = s.scoreid

        group by
            pl.locationid) as topPost on l.locationid = topPost.locationid
        inner join dbo.postlocations pl on pl.locationid = l.locationid
        inner join dbo.posts p on pl.PostId = p.PostId
        inner join dbo.reviews r on p.postid = r.postid
        inner join dbo.scores s on r.scoreid = s.scoreid and s.basescore = toppost.topscore
    group by l.locationid) as bar on l.locationid = bar.locationid
    inner join posts p on bar.postid = p.postid


问:
Regex matches only once using find method in a loop
I'm trying to use regex in Java to extract all results between { } and loop through them one at a time.

This is the code I'm using:

```<code>Pattern p = Pattern.compile("(\\{.*})");
Matcher m = p.matcher(validatePage);
while (m.find()) {
    JSONObject jsonObj = new JSONObject(m.group(1));
    System.out.println(jsonObj);
}
</code>```

This is the text I'm searching through

```<code><tr><td class='warning'></td><td>test-testing-tester@2016-07-08.txt</td>
<td>TEST</td><td class='warningMessage'>[WARNING]</td><td
class='warningMessage'>File with the revision 2016-07-08 validated
successfully and is ready to be published. Warnings were detected. Please
see report.</td></tr>
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, version is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, release is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.rxt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, correction is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":50,"column":3,"offset":825,"length":135,"message":"extension, version is missing"}
</code>```

However m find() is looping through only once, prints the first result fine and then ends and I can't figure out why. When I run it through regex matcher it finds all the results fine. Is there something I'm missing that I need to do to match each result and loop through it?

答:
You can use (\\{.*?}) to make your regex non-greedy

Remove unwanted group as

```<code>Pattern p = Pattern.compile("\\{.*?}");
Matcher m = p.matcher(validatePage);
while (m.find()) {
    JSONObject jsonObj = new JSONObject(m.group());
    System.out.println(jsonObj);
}
</code>```

Body:
I'm trying to use regex in Java to extract all results between { } and loop through them one at a time.

This is the code I'm using:

Pattern p = Pattern.compile("(\\{.*})");
Matcher m = p.matcher(validatePage);
while (m.find()) {
    JSONObject jsonObj = new JSONObject(m.group(1));
    System.out.println(jsonObj);
}

This is the text I'm searching through

	test-testing-tester@2016-07-08.txt
TEST	[WARNING]	File with the revision 2016-07-08 validated
successfully and is ready to be published. Warnings were detected. Please
see report.

{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, version is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, release is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.rxt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, correction is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":50,"column":3,"offset":825,"length":135,"message":"extension, version is missing"}

However m find() is looping through only once, prints the first result fine and then ends and I can't figure out why. When I run it through regex matcher it finds all the results fine. Is there something I'm missing that I need to do to match each result and loop through it?

Body:
You can use (\\{.*?}) to make your regex non-greedy

Remove unwanted group as

Pattern p = Pattern.compile("\\{.*?}");
Matcher m = p.matcher(validatePage);
while (m.find()) {
    JSONObject jsonObj = new JSONObject(m.group());
    System.out.println(jsonObj);
}


问:
How to get length of array in a i18n-file in JavaScript/angularJS?
My translation file looks like this:

```<code>{
    "RANDOM": [
      {
        "ITEM": "basdf"
      },
      {
        "ITEM": "casdf"
      },
      {
        "ITEM": "dasdf"
      },
      {
        "ITEM": "easdf"
      }
    ]

}
</code>```

I want to randomly display one of the items:

```<code>getQuestion() {
  const sizeOfRandomItems = 4;
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}
</code>```

But whenever I wanted to add a new item in my translation file, I'd also have to manually update sizeOfRandomItems. Is there a way to get the size of the RANDOM array in the translation file?

I alread tried:

```<code>const arraySize = this.$filter('i18n')('RANDOM');
console.log(arraySize.length);
</code>```

But first I get a warning:

```<code>i18n-translate.js:205 Missing key:
</code>```

it returns 6 (which is the number of charachters in the key that holds the array RANDOM)

答:
if you are willing to use some library, you could load the json using Jquery.
Parse it into an array and get the array length. Of cours this solutions will be heavy if you have alot of key, so i suggest you keep the result into a variable somewhere.

var length;
function getQuestion() {
  const sizeOfRandomItems = 4;
  const randomNumber = Math.floor(Math.random() * (length ? length : getJsonLength()));
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}

function getJsonLength() {
  $.getJSON("i18n.json", function(json) {
    var array = JSON.parse(json)
    length = array.length;
  });
}```

Body:
My translation file looks like this:

{
    "RANDOM": [
      {
        "ITEM": "basdf"
      },
      {
        "ITEM": "casdf"
      },
      {
        "ITEM": "dasdf"
      },
      {
        "ITEM": "easdf"
      }
    ]

}

I want to randomly display one of the items:

getQuestion() {
  const sizeOfRandomItems = 4;
  const randomNumber = Math.floor(Math.random() * sizeOfRandomItems);
  return this.$filter('i18n')('RANDOM.' + randomNumber + '.ITEM');
}

But whenever I wanted to add a new item in my translation file, I'd also have to manually update sizeOfRandomItems. Is there a way to get the size of the RANDOM array in the translation file?

I alread tried:

const arraySize = this.$filter('i18n')('RANDOM');
console.log(arraySize.length);

But first I get a warning:

i18n-translate.js:205 Missing key:

it returns 6 (which is the number of charachters in the key that holds the array RANDOM)


问:
Is there a difference between activations functions in tensorflow? tf.nn.tanh vs tf.tanh
I want to setup a neuronal network and I am asking myself if there is a difference between those two functions?

tf.nn.tanh vs tf.tanh

答:
Easy enough to confirm they are the same:</p>

```<code>In [1]: import tensorflow as tf

In [2]: tf.nn.tanh
Out[2]: <function tensorflow.python.ops.math_ops.tanh>

In [3]: tf.tanh
Out[3]: <function tensorflow.python.ops.math_ops.tanh>

In [4]: tf.nn.tanh == tf.tanh
Out[4]: True

In [5]: tf.__version__
Out[5]: '0.11.0rc1'
</code>```

Body:
Easy enough to confirm they are the same:

In [1]: import tensorflow as tf

In [2]: tf.nn.tanh
Out[2]: <function tensorflow.python.ops.math_ops.tanh>

In [3]: tf.tanh
Out[3]: <function tensorflow.python.ops.math_ops.tanh>

In [4]: tf.nn.tanh == tf.tanh
Out[4]: True

In [5]: tf.__version__
Out[5]: '0.11.0rc1'


问:
How to initialize Parse and point to serverURL using Angular2
I am attempting to use a Parse server and am currently running into issues with initializing Parse in javascript and pointing to the correct serverURL. Curious if anyone else has had any luck doing this with Angular2 yet?</p>

答:
A bit late but I've found the trick when the typescript throws a Cannot assign to 'serverURL' because it is a constant or a read-only property

```<code>// Use parse with typescript
import * as Parse from 'parse';
// To set the server URL
let parse = require('parse');
</code>```

Now you have access to parse.serverUrl, which is the same as Parse.serverUrl except that the TS definition will throw a read-only error.

Body:
A bit late but I've found the trick when the typescript throws a Cannot assign to 'serverURL' because it is a constant or a read-only property

// Use parse with typescript
import * as Parse from 'parse';
// To set the server URL
let parse = require('parse');

Now you have access to parse.serverUrl, which is the same as Parse.serverUrl except that the TS definition will throw a read-only error.


问:
Apache Ignite: How can I improve insertion performance?
What additional things can I do beyond using the IDataStreamer and IBinaryObject to decrease insertion time into Apache Ignite.NET? It is possible to get a significant performance increase or is this as good as it will get?

I'm using:

.NET

41 Query Fields: 1 string field and 40 float fields per row

IBinaryObject / WithKeepBinary

IDataStreamer

Default JVM settings

Partitioned Cache

No Persistance

I used this example as a starting point:
https://github.com/apache/ignite/blob/master/modules/platforms/dotnet/examples/Apache.Ignite.Examples/Datagrid/DataStreamerExample.cs

Here's my usage of the IDataStreamer:

```<code>using (var ds = m_ignite.GetDataStreamer<string, IBinaryObject>(CacheName)) {
    foreach (var binaryRow in rows.Select(r => BuildRow(r))) {
        var key = binaryRow.GetField<string>(PrimaryKeyName);
        ds.AddData(key, binaryRow);
    }
}
</code>```

Performance results: (5 nodes all with the same specifications)

```<code>BenchmarkDotNet=v0.10.8, OS=Windows 8.1 (6.3.9600)
Processor=Intel Xeon CPU E5-2698 v4 2.20GHz Intel Xeon CPU E5-2698 v4 2.20GHz, ProcessorCount=4
Frequency=14318180 Hz, Resolution=69.8413 ns, Timer=HPET
  [Host]     : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2053.0
  Job-UZDKMF : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2053.0

RunStrategy=Monitoring  TargetCount=1

NumRows      Mean (ms)      Per Row (ms/row)
10           359.50*        35.95*
100          465.50*        4.66*
1,000        797.80*        0.80*
10,000       4,479.80       0.45
100,000      37,611.60      0.38
500,000      184,640.00     0.37
1,000,000    366,801.40     0.37
2,000,000    732,562.40     0.37
4,000,000    1,458,913.60   0.36

*Measurement is larger because it also measures some lightweight work before inserting the rows
</code>```

Any hints, tips, or documentation is appreciated. Thank you!

答:
Do not call GetField to retrieve key, return it directly from BuildRow (i.e. return KeyValuePair<string, IBinaryObject>)

Parallelise the insertion (and BuildRow calls):

```<code>Parallel.ForEach(rows, r =>
{
    KeyValuePair<string, IBinaryObject> pair = BuildRow(r);
    ds.AddData(pair);
});
</code>```

Run more Ignite nodes on more machines

If rows come from external data source, you can make every Ignite node load only the related part. You can do that by executing the DataStreamer on each row via ICompute.Broadcast and, while iterating over rows, check if the key belongs to current node:

```<code>IAffinity aff = m_ignite.GetAffinity(cacheName);
IClusterNode localNode = m_ignite.GetCluster().GetLocalNode();
Parallel.ForEach(rows, r =>
{
    string key = GetKey(r);
    if (aff.IsPrimary(localNode, key))
    {
        KeyValuePair<string, IBinaryObject> pair = BuildRow(r);
        ds.AddData(pair);
    }
});
</code>```

Body:
What additional things can I do beyond using the IDataStreamer and IBinaryObject to decrease insertion time into Apache Ignite.NET? It is possible to get a significant performance increase or is this as good as it will get?

I'm using:

.NET

41 Query Fields: 1 string field and 40 float fields per row

IBinaryObject / WithKeepBinary

IDataStreamer

Default JVM settings

Partitioned Cache

No Persistance

I used this example as a starting point:
https://github.com/apache/ignite/blob/master/modules/platforms/dotnet/examples/Apache.Ignite.Examples/Datagrid/DataStreamerExample.cs

Here's my usage of the IDataStreamer:

using (var ds = m_ignite.GetDataStreamer<string, IBinaryObject>(CacheName)) {
    foreach (var binaryRow in rows.Select(r => BuildRow(r))) {
        var key = binaryRow.GetField<string>(PrimaryKeyName);
        ds.AddData(key, binaryRow);
    }
}

Performance results: (5 nodes all with the same specifications)

BenchmarkDotNet=v0.10.8, OS=Windows 8.1 (6.3.9600)
Processor=Intel Xeon CPU E5-2698 v4 2.20GHz Intel Xeon CPU E5-2698 v4 2.20GHz, ProcessorCount=4
Frequency=14318180 Hz, Resolution=69.8413 ns, Timer=HPET
  [Host]     : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2053.0
  Job-UZDKMF : Clr 4.0.30319.42000, 64bit RyuJIT-v4.7.2053.0

RunStrategy=Monitoring  TargetCount=1

NumRows      Mean (ms)      Per Row (ms/row)
10           359.50*        35.95*
100          465.50*        4.66*
1,000        797.80*        0.80*
10,000       4,479.80       0.45
100,000      37,611.60      0.38
500,000      184,640.00     0.37
1,000,000    366,801.40     0.37
2,000,000    732,562.40     0.37
4,000,000    1,458,913.60   0.36

*Measurement is larger because it also measures some lightweight work before inserting the rows

Any hints, tips, or documentation is appreciated. Thank you!

Body:
Do not call GetField to retrieve key, return it directly from BuildRow (i.e. return KeyValuePair<string, IBinaryObject>)

Parallelise the insertion (and BuildRow calls):

Parallel.ForEach(rows, r =>
{
    KeyValuePair<string, IBinaryObject> pair = BuildRow(r);
    ds.AddData(pair);
});

Run more Ignite nodes on more machines

If rows come from external data source, you can make every Ignite node load only the related part. You can do that by executing the DataStreamer on each row via ICompute.Broadcast and, while iterating over rows, check if the key belongs to current node:

IAffinity aff = m_ignite.GetAffinity(cacheName);
IClusterNode localNode = m_ignite.GetCluster().GetLocalNode();
Parallel.ForEach(rows, r =>
{
    string key = GetKey(r);
    if (aff.IsPrimary(localNode, key))
    {
        KeyValuePair<string, IBinaryObject> pair = BuildRow(r);
        ds.AddData(pair);
    }
});