问:
Textview in a fragment of Viewpager doesn't update right
I have created A layout and I dynamically add tabs according to data I receive. I do the same with fragments updating the Text View dynamically. Although when the layout loads and if I swipe through the fragments or view pager (sorry I am new to all these hope my terminology is right) they update just okay (meaning there is sometimes lag in updating not much of an issue) and with right data. although, if in fresh I open the layout and click on tab to change my fragments I get no data or wrong data. Example:- when Layout loads for first time my first & third tab load up fine. If I click on a second Tab (not swiping but touching the tabs on top for the whole time), my second tab doesn't have any data in its fragment. On moving round here and there selecting tabs randomly first tab loads second tabs data, but second tab never loads anything. Its not the same when I swipe if I load page new or for first time.
Let me know where I am doing wrong. Thank you.

Here is my code:-

Layout file - show_score.xml

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.lp.activity.ShowScorePassagesActivity">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/children_school"
        android:scaleType="centerCrop"
        android:alpha="0.5"
        android:layout_below="@+id/appBackBar"/>

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <include android:id="@+id/appBackBar"
            layout="@layout/detail_appbar"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/passagetabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Fragment File - fragment_show_score_passage.xml

```<code>   <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lp.activity.ShowScorePassagesActivity$PlaceholderFragment">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!-- TODO: Update blank fragment layout -->
        <android.support.v7.widget.CardView
            android:id="@+id/cardView4"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            app:cardElevation="5dp"
            android:scaleType="fitXY"
            android:layout_margin="5dp">
            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/scrollbar_shape_style">
                <TextView
                    android:id="@+id/showScore"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:textSize="18dp"
                    android:scaleType="fitXY"
                    android:text="TextView"
                    android:autoLink="web"
                    android:linksClickable="true"
                    android:padding="20dp"
                    android:clipToPadding="false"/>
            </ScrollView>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@+id/cardView5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardElevation="5dp"
            android:layout_below="@+id/cardView4"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp">
            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/scrollbar_shape_style">
                <GridView
                    android:id="@+id/fluencyAudioGrid"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:numColumns="auto_fit"
                    android:horizontalSpacing="2dp"
                    android:verticalSpacing="5dp"
                    android:columnWidth="120dp"
                    android:paddingTop="10dp"
                    android:paddingBottom="10dp"
                    android:clipToPadding="false"
                    android:stretchMode="spacingWidthUniform"
                    layout="@layout/icons_for_dashboard"
                    android:scrollbarThumbVertical="@drawable/scroolbar_style"
          android:scrollbarTrackVertical="@drawable/scroolbar_style_background">
                </GridView>
            </ScrollView>
        </android.support.v7.widget.CardView>
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>
</code>```

And the main Java File where the magic happens - ShowScorePassageActivity.java

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

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    public GridView gridView;
    public ArrayList<String> gridItems = new ArrayList<String>();
    public static TextView fragTextView;
    static String fragNewTextView = "";
    public static ArrayList<String> fluencyMarksList = new ArrayList<>();
    public TabLayout tabLayout;

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

        Intent in = getIntent();
        String intentData = in.getStringExtra("intentData");
        String fluencyMarks = in.getStringExtra("fluencyMarks");
        tabLayout = (TabLayout) findViewById(R.id.passagetabs);
        String mFluencyMarkList []= fluencyMarks.split("@");
        fluencyMarksList = new ArrayList<String>(Arrays.asList(mFluencyMarkList));
        int count = 1;
        int counts=fluencyMarksList.size();
        for(int i = 0; i < counts; i++){
            tabLayout.addTab(tabLayout.newTab().setText("Passage "+count));
            count=count+1;
        }
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        mViewPager = (ViewPager) findViewById(R.id.container);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mViewPager.setCurrentItem(tab.getPosition());
                int position =  tab.getPosition();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                    if (position ==0){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0), Html.FROM_HTML_MODE_COMPACT));
                    }
                    else if (position ==1){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1) , Html.FROM_HTML_MODE_COMPACT));
                    }
                    else if (position ==2){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2) , Html.FROM_HTML_MODE_COMPACT));
                    }
                } else {
                    if (position ==0){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
                    }
                    else if (position ==1){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1)));
                    }
                    else if (position ==2){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2)));
                    }
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                fragTextView.setText("");
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
    @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_show_score_passages, 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;
        }
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_show_score_passages, container, false);
            fragTextView = (TextView) rootView.findViewById(R.id.showScore);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {

                fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0) , Html.FROM_HTML_MODE_COMPACT));
            } else {

                fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
            }
            return rootView;
        }
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }
    }
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        int mNumOfTabs;
        Fragment fragment = null;

        public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
            super(fm);
            this.mNumOfTabs=NumOfTabs;

        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            return mNumOfTabs;
        }
    }
}
</code>```

答:
This is what I did:

It is only a example of what worked for me in the hopes of helping you

In OnCreate:

```<code>ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
this.addPages(mViewPager);
mViewPager.setOffscreenPageLimit(3);

TabLayout tabLayout = (TabLayout) findViewById(R.id.mTab_ID);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(listener(mViewPager));
</code>```

Then add the fragments to the TabLayout by doing:

```<code>//ADD ALL PAGES TO TABLAYOUT
private void addPages(ViewPager pager) {
    adapter = new MyFragPagerAdapter(getSupportFragmentManager());
    adapter.addPage(new FragmentAdapter1());
    adapter.addPage(new FragmentAdapter2());
    adapter.addPage(new FragmentAdapter3());

    //SET ADAPTER TO PAGER
    pager.setAdapter(adapter);
}
</code>```

Then implement TabLayout click events OnTabSelectedListener by doing:

```<code>//TabLayout Click Events
private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            pager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}
</code>```

Body:
I have created A layout and I dynamically add tabs according to data I receive. I do the same with fragments updating the Text View dynamically. Although when the layout loads and if I swipe through the fragments or view pager (sorry I am new to all these hope my terminology is right) they update just okay (meaning there is sometimes lag in updating not much of an issue) and with right data. although, if in fresh I open the layout and click on tab to change my fragments I get no data or wrong data. Example:- when Layout loads for first time my first & third tab load up fine. If I click on a second Tab (not swiping but touching the tabs on top for the whole time), my second tab doesn't have any data in its fragment. On moving round here and there selecting tabs randomly first tab loads second tabs data, but second tab never loads anything. Its not the same when I swipe if I load page new or for first time.
Let me know where I am doing wrong. Thank you.

Here is my code:-

Layout file - show_score.xml

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.lp.activity.ShowScorePassagesActivity">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/children_school"
        android:scaleType="centerCrop"
        android:alpha="0.5"
        android:layout_below="@+id/appBackBar"/>

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <include android:id="@+id/appBackBar"
            layout="@layout/detail_appbar"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/passagetabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

Fragment File - fragment_show_score_passage.xml

   <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lp.activity.ShowScorePassagesActivity$PlaceholderFragment">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.CardView
            android:id="@+id/cardView4"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            app:cardElevation="5dp"
            android:scaleType="fitXY"
            android:layout_margin="5dp">
            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/scrollbar_shape_style">
                <TextView
                    android:id="@+id/showScore"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:textSize="18dp"
                    android:scaleType="fitXY"
                    android:text="TextView"
                    android:autoLink="web"
                    android:linksClickable="true"
                    android:padding="20dp"
                    android:clipToPadding="false"/>
            </ScrollView>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@+id/cardView5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardElevation="5dp"
            android:layout_below="@+id/cardView4"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp">
            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/scrollbar_shape_style">
                <GridView
                    android:id="@+id/fluencyAudioGrid"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:numColumns="auto_fit"
                    android:horizontalSpacing="2dp"
                    android:verticalSpacing="5dp"
                    android:columnWidth="120dp"
                    android:paddingTop="10dp"
                    android:paddingBottom="10dp"
                    android:clipToPadding="false"
                    android:stretchMode="spacingWidthUniform"
                    layout="@layout/icons_for_dashboard"
                    android:scrollbarThumbVertical="@drawable/scroolbar_style"
          android:scrollbarTrackVertical="@drawable/scroolbar_style_background">
                </GridView>
            </ScrollView>
        </android.support.v7.widget.CardView>
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

And the main Java File where the magic happens - ShowScorePassageActivity.java

    public class ShowScorePassagesActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    public GridView gridView;
    public ArrayList<String> gridItems = new ArrayList<String>();
    public static TextView fragTextView;
    static String fragNewTextView = "";
    public static ArrayList<String> fluencyMarksList = new ArrayList<>();
    public TabLayout tabLayout;

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

        Intent in = getIntent();
        String intentData = in.getStringExtra("intentData");
        String fluencyMarks = in.getStringExtra("fluencyMarks");
        tabLayout = (TabLayout) findViewById(R.id.passagetabs);
        String mFluencyMarkList []= fluencyMarks.split("@");
        fluencyMarksList = new ArrayList<String>(Arrays.asList(mFluencyMarkList));
        int count = 1;
        int counts=fluencyMarksList.size();
        for(int i = 0; i < counts; i++){
            tabLayout.addTab(tabLayout.newTab().setText("Passage "+count));
            count=count+1;
        }
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        mViewPager = (ViewPager) findViewById(R.id.container);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mViewPager.setCurrentItem(tab.getPosition());
                int position =  tab.getPosition();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                    if (position ==0){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0), Html.FROM_HTML_MODE_COMPACT));
                    }
                    else if (position ==1){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1) , Html.FROM_HTML_MODE_COMPACT));
                    }
                    else if (position ==2){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2) , Html.FROM_HTML_MODE_COMPACT));
                    }
                } else {
                    if (position ==0){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
                    }
                    else if (position ==1){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1)));
                    }
                    else if (position ==2){
                        fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2)));
                    }
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                fragTextView.setText("");
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
    @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_show_score_passages, 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;
        }
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_show_score_passages, container, false);
            fragTextView = (TextView) rootView.findViewById(R.id.showScore);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {

                fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0) , Html.FROM_HTML_MODE_COMPACT));
            } else {

                fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
            }
            return rootView;
        }
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }
    }
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        int mNumOfTabs;
        Fragment fragment = null;

        public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
            super(fm);
            this.mNumOfTabs=NumOfTabs;

        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            return mNumOfTabs;
        }
    }
}

Body:
This is what I did:

It is only a example of what worked for me in the hopes of helping you

In OnCreate:

ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
this.addPages(mViewPager);
mViewPager.setOffscreenPageLimit(3);

TabLayout tabLayout = (TabLayout) findViewById(R.id.mTab_ID);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(listener(mViewPager));

Then add the fragments to the TabLayout by doing:

//ADD ALL PAGES TO TABLAYOUT
private void addPages(ViewPager pager) {
    adapter = new MyFragPagerAdapter(getSupportFragmentManager());
    adapter.addPage(new FragmentAdapter1());
    adapter.addPage(new FragmentAdapter2());
    adapter.addPage(new FragmentAdapter3());

    //SET ADAPTER TO PAGER
    pager.setAdapter(adapter);
}

Then implement TabLayout click events OnTabSelectedListener by doing:

//TabLayout Click Events
private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            pager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}


来源: stackexchange

问:
Angular 4 Redirecting to Root on Refresh
I have an Angular 4 single page application. When I refresh the page, or enter a valid URL into the browser, I get redirected to the app's root route.

I've changed my nginx config to redirect all requests to /index.html, which fixed my initial issue of getting 404s on browser refresh.

```<code>server {
    listen  80;

    server_name bla.com www.bla.com

    location / {
        root  /home/admin/web/bla.com/public_html;
        index  index.html index.htm;
        try_files $uri $uri/ =404;
    }

    error_page 404 /index.html;

    error_page  500 502 503 504  /50x.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    location = /50x.html {
        root  /usr/share/nginx/html;
    }
}
</code>```

** Edit **

Angular routing is simply handled by the RouterModule:

```<code>// ...

import { RouterModule, Routes } from '@angular/router';

// ...

const appRoutes: Routes = [
  { path: '', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'clients', component: ClientsComponent, canActivate: [AuthGuard], children: [
    { path: 'add', component: AddClientComponent, canActivate: [AuthGuard]}
  ]},
  { path: 'projects', component: ProjectsComponent, canActivate: [AuthGuard], children: [
    { path: 'add', component: AddProjectComponent, canActivate: [AuthGuard] }
  ]},
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: 'invoices', component: InvoicesComponent, canActivate: [AuthGuard], children: [
    { path: 'invoices/new-invoice', component: NewInvoiceComponent, canActivate: [AuthGuard] }
  ]}
];
</code>```

I don't really want to use HashLocationStrategy, so is there a way I can get Angular to serve the correct page when the browser refreshes or when a URL is entered?

答: I guess [AuthGuard] is causing you the trouble.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have an Angular 4 single page application. When I refresh the page, or enter a valid URL into the browser, I get redirected to the app's root route.

I've changed my nginx config to redirect all requests to /index.html, which fixed my initial issue of getting 404s on browser refresh.

server {
    listen  80;

    server_name bla.com www.bla.com

    location / {
        root  /home/admin/web/bla.com/public_html;
        index  index.html index.htm;
        try_files $uri $uri/ =404;
    }

    error_page 404 /index.html;

    error_page  500 502 503 504  /50x.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    location = /50x.html {
        root  /usr/share/nginx/html;
    }
}

** Edit **

Angular routing is simply handled by the RouterModule:

// ...

import { RouterModule, Routes } from '@angular/router';

// ...

const appRoutes: Routes = [
  { path: '', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'clients', component: ClientsComponent, canActivate: [AuthGuard], children: [
    { path: 'add', component: AddClientComponent, canActivate: [AuthGuard]}
  ]},
  { path: 'projects', component: ProjectsComponent, canActivate: [AuthGuard], children: [
    { path: 'add', component: AddProjectComponent, canActivate: [AuthGuard] }
  ]},
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: 'invoices', component: InvoicesComponent, canActivate: [AuthGuard], children: [
    { path: 'invoices/new-invoice', component: NewInvoiceComponent, canActivate: [AuthGuard] }
  ]}
];

I don't really want to use HashLocationStrategy, so is there a way I can get Angular to serve the correct page when the browser refreshes or when a URL is entered?


问:
How to marge two arrays data and save one SQL table
I have two array. I want merge and insert to the database using php. here i put some array data. but my array is very big one.

Array1

```<code>Array
(
    [1] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [2] => Array
        (
            [ALT_ID] => 2003458
            [STUDENT_ID] => 2495
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [3] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [4] => Array
        (
            [ALT_ID] => 2003587
            [STUDENT_ID] => 2624
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [5] => Array
        (
            [ALT_ID] => 2003614
            [STUDENT_ID] => 2651
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [6] => Array
        (
            [ALT_ID] => 2003682
            [STUDENT_ID] => 2721
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [7] => Array
        (
            [ALT_ID] => 2003685
            [STUDENT_ID] => 2724
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [8] => Array
        (
            [ALT_ID] => 2003777
            [STUDENT_ID] => 2814
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )
)
</code>```

Array2

```<code>Array
(
    [1] => Array
        (
            [COURSE_ID] => 1
            [TITLE] => Programming Methodology
            [SHORT_NAME] => ECSI402
            [MODULE_STATUS] => Core
        )

    [2] => Array
        (
            [COURSE_ID] => 2
            [TITLE] => Communication and Learning Skills in Computer Science  (SE)
            [SHORT_NAME] => ECSI400
            [MODULE_STATUS] => Core
        )

    [3] => Array
        (
            [COURSE_ID] => 3
            [TITLE] => Computer Systems Fundamentals
            [SHORT_NAME] => ECSI404
            [MODULE_STATUS] => Core
        )

    [4] => Array
        (
            [COURSE_ID] => 4
            [TITLE] => Information and Data Modeling  (SE)
            [SHORT_NAME] => EBSI401
            [MODULE_STATUS] => Core
        )

    [5] => Array
        (
            [COURSE_ID] => 5
            [TITLE] => Software Development Principles
            [SHORT_NAME] => ECSI406
            [MODULE_STATUS] => Core
        )
)
</code>```

I want these two data submit to the one table. this is the SQL query for that.

```<code>INSERT INTO MODULE_REG (STUDENT_ID, COURSE_ID, DATE_REGISTERED, REGISTERED, ACADEMIC_SESSION)
</code>```

My database table i want save like this. this is sample one. i have to submit these two arrays all data for like this.

```<code> +-----------+----------+-----------+----------------+-------------+
|student id | course id| registered| data_registered| academic ses|
+-----------+----------+-----------+----------------+-------------+
|  2235     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    3     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    3     |     Y     |  2017.11.16    |  Level 4    |
+-----------+----------+-----------+----------------+-------------+
</code>```

答:
This is the answer. $result is array1..
$result1 is array2

```<code>     foreach ($result as $value){

    $value[STUDENT_ID];
    $value[TITLE];
   foreach($result1 as $values){
    $values[COURSE_ID];

    $date = date("Y-m-d");

    $sql= "INSERT INTO MODULE_REGISTRATION (STUDENT_ID, COURSE_ID,REGISTERED, DATE_REGISTERED, ACADEMIC_SESSION) "
    . "VALUES ('".$value[STUDENT_ID]."','".$values[COURSE_ID]."', 'Y' ,'".$date. "','".$value[TITLE]."')";
    DBQuery($sql);

    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two array. I want merge and insert to the database using php. here i put some array data. but my array is very big one.

Array1

Array
(
    [1] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [2] => Array
        (
            [ALT_ID] => 2003458
            [STUDENT_ID] => 2495
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [3] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [4] => Array
        (
            [ALT_ID] => 2003587
            [STUDENT_ID] => 2624
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [5] => Array
        (
            [ALT_ID] => 2003614
            [STUDENT_ID] => 2651
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [6] => Array
        (
            [ALT_ID] => 2003682
            [STUDENT_ID] => 2721
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [7] => Array
        (
            [ALT_ID] => 2003685
            [STUDENT_ID] => 2724
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [8] => Array
        (
            [ALT_ID] => 2003777
            [STUDENT_ID] => 2814
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )
)

Array2

Array
(
    [1] => Array
        (
            [COURSE_ID] => 1
            [TITLE] => Programming Methodology
            [SHORT_NAME] => ECSI402
            [MODULE_STATUS] => Core
        )

    [2] => Array
        (
            [COURSE_ID] => 2
            [TITLE] => Communication and Learning Skills in Computer Science  (SE)
            [SHORT_NAME] => ECSI400
            [MODULE_STATUS] => Core
        )

    [3] => Array
        (
            [COURSE_ID] => 3
            [TITLE] => Computer Systems Fundamentals
            [SHORT_NAME] => ECSI404
            [MODULE_STATUS] => Core
        )

    [4] => Array
        (
            [COURSE_ID] => 4
            [TITLE] => Information and Data Modeling  (SE)
            [SHORT_NAME] => EBSI401
            [MODULE_STATUS] => Core
        )

    [5] => Array
        (
            [COURSE_ID] => 5
            [TITLE] => Software Development Principles
            [SHORT_NAME] => ECSI406
            [MODULE_STATUS] => Core
        )
)

I want these two data submit to the one table. this is the SQL query for that.

INSERT INTO MODULE_REG (STUDENT_ID, COURSE_ID, DATE_REGISTERED, REGISTERED, ACADEMIC_SESSION)

My database table i want save like this. this is sample one. i have to submit these two arrays all data for like this.

 +-----------+----------+-----------+----------------+-------------+
|student id | course id| registered| data_registered| academic ses|
+-----------+----------+-----------+----------------+-------------+
|  2235     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    3     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    3     |     Y     |  2017.11.16    |  Level 4    |
+-----------+----------+-----------+----------------+-------------+

Body:
This is the answer. $result is array1..
$result1 is array2

     foreach ($result as $value){

    $value[STUDENT_ID];
    $value[TITLE];
   foreach($result1 as $values){
    $values[COURSE_ID];

    $date = date("Y-m-d");

    $sql= "INSERT INTO MODULE_REGISTRATION (STUDENT_ID, COURSE_ID,REGISTERED, DATE_REGISTERED, ACADEMIC_SESSION) "
    . "VALUES ('".$value[STUDENT_ID]."','".$values[COURSE_ID]."', 'Y' ,'".$date. "','".$value[TITLE]."')";
    DBQuery($sql);

    }
}


问:
why ionic 3 google map with lat lang is not loading on android
Why my google map is not appearing in on android device.

I'm able console.log(); lat, lang in browser. device will ask permission for location access but it will not render map.

below code works fine for predefined lat, lang

```<code> ionViewDidLoad() {
    console.log('ionViewDidLoad GoogleMapTestPage');
   this.loadMapHandler();

  }

    loadMapHandler() {

      //console.log(lat,lang);

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

      }
</code>```

The above code works fine on android

when i try to get current location of user and  and pass lat, lang to another

function then i will not work

below is my code which is not working

code not working on android: ask permission but doesn't work

```<code>    import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';
     constructor(...,public googleMaps: GoogleMaps,private geolocation : Geolocation) {
      }

  ionViewDidLoad() {

   this.loadMap();

  }
    loadMap(){

         this.geolocation.getCurrentPosition().then((position) => {

           this.loadMapHandler(position.coords.latitude,position.coords.longitude);

        }, (err) => {
          console.log(err);
        });
    }

    loadMapHandler(lat,lang) {

      console.log(lat,lang);  // console.log('is giving map co-ordinates');

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     let ionic: LatLng = new LatLng(lat,lang);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

    }
</code>```

Thanks in Advance!!!

答:
If you are using the GoogleMaps plugin I would recommend to use the built-in function:

```<code>    this.mapElement = document.getElementById('map');
    let mapOptions: GoogleMapOptions = {
    };

    this.map = this.googleMapsService.create(this.mapElement, mapOptions);

    // Wait the MAP_READY before using any methods.
    this.map.one(GoogleMapsEvent.MAP_READY)
      .then(() => {

this.map.getMyLocation().then((myLocation: MyLocation) => {
      this.map.setCameraTarget(myLocation.latLng);
      this.map.setCameraZoom(18);
    });
</code>```

And you are fine.

UPDATE:

```<code>    map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

map.getMyLocation().then((myLocation) => {
      map.setCameraTarget(myLocation.latLng);
      map.setCameraZoom(18);
    });

      }
</code>```

Using your first solution with adding the map.getMyLocation() part should work fine.

Body:
Why my google map is not appearing in on android device.

I'm able console.log(); lat, lang in browser. device will ask permission for location access but it will not render map.

below code works fine for predefined lat, lang

 ionViewDidLoad() {
    console.log('ionViewDidLoad GoogleMapTestPage');
   this.loadMapHandler();

  }

    loadMapHandler() {

      //console.log(lat,lang);

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

      }

The above code works fine on android

when i try to get current location of user and  and pass lat, lang to another

function then i will not work

below is my code which is not working

code not working on android: ask permission but doesn't work

    import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';
     constructor(...,public googleMaps: GoogleMaps,private geolocation : Geolocation) {
      }

  ionViewDidLoad() {

   this.loadMap();

  }
    loadMap(){

         this.geolocation.getCurrentPosition().then((position) => {

           this.loadMapHandler(position.coords.latitude,position.coords.longitude);

        }, (err) => {
          console.log(err);
        });
    }

    loadMapHandler(lat,lang) {

      console.log(lat,lang);  // console.log('is giving map co-ordinates');

     // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     let ionic: LatLng = new LatLng(lat,lang);

     // create CameraPosition
     let position: any = {
       target: LatLng,
       zoom: 18,
       tilt: 30
     };

     map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

    }

Thanks in Advance!!!

Body:
If you are using the GoogleMaps plugin I would recommend to use the built-in function:

    this.mapElement = document.getElementById('map');
    let mapOptions: GoogleMapOptions = {
    };

    this.map = this.googleMapsService.create(this.mapElement, mapOptions);

    // Wait the MAP_READY before using any methods.
    this.map.one(GoogleMapsEvent.MAP_READY)
      .then(() => {

this.map.getMyLocation().then((myLocation: MyLocation) => {
      this.map.setCameraTarget(myLocation.latLng);
      this.map.setCameraZoom(18);
    });

And you are fine.

UPDATE:

    map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });
        });

map.getMyLocation().then((myLocation) => {
      map.setCameraTarget(myLocation.latLng);
      map.setCameraZoom(18);
    });

      }

Using your first solution with adding the map.getMyLocation() part should work fine.


问:
In HTTP post request, How to pass JSON array having multiple Object in URL query
I need to post a JSON array having objects at backend in a URL query parameter.

Here is the sample array:

[
    {
        "question": "What is the name of your favorite childhood friend?",
        "answer": "1"
    },
    {
        "question": "What is the name of your pet?",
        "answer": "1"
    },
    {
        "question": "Who is your favorite musican?",
        "answer": "1"
    }
]
```

It is working fine with body parameters, but I have to sent in a URL query. Can anyone please help?

Body:
I need to post a JSON array having objects at backend in a URL query parameter.

Here is the sample array:

[
    {
        "question": "What is the name of your favorite childhood friend?",
        "answer": "1"
    },
    {
        "question": "What is the name of your pet?",
        "answer": "1"
    },
    {
        "question": "Who is your favorite musican?",
        "answer": "1"
    }
]

It is working fine with body parameters, but I have to sent in a URL query. Can anyone please help?


问:
How to select a dropdown list element using webdriver selenium in python where it is of input type?
The HTML script is :

```<code>    <input id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"
    type="text" class="selectbox" autocomplete="off" readonly=""
    tabindex="0" style="width: 325px;">

    <ul id="the_list">
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_-1"
    class="">Please Select</li>
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_18">john</li>
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_20">erine</li>
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_22">devin</li>
</code>```

Here the user will give the name like john , erine or devin and i have to select that item from the list .Using selenium web driver in python 2.7 .

Here's my progress till now :

```<code>   import selenium
   from selenium.webdriver.common.action_chains import ActionChains
   from selenium.webdriver.support.select import Select
   elem = driver.find_element_by_xpath('//*
   [@id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"]')
   elem.send_keys(name)
</code>```

答:
It is not that clear from your Question if it mandatory to use send_keys() to the <input> tag for the
 elements to showup/expand. Assuming it as a False Positive, to select a dropdown list element you can write a function as below :

```<code>def select_option(option):
    driver.find_element_by_xpath("//ul[@id='the_list']/li[contains(.,'" + option + "')]").click()
</code>```

Body:
The HTML script is :

    <input id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"
    type="text" class="selectbox" autocomplete="off" readonly=""
    tabindex="0" style="width: 325px;">

Please Select

john

erine

devin

Here the user will give the name like john , erine or devin and i have to select that item from the list .Using selenium web driver in python 2.7 .

Here's my progress till now :

   import selenium
   from selenium.webdriver.common.action_chains import ActionChains
   from selenium.webdriver.support.select import Select
   elem = driver.find_element_by_xpath('//*
   [@id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"]')
   elem.send_keys(name)

Body:
It is not that clear from your Question if it mandatory to use send_keys() to the <input> tag for the <li> elements to showup/expand. Assuming it as a False Positive, to select a dropdown list element you can write a function as below :

def select_option(option):
    driver.find_element_by_xpath("//ul[@id='the_list']/li[contains(.,'" + option + "')]").click()


问:
What is your method of "folksonomy" tagging for files on your local machine?
Way back in the days when "delicious" was just "del.icio.us", I had assumed that everyone had finally caught on that Ontology is overrated.

So why am I still having to roll my own tagging system using sqlite and a bunch of ruby scripts in order to address this obvious deficiency on my own local machine? I can tag on-line web links, blog posts, questions on stackoverflow.com, and all kinds of web-centric miscellany, but this very basic concept still seems to be missing (or hideously crippled) in the few operating systems I get to use. Perhaps I am just using the wrong OSs?

From what I've seen out there, the pickins' seem pretty slim.

What do you use?

答: I don't use tags, I just don't have the discipline to do it all the time. I find that searching, using a desktop search tool like Copernic Desktop Search, works the best for me.</p>

OwnerDisplayName: dreftymac

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Patrick Cuff


问:
jqueryui dialog, direction of slide
I'm using jquery dialog and want to slide on show. How do I specify the direction of the slide?</p>

```<code>$('.selector').dialog({ show: 'slide' });
</code>```

答:
I resolve the problem in this way:
I have edit the UI file "jquery-ui-1.7.2.custom.min.js" in Dialog section

Original code:

```<code>d.show(e.show);// <--or iDialog.show(options.show) in ui.dialog.js
</code>```

Modified code:

```<code>d.show(e.show,e.showOpt); // or iDialog.show(options.show,options.showOpt) in ui.dialog.js
</code>```

I create my dialog adding a new parameter "showOpt" that can contain the jquery effect options

```<code>$j( "#dialog_box" ).dialog({
    modal: true,
    width:500,
    height:500,
    show: "slide",
    showOpt: {direction: 'up'}
    });
</code>```

Title: jqueryui dialog, direction of slide

Body:
I'm using jquery dialog and want to slide on show. How do I specify the direction of the slide?

$('.selector').dialog({ show: 'slide' });

Body:
I resolve the problem in this way:
I have edit the UI file "jquery-ui-1.7.2.custom.min.js" in Dialog section

Original code:

d.show(e.show);// <--or iDialog.show(options.show) in ui.dialog.js

Modified code:

d.show(e.show,e.showOpt); // or iDialog.show(options.show,options.showOpt) in ui.dialog.js

I create my dialog adding a new parameter "showOpt" that can contain the jquery effect options

$j( "#dialog_box" ).dialog({
    modal: true,
    width:500,
    height:500,
    show: "slide",
    showOpt: {direction: 'up'}
    });


问:
Why is the json string null when I pass a inner object to Gson().toJson(object) in Kotlin?
I convert a object to a json string using Gson in Kotlin.

The var json2 can return correct result, but the var json1 return null,  why?

```<code>import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import bll.SettingManage
import info.dodata.mirror.R
import model.MSetting
import com.google.gson.Gson
import utility.PreferenceTool

class UIMain : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        data class WiFiDefA(val Name:String, val Status: String)

        var  aWiFiDefA=WiFiDefA("a","b")
        var  json1=Gson().toJson(aWiFiDefA)

        var aWiFiDefB=WiFiDefB("c","d")
        var json2=Gson().toJson(aWiFiDefB)

    }

    data class WiFiDefB(val Name:String, val Status: String)

}
</code>```

答:
As I have tried with GSON lib, I have declared both classes outside of the onCreate() method.

Like below:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val  aWiFiDefA=WiFiDefA("a","b")
    val json1=Gson().toJson(aWiFiDefA)

    Log.d("json1",json1.toString())
    var aWiFiDefB=WiFiDefB("c","d")
    var json2= Gson().toJson(aWiFiDefB)
    Log.d("json2",json2.toString())
}
data class WiFiDefA(val Name:String, val Status: String)
data class WiFiDefB(val Name:String, val Status: String)
</code>```

Which gives me an output which you required.
Output:

```<code>11-17 11:58:50.448 27978-27978/? D/json1: {"Name":"a","Status":"b"}
11-17 11:58:50.452 27978-27978/? D/json2: {"Name":"c","Status":"d"}
</code>```

But when I have tried your code getting output like below:

```<code>11-17 11:58:01.312 27584-27584/? D/json1: null
11-17 11:58:01.320 27584-27584/? D/json2: {"Name":"c","Status":"d"}
</code>```

We can not create class into method scope. You can create Nested and Inner Classes a class as a nested class if you want.

https://kotlinlang.org/docs/reference/nested-classes.html#nested-and-inner-classes

Body:
I convert a object to a json string using Gson in Kotlin.

The var json2 can return correct result, but the var json1 return null,  why?

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import bll.SettingManage
import info.dodata.mirror.R
import model.MSetting
import com.google.gson.Gson
import utility.PreferenceTool

class UIMain : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_main)

        data class WiFiDefA(val Name:String, val Status: String)

        var  aWiFiDefA=WiFiDefA("a","b")
        var  json1=Gson().toJson(aWiFiDefA)

        var aWiFiDefB=WiFiDefB("c","d")
        var json2=Gson().toJson(aWiFiDefB)

    }

    data class WiFiDefB(val Name:String, val Status: String)

}

Body:
As I have tried with GSON lib, I have declared both classes outside of the onCreate() method.

Like below:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val  aWiFiDefA=WiFiDefA("a","b")
    val json1=Gson().toJson(aWiFiDefA)

    Log.d("json1",json1.toString())
    var aWiFiDefB=WiFiDefB("c","d")
    var json2= Gson().toJson(aWiFiDefB)
    Log.d("json2",json2.toString())
}
data class WiFiDefA(val Name:String, val Status: String)
data class WiFiDefB(val Name:String, val Status: String)

Which gives me an output which you required.
Output:

11-17 11:58:50.448 27978-27978/? D/json1: {"Name":"a","Status":"b"}
11-17 11:58:50.452 27978-27978/? D/json2: {"Name":"c","Status":"d"}

But when I have tried your code getting output like below:

11-17 11:58:01.312 27584-27584/? D/json1: null
11-17 11:58:01.320 27584-27584/? D/json2: {"Name":"c","Status":"d"}

We can not create class into method scope. You can create Nested and Inner Classes a class as a nested class if you want.

https://kotlinlang.org/docs/reference/nested-classes.html#nested-and-inner-classes


问:
msbuild - export all properties defined in block to MSBuild calls
```<code><Target Name="micropython_prebuild">

    <PropertyGroup>
        <uP_PrebuildPyExe>"$(ProjectDir)\Source\micropython\py\make_prebuild_wrapper.exe"</uP_PrebuildPyExe>
        <GnuCat>$(uP_PrebuildPyExe) gnu_cat</GnuCat>
        <GnuSed>$(uP_PrebuildPyExe) gnu_sed</GnuSed>
        <uP_GenHdrFolder>$(ObjectFolder)\genhdr</uP_GenHdrFolder>
        <uP_QSTR_GEN_EXTRA_CFLAGS>-DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB -DN_ARM -DN_XTENSA</uP_QSTR_GEN_EXTRA_CFLAGS>
        <uP_SRC>$(ProjectDir)\Source\micropython</uP_SRC>
        <uP_MPY_CROSS>"$(ProjectDir)\Source\micropython\mpy-cross\mpy-cross.exe"</uP_MPY_CROSS>
    </PropertyGroup>

    <MakeDir Directories="$(uP_GenHdrFolder)\"/>

    <MSBuild
        Projects="$(MSBuildProjectFile)"
        Condition="'' == ''"
        Targets="prebuild_mpversion"
        Properties="uP_PrebuildPyExe=$(uP_PrebuildPyExe);
                    uP_GenHdrFolder=$(uP_GenHdrFolder)"
    />
</Target>
</code>```

How do I "export" all the properties I've defined at the top to the calls to MSBuild within this target?

Otherwise, I have to set the Properties of each MSBuild.

答:
You can also create a single property that contains all the definitions:</p>

```<code><Target Name="micropython_prebuild">

    <PropertyGroup>
      <PrebuildProperties>
        uP_PrebuildPyExe="$(ProjectDir)\Source\micropython\py\make_prebuild_wrapper.exe";
        GnuCat=$(uP_PrebuildPyExe) gnu_cat;
        GnuSed=$(uP_PrebuildPyExe) gnu_sed;
        uP_GenHdrFolder=$(ObjectFolder)\genhdr;
        uP_QSTR_GEN_EXTRA_CFLAGS=-DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB -DN_ARM -DN_XTENSA;
        uP_SRC=$(ProjectDir)\Source\micropython;
        uP_MPY_CROSS="$(ProjectDir)\Source\micropython\mpy-cross\mpy-cross.exe";
      </PrebuildProperties>
    </PropertyGroup>

    <MakeDir Directories="$(uP_GenHdrFolder)\"/>

    <MSBuild
        Projects="$(MSBuildProjectFile)"
        Condition="'' == ''"
        Targets="prebuild_mpversion"
        Properties="$(PrebuildProperties)"
    />
</Target>
</code>```

Body:
<Target Name="micropython_prebuild">

    <PropertyGroup>
        <uP_PrebuildPyExe>"$(ProjectDir)\Source\micropython\py\make_prebuild_wrapper.exe"</uP_PrebuildPyExe>
        <GnuCat>$(uP_PrebuildPyExe) gnu_cat</GnuCat>
        <GnuSed>$(uP_PrebuildPyExe) gnu_sed</GnuSed>
        <uP_GenHdrFolder>$(ObjectFolder)\genhdr</uP_GenHdrFolder>
        <uP_QSTR_GEN_EXTRA_CFLAGS>-DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB -DN_ARM -DN_XTENSA</uP_QSTR_GEN_EXTRA_CFLAGS>
        <uP_SRC>$(ProjectDir)\Source\micropython</uP_SRC>
        <uP_MPY_CROSS>"$(ProjectDir)\Source\micropython\mpy-cross\mpy-cross.exe"</uP_MPY_CROSS>
    </PropertyGroup>

    <MakeDir Directories="$(uP_GenHdrFolder)\"/>

    <MSBuild
        Projects="$(MSBuildProjectFile)"
        Condition="'' == ''"
        Targets="prebuild_mpversion"
        Properties="uP_PrebuildPyExe=$(uP_PrebuildPyExe);
                    uP_GenHdrFolder=$(uP_GenHdrFolder)"
    />
</Target>

How do I "export" all the properties I've defined at the top to the calls to MSBuild within this target?

Otherwise, I have to set the Properties of each MSBuild.

Body:
You can also create a single property that contains all the definitions:

<Target Name="micropython_prebuild">

    <PropertyGroup>
      <PrebuildProperties>
        uP_PrebuildPyExe="$(ProjectDir)\Source\micropython\py\make_prebuild_wrapper.exe";
        GnuCat=$(uP_PrebuildPyExe) gnu_cat;
        GnuSed=$(uP_PrebuildPyExe) gnu_sed;
        uP_GenHdrFolder=$(ObjectFolder)\genhdr;
        uP_QSTR_GEN_EXTRA_CFLAGS=-DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB -DN_ARM -DN_XTENSA;
        uP_SRC=$(ProjectDir)\Source\micropython;
        uP_MPY_CROSS="$(ProjectDir)\Source\micropython\mpy-cross\mpy-cross.exe";
      </PrebuildProperties>
    </PropertyGroup>

    <MakeDir Directories="$(uP_GenHdrFolder)\"/>

    <MSBuild
        Projects="$(MSBuildProjectFile)"
        Condition="'' == ''"
        Targets="prebuild_mpversion"
        Properties="$(PrebuildProperties)"
    />
</Target>


问:
How to query a pandas DataFrame using an array of tuples ?
I have a pandas DataFrame with the following structure:

And I have an array of tuples

arr_tuples = [(0,3),(1,1),(1,3),(2,1)]

Each tuple in the array represent the row and column index of the above dataframe respectively.

I can find all the values in the data frame for the indices in arr_tuples using for loop like this:

```<code>value_array = []
for item in arr_tuples:
    row = item[0]
    col = item[1]
    value = df.iloc[row,col] # I also tried df.get_value here with similar result
    value_array.append(value)
</code>```

But this seems to be a very slow method. If there are a lot of tuples in my arr_tuples, this will take a long time.

Is there a better and faster way to achieve the same ?
Is there any way in pandas where I can use a list/array of tuples (containing row and column index) to get values in a dataframe ?

答:
You can use pd.DataFrame.lookup with some zip and unpacking trickery

```<code>df.lookup(*zip(*arr_tuples))

array([ 4,  5,  7, 12])
</code>```

list(zip(*arr_tuples)) creates two tuples out of the list of tuples

```<code>[(0, 1, 1, 2), (3, 1, 3, 1)]
</code>```

Well that's perfect because the first tuple are indices and the second are columns.  That's what pd.DataFrame.lookup accepts as arguments.  So if I unpack those, it'll just work

```<code>df.lookup(*zip(*arr_tuples))

array([ 4,  5,  7, 12])
</code>```

Body:
I have a pandas DataFrame with the following structure:

And I have an array of tuples

arr_tuples = [(0,3),(1,1),(1,3),(2,1)]

Each tuple in the array represent the row and column index of the above dataframe respectively.

I can find all the values in the data frame for the indices in arr_tuples using for loop like this:

value_array = []
for item in arr_tuples:
    row = item[0]
    col = item[1]
    value = df.iloc[row,col] # I also tried df.get_value here with similar result
    value_array.append(value)

But this seems to be a very slow method. If there are a lot of tuples in my arr_tuples, this will take a long time.

Is there a better and faster way to achieve the same ?
Is there any way in pandas where I can use a list/array of tuples (containing row and column index) to get values in a dataframe ?

Body:
You can use pd.DataFrame.lookup with some zip and unpacking trickery

df.lookup(*zip(*arr_tuples))

array([ 4,  5,  7, 12])

list(zip(*arr_tuples)) creates two tuples out of the list of tuples

[(0, 1, 1, 2), (3, 1, 3, 1)]

Well that's perfect because the first tuple are indices and the second are columns.  That's what pd.DataFrame.lookup accepts as arguments.  So if I unpack those, it'll just work

df.lookup(*zip(*arr_tuples))

array([ 4,  5,  7, 12])


问:
How to query the most recent row for each value in column X?
I'm trying to query the most recent row for each value in a column X.

My current attempt is:

```<code>SELECT max(mytimestamp), mytable.* FROM mytable GROUP BY X
</code>```

but while the first column in the result contains the latest timestamp, the other columns are not from the most recent row.

How do I fix that?

答:
I dont think you need the group by:

SELECT max(timestamp), mytable.* FROM mytable limt 1;

Body:
I'm trying to query the most recent row for each value in a column X.

My current attempt is:

SELECT max(mytimestamp), mytable.* FROM mytable GROUP BY X

but while the first column in the result contains the latest timestamp, the other columns are not from the most recent row.

How do I fix that?


问:
keys in object are undefined but object is not (react-redux)
So I have a strange issue with the data I'm fetching from an API. In my reducer I've set the initial state to an empty object and in my component's render method I'm accessing this fetched data using this.props.data.value.one.

The actual fetched data from the API look like this:

```<code>{data:
  {value: {one: '1'}}
}
</code>```

However when I try to console.log(this.props.data) it will log {value: {one: '1'}} after logging undefined a couple of times but will log this.props.data.value.one as undefined.

I'm doing similar stuff in my other reducers which are getting data from other API's and they work fine.

App.js Component:

```<code>@connect(store => store)
...
componentWillMount = () => {//API Call here}
render = () => {
 return (
    <div><p>{this.props.data.value.one}</p><div>
 )
}
</code>```

reducer.js:

```<code>...
export default function reducer(state={data: {}}, action) {
  ...
  case 'FETCHED_DATA':
    return {...state, data: action.data}
</code>```

action.js:

```<code>...
fetchData = user => dispatch => {
  //request.get...
     .then(res => dispatch({type: 'FETCHED_DATA', data: res.body.data})
}
</code>```

答:
Since you set you initial state to be an empty object, and the data you get is though an API call which is async, so when the component renders first time this.props.data is undefined.

What you need to do is check if the data is available before using it

Add a conditional check like

```<code>this.props.data && this.props.data.value.one
</code>```

Body:
So I have a strange issue with the data I'm fetching from an API. In my reducer I've set the initial state to an empty object and in my component's render method I'm accessing this fetched data using this.props.data.value.one.

The actual fetched data from the API look like this:

{data:
  {value: {one: '1'}}
}

However when I try to console.log(this.props.data) it will log {value: {one: '1'}} after logging undefined a couple of times but will log this.props.data.value.one as undefined.

I'm doing similar stuff in my other reducers which are getting data from other API's and they work fine.

App.js Component:

@connect(store => store)
...
componentWillMount = () => {//API Call here}
render = () => {
 return (

{this.props.data.value.one}

 )
}

reducer.js:

...
export default function reducer(state={data: {}}, action) {
  ...
  case 'FETCHED_DATA':
    return {...state, data: action.data}

action.js:

...
fetchData = user => dispatch => {
  //request.get...
     .then(res => dispatch({type: 'FETCHED_DATA', data: res.body.data})
}

Body:
Since you set you initial state to be an empty object, and the data you get is though an API call which is async, so when the component renders first time this.props.data is undefined.

What you need to do is check if the data is available before using it

Add a conditional check like

this.props.data && this.props.data.value.one


问:
How to display ckeditor saved html data from database to normal text in MVC 5
I am using Mvc 5 razor,and have used ckeditor to save data in database but when i am retrieving data on the view it is coming with all the html tags pls helpme how to display it in normal text form on the view</p>

```<code>     <div class="panel panel-default">
                        <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree" id="Inclusions">
                            <div class="panel-heading">
                                <h4 class="panel-title">  INCLUSIONS </h4>
                            </div>
                        </a>
                        <div id="collapseThree" class="panel-collapse collapse">
                            <div class="panel-body">
                                @Html.Raw(Html.DisplayFor(Model => Model.Itinerarydetail.Inclusions));
                            </div>
                        </div>
                    </div>
</code>```

答:
Here in my view when you get data from database use @Html.Raw

```<code><div class="form-group">
        @Html.LabelFor(model => model.Description,htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-sm-8">
            <textarea type="text" class="ckeditor" name="Description">@item.Description</textarea>
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>
</code>```

Body:
I am using Mvc 5 razor,and have used ckeditor to save data in database but when i am retrieving data on the view it is coming with all the html tags pls helpme how to display it in normal text form on the view

  INCLUSIONS

                                @Html.Raw(Html.DisplayFor(Model => Model.Itinerarydetail.Inclusions));

Body:
Here in my view when you get data from database use @Html.Raw

<div class="form-group">
        @Html.LabelFor(model => model.Description,htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-sm-8">
            <textarea type="text" class="ckeditor" name="Description">@item.Description</textarea>
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>


问:
How can I make Bootstrap columns all the same height?
I'm using Bootstrap. How can I make three columns all the same height?

Here is a screenshot of the problem. I would like the blue and red columns to be the same height as the yellow column.

Here is the code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        some content

        catz

        some more content

```

答:
If anyone using bootstrap 4 and looking for equal height columns just use row-eq-height to parent div

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />

.row.row-eq-height > .col-xs-4

.row.row-eq-height > .col-xs-4
this is
a much
taller
column
than the others

.row.row-eq-height > .col-xs-4

```

Ref: http://getbootstrap.com.vn/examples/equal-height-columns/

Body:
If anyone using bootstrap 4 and looking for equal height columns just use row-eq-height to parent div

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="row row-eq-height">
  <div class="col-xs-4" style="border: 1px solid grey;">.row.row-eq-height &gt; .col-xs-4</div>
  <div class="col-xs-4" style="border: 1px solid grey;">.row.row-eq-height &gt; .col-xs-4<br>this is<br>a much<br>taller<br>column<br>than the others</div>
  <div class="col-xs-4" style="border: 1px solid grey;">.row.row-eq-height &gt; .col-xs-4</div>
</div>

Ref: http://getbootstrap.com.vn/examples/equal-height-columns/


问:
How can I find kafka config file?
I have an error using kafka Error while executing topic command replication factor: 1 larger than available brokers: 0 when I tried to create a topic.

And I found the solution (Error creating Kafka Topics- Replication factor larger than available brokers) by modifying config file

```<code>cp config/server.properties config/server-1.properties
cp config/server.properties config/server-2.properties)
</code>```

But my problem is that I can't find the config file cp: config/server.properties: No such file or directory

Could someone help me how to find it using terminal on Mac?

答: If you are using the docker image from confluent, e.g. confluentinc/cp-enterprise-kafka, they are located in /etc/kafka.

Title: How can I find kafka config file?

Body:
I have an error using kafka Error while executing topic command replication factor: 1 larger than available brokers: 0 when I tried to create a topic.

And I found the solution (Error creating Kafka Topics- Replication factor larger than available brokers) by modifying config file

cp config/server.properties config/server-1.properties
cp config/server.properties config/server-2.properties)

But my problem is that I can't find the config file cp: config/server.properties: No such file or directory

Could someone help me how to find it using terminal on Mac?


问:
Fixing HttpClient warning "Invalid expires attribute" using fluent API
I'm using the fluent API of HttpClient to make a GET request:

```<code>String jsonResult = Request.Get(requestUrl)
            .connectTimeout(2000)
            .socketTimeout(2000)
            .execute().returnContent().asString();
</code>```

But for each request I get the following warning:

```<code>apr 07, 2016 12:26:46 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
WARNING: Invalid cookie header: "Set-Cookie: WMF-Last-Access=07-Apr-2016;Path=/;HttpOnly;Expires=Mon, 09 May 2016 00:00:00 GMT". Invalid 'expires' attribute: Mon, 09 May 2016 00:00:00 GMT
</code>```

How can I fix this and keep using the fluent interface? Ideally I'd want a proper way to fix it, but since I don't really care about the cookies in my use case any solution that just allows me to stop displaying the warnings (besides redirecting stderr, cause I need that) is welcome.

答:
If you want to use HttpClientBuilder you can use the following sytax:

```<code>        HttpClient httpClient = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.STANDARD).build()).build();
</code>```

Body:
I'm using the fluent API of HttpClient to make a GET request:

String jsonResult = Request.Get(requestUrl)
            .connectTimeout(2000)
            .socketTimeout(2000)
            .execute().returnContent().asString();

But for each request I get the following warning:

apr 07, 2016 12:26:46 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
WARNING: Invalid cookie header: "Set-Cookie: WMF-Last-Access=07-Apr-2016;Path=/;HttpOnly;Expires=Mon, 09 May 2016 00:00:00 GMT". Invalid 'expires' attribute: Mon, 09 May 2016 00:00:00 GMT

How can I fix this and keep using the fluent interface? Ideally I'd want a proper way to fix it, but since I don't really care about the cookies in my use case any solution that just allows me to stop displaying the warnings (besides redirecting stderr, cause I need that) is welcome.

Body:
If you want to use HttpClientBuilder you can use the following sytax:

        HttpClient httpClient = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.STANDARD).build()).build();


问:
How to draw checkbox or tick mark in GitHub Markdown table?
I am able to draw checkbox in Github README.md lists using

```<code>- [ ] (for unchecked checkbox)
- [x] (for checked checkbox)
</code>```

But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?

答:
Following is how I draw a checkbox in a table!

```<code>| Checkbox Experiments | [ ] unchecked header  | [x] checked header  |
| ---------------------|:---------------------:|:-------------------:|
| checkbox             | [ ] row               | [x] row             |
</code>```

Displays like this:

Body:
I am able to draw checkbox in Github README.md lists using

- [ ] (for unchecked checkbox)
- [x] (for checked checkbox)

But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?

Body:
Following is how I draw a checkbox in a table!

| Checkbox Experiments | [ ] unchecked header  | [x] checked header  |
| ---------------------|:---------------------:|:-------------------:|
| checkbox             | [ ] row               | [x] row             |

Displays like this:


问:
nodejs 3des decrypt didn't get expected result
My nodejs 3DES decryption didn't get expected result. Is there anything wrong with my code?

```<code>let cryptojs = require('crypto-js')
var key = '551408C3D129EC64DA505CB48CD61D57551408C3D129EC64';
var ciphertext = 'C5F21F0F82038833851BA3092D613F085A60DB1E189E10F6';
var iv = cryptojs.enc.Hex.parse("0".repeat(16));

key = cryptojs.enc.Hex.parse(key);
var result = cryptojs.TripleDES.decrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});
console.log ('decrypted ' + result.toString(cryptojs.enc.Hex));
</code>```

result is '90d49e1085d5251f87dbcd6292570ba30e8a6e0f84d8331c97a579ef0ba6ac867342f2f6'

however expected result should be '466F0198321458864627662057083A457601185220050000'

答:
after some more testing found out need to add one more line of code before decrypt :

```<code>ciphertext = cryptojs.format.Hex.parse(ciphertext);
</code>```

complete code as below :

```<code>let cryptojs = require('crypto-js')
var key = '551408C3D129EC64DA505CB48CD61D57551408C3D129EC64';
var ciphertext = 'C5F21F0F82038833851BA3092D613F085A60DB1E189E10F6';
var iv = cryptojs.enc.Hex.parse("0".repeat(16));

key = cryptojs.enc.Hex.parse(key);
ciphertext = cryptojs.format.Hex.parse(ciphertext);
var result = cryptojs.TripleDES.decrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});
console.log ('decrypted ' + result.toString(cryptojs.enc.Hex));
</code>```

result is

```<code>decrypted 466f0198321458864627662057083a457601185220050000
</code>```

Body:
My nodejs 3DES decryption didn't get expected result. Is there anything wrong with my code?

let cryptojs = require('crypto-js')
var key = '551408C3D129EC64DA505CB48CD61D57551408C3D129EC64';
var ciphertext = 'C5F21F0F82038833851BA3092D613F085A60DB1E189E10F6';
var iv = cryptojs.enc.Hex.parse("0".repeat(16));

key = cryptojs.enc.Hex.parse(key);
var result = cryptojs.TripleDES.decrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});
console.log ('decrypted ' + result.toString(cryptojs.enc.Hex));

result is '90d49e1085d5251f87dbcd6292570ba30e8a6e0f84d8331c97a579ef0ba6ac867342f2f6'

however expected result should be '466F0198321458864627662057083A457601185220050000'

Body:
after some more testing found out need to add one more line of code before decrypt :

ciphertext = cryptojs.format.Hex.parse(ciphertext);

complete code as below :

let cryptojs = require('crypto-js')
var key = '551408C3D129EC64DA505CB48CD61D57551408C3D129EC64';
var ciphertext = 'C5F21F0F82038833851BA3092D613F085A60DB1E189E10F6';
var iv = cryptojs.enc.Hex.parse("0".repeat(16));

key = cryptojs.enc.Hex.parse(key);
ciphertext = cryptojs.format.Hex.parse(ciphertext);
var result = cryptojs.TripleDES.decrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});
console.log ('decrypted ' + result.toString(cryptojs.enc.Hex));

result is

decrypted 466f0198321458864627662057083a457601185220050000


问:
It is possible pass the value of an id from a template, to function (AngulasJS2)
It is possible pass the value of an id from a template, to function (AngulasJS2).

```<code> template: `
  <div class="container" *ngFor="#mov of movs">
  ..//
  <button class="btn btn-primary" type="button"
  ..//
  (click)="test(id)" [id]="mov"
  >
  ..//

  ..//
  test(id: string) {
  //test
  var logo1: HTMLElement = document.getElementById(id);
  ..//
  }
</code>```

right now I'm using it and it works,

```<code> (click)="test(''+mov)" [id]="mov"
</code>```

but with this code does not work.

```<code>(click)="test(id)" [id]="mov"
</code>```

I'm sorry for my English

答:
You can simply do this as well:

```<code><div class="container" *ngFor="let mov of movs" >
..//
  <button class="btn btn-primary" type="button"
 ..//
    (click)="test(mov)" [id]="mov">
</code>```

plunker link: https://plnkr.co/edit/iFRJI8perdwmWpZoBcvW?p=preview

Body:
It is possible pass the value of an id from a template, to function (AngulasJS2).

 template: `

  ..//
  <button class="btn btn-primary" type="button"
  ..//
  (click)="test(id)" [id]="mov"
  >
  ..//

  ..//
  test(id: string) {
  //test
  var logo1: HTMLElement = document.getElementById(id);
  ..//
  }

right now I'm using it and it works,

 (click)="test(''+mov)" [id]="mov"

but with this code does not work.

(click)="test(id)" [id]="mov"

I'm sorry for my English

Body:
You can simply do this as well:

<div class="container" *ngFor="let mov of movs" >
..//
  <button class="btn btn-primary" type="button"
 ..//
    (click)="test(mov)" [id]="mov">

plunker link: https://plnkr.co/edit/iFRJI8perdwmWpZoBcvW?p=preview


问:
Swift 4: Dismiss closure code not executing
First let me say ive tried just about everything out there to fix this problem and I cant for the life of me figure it out.

The code:

```<code> self.messagesControl?.showChatController()
</code>```

is not running , it is inside a dismiss() closure why is that the print line following this runs , and not the line of code above? please help!

messagesControl method call

```<code> var messagesControl : MessagesViewController?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.dismiss(animated: true, completion: {
            self.messagesControl?.showChatController()
            print("dismiss closure finished running")
        })

}
</code>```

showChatController()

```<code> func showChatController()
{
    performSegue(withIdentifier: "goToChatLogControllerPlz", sender: self)
}
</code>```

Expected Result:
segue is run print line executes

Observed Result:

print line executes. no segue :(

EDIT

i have replaced :

```<code>self.messagesControl?.showChatController()
</code>```

With:

```<code>      self.performSegue(withIdentifier: "showChatController", sender: self)
</code>```

Still getting same result tho :(

答:
The problem is that you're trying to perform a segue from a View Controller that does not exist anymore. What you should do is connect the segue to the parent of the view controller in question and have the parent view controller perform the segue. Your code will look something like this

```<code>var messagesControl : MessagesViewController?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    dismiss(animated: true, completion: { [weak self]
        self?.parent?.showChatController()
    })
}
</code>```

In the parent view controller

```<code>func showChatController(){
    performSegue(withIdentifier: "goToChatLogControllerPlz", sender: self)
}
</code>```

Body:
First let me say ive tried just about everything out there to fix this problem and I cant for the life of me figure it out.

The code:

 self.messagesControl?.showChatController()

is not running , it is inside a dismiss() closure why is that the print line following this runs , and not the line of code above? please help!

messagesControl method call

 var messagesControl : MessagesViewController?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.dismiss(animated: true, completion: {
            self.messagesControl?.showChatController()
            print("dismiss closure finished running")
        })

}

showChatController()

 func showChatController()
{
    performSegue(withIdentifier: "goToChatLogControllerPlz", sender: self)
}

Expected Result:
segue is run print line executes

Observed Result:

print line executes. no segue :(

EDIT

i have replaced :

self.messagesControl?.showChatController()

With:

      self.performSegue(withIdentifier: "showChatController", sender: self)

Still getting same result tho :(

Body:
The problem is that you're trying to perform a segue from a View Controller that does not exist anymore. What you should do is connect the segue to the parent of the view controller in question and have the parent view controller perform the segue. Your code will look something like this

var messagesControl : MessagesViewController?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    dismiss(animated: true, completion: { [weak self]
        self?.parent?.showChatController()
    })
}

In the parent view controller

func showChatController(){
    performSegue(withIdentifier: "goToChatLogControllerPlz", sender: self)
}


问:
Click on current row for expand details in jQuery
I want to click on particular row to expand that row with some data. I tried with this jQuery but it is not working.

could anybody help, where I missed something.

jQuery

this is working fine but I want to do with current row

```<code>$('.item-id-expand').click(function(){
  $('.item-id-close').css("display", "inline-block");
  $('.item-id-expand').hide();
  $('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $('.item-id-close').hide();
  $('.item-id-expand').show();
  $('.order-details-row1-details').hide();
});
</code>```

Here I tried with this but its not working

```<code>$('.item-id-expand', this).click(function(){
  $(this).find('.item-id-close').css("display", "inline-block");
  $(this).find('.item-id-expand').hide();
  $(this).find('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $(this).find('.item-id-close').hide();
  $(this).find('.item-id-expand').show();
  $(this).find('.order-details-row1-details').hide();
});
</code>```

Html

```<code><div class="order-details">
  <ul class="order-details-head">
    <li>Item ID</li>
    <li>Name</li>
    <li>Qty</li>
    <li>Status</li>
  </ul>
  <ul class="order-details-row1">
    <li><div class="item-id-expand">+</div><div class="item-id-close">-</div>123456</li>
    <li>php 11 echo </li>
    <li>php 12 echo </li>
    <li>php 13 echo </li>
  </ul>
  <div class="order-details-row1-details">
    <ul class="order-details-row1-details-head">
      <li>Date</li>
      <li>Description</li>
    </ul>
    <ul class="order-details-row1-details1">
      <li> echo datetrack</li>
      <li>php echo </li>
    </ul>
  </div>
  <ul class="order-details-row1">
    <li><div class="item-id-expand">+</div><div class="item-id-close">-</div>654321</li>
    <li>php 21 echo </li>
    <li>php 22 echo </li>
    <li>php 23 echo </li>
  </ul>
  <div class="order-details-row1-details">
    <ul class="order-details-row1-details-head">
      <li>Date</li>
      <li>Description</li>
    </ul>
    <ul class="order-details-row1-details1">
      <li> echo datetrack</li>
      <li>php echo </li>
    </ul>
  </div>
</div>
</code>```

答:
hi use this jquery code it will work

```<code>$(document).ready(function(){
$('.item-id-close').hide();
$('.order-details-row1-details').hide();
 $('.item-id-expand').click(function(){

  $(this).hide();
  $(this).siblings('.item-id-close').show();

  $(this).parents('.order-details-row1').next('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){

 $(this).hide();
  $(this).siblings('.item-id-expand').show();

  $(this).parents('.order-details-row1').next('.order-details-row1-details').hide();
});
});
</code>```

Body:
I want to click on particular row to expand that row with some data. I tried with this jQuery but it is not working.

could anybody help, where I missed something.

jQuery

this is working fine but I want to do with current row

$('.item-id-expand').click(function(){
  $('.item-id-close').css("display", "inline-block");
  $('.item-id-expand').hide();
  $('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $('.item-id-close').hide();
  $('.item-id-expand').show();
  $('.order-details-row1-details').hide();
});

Here I tried with this but its not working

$('.item-id-expand', this).click(function(){
  $(this).find('.item-id-close').css("display", "inline-block");
  $(this).find('.item-id-expand').hide();
  $(this).find('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $(this).find('.item-id-close').hide();
  $(this).find('.item-id-expand').show();
  $(this).find('.order-details-row1-details').hide();
});

Html

Item ID

Name

Qty

Status

+

-
123456

php 11 echo

php 12 echo

php 13 echo

Date

Description

 echo datetrack

php echo

+

-
654321

php 21 echo

php 22 echo

php 23 echo

Date

Description

 echo datetrack

php echo

Body:
hi use this jquery code it will work

$(document).ready(function(){
$('.item-id-close').hide();
$('.order-details-row1-details').hide();
 $('.item-id-expand').click(function(){

  $(this).hide();
  $(this).siblings('.item-id-close').show();

  $(this).parents('.order-details-row1').next('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){

 $(this).hide();
  $(this).siblings('.item-id-expand').show();

  $(this).parents('.order-details-row1').next('.order-details-row1-details').hide();
});
});


问:
iOS - How to do drag and drop feature if my sectioned collectionView has a collectionView inside?
I have a collectionview(A) which has a few sections and in this collectionview the cell has a collectionview(B) too.

I want to add a drag and drop feature to my app so that I can re order the cells inside the B collectionview. I also want to be able to move the cells from one B collectionview to another B collectionview.

I've looked at this github tutorial but it doens't help me because of my specific situation.

https://github.com/mmick66/KDDragAndDropCollectionView

So, once again, this is the structure:

```<code>  - collectionView-A (it has multiple sections)
     - cell:
            - collectionView-B
                - cell:
                       - Label
</code>```

答:
With the release of iOS-11, Apple introduced Drag and Drop in UITableView and UICollectionView.

You can refer to below links for the complete implementation details:

How Drag and Drop works in Collection View

https://medium.com/@p.gpt10/drag-it-drop-it-in-collection-table-ios-11-6bd28795b313

Sample Project - It includes drag-drop within 2 collection views as well as reordering.

https://github.com/pgpt10/DragAndDrop-CollectionView

Let me know if you still face any issue with that.

Body:
I have a collectionview(A) which has a few sections and in this collectionview the cell has a collectionview(B) too.

I want to add a drag and drop feature to my app so that I can re order the cells inside the B collectionview. I also want to be able to move the cells from one B collectionview to another B collectionview.

I've looked at this github tutorial but it doens't help me because of my specific situation.

https://github.com/mmick66/KDDragAndDropCollectionView

So, once again, this is the structure:

  - collectionView-A (it has multiple sections)
     - cell:
            - collectionView-B
                - cell:
                       - Label


问:
Table relationship in hive, Spark Sql and Azure USQL
Is there any way i can maintain table relationship in Hive, Spark SQL and Azure U SQL. Does any of these support creating relationships like in Oracle or SQL Server. In oracle i can get the relationships using user_constraints table. Looking for something similar to that for processing in ML.</p>

答:
None of the big data tools maintain constraints. If we just consider hive it doesn't even bother while you are writing data to the table whether the table schema is maintained or not as Hive follows schema on read approach.
While reading the data if you want to establish any relation, one has to work with joins.</p>


问:
Linux command 'll' is not working
I am able to run ll command with my user but not with sudo, it giving me error as command not found!</p>

答:
Try sudo ls -l.

As ll is a shorthand for ls -l.

Title: Linux command 'll' is not working


问:
Error with FirebaseAuthListener
Error with FirebaseAuthListener in Android Studio.

```<code>Unexpected cast to EditText: layout tag was TextView
</code>```

答:
As the error says, you declared your view on the XML file as TextView while casting it to EditView on the activity.

You should change your view at the XML to EditView in order to have a password input (Contrasenia).

Title: Error with FirebaseAuthListener

Body:
Error with FirebaseAuthListener in Android Studio.

Unexpected cast to EditText: layout tag was TextView


问:
Central error logging service for web applications
I'm about to launch a new website and I'm using Pingdom to track the uptime of the site, but I'm interesting in logging any errors generated by the site in a central location. I'd like to put code into my top level exception handler that will package up the exception and send it to another application, which would then generate an email and send it to me.

I will be logging locally of course, but the logs are difficult to get to when I'm out and about. I have the option of writing my own solution to this, but I don't want to reinvent the wheel if something better exists.

Does anyone know of any companies/sites that offer such a service?

If not, would anyone consider this a useful service?

答: Something like this: http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/</p>


问:
Log the actual data sent in the request in SoapUI
I have the request which uses in-line script:

```<code><Req>
 <TransactionId>${= new Date().format("yyyy_MM_dd_HH_mm_ss_SSS")}</TransactionId>
</Req>
</code>```

How can I log value of TransactionId or whole request?

答:
Create a Script Assertion for the same test step.

And add the below code to achieve the same i.e., logs the entire request:

```<code>log.info context.rawRequest
</code>```

In order to get the TransactionId, you can parse the request and extract the value with below code:

```<code>def xmlRequest = new XmlSlurper().parseText(context.rawRequest)
def tId = xmlRequest.'**'.find {it.name = 'TransactionId'}?.text()
log.info "Transaction id sent in the request is: $tId"
</code>```

Body:
I have the request which uses in-line script:

<Req>
 <TransactionId>${= new Date().format("yyyy_MM_dd_HH_mm_ss_SSS")}</TransactionId>
</Req>

How can I log value of TransactionId or whole request?

Body:
Create a Script Assertion for the same test step.

And add the below code to achieve the same i.e., logs the entire request:

log.info context.rawRequest

In order to get the TransactionId, you can parse the request and extract the value with below code:

def xmlRequest = new XmlSlurper().parseText(context.rawRequest)
def tId = xmlRequest.'**'.find {it.name = 'TransactionId'}?.text()
log.info "Transaction id sent in the request is: $tId"


问:
How to capture cURL output to a file?
I have a text document that contains a bunch of URLs in this format:

```<code>URL = "sitehere.com"
</code>```

What I'm looking to do is to run curl -K myfile.txt, and get the output of the response cURL returns, into a file.

How can I do this?

答:
For a single file you can use -O instead of -o filename to use the last segment of the URL path as the filename. Example:

```<code>curl http://example.com/folder/big-file.iso -O
</code>```

will save the results to a new file named big-file.iso in the current folder. In this way it works similar to wget but allows you to specify other curl options that are not available when using wget.

Title: How to capture cURL output to a file?

Body:
I have a text document that contains a bunch of URLs in this format:

URL = "sitehere.com"

What I'm looking to do is to run curl -K myfile.txt, and get the output of the response cURL returns, into a file.

How can I do this?

Body:
For a single file you can use -O instead of -o filename to use the last segment of the URL path as the filename. Example:

curl http://example.com/folder/big-file.iso -O

will save the results to a new file named big-file.iso in the current folder. In this way it works similar to wget but allows you to specify other curl options that are not available when using wget.