问:
Intent Error in Android Studio (workout app)
For my school project, I'm currently doing simple workout app. But I'm stuck on countdown timer because app keeps crashing. First, there are some welcome screens; and then, you proceed to make your own workout (choose exercises, rest and number of rounds). It works fine, and it even work to get all these variables into next class using Intent. Here is button NEXT code:

```<code>    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(CustomWorkout.this, GetReady.class);
            myIntent.putExtra("all_exercises", Exercises); //arraylist of exercises
            myIntent.putExtra("total_rounds", total_rounds); //number of rounds
            myIntent.putExtra("total_rest", total_rest); //rest time
            startActivity(myIntent);
        }
    });
</code>```

As you can see above, I then call GetReady() class which is simple 5 second countdown timer to prepare yourself for first exercise. GetReady looks like this:

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.getready);

    getReady();
}

public void getReady(){
    timer = (TextView) findViewById(R.id.timer);
    cTimer= new CountDownTimer(5000, 1000) {

        public void onTick(long millisUntilFinished) {
            timer.setText("" + millisUntilFinished / 1000);

        }

        public void onFinish() {
            startActivity(new Intent(GetReady.this, Exercises.class));
        }
    }.start();
}
</code>```

And now it comes to error (and crashing of the app). On finish of countdown I call Exercise() class (which is screen with name of current exercise and button done -> on click you start countdown timer again). Code:

```<code>Intent i = getIntent();
    all_exercises = (ArrayList<String>) i.getSerializableExtra("all_exercises"); //getting exercises from Intent set in first class
    rounds=(int)i.getSerializableExtra("total_rounds");
    exercise_name = (TextView) findViewById(R.id.exercise_name);
    exercise_name.setText(all_exercises.get(0));

    final Button done=(Button) findViewById(R.id.done);

    done.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent in = new Intent(Exercises.this, Countdown.class); //starting Countdown
            startActivity(in);
        }
    });
</code>```

GetReady timer countdowns normally and then the crash happens. If I set in first class that button NEXT should call Exercises class instead of GetReady it doesn't crash (but it crashes on Countdown class instead).

Crash log:

```<code>FATAL EXCEPTION: main
   Process: com.msimonic.worldofworkout, PID: 8968
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.msimonic.worldofworkout/com.msimonic.worldofworkout.Exercises}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
   at com.msimonic.worldofworkout.Exercises.onCreate(Exercises.java:39)
   at android.app.Activity.performCreate(Activity.java:6237)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
</code>```

答:
You have to pass on the data in GetReady so you can access them in Exercises. In order to write less code, I put them into a Bundle and simply transfer this Bundle:

In the OnClickListener:

```<code>next.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent myIntent = new Intent(CustomWorkout.this, GetReady.class);
        Bundle b = new Bundle();
        b.putSerializable("all_exercises", Exercises); //arraylist of exercises

        b.putInt("total_rounds", total_rounds); //number of rounds
        b.putInt("total_rest", total_rest); //rest time
        myIntent.putExtra("myData", b);
        startActivity(myIntent);
    }
});
</code>```

In GetReady.java:

```<code>public void getReady(){
    timer = (TextView) findViewById(R.id.timer);
    cTimer= new CountDownTimer(5000, 1000) {

        public void onTick(long millisUntilFinished) {
            timer.setText("" + millisUntilFinished / 1000);

        }

        public void onFinish() {
            Bundle b = GetReady.this.getIntent().getBundleExtra("myData");
            Intent myNextIntent = new Intent(GetReady.this, Exercises.class);
            myNextIntent.putExtra("myDataFromGetReady", b);
            startActivity(myNextIntent);
        }
    }.start();
}
</code>```

In Excercises.java:

```<code>Intent i = getIntent();
Bundle b = i.getBundleExtra("myDataFromGetReady");

// now get the data from the Bundle:
all_exercises = (ArrayList<String>) b.getSerializable("all_exercises");
rounds= b.getInt("total_rounds", -1);

exercise_name = (TextView) findViewById(R.id.exercise_name);
exercise_name.setText(all_exercises.get(0));

final Button done=(Button) findViewById(R.id.done);

// ... and so on ...
</code>```

Body:
For my school project, I'm currently doing simple workout app. But I'm stuck on countdown timer because app keeps crashing. First, there are some welcome screens; and then, you proceed to make your own workout (choose exercises, rest and number of rounds). It works fine, and it even work to get all these variables into next class using Intent. Here is button NEXT code:

    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(CustomWorkout.this, GetReady.class);
            myIntent.putExtra("all_exercises", Exercises); //arraylist of exercises
            myIntent.putExtra("total_rounds", total_rounds); //number of rounds
            myIntent.putExtra("total_rest", total_rest); //rest time
            startActivity(myIntent);
        }
    });

As you can see above, I then call GetReady() class which is simple 5 second countdown timer to prepare yourself for first exercise. GetReady looks like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.getready);

    getReady();
}

public void getReady(){
    timer = (TextView) findViewById(R.id.timer);
    cTimer= new CountDownTimer(5000, 1000) {

        public void onTick(long millisUntilFinished) {
            timer.setText("" + millisUntilFinished / 1000);

        }

        public void onFinish() {
            startActivity(new Intent(GetReady.this, Exercises.class));
        }
    }.start();
}

And now it comes to error (and crashing of the app). On finish of countdown I call Exercise() class (which is screen with name of current exercise and button done -> on click you start countdown timer again). Code:

Intent i = getIntent();
    all_exercises = (ArrayList<String>) i.getSerializableExtra("all_exercises"); //getting exercises from Intent set in first class
    rounds=(int)i.getSerializableExtra("total_rounds");
    exercise_name = (TextView) findViewById(R.id.exercise_name);
    exercise_name.setText(all_exercises.get(0));

    final Button done=(Button) findViewById(R.id.done);

    done.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent in = new Intent(Exercises.this, Countdown.class); //starting Countdown
            startActivity(in);
        }
    });

GetReady timer countdowns normally and then the crash happens. If I set in first class that button NEXT should call Exercises class instead of GetReady it doesn't crash (but it crashes on Countdown class instead).

Crash log:

FATAL EXCEPTION: main
   Process: com.msimonic.worldofworkout, PID: 8968
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.msimonic.worldofworkout/com.msimonic.worldofworkout.Exercises}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
   at com.msimonic.worldofworkout.Exercises.onCreate(Exercises.java:39)
   at android.app.Activity.performCreate(Activity.java:6237)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)

Body:
You have to pass on the data in GetReady so you can access them in Exercises. In order to write less code, I put them into a Bundle and simply transfer this Bundle:

In the OnClickListener:

next.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent myIntent = new Intent(CustomWorkout.this, GetReady.class);
        Bundle b = new Bundle();
        b.putSerializable("all_exercises", Exercises); //arraylist of exercises

        b.putInt("total_rounds", total_rounds); //number of rounds
        b.putInt("total_rest", total_rest); //rest time
        myIntent.putExtra("myData", b);
        startActivity(myIntent);
    }
});

In GetReady.java:

public void getReady(){
    timer = (TextView) findViewById(R.id.timer);
    cTimer= new CountDownTimer(5000, 1000) {

        public void onTick(long millisUntilFinished) {
            timer.setText("" + millisUntilFinished / 1000);

        }

        public void onFinish() {
            Bundle b = GetReady.this.getIntent().getBundleExtra("myData");
            Intent myNextIntent = new Intent(GetReady.this, Exercises.class);
            myNextIntent.putExtra("myDataFromGetReady", b);
            startActivity(myNextIntent);
        }
    }.start();
}

In Excercises.java:

Intent i = getIntent();
Bundle b = i.getBundleExtra("myDataFromGetReady");

// now get the data from the Bundle:
all_exercises = (ArrayList<String>) b.getSerializable("all_exercises");
rounds= b.getInt("total_rounds", -1);

exercise_name = (TextView) findViewById(R.id.exercise_name);
exercise_name.setText(all_exercises.get(0));

final Button done=(Button) findViewById(R.id.done);

// ... and so on ...


来源: stackexchange

问:
Babel fails to compile ES6 object cloning with spread operator
I use grunt-babel to compile my ES6 code. But it returns Warning: dist/app.js: Unexpected token (321:9) Use --force to continue. when I try to use {...obj} to copy and extend object. Following code is working perfect in console of Chrome v61 but Babel doesn't like it. What is the problem?

```<code>let a = { a: 12 };
let b = { ...a, b: 15 };
</code>```

I am using env preset. (babel-core v.6.26.0 and babel-preset-env v.1.6.1)

答:
The spread property for objects is not part of ES6. Currently, as of Dec 2017, it is part of the stage 3 proposal for ECMAScript. You can have a look at the proposal here.

You need a babel preset that includes features not yet officially in the language. The babel-preset-env does not include those features.

To solve your problem, you could use something like babel-preset-stage-3 and add "stage-3" to the list of presets in your .babelrc.

Side note:

An alternative to the spread syntax for objects in ES6 is to use Object.assign

```<code>let b = Object.assign({}, a, { b: 15 });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use grunt-babel to compile my ES6 code. But it returns Warning: dist/app.js: Unexpected token (321:9) Use --force to continue. when I try to use {...obj} to copy and extend object. Following code is working perfect in console of Chrome v61 but Babel doesn't like it. What is the problem?

let a = { a: 12 };
let b = { ...a, b: 15 };

I am using env preset. (babel-core v.6.26.0 and babel-preset-env v.1.6.1)

Body:
The spread property for objects is not part of ES6. Currently, as of Dec 2017, it is part of the stage 3 proposal for ECMAScript. You can have a look at the proposal here.

You need a babel preset that includes features not yet officially in the language. The babel-preset-env does not include those features.

To solve your problem, you could use something like babel-preset-stage-3 and add "stage-3" to the list of presets in your .babelrc.

Side note:

An alternative to the spread syntax for objects in ES6 is to use Object.assign

let b = Object.assign({}, a, { b: 15 });


问:
Tabbed Activity Android
I'm developing an android app where I have 3 tabs: order status, order details, order Info.
my problem is that I get an error message when I try to add Fragment to this app.
here is my code:

orderTabbedFraagment.java

```<code>package com.example.kamran.bluewhite;

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class OrderInfoTabbed extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_order_info_tabbed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_order_info_tabbed, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    orderInfoFragment a = new orderInfoFragment();
                    return a;
            }
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Order Details";
                case 1:
                    return "Order Info";
                case 2:
                    return "Order Status";

            }
            return null;
        }
    }
}
</code>```

orderInfoFragment .java

```<code>package com.example.kamran.bluewhite;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

/**
 * Created by rahafo on 12/5/2017.
 */

public class orderInfoFragment extends Fragment{
    double sum=0;
    DatabaseReference mDatabase;
    ListView shoppingList;
    ArrayList<Shopping_cart> Shopping_cart;
    DatabaseReference Shopping_cartRef;
    DatabaseReference ShoppingcartProduct;
    ProgressDialog mProgressDialog;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_order_info,container,false);

        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setMessage("Loading Products..");
        mProgressDialog.show();
        Intent i = getActivity().getIntent();

        String uid = i.getExtras().getString("name","");
        Shopping_cart = new ArrayList<Shopping_cart>();
        LinearLayout productList = (LinearLayout) view.findViewById(R.id.shoppingList);

        mDatabase = FirebaseDatabase.getInstance().getReference();

        Shopping_cartRef = mDatabase.child("Order");
        ShoppingcartProduct = Shopping_cartRef.child(uid).child("products");

        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {

                    Shopping_cart product = ds.getValue(Shopping_cart.class);

                    Shopping_cart.add(product);
                    adapterShopping itemsAdapter = new adapterShopping(getActivity(), Shopping_cart);
                    shoppingList = (ListView) view.findViewById(R.id.listViewshopping);
                    shoppingList.setAdapter(itemsAdapter);

                }

                mProgressDialog.dismiss();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        ShoppingcartProduct.addListenerForSingleValueEvent(eventListener);

        return view;
    }
}
</code>```

The error I got is: Error:(134, 28) error: incompatible types: orderInfoFragment cannot be converted to Fragment
but orderInfoFragment  is extending Fragment so I don't know what is the problem!
Did I do something wrong?

答:
You are mixing imports which is quite common issue. Either you need to stick to support library provided components like Fragments and stuff (so you should have import android.support.... entries) - this is what you have in OrderInfoTabbed class code. Or use plaftorm provided Fragments and stuff - as you did in orderInfoFragment class. But while you can mix them, and technically it is possible to use both in your code on purpose, these are NOT equivalent and as you can see cannot be cast from one to the other.

As solution, remove import android.app.... entries and re-add it (see Android Studio can help you) bit this time pay attention to which one you choose as AS will show you list of options.

If unsure which one you want stick to support lib's one which is what I believe you wanted anyway.

Title: Tabbed Activity Android

Body:
I'm developing an android app where I have 3 tabs: order status, order details, order Info.
my problem is that I get an error message when I try to add Fragment to this app.
here is my code:

orderTabbedFraagment.java

package com.example.kamran.bluewhite;

import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class OrderInfoTabbed extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_order_info_tabbed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_order_info_tabbed, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    orderInfoFragment a = new orderInfoFragment();
                    return a;
            }
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Order Details";
                case 1:
                    return "Order Info";
                case 2:
                    return "Order Status";

            }
            return null;
        }
    }
}

orderInfoFragment .java

package com.example.kamran.bluewhite;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

/**
 * Created by rahafo on 12/5/2017.
 */

public class orderInfoFragment extends Fragment{
    double sum=0;
    DatabaseReference mDatabase;
    ListView shoppingList;
    ArrayList<Shopping_cart> Shopping_cart;
    DatabaseReference Shopping_cartRef;
    DatabaseReference ShoppingcartProduct;
    ProgressDialog mProgressDialog;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_order_info,container,false);

        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setMessage("Loading Products..");
        mProgressDialog.show();
        Intent i = getActivity().getIntent();

        String uid = i.getExtras().getString("name","");
        Shopping_cart = new ArrayList<Shopping_cart>();
        LinearLayout productList = (LinearLayout) view.findViewById(R.id.shoppingList);

        mDatabase = FirebaseDatabase.getInstance().getReference();

        Shopping_cartRef = mDatabase.child("Order");
        ShoppingcartProduct = Shopping_cartRef.child(uid).child("products");

        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {

                    Shopping_cart product = ds.getValue(Shopping_cart.class);

                    Shopping_cart.add(product);
                    adapterShopping itemsAdapter = new adapterShopping(getActivity(), Shopping_cart);
                    shoppingList = (ListView) view.findViewById(R.id.listViewshopping);
                    shoppingList.setAdapter(itemsAdapter);

                }

                mProgressDialog.dismiss();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        ShoppingcartProduct.addListenerForSingleValueEvent(eventListener);

        return view;
    }
}

The error I got is: Error:(134, 28) error: incompatible types: orderInfoFragment cannot be converted to Fragment
but orderInfoFragment  is extending Fragment so I don't know what is the problem!
Did I do something wrong?


问:
RecyclerView strange behavior after notifyItemRangeChanged

I am facing some problems with notifyItemRemoved and notifyItemRangeChanged.

I have a RecyclerView which is populated by cards. Every card has its own button. I've implemented on RecyclerView's method onBindViewHolder an OnClickListener for the button. When pressed, I want the card to delete itself. I have the following code:

```<code> holder.deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                mDataset.remove(holder.getAdapterPosition());
                notifyItemRemoved(holder.getAdapterPosition());
                notifyItemRangeChanged(holder.getAdapterPosition(), mDataset.size());
        }
    });
</code>```

There is a strange behavior with deleting. The card I want to delete disappears for a short time then fastly reappears and if I try to press the delete button again, it gives an ArrayIndexOutOfBoundsException error.

Did anyone experience anything like this? Any help is greatly appreciated!

答:
Remove this </p>

```<code>notifyItemRangeChanged(holder.getAdapterPosition(), mDataset.size());
</code>```

Body:
I am facing some problems with notifyItemRemoved and notifyItemRangeChanged.

I have a RecyclerView which is populated by cards. Every card has its own button. I've implemented on RecyclerView's method onBindViewHolder an OnClickListener for the button. When pressed, I want the card to delete itself. I have the following code:

 holder.deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                mDataset.remove(holder.getAdapterPosition());
                notifyItemRemoved(holder.getAdapterPosition());
                notifyItemRangeChanged(holder.getAdapterPosition(), mDataset.size());
        }
    });

There is a strange behavior with deleting. The card I want to delete disappears for a short time then fastly reappears and if I try to press the delete button again, it gives an ArrayIndexOutOfBoundsException error.

Did anyone experience anything like this? Any help is greatly appreciated!

Body:
Remove this

notifyItemRangeChanged(holder.getAdapterPosition(), mDataset.size());


问:
visual c++ cross platform android: Include prebuilt shared library
I'm using the Visual C++ Cross Platform Tools for Android as described here: https://msdn.microsoft.com/en-us/library/dn707591.aspx

Everything works fine so far (I can build and run on my phone the templates under File -> New Project -> Cross Platform -> Android). However, I can't find out how to link my app to a prebuilt shared library in the form of an *.so file.

So far, I tried the following steps:

Step 1

To test the ability of Visual Studio to link to a prebuilt shared library, I created a small shared library as follows:

SharedLibrary.cpp:

```<code>#include "SharedLibrary.h"

const char * SharedLibrary::GetString()
{
    return "Hello from Shared Library";
}

void SharedLibrary()
{
}

SharedLibrary::SharedLibrary()
{
}

SharedLibrary::~SharedLibrary()
{
}
</code>```

SharedLibrary.h:

```<code>#pragma once

class SharedLibrary
{
public:
    const char * GetString();
    SharedLibrary();
    ~SharedLibrary();
};
</code>```

Android.mk:

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := SharedLibrary
LOCAL_SRC_FILES := SharedLibrary.cpp
include $(BUILD_SHARED_LIBRARY)
</code>```

Step 2

I then compiled this shared library using the command ndk-build, which gives me a file libSharedLibrary.so

Step 3

I then created a Visual Studio project: File -> New -> Project -> Cross Platform -> Android -> Basic Application (Android, Ant). This project compiles and runs fine.

Step 4

The next step is where I am stuck: I need to somehow link the libSharedLibrary.so file to the Visual Studio project. I couldn't find anything in the project options of the Visual Studio project which allows me to do this.

So, here is my question:
How do I have to setup my Visual C++ cross platform Android project in order to link a shared object (*.so) to it?

This is my first stackoverflow post, so feel free to correct me, if I did anything wrong in my post.

答:
After investing a stupidly large amount of time, I found the solution (thanks Microsoft for not documenting this functionality anywhere...):

Open the Visual Studio solution

Go to the Android Packaging Project

Right-click on the project, then choose 'Add' -> 'New Folder'

Name the new folder 'libs' (this naming is mandatory!)

Create a subfolder for each targeted processor architecture (for example 'armeabi-v7a')

Drag and drop the respective *.so file into these subfolders

When compiling the project, the 'libs' folder and its content get copied into the compiled *.apk file.

Hope this helped out somebody!

ContentLicense: CC BY-SA 4.0

Body:
I'm using the Visual C++ Cross Platform Tools for Android as described here: https://msdn.microsoft.com/en-us/library/dn707591.aspx

Everything works fine so far (I can build and run on my phone the templates under File -> New Project -> Cross Platform -> Android). However, I can't find out how to link my app to a prebuilt shared library in the form of an *.so file.

So far, I tried the following steps:

Step 1

To test the ability of Visual Studio to link to a prebuilt shared library, I created a small shared library as follows:

SharedLibrary.cpp:

#include "SharedLibrary.h"

const char * SharedLibrary::GetString()
{
    return "Hello from Shared Library";
}

void SharedLibrary()
{
}

SharedLibrary::SharedLibrary()
{
}

SharedLibrary::~SharedLibrary()
{
}

SharedLibrary.h:

#pragma once

class SharedLibrary
{
public:
    const char * GetString();
    SharedLibrary();
    ~SharedLibrary();
};

Android.mk:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := SharedLibrary
LOCAL_SRC_FILES := SharedLibrary.cpp
include $(BUILD_SHARED_LIBRARY)

Step 2

I then compiled this shared library using the command ndk-build, which gives me a file libSharedLibrary.so

Step 3

I then created a Visual Studio project: File -> New -> Project -> Cross Platform -> Android -> Basic Application (Android, Ant). This project compiles and runs fine.

Step 4

The next step is where I am stuck: I need to somehow link the libSharedLibrary.so file to the Visual Studio project. I couldn't find anything in the project options of the Visual Studio project which allows me to do this.

So, here is my question:
How do I have to setup my Visual C++ cross platform Android project in order to link a shared object (*.so) to it?

This is my first stackoverflow post, so feel free to correct me, if I did anything wrong in my post.


问:
Is OkHttp compatible with socket.io?
I'm working on a project where we're trying to send data from an Android app through OKHttp websockets, and we're trying to receive that data on a nodejs server that's using socket.io. We can't seem to figure out how to receive the messages on the node.js side and I'm wondering if this structure is possible to do.</p>

答: According to this answer from OkHttp maintainer socket.io leverages websockets but in a non-standard way hence they don't support it.</p>

Title: Is OkHttp compatible with socket.io?


问:
Issue with TFS 2017 Data Warehouse
We have migrated our Team Foundation Server from 2013 to 2017 recently. In previous version there was no Data Warehouse or reporting configured.

After moving to TFS 2017, we configured Data Warehouse and Reporting services which went fine without any issue.

Now issue we are facing is, in reports we are not able to see any Build related data, only data we see is from old XAML build and nothing from new TFS 2017 build.

when I looked into DimBuild table of TFS Warehouse, it has only old data no new rows.

we tried to re-create warehouse and re-start TFS Warehouse services from Warehouse Administration link, but nothing is helping.

Anyone has any idea?

答:
You're not seeing it because it's not supposed to be there.

The data warehouse does not contain information for non-XAML builds, nor does it contain any release information.

Title: Issue with TFS 2017 Data Warehouse


问:
AspNetCore v2.0 — Render razor-views in another project for integration tests
I want to write integration test for my web-application. I used Microsoft.AspNetCore.TestHost.TestServer to communicate with controllers via url. But views cannot be rendered. In response I get error-message:

One or more compilation references are missing. Ensure that your
  project is referencing 'Microsoft.NET.Sdk.Web' and the
  'PreserveCompilationContext' property is not set to false.

In my .csproj I tried to change project-sdk on Microsoft.NET.Sdk.Web, I tried to add <PreserveCompilationContext>true</PreserveCompilationContext>. Also I tried to rewrite the code as described in Microsoft-docs (here in here).
But I still have the same error-message.

Steps to Reproduce:

Create test-project "WebApplication1.IntegrationTests".

Add reference on WebApplication-project.

Add nuget-package "Microsoft.AspNetCore.TestHost"

Send get-request to "/Home/Index" via TestServer.

Read response with error-message.

```<code>using WebApplication1;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication1.IntegrationTests
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Path to contentRoot folder.
            var contentRootPath = @"..\..\..\..\WebApplication1";

            var builder = new WebHostBuilder()
                .UseStartup<Startup>()
                .UseEnvironment(EnvironmentName.Development)
                .UseContentRoot(contentRootPath);

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var response = client.GetAsync("/Home/Index").Result;
            var responseString = response.Content.ReadAsStringAsync().Result;
        }
    }
}
</code>```

Rendered responseString in browser:

答:
In order to test an ASP.NET Core 2.0 application recently, I have had to update the csproj file of the integration test project with the <PreserveCompilationContext>true</PreserveCompilationContext> property and with an additional target to copy the .deps.json file.

```<code><!--
  Work around https://github.com/NuGet/Home/issues/4412. MVC uses DependencyContext.Load() which looks next to a .dll
  for a .deps.json. Information isn't available elsewhere. Need the .deps.json file for all web site applications.
-->
<Target Name="CopyDepsFiles" AfterTargets="Build" Condition="'$(TargetFramework)'!=''">
  <ItemGroup>
    <DepsFilePaths Include="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />
  </ItemGroup>
  <Copy SourceFiles="%(DepsFilePaths.FullPath)" DestinationFolder="$(OutputPath)" Condition="Exists('%(DepsFilePaths.FullPath)')" />
</Target>
</code>```

You can check the source code of the full integration test project in github. There might be additional differences, like I have used a full path with the .UseContentRoot(path) method.

Body:
I want to write integration test for my web-application. I used Microsoft.AspNetCore.TestHost.TestServer to communicate with controllers via url. But views cannot be rendered. In response I get error-message:

One or more compilation references are missing. Ensure that your
  project is referencing 'Microsoft.NET.Sdk.Web' and the
  'PreserveCompilationContext' property is not set to false.

In my .csproj I tried to change project-sdk on Microsoft.NET.Sdk.Web, I tried to add <PreserveCompilationContext>true</PreserveCompilationContext>. Also I tried to rewrite the code as described in Microsoft-docs (here in here).
But I still have the same error-message.

Steps to Reproduce:

Create test-project "WebApplication1.IntegrationTests".

Add reference on WebApplication-project.

Add nuget-package "Microsoft.AspNetCore.TestHost"

Send get-request to "/Home/Index" via TestServer.

Read response with error-message.

using WebApplication1;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication1.IntegrationTests
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Path to contentRoot folder.
            var contentRootPath = @"..\..\..\..\WebApplication1";

            var builder = new WebHostBuilder()
                .UseStartup<Startup>()
                .UseEnvironment(EnvironmentName.Development)
                .UseContentRoot(contentRootPath);

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var response = client.GetAsync("/Home/Index").Result;
            var responseString = response.Content.ReadAsStringAsync().Result;
        }
    }
}

Rendered responseString in browser:

Body:
In order to test an ASP.NET Core 2.0 application recently, I have had to update the csproj file of the integration test project with the <PreserveCompilationContext>true</PreserveCompilationContext> property and with an additional target to copy the .deps.json file.

<!--
  Work around https://github.com/NuGet/Home/issues/4412. MVC uses DependencyContext.Load() which looks next to a .dll
  for a .deps.json. Information isn't available elsewhere. Need the .deps.json file for all web site applications.
-->
<Target Name="CopyDepsFiles" AfterTargets="Build" Condition="'$(TargetFramework)'!=''">
  <ItemGroup>
    <DepsFilePaths Include="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />
  </ItemGroup>
  <Copy SourceFiles="%(DepsFilePaths.FullPath)" DestinationFolder="$(OutputPath)" Condition="Exists('%(DepsFilePaths.FullPath)')" />
</Target>

You can check the source code of the full integration test project in github. There might be additional differences, like I have used a full path with the .UseContentRoot(path) method.


问:
How to generate Schema.json of swapi-graphql for Android project?
I am working on Graphql android project, my (Facebook, through the GraphQL GitHub organization, provides a sample schema and local database of Star Wars objects.)Swapi local host is up and running for request. I am also using Apollo Android. In my Android project I need Schema.json file for the variant debug. But I don't know how to generate Schema.json file.

1. So how to generate Schema.json file?
2. Do I need multiple Schema json file for each data type planet, person, vehicle etc in single android project or one schema file contains all the information?

答:
How to generate Schema.json file?
    use apollo-codegen
        `apollo-codegen download-schema http://localhost:8080/graphql --output schema.json.
Give output file schema.JSON.
Do I Need Multiple Schema json file? No, one schema for an API.

`


问:
Not able to install codedeploy-agent.msi using Cloudformation
I am trying to deploy codedeploy-agent.msi to an ec2 instance (win 2012).  Its behind a private subnet with NO NAT gateway, but with S3 endpoint, i tested this powershell.exe -Command Read-S3Object -BucketName aws-codedeploy-us-west-2 -Key latest/codedeploy-agent.msi -File codedeploy-agent.msi is working. agent is being downloaded through powershell from the ec2 instance.

However, with below cloudfromation script the instance gets created without the agent installed.  There is no c:\cfn folder and cfn-init.log files are missing.  What could be the issue???

```<code>"WorkerInstance": {
            "Type": "AWS::EC2::Instance",
            "Metadata": {
                "AWS::CloudFormation::Init": {
                    "config": {
                        "commands": {
                            "00-download-host-agent": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "powershell.exe -Command \"Read-S3Object ",
                                            "-BucketName aws-codedeploy-us-west-2 ",
                                            "-Key latest/codedeploy-agent.msi ",
                                            "-File codedeploy-agent.msi\""
                                        ]
                                    ]
                                },
                                "cwd": "C:/cfn",
                                "waitAfterCompletion" : 0
                            },
                            "01-install-host-agent": {
                                "command": "C:\\cfn\\codedeploy-agent.msi /quiet /l C:\\cfn\\host-agent-install-log.txt",
                                "ignoreErrors": "true",
                                "waitAfterCompletion" : 0
                            },
                            "02-signal-ready": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "\"C:\\Program Files\\Amazon\\cfn-bootstrap\\cfn-signal\"",
                                            " -e 0 \"",
                                            "\""
                                        ]
                                    ]
                                }
                            }
                        },
                        "services": {
                            "windows": {
                                "codedeploy-agent": {
                                    "enabled": "true",
                                    "ensureRunning": "true",
                                    "commands": [
                                        "01-install-host-agent"
                                    ]
                                }
                            }
                        }
                    }
                }
            },
            "Properties": {
                "DisableApiTermination": "false",
                "InstanceInitiatedShutdownBehavior": "stop",
                "IamInstanceProfile": {
                            "Ref": "IAMRole"
                        },
                "ImageId": "ami-c55089bd",
                "InstanceType": "t2.medium",
                "KeyName": "mykey",
                "Monitoring": "true",
                "Tags": [{
                        "Key": "CodeDeployGroup",
                        "Value": {
                            "Fn::Join": ["-", ["app", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "CodeDeployGroup"
                                ]]
                        }
                    }, {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": ["-", ["App", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "Worker"
                                ]]
                        }
                    }
                ],
                        "NetworkInterfaces": [{
                        "DeleteOnTermination": "true",
                        "Description": "Primary network interface",
                        "DeviceIndex": 0,
                        "SubnetId": "subnet-70234568",
                        "GroupSet": ["sg-8affd7", "sg-fdffsfsd4"]
                    }
                ]
            }
        }
</code>```

答:
The command looks fine. You can try specifying an execution policy for the powershell command. This CFN templates works for me:</p>

```<code>        "WorkerInstance" : {
            "Type" : "AWS::EC2::Instance",
            "Metadata" : {
                "AWS::CloudFormation::Init" : {
                    "config" : {
                        "commands" : {
                            "00-download-host-agent" : {
                                "command" : {"Fn::Join" : [ "", [
                                    "powershell.exe -executionpolicy remotesigned -Command \"Read-S3Object ",
                                    "-BucketName aws-codedeploy-us-west-2 ",
                                    "-Key latest/codedeploy-agent.msi ",
                                    "-File codedeploy-agent.msi\""
                                ]]},
                                "cwd" : "C:/cfn",
                                "waitAfterCompletion" : 0
                            },
                            "01-install-host-agent" : {
                                "command" : "C:\\cfn\\codedeploy-agent.msi /quiet /l C:\\cfn\\host-agent-install-log.txt",
                                "ignoreErrors" : "true",
                                "waitAfterCompletion" : 0
                            },
                            "02-signal-ready" : {
                                "command" : {
                                    "Fn::Join" : [ "", [
                                        "\"C:\\Program Files\\Amazon\\cfn-bootstrap\\cfn-signal\"",
                                        " -e 0 \"",
                                        { "Ref" : "WaitHandle" },
                                        "\""
                                    ]]
                                },
                                "waitAfterCompletion" : 0
                            }
                        },
                        "services" : {
                            "windows" : {
                                "codedeploy-agent" : {
                                    "enabled" : "true",
                                    "ensureRunning" : "true",
                                    "commands" : [ "01-install-host-agent" ]
                                }
                            }
                        }
                    }
                }
            },
</code>```

Body:
I am trying to deploy codedeploy-agent.msi to an ec2 instance (win 2012).  Its behind a private subnet with NO NAT gateway, but with S3 endpoint, i tested this powershell.exe -Command Read-S3Object -BucketName aws-codedeploy-us-west-2 -Key latest/codedeploy-agent.msi -File codedeploy-agent.msi is working. agent is being downloaded through powershell from the ec2 instance.

However, with below cloudfromation script the instance gets created without the agent installed.  There is no c:\cfn folder and cfn-init.log files are missing.  What could be the issue???

"WorkerInstance": {
            "Type": "AWS::EC2::Instance",
            "Metadata": {
                "AWS::CloudFormation::Init": {
                    "config": {
                        "commands": {
                            "00-download-host-agent": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "powershell.exe -Command \"Read-S3Object ",
                                            "-BucketName aws-codedeploy-us-west-2 ",
                                            "-Key latest/codedeploy-agent.msi ",
                                            "-File codedeploy-agent.msi\""
                                        ]
                                    ]
                                },
                                "cwd": "C:/cfn",
                                "waitAfterCompletion" : 0
                            },
                            "01-install-host-agent": {
                                "command": "C:\\cfn\\codedeploy-agent.msi /quiet /l C:\\cfn\\host-agent-install-log.txt",
                                "ignoreErrors": "true",
                                "waitAfterCompletion" : 0
                            },
                            "02-signal-ready": {
                                "command": {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "\"C:\\Program Files\\Amazon\\cfn-bootstrap\\cfn-signal\"",
                                            " -e 0 \"",
                                            "\""
                                        ]
                                    ]
                                }
                            }
                        },
                        "services": {
                            "windows": {
                                "codedeploy-agent": {
                                    "enabled": "true",
                                    "ensureRunning": "true",
                                    "commands": [
                                        "01-install-host-agent"
                                    ]
                                }
                            }
                        }
                    }
                }
            },
            "Properties": {
                "DisableApiTermination": "false",
                "InstanceInitiatedShutdownBehavior": "stop",
                "IamInstanceProfile": {
                            "Ref": "IAMRole"
                        },
                "ImageId": "ami-c55089bd",
                "InstanceType": "t2.medium",
                "KeyName": "mykey",
                "Monitoring": "true",
                "Tags": [{
                        "Key": "CodeDeployGroup",
                        "Value": {
                            "Fn::Join": ["-", ["app", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "CodeDeployGroup"
                                ]]
                        }
                    }, {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": ["-", ["App", {
                                        "Ref": "EnvType"
                                    }, {
                                        "Ref": "EnvVersion"
                                    }, "Worker"
                                ]]
                        }
                    }
                ],
                        "NetworkInterfaces": [{
                        "DeleteOnTermination": "true",
                        "Description": "Primary network interface",
                        "DeviceIndex": 0,
                        "SubnetId": "subnet-70234568",
                        "GroupSet": ["sg-8affd7", "sg-fdffsfsd4"]
                    }
                ]
            }
        }

Body:
The command looks fine. You can try specifying an execution policy for the powershell command. This CFN templates works for me:

        "WorkerInstance" : {
            "Type" : "AWS::EC2::Instance",
            "Metadata" : {
                "AWS::CloudFormation::Init" : {
                    "config" : {
                        "commands" : {
                            "00-download-host-agent" : {
                                "command" : {"Fn::Join" : [ "", [
                                    "powershell.exe -executionpolicy remotesigned -Command \"Read-S3Object ",
                                    "-BucketName aws-codedeploy-us-west-2 ",
                                    "-Key latest/codedeploy-agent.msi ",
                                    "-File codedeploy-agent.msi\""
                                ]]},
                                "cwd" : "C:/cfn",
                                "waitAfterCompletion" : 0
                            },
                            "01-install-host-agent" : {
                                "command" : "C:\\cfn\\codedeploy-agent.msi /quiet /l C:\\cfn\\host-agent-install-log.txt",
                                "ignoreErrors" : "true",
                                "waitAfterCompletion" : 0
                            },
                            "02-signal-ready" : {
                                "command" : {
                                    "Fn::Join" : [ "", [
                                        "\"C:\\Program Files\\Amazon\\cfn-bootstrap\\cfn-signal\"",
                                        " -e 0 \"",
                                        { "Ref" : "WaitHandle" },
                                        "\""
                                    ]]
                                },
                                "waitAfterCompletion" : 0
                            }
                        },
                        "services" : {
                            "windows" : {
                                "codedeploy-agent" : {
                                    "enabled" : "true",
                                    "ensureRunning" : "true",
                                    "commands" : [ "01-install-host-agent" ]
                                }
                            }
                        }
                    }
                }
            },


问:
Delete Duplicates VBA
I am trying to erase duplicate rows starting from bottom, but it isnt working. It keeps two copies but deletes other duplicate items.

```<code>With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    wb_DST.Sheets(sWs_DST).Range(("A13:A" & lncheckduplicatescolumn - 2 & ":" & "AW13:AW" & lncheckduplicatescolumn - 2)).Sort key1:=wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2), order1:=xlDescending, Header:=xlNo

    Dim row As Range
    Dim rng As Range
    Dim cell As Range
    Dim i As Integer
    Set rng = wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2)
    For Each cell In rng
        If cell.Value = cell.Offset(-1, 0).Value Then
            .cell.Offset(-1, 0).EntireRow.Delete
        End If
    Next
End with
</code>```

If Excel shows

```<code>Column A       Column B
A                 1
A                 2
A                 3
</code>```

I want the code to retain the last row, and delete the ones above it.

The result should be

```<code>Column A            Column B
A                    3
</code>```

Thanks,

答:
```<code>Dim x as integer
Dim y as string
Dim J as integer
Dim I as integer

x = activesheet.range("A" & Activesheet.range("A1").endxl.down).count 'This will count the total number of rows.

for i = x to 2 'this should count backwards from bottom to top, since you have headers, stop at row 2
 y = Activesheet.range("A" & i).value 'places value in a variable
      For j = x - i - 1 to 1 'this is another loop, but it should start above the whatever the cell that Y got its value
        if activesheet.range("a" & j).value = y then 'comparison
            'do what you need to delete the row
        end if

Next
Next
</code>```

I think this will go start at the bottom, put that first value in a variable, and then will go through the rest of the list check the values to see if is compatible. The second for loop might need to be adjusted.

Title: Delete Duplicates VBA

Body:
I am trying to erase duplicate rows starting from bottom, but it isnt working. It keeps two copies but deletes other duplicate items.

With wb_DST.Sheets(sWs_DST)
    lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
    wb_DST.Sheets(sWs_DST).Range(("A13:A" & lncheckduplicatescolumn - 2 & ":" & "AW13:AW" & lncheckduplicatescolumn - 2)).Sort key1:=wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2), order1:=xlDescending, Header:=xlNo

    Dim row As Range
    Dim rng As Range
    Dim cell As Range
    Dim i As Integer
    Set rng = wb_DST.Sheets(sWs_DST).Range("A13:A" & lncheckduplicatescolumn - 2)
    For Each cell In rng
        If cell.Value = cell.Offset(-1, 0).Value Then
            .cell.Offset(-1, 0).EntireRow.Delete
        End If
    Next
End with

If Excel shows

Column A       Column B
A                 1
A                 2
A                 3

I want the code to retain the last row, and delete the ones above it.

The result should be

Column A            Column B
A                    3

Thanks,

Body:
Dim x as integer
Dim y as string
Dim J as integer
Dim I as integer

x = activesheet.range("A" & Activesheet.range("A1").endxl.down).count 'This will count the total number of rows.

for i = x to 2 'this should count backwards from bottom to top, since you have headers, stop at row 2
 y = Activesheet.range("A" & i).value 'places value in a variable
      For j = x - i - 1 to 1 'this is another loop, but it should start above the whatever the cell that Y got its value
        if activesheet.range("a" & j).value = y then 'comparison
            'do what you need to delete the row
        end if

Next
Next

I think this will go start at the bottom, put that first value in a variable, and then will go through the rest of the list check the values to see if is compatible. The second for loop might need to be adjusted.


问:
Accessing Windows API Constants and Structs for P/Invoke
Quick question: How can I access the BN_CLICKED constant and other constants defined for the Win32 API from .NET? Are they defined in some library? Do I have to define them myself? If so, where can I find these values? And are the values version-specific between versions of Windows?</p>

答:
The MagNumDB website (by SO user Simon Mourier) is an easy way to look up constants:

http://www.magnumdb.com/search?q=BN_CLICKED

ContentLicense: CC BY-SA 2.5


答:
not a pretty answer - but from what it looks like, you should be ending up with the last and first occurrence of the duplicate:

```<code> Column A    Column B
 A           1
 A           3
</code>```

To patch your answer (there are more elegant ways), you could find the last row again after the loop is finished and check for one last duplicate:

```<code> For Each cell In rng
    If cell.Value = cell.Offset(-1, 0).Value Then
        .cell.Offset(-1, 0).EntireRow.Delete
    End If
 Next
</code>```

redefine your last row

```<code> lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
</code>```

and check for one more duplicate

```<code> If Range("A" & lncheckduplicatescolumn).Value = Range("A" & lncheckduplicatescolumn).Offset(-1, 0).Value Then
    .cell.Offset(-1, 0).EntireRow.Delete
 End If
</code>```

Title: Delete Duplicates VBA

Body:
not a pretty answer - but from what it looks like, you should be ending up with the last and first occurrence of the duplicate:

 Column A    Column B
 A           1
 A           3

To patch your answer (there are more elegant ways), you could find the last row again after the loop is finished and check for one last duplicate:

 For Each cell In rng
    If cell.Value = cell.Offset(-1, 0).Value Then
        .cell.Offset(-1, 0).EntireRow.Delete
    End If
 Next

redefine your last row

 lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row

and check for one more duplicate

 If Range("A" & lncheckduplicatescolumn).Value = Range("A" & lncheckduplicatescolumn).Offset(-1, 0).Value Then
    .cell.Offset(-1, 0).EntireRow.Delete
 End If


问:
Efficiently mapping unhashable objects to their index in a list
A Python list

```<code>f = [x0, x1, x2]
</code>```

may be seen as an efficient representation of a mapping from [0, 1, ..., len(f) - 1] to the set of its elements. By "efficient" I mean that f[i] returns the element associated with i in O(1) time.

The inverse mapping may be defined as follows:

```<code>class Inverse:
    def __init__(self, f):
        self.f = f

    def __getitem__(self, x):
        return self.f.index(x)
</code>```

This works, but Inverse(f)[x] takes O(n) time on average.

Alternatively, one may use a dict:

```<code>f_inv = {x: i for i, x in enumerate(f)}
</code>```

This has O(1) average time complexity, but it requires the objects in the list to be hashable.

Is there a way to define an inverse mapping that provides equality-based lookups, in O(1) average time, with unhashable objects?

Edit: sample input and expected output:

```<code>>>> f = [x0, x1, x2]
>>> f_inv = Inverse(f)  # this is to be defined
>>> f_inv[x0]  # in O(1) time
0
>>> f_inv[x2]  # in O(1) time
2
</code>```

答:
Unfortunately you're stuck with an algorithm limitation here. Fast lookup structures, like hash tables or binary trees, are efficient because they put objects in particular buckets or order them based on their values. This requires them to be hashable or comparable consistently for the entire time you are storing them in this structure, otherwise a lookup is very likely to fail.

If the objects you need are mutable (usually the reason they are not hashable) then any time an object you are tracking changes you need to update the data structure. The safest way to do this is to create immutable objects. If you need to change an object, then create a new one, remove the old one from the dictionary, and insert the new object as a key with the same value.

The operations here are still O(1) with respect to the size of the dictionary, you just need to consider whether the cost of copying objects on every change is worth it.

Body:
A Python list

f = [x0, x1, x2]

may be seen as an efficient representation of a mapping from [0, 1, ..., len(f) - 1] to the set of its elements. By "efficient" I mean that f[i] returns the element associated with i in O(1) time.

The inverse mapping may be defined as follows:

class Inverse:
    def __init__(self, f):
        self.f = f

    def __getitem__(self, x):
        return self.f.index(x)

This works, but Inverse(f)[x] takes O(n) time on average.

Alternatively, one may use a dict:

f_inv = {x: i for i, x in enumerate(f)}

This has O(1) average time complexity, but it requires the objects in the list to be hashable.

Is there a way to define an inverse mapping that provides equality-based lookups, in O(1) average time, with unhashable objects?

Edit: sample input and expected output:

>>> f = [x0, x1, x2]
>>> f_inv = Inverse(f)  # this is to be defined
>>> f_inv[x0]  # in O(1) time
0
>>> f_inv[x2]  # in O(1) time
2


问:
error in my simpsons rule integration
I have written the following code to use simpson's rule to integrate an arbitrary function, in my case, sin(x):

```<code>import math

delta_x=(x2-x1)/N

def simpson(x1,x2,f,N):
    sum=0
    i=1
    for i in range(1,N+1):

        sum+=f(x1+i*delta_x)

    sum1=(3*delta_x)*sum

    return(sum1)

print(simpson(0,math.pi,math.sin(x),100))
</code>```

however I get the error 'float object not callable' on the sum+=f(x1+i*delta_x) line. Anyone know what could be wrong?

Thanks :)

答:
The f argument to your function is supposed to be a function. math.sin(x) doesn't return a function, it calculates the sin of x and returns that number. simpson() is then trying to call it as a function.

You should just pass math.sin, it will be called by simpson() in the loop.

```<code>print(simpson(0,math.pi,math.sin,100))
</code>```

Title: error in my simpsons rule integration

Body:
I have written the following code to use simpson's rule to integrate an arbitrary function, in my case, sin(x):

import math

delta_x=(x2-x1)/N

def simpson(x1,x2,f,N):
    sum=0
    i=1
    for i in range(1,N+1):

        sum+=f(x1+i*delta_x)

    sum1=(3*delta_x)*sum

    return(sum1)

print(simpson(0,math.pi,math.sin(x),100))

however I get the error 'float object not callable' on the sum+=f(x1+i*delta_x) line. Anyone know what could be wrong?

Thanks :)

Body:
The f argument to your function is supposed to be a function. math.sin(x) doesn't return a function, it calculates the sin of x and returns that number. simpson() is then trying to call it as a function.

You should just pass math.sin, it will be called by simpson() in the loop.

print(simpson(0,math.pi,math.sin,100))


问:
Rails PostgreSQL checking an array

I have looked heavily into replicating the answer provided here Postgresql: comparing arrays results in "malformed array literal" error
However I still receive an error.

I have two tables Locations, and Customers.
Locations belongs to customers

```<code>addresses = ["1 Mullberry St", "24 Western Ave", "923 Shetland Dr"]

Customer.joins(:location)
  .where("'#{addresses}'::text[] && locations.street1")
  .pluck(:email)
</code>```

Below is the SQL and the error that I receive

```<code>SELECT "customers"."email"
  FROM "customers"
    INNER JOIN "locations" ON "locations"."customer_id" = "customers"."id"
      WHERE ('{'1 Mullberry St', '24 Western Ave', '923 Shetland
Dr'}'::text[] && locations.street1)

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "1"
</code>```

答:
Are you trying to get the emails from customers which have their location.street1 in that list?

If that's the case then the SQL you want to end up with is more like:

```<code>SELECT "customers"."email"
FROM "customers" INNER JOIN "locations" ON "locations"."customer_id" = "customers"."id"
WHERE locations.street1 IN ('1 Mullberry St', '24 Western Ave', '923 Shetland Dr')
</code>```

To do that in Rails should be as simple as:

```<code>Customer.joins(:location)
  .where("locations.street1" => addresses)
  .pluck(:email)
</code>```

Title: Rails PostgreSQL checking an array

Body:
I have looked heavily into replicating the answer provided here Postgresql: comparing arrays results in "malformed array literal" error
However I still receive an error.

I have two tables Locations, and Customers.
Locations belongs to customers

addresses = ["1 Mullberry St", "24 Western Ave", "923 Shetland Dr"]

Customer.joins(:location)
  .where("'#{addresses}'::text[] && locations.street1")
  .pluck(:email)

Below is the SQL and the error that I receive

SELECT "customers"."email"
  FROM "customers"
    INNER JOIN "locations" ON "locations"."customer_id" = "customers"."id"
      WHERE ('{'1 Mullberry St', '24 Western Ave', '923 Shetland
Dr'}'::text[] && locations.street1)

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "1"

Body:
Are you trying to get the emails from customers which have their location.street1 in that list?

If that's the case then the SQL you want to end up with is more like:

SELECT "customers"."email"
FROM "customers" INNER JOIN "locations" ON "locations"."customer_id" = "customers"."id"
WHERE locations.street1 IN ('1 Mullberry St', '24 Western Ave', '923 Shetland Dr')

To do that in Rails should be as simple as:

Customer.joins(:location)
  .where("locations.street1" => addresses)
  .pluck(:email)


问:
Azure search : Proximity search with wild cards
Proximity with phrase search using wild cards is not maintaining the order and giving the wrong result

I am trying to search “Bal* Peti*”~5 for which the result should have both the specified words in the same order within a proximity of 5.

but the result doesnt respect the order and both the specified words arent available in few  cases.

答:
The proximity operator ~ defines how many transpositions of phrase query terms are allowed. Currently the proximity operator does not support wildcards.

Let's look at a few phrase queries and one document has three terms on subsequent positions: A B C

"A B" will match - this is equivalent to "A B"~0
"A C"~1 will match - term C moved forward by one position
"C B" won't match
"C B"~1 won't match - with only one allowed transposition we can move terms B and C to the same position
"C B"~2 will match - by allowing two transpositions the terms can reverse order of the phrase query terms

We don't have immediate plans to change this behavior, please vote on our User Voice page to help us prioritize.


问:
Code Golf: Finite-state machine!

Finite state machine

A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected. Leaving some formalities aside, A run of a finite state machine is composed of:

alphabet, a set of characters.

states, usually visualized as circles. One of the states must be the start state. Some of the states might be accepting, usually visualized as double circles.

transitions, usually visualized as directed arches between states, are directed links between states associated with an alphabet letter.

input string, a list of alphabet characters.

A run on the machine begins at the starting state. Each letter of the input string is read; If there is a transition between the current state and another state which corresponds to the letter, the current state is changed to the new state. After the last letter was read, if the current state is an accepting state, the input string is accepted. If the last state was not an accepting state, or a letter had no corresponding arch from a state during the run, the input string is rejected.

Note: This short descruption is far from being a full, formal definition of a FSM; Wikipedia's fine article is a great introduction to the subject.

Example

For example, the following machine tells if a binary number, read from left to right, has an even number of 0s:

The alphabet is the set {0,1}.

The states are S1 and S2.

The transitions are (S1, 0) -> S2, (S1, 1) -> S1, (S2, 0) -> S1 and (S2, 1) -> S2.

The input string is any binary number, including an empty string.

The rules:

Implement a FSM in a language of your choice.

Input

The FSM should accept the following input:

```<code><States>       List of state, separated by space mark.
               The first state in the list is the start state.
               Accepting states begin with a capital letter.
<transitions>  One or more lines.
               Each line is a three-tuple:
               origin state, letter, destination state)
<input word>   Zero or more characters, followed by a newline.
</code>```

For example, the aforementioned machine with 1001010 as an input string, would be written as:

```<code>S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010
</code>```

Output

The FSM's run, written as <State> <letter> -> <state>, followed by the final state. The output for the example input would be:

```<code>S1 1 -> S1
S1 0 -> s2
s2 0 -> S1
S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
s2 0 -> S1
ACCEPT
</code>```

For the empty input '':

```<code>S1
ACCEPT
</code>```

Note: Following your comments, the S1 line (showing the first state) might be omitted, and the following output is also acceptable:

```<code>ACCEPT
</code>```

For 101:

```<code>S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
REJECT
</code>```

For '10X':

```<code>S1 1 -> S1
S1 0 -> s2
s2 X
REJECT
</code>```

Prize

A 250 rep bounty will be given to the shortest solution.

Reference implementation

A reference Python implementation is available here. Note that output requirements have been relaxed for empty-string input.

Addendum

Output format

Following popular demand, the following output is also acceptable for empty input string:

```<code>ACCEPT
</code>```

or

```<code>REJECT
</code>```

Without the first state written in the previous line.

State names

Valid state names are an English letter followed by any number of letters, _ and digits, much like variable names, e.g. State1, state0, STATE_0.

Input format

Like most code golfs, you can assume your input is correct.

Summary of answers:

Cobol - 4078 characters

Python - 171 characters, 568 characters, 203 characters, 218 characters, 269 characters

sed - 137 characters

ruby - 145 characters, 183 characters

Haskell - 192 characters, 189 characters

LISP - 725 characters

Perl - 184 characters

Bash - 184 characters

Rexx - 205 characters

Lua - 356 characters

F# - 420 characters

C# - 356 characters

Mixal - 898 characters

The sed 137 solution is the shortest, ruby 145 is #2. Currently, I can't get the sed solution to work:

```<code>cat test.fsm | sed -r solution.sed
sed -r solution.sed test.fsm
</code>```

both gave me:

```<code>S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010
</code>```0

so unless It there are clarifications the bounty goes to the ruby solution.

答:
F# 420

Not bad for immutable golf I think.  I didn't do very good on the course today though.

```<code>open System
let f,p,a=Array.fold,printf,Map.add
let l=Console.In.ReadToEnd().Split '\n'
let e,s=l.Length,l.[0].Split ' '
let t,w=Map.ofList[for q in s->q,Map.empty],[|"ACCEPT";"REJECT"|]
let m=f(fun t (r:String)->let s=r.Split ' 'in a s.[0](t.[s.[0]]|>a s.[1].[0]s.[2])t)t l.[1..e-2]
try let r=l.[e-1].ToCharArray()|>f(fun s c->p"%s %c "s c;let n=m.[s].[c]in p"-> %s\n"n;n)s.[0]in p"%s"w.[int r.[0]/97]with|_->p"%s"w.[1]
</code>```

33 lines for un-golfed F#.  I'll update again in a bit after I've golfed.

```<code>open System

let input = Console.In.ReadToEnd()
//let input = "S1 s2\nS1 0 s2\nS1 1 S1\ns2 0 S1\ns2 1 s2\n1001010"
let lines = input.Split '\n'
let length = lines.Length
let states = lines.[0].Split ' '

let stateMap = Map.ofList [for state in states -> (state, Map.empty)]

let folder stateMap (line:String) =
    let s = line.Split ' '
    stateMap |> Map.add s.[0] (stateMap.[s.[0]] |> Map.add s.[1].[0] s.[2])

let machine = Array.fold folder stateMap lines.[1 .. (length-2)]

let stateMachine state char =
    printf "%s %c " state char
    let newState = machine.[state].[char]
    printfn "-> %s" newState
    newState

try
    let result =
        lines.[length-1].ToCharArray()
        |> Array.fold stateMachine states.[0]

    if Char.IsUpper result.[0] then
        printf "ACCEPT"
    else
        printf "REJECT"
with
    | _ -> printf "REJECT"
</code>```

Title: Code Golf: Finite-state machine!

Body:
Finite state machine

A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected. Leaving some formalities aside, A run of a finite state machine is composed of:

alphabet, a set of characters.

states, usually visualized as circles. One of the states must be the start state. Some of the states might be accepting, usually visualized as double circles.

transitions, usually visualized as directed arches between states, are directed links between states associated with an alphabet letter.

input string, a list of alphabet characters.

A run on the machine begins at the starting state. Each letter of the input string is read; If there is a transition between the current state and another state which corresponds to the letter, the current state is changed to the new state. After the last letter was read, if the current state is an accepting state, the input string is accepted. If the last state was not an accepting state, or a letter had no corresponding arch from a state during the run, the input string is rejected.

Note: This short descruption is far from being a full, formal definition of a FSM; Wikipedia's fine article is a great introduction to the subject.

Example

For example, the following machine tells if a binary number, read from left to right, has an even number of 0s:

The alphabet is the set {0,1}.

The states are S1 and S2.

The transitions are (S1, 0) -> S2, (S1, 1) -> S1, (S2, 0) -> S1 and (S2, 1) -> S2.

The input string is any binary number, including an empty string.

The rules:

Implement a FSM in a language of your choice.

Input

The FSM should accept the following input:

<States>       List of state, separated by space mark.
               The first state in the list is the start state.
               Accepting states begin with a capital letter.
<transitions>  One or more lines.
               Each line is a three-tuple:
               origin state, letter, destination state)
<input word>   Zero or more characters, followed by a newline.

For example, the aforementioned machine with 1001010 as an input string, would be written as:

S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010

Output

The FSM's run, written as <State> <letter> -> <state>, followed by the final state. The output for the example input would be:

S1 1 -> S1
S1 0 -> s2
s2 0 -> S1
S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
s2 0 -> S1
ACCEPT

For the empty input '':

S1
ACCEPT

Note: Following your comments, the S1 line (showing the first state) might be omitted, and the following output is also acceptable:

ACCEPT

For 101:

S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
REJECT

For '10X':

S1 1 -> S1
S1 0 -> s2
s2 X
REJECT

Prize

A 250 rep bounty will be given to the shortest solution.

Reference implementation

A reference Python implementation is available here. Note that output requirements have been relaxed for empty-string input.

Addendum

Output format

Following popular demand, the following output is also acceptable for empty input string:

ACCEPT

or

REJECT

Without the first state written in the previous line.

State names

Valid state names are an English letter followed by any number of letters, _ and digits, much like variable names, e.g. State1, state0, STATE_0.

Input format

Like most code golfs, you can assume your input is correct.

Summary of answers:

Cobol - 4078 characters

Python - 171 characters, 568 characters, 203 characters, 218 characters, 269 characters

sed - 137 characters

ruby - 145 characters, 183 characters

Haskell - 192 characters, 189 characters

LISP - 725 characters

Perl - 184 characters

Bash - 184 characters

Rexx - 205 characters

Lua - 356 characters

F# - 420 characters

C# - 356 characters

Mixal - 898 characters

The sed 137 solution is the shortest, ruby 145 is #2. Currently, I can't get the sed solution to work:

cat test.fsm | sed -r solution.sed
sed -r solution.sed test.fsm

both gave me:

sed: -e expression #1, char 12: unterminated `s' command

so unless It there are clarifications the bounty goes to the ruby solution.

Body:
F# 420

Not bad for immutable golf I think.  I didn't do very good on the course today though.

open System
let f,p,a=Array.fold,printf,Map.add
let l=Console.In.ReadToEnd().Split '\n'
let e,s=l.Length,l.[0].Split ' '
let t,w=Map.ofList[for q in s->q,Map.empty],[|"ACCEPT";"REJECT"|]
let m=f(fun t (r:String)->let s=r.Split ' 'in a s.[0](t.[s.[0]]|>a s.[1].[0]s.[2])t)t l.[1..e-2]
try let r=l.[e-1].ToCharArray()|>f(fun s c->p"%s %c "s c;let n=m.[s].[c]in p"-> %s\n"n;n)s.[0]in p"%s"w.[int r.[0]/97]with|_->p"%s"w.[1]

33 lines for un-golfed F#.  I'll update again in a bit after I've golfed.

open System

let input = Console.In.ReadToEnd()
//let input = "S1 s2\nS1 0 s2\nS1 1 S1\ns2 0 S1\ns2 1 s2\n1001010"
let lines = input.Split '\n'
let length = lines.Length
let states = lines.[0].Split ' '

let stateMap = Map.ofList [for state in states -> (state, Map.empty)]

let folder stateMap (line:String) =
    let s = line.Split ' '
    stateMap |> Map.add s.[0] (stateMap.[s.[0]] |> Map.add s.[1].[0] s.[2])

let machine = Array.fold folder stateMap lines.[1 .. (length-2)]

let stateMachine state char =
    printf "%s %c " state char
    let newState = machine.[state].[char]
    printfn "-> %s" newState
    newState

try
    let result =
        lines.[length-1].ToCharArray()
        |> Array.fold stateMachine states.[0]

    if Char.IsUpper result.[0] then
        printf "ACCEPT"
    else
        printf "REJECT"
with
    | _ -> printf "REJECT"


问:
Set Title in View in mvvmcross 5.1
Good afternoon.

I was using Xamarin and MVVMCROSS version 5.0 to create multiple tabs and navigate them between them.
In my code i have a Root page that directs to the pages:

```<code>[MvxRootPresentation(WrapInNavigationController = true)]
public sealed partial class RootView : MvxTabBarViewController<RootViewModel>
{
    private bool _isPresentedFirstTime = true;

    public RootView()
    {
        // ViewDidLoad();
    }

    public override void ViewWillAppear(bool animated)
    {
        base.ViewWillAppear(animated);

        if (ViewModel != null && _isPresentedFirstTime)
        {
            _isPresentedFirstTime = false;

            ViewModel.ShowInitialViewModels();
        }

        //Alterando o BackGround da tabBar
        this.TabBar.BarTintColor = UIColor.FromRGBA(237, 146, 4, 1);
        this.TabBar.Translucent = false;
        //this.TabBar.Opaque = false;
        //Cor do ícone antes de selecionado
        this.TabBar.UnselectedItemTintColor = UIColor.White;
        //Cor do ícone após seleção
        this.TabBar.SelectedImageTintColor = UIColor.Black;

        //Setando imagem antes e depois da seleção
        this.TabBar.Items[4].Image = UIImage.FromBundle("valdemarMenuBar.png").ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
        this.TabBar.Items[4].SelectedImage = UIImage.FromBundle("valdemarMenuBar.png").ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
    }
</code>```

...

In each of the Views I set the Titles of the navigations bars according to the example below:

```<code>    [MvxTabPresentation(WrapInNavigationController = true, TabIconName = "newOrder", TabName = "Novo Pedido")]
public partial class NewOrder2ViewController : BaseScrollViewController
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        if (ViewModel == null)
        {
            return;
        }

        Title = "Novo Pedido";

        ...
</code>```

When I upgraded to version 5.1.1 of MVVMCROSS this functionality has stopped.
Can anyone help me about what happened.
I did not find anything in the documentation for this new version of MVVMCROSS.

Thank you very much in advance.

答:
You're seeing this strange behavior because you have two UINavigationControllers ovelapped on each tab, one over the other (this is because your TabBarViewController is wrapped in a navigation controller).

In order to fix it, you just need to change the value of the attribute property:

```<code>[MvxRootPresentation(WrapInNavigationController = false)]
public sealed partial class RootView : MvxTabBarViewController<RootViewModel>
{
    //...
}
</code>```

Title: Set Title in View in mvvmcross 5.1

Body:
Good afternoon.

I was using Xamarin and MVVMCROSS version 5.0 to create multiple tabs and navigate them between them.
In my code i have a Root page that directs to the pages:

[MvxRootPresentation(WrapInNavigationController = true)]
public sealed partial class RootView : MvxTabBarViewController<RootViewModel>
{
    private bool _isPresentedFirstTime = true;

    public RootView()
    {
        // ViewDidLoad();
    }

    public override void ViewWillAppear(bool animated)
    {
        base.ViewWillAppear(animated);

        if (ViewModel != null && _isPresentedFirstTime)
        {
            _isPresentedFirstTime = false;

            ViewModel.ShowInitialViewModels();
        }

        //Alterando o BackGround da tabBar
        this.TabBar.BarTintColor = UIColor.FromRGBA(237, 146, 4, 1);
        this.TabBar.Translucent = false;
        //this.TabBar.Opaque = false;
        //Cor do ícone antes de selecionado
        this.TabBar.UnselectedItemTintColor = UIColor.White;
        //Cor do ícone após seleção
        this.TabBar.SelectedImageTintColor = UIColor.Black;

        //Setando imagem antes e depois da seleção
        this.TabBar.Items[4].Image = UIImage.FromBundle("valdemarMenuBar.png").ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
        this.TabBar.Items[4].SelectedImage = UIImage.FromBundle("valdemarMenuBar.png").ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
    }

...

In each of the Views I set the Titles of the navigations bars according to the example below:

    [MvxTabPresentation(WrapInNavigationController = true, TabIconName = "newOrder", TabName = "Novo Pedido")]
public partial class NewOrder2ViewController : BaseScrollViewController
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        if (ViewModel == null)
        {
            return;
        }

        Title = "Novo Pedido";

        ...

When I upgraded to version 5.1.1 of MVVMCROSS this functionality has stopped.
Can anyone help me about what happened.
I did not find anything in the documentation for this new version of MVVMCROSS.

Thank you very much in advance.

Body:
You're seeing this strange behavior because you have two UINavigationControllers ovelapped on each tab, one over the other (this is because your TabBarViewController is wrapped in a navigation controller).

In order to fix it, you just need to change the value of the attribute property:

[MvxRootPresentation(WrapInNavigationController = false)]
public sealed partial class RootView : MvxTabBarViewController<RootViewModel>
{
    //...
}