问:
Failed to start spring boot integration test when setting the application type as reactive
I have an application using Spring Webflux via Spring boot 2.0.0.M3.

The application is set as REACTIVE type when running it.

```<code>public static void main(String[] args) {
    SpringApplication application = new SpringApplication(AgentApplication.class);
    application.setWebApplicationType(WebApplicationType.REACTIVE);
    application.run(args);
}
</code>```

The reactive app works fine if running the main application. But I failed to start this app in my spring boot integration test.

I declared the test as below,

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    properties = {"spring.main.webApplicationType=reactive"})
@ActiveProfiles("integTest")
public class NoteHandlerTest {

@Autowired
private WebTestClient webClient;

@Test
public void testGetNoteNotFound() throws Exception {
    this.webClient.get().uri("/note/request/{id}", "nosuchid").accept(MediaType.APPLICATION_JSON_UTF8)
            .exchange().expectStatus().isOk();
}

}
</code>```

I got below error when running the test case,

java.lang.IllegalStateException: Failed to load ApplicationContext

at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at
  org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:107)
    at
  org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at
  org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at
  org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
    at
  org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)   at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  Caused by: org.springframework.context.ApplicationContextException:
  Unable to start reactive web server; nested exception is
  org.springframework.context.ApplicationContextException: Unable to
  start ReactiveWebApplicationContext due to missing
  ReactiveWebServerFactory bean.    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:64)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:49)
    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
    at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
    at
  org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:136)
    at
  org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:177)
    at
  org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:99)
    at
  org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:65)
    at
  org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at
  org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at
  org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
    at
  org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:73)
    at
  org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at
  org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:349)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:317)
    at
  org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:138)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    ... 25 more Caused by:
  org.springframework.context.ApplicationContextException: Unable to
  start ReactiveWebApplicationContext due to missing
  ReactiveWebServerFactory bean.  at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.getWebServerFactory(ReactiveWebServerApplicationContext.java:103)
    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.createWebServer(ReactiveWebServerApplicationContext.java:87)
    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:61)
    ... 44 more

Does it have any configuration issue to run spring boot integration test with webflux?

You can access the complete demo project from here.

答:
Isn't it just a typo in your configuration property?

"spring.main.web-application-type=reactive"

Body:
I have an application using Spring Webflux via Spring boot 2.0.0.M3.

The application is set as REACTIVE type when running it.

public static void main(String[] args) {
    SpringApplication application = new SpringApplication(AgentApplication.class);
    application.setWebApplicationType(WebApplicationType.REACTIVE);
    application.run(args);
}

The reactive app works fine if running the main application. But I failed to start this app in my spring boot integration test.

I declared the test as below,

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    properties = {"spring.main.webApplicationType=reactive"})
@ActiveProfiles("integTest")
public class NoteHandlerTest {

@Autowired
private WebTestClient webClient;

@Test
public void testGetNoteNotFound() throws Exception {
    this.webClient.get().uri("/note/request/{id}", "nosuchid").accept(MediaType.APPLICATION_JSON_UTF8)
            .exchange().expectStatus().isOk();
}

}

I got below error when running the test case,

java.lang.IllegalStateException: Failed to load ApplicationContext

at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at
  org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:107)
    at
  org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at
  org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at
  org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
    at
  org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)   at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  Caused by: org.springframework.context.ApplicationContextException:
  Unable to start reactive web server; nested exception is
  org.springframework.context.ApplicationContextException: Unable to
  start ReactiveWebApplicationContext due to missing
  ReactiveWebServerFactory bean.    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:64)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:49)
    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
    at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
    at
  org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:136)
    at
  org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:177)
    at
  org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:99)
    at
  org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:65)
    at
  org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at
  org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at
  org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
    at
  org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:73)
    at
  org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at
  org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:349)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:317)
    at
  org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:138)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    ... 25 more Caused by:
  org.springframework.context.ApplicationContextException: Unable to
  start ReactiveWebApplicationContext due to missing
  ReactiveWebServerFactory bean.  at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.getWebServerFactory(ReactiveWebServerApplicationContext.java:103)
    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.createWebServer(ReactiveWebServerApplicationContext.java:87)
    at
  org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:61)
    ... 44 more

Does it have any configuration issue to run spring boot integration test with webflux?

You can access the complete demo project from here.


来源: stackexchange

问:
Typography and spacing in material-ui
I defined raw theme for material-ui in theme.ts:

```<code>import {Colors, Spacing} from 'material-ui/lib/styles/';
import {ColorManipulator} from 'material-ui/lib/utils/';
import {Styles} from 'material-ui';

export default <Styles.RawTheme> {
    spacing: Spacing,
    fontFamily: 'Roboto, sans-serif',
    palette: <Styles.ThemePalette> {
        primary1Color: Colors.red500,
        primary2Color: Colors.red700,
        primary3Color: Colors.lightBlack,
        accent1Color: Colors.orangeA200,
        accent2Color: Colors.grey100,
        accent3Color: Colors.grey500,
        textColor: Colors.darkBlack,
        alternateTextColor: Colors.white,
        canvasColor: Colors.white,
        borderColor: Colors.grey300,
        disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3),
        pickerHeaderColor: Colors.red500,
    }
};
</code>```

Then in my custom React component app.tsx I applied this theme:

```<code>import * as React from 'react';
import {AppBar, AppCanvas} from 'material-ui';
import {ThemeManager, ThemeDecorator} from 'material-ui/lib/styles/';
import Theme from 'theme';

@ThemeDecorator(ThemeManager.getMuiTheme(Theme))
export class App extends React.Component<{}, {}> {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <AppBar title={ 'App' } showMenuIconButton={false}/>
                <AppCanvas>
                    <h1>Test</h1>
                </AppCanvas>
            </div>
        );
    }
}
</code>```

But h1 header is not styled as it has to be in Material design. No Roboto font, smaller size.

Does material-ui have built-in styles or something else that I can use to easily style headers according to Material guidelines and also give spacing (margins and padding) to elements?

答:
UPDATE:

material-ui now has Typography component:

```<code><Typography variant="h1" component="h2">
  h1. Heading
</Typography>
</code>```

Also there are possibilities for typography customizations and utilities to control alignment, wrapping, weight, and more.

OLD ANSWER:

material-ui 1.0 will come with Typography component: usage and API.

You can try it right now by installing material-ui@next:

```<code>npm install material-ui@next --save
</code>```

ContentLicense: CC BY-SA 3.0

Title: Typography and spacing in material-ui

Body:
I defined raw theme for material-ui in theme.ts:

import {Colors, Spacing} from 'material-ui/lib/styles/';
import {ColorManipulator} from 'material-ui/lib/utils/';
import {Styles} from 'material-ui';

export default

Body:
UPDATE:

material-ui now has Typography component:

<Typography variant="h1" component="h2">
  h1. Heading
</Typography>

Also there are possibilities for typography customizations and utilities to control alignment, wrapping, weight, and more.

OLD ANSWER:

material-ui 1.0 will come with Typography component: usage and API.

You can try it right now by installing material-ui@next:

npm install material-ui@next --save

ContentLicense: CC BY-SA 4.0


问:
Separate long text into pages for viewpager showing blank sometimes

i have long text and i m separating this text into pages but for the first time it shows but second time it showing blank screen..

i have taken code from this link reference link

2.Problem

if i swiped all the pages to Left so sometimes when i swipe right this won't swipe

Why data only showing for the first time and not not thenAfter ...is this Fragment Proble?

codes are below

```<code>public class FeedDetail extends Fragment {
    View view;
    Feeds feeds;
    private ViewPager pagesView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.feed_detail, container, false);

        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bindViews();
    }

    private void bindViews() {

        pagesView = (ViewPager) view.findViewById(R.id.pages);

        Bundle bundle = getArguments();
        if (bundle != null) {
            feeds = (Feeds) bundle.getSerializable("data");
            if (feeds != null) {
                try {
                    pagesView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            PageSplitter pageSplitter = new PageSplitter(pagesView.getWidth(), pagesView.getHeight(), 1, 0);

                            TextPaint textPaint = new TextPaint();
                            textPaint.setTextSize(getResources().getDimension(R.dimen.text_size));
                            pageSplitter.append(feeds.getDescription(), textPaint);
                            pagesView.setAdapter(new TextPagerAdapter(getActivity().getSupportFragmentManager(), pageSplitter.getPages()));
                            pagesView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    });
                } catch (Exception e) {
                    Log.e("catch", e.toString());
                }

            }

        }
</code>```

TextPagerAdapter.class

```<code>public class TextPagerAdapter extends FragmentPagerAdapter {
private final List<CharSequence> pageTexts;

public TextPagerAdapter(FragmentManager fm, List<CharSequence> pageTexts) {
    super(fm);
    this.pageTexts = pageTexts;
}

@Override
public Fragment getItem(int i) {
    return PageFragment.newInstance(pageTexts.get(i));
}

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

}

PagerFragment class

```<code>public class PageFragment extends Fragment {
private final static String PAGE_TEXT = "PAGE_TEXT";

public static PageFragment newInstance(CharSequence pageText) {
    PageFragment frag = new PageFragment();
    Bundle args = new Bundle();
    args.putCharSequence(PAGE_TEXT, pageText);
    frag.setArguments(args);
    return frag;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    CharSequence text = getArguments().getCharSequence(PAGE_TEXT);
    TextView pageView = (TextView) inflater.inflate(R.layout.page, container, false);
    pageView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size));
    pageView.setText(text);
    return pageView;
}
</code>```

}

PageSplitter class

```<code>public class PageSplitter {
private final int pageWidth;
private final int pageHeight;
private final float lineSpacingMultiplier;
private final int lineSpacingExtra;
private final List<CharSequence> pages = new ArrayList<CharSequence>();
private SpannableStringBuilder currentLine = new SpannableStringBuilder();
private SpannableStringBuilder currentPage = new SpannableStringBuilder();
private int currentLineHeight;
private int pageContentHeight;
private int currentLineWidth;
private int textLineHeight;

public PageSplitter(int pageWidth, int pageHeight, float lineSpacingMultiplier, int lineSpacingExtra) {
    this.pageWidth = pageWidth;
    this.pageHeight = pageHeight;
    this.lineSpacingMultiplier = lineSpacingMultiplier;
    this.lineSpacingExtra = lineSpacingExtra;
}

public void append(String text, TextPaint textPaint) {
    textLineHeight = (int) Math.ceil(textPaint.getFontMetrics(null) * lineSpacingMultiplier + lineSpacingExtra);
    String[] paragraphs = text.split("\n", -1);
    int i;
    for (i = 0; i < paragraphs.length - 1; i++) {
        appendText(paragraphs[i], textPaint);
        appendNewLine();
    }
    appendText(paragraphs[i], textPaint);
}

private void appendText(String text, TextPaint textPaint) {
    String[] words = text.split(" ", -1);
    int i;
    for (i = 0; i < words.length - 1; i++) {
        appendWord(words[i] + " ", textPaint);
    }
    appendWord(words[i], textPaint);
}

private void appendNewLine() {
    currentLine.append("\n");
    checkForPageEnd();
    appendLineToPage(textLineHeight);
}

private void checkForPageEnd() {
    if (pageContentHeight + currentLineHeight > pageHeight) {
        pages.add(currentPage);
        currentPage = new SpannableStringBuilder();
        pageContentHeight = 0;
    }
}

private void appendWord(String appendedText, TextPaint textPaint) {
    int textWidth = (int) Math.ceil(textPaint.measureText(appendedText));
    if (currentLineWidth + textWidth >= pageWidth) {
        checkForPageEnd();
        appendLineToPage(textLineHeight);
    }
    appendTextToLine(appendedText, textPaint, textWidth);
}

private void appendLineToPage(int textLineHeight) {
    currentPage.append(currentLine);
    pageContentHeight += currentLineHeight;

    currentLine = new SpannableStringBuilder();
    currentLineHeight = textLineHeight;
    currentLineWidth = 0;
}

private void appendTextToLine(String appendedText, TextPaint textPaint, int textWidth) {
    currentLineHeight = Math.max(currentLineHeight, textLineHeight);
    currentLine.append(renderToSpannable(appendedText, textPaint));
    currentLineWidth += textWidth;
}

public List<CharSequence> getPages() {
    List<CharSequence> copyPages = new ArrayList<CharSequence>(pages);
    SpannableStringBuilder lastPage = new SpannableStringBuilder(currentPage);
    if (pageContentHeight + currentLineHeight > pageHeight) {
        copyPages.add(lastPage);
        lastPage = new SpannableStringBuilder();
    }
    lastPage.append(currentLine);
    copyPages.add(lastPage);
    return copyPages;
}

private SpannableString renderToSpannable(String text, TextPaint textPaint) {
    SpannableString spannable = new SpannableString(text);

    if (textPaint.isFakeBoldText()) {
        spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, spannable.length(), 0);
    }
    return spannable;
}
</code>```

**fragment transaction method

```<code> public void changeFragment(final Fragment fragment, final String fragmenttag) {

    try {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
                fragmentTransaction.replace(R.id.fram, fragment, fragmenttag);
                fragmentTransaction.commit();
                fragmentTransaction.addToBackStack(null);
            }
        }, 50);
    } catch (Exception e) {

    }

}
</code>```

答:
Some remarks

I think you shouldn't do the FragmentManager stuff inside another Thread, because all operations related to set Views need to be handled on MainThread.

Your PageSplitter is not working for me or maybe I just don't understand the concept of your splitting. I thought you want to split a whole text by "\n" and additionally you want to apply some TextPaint. Maybe elaborate what you exactly want to achieve.

working example

This example implements a simple splitting instead of your PageSplitter but I think you get an idea what I proposed to your original question. The SnapCenterListener is just a approach to snap horizontally to a certain item of the RecyclerView, there are probably more advanced implementations.

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

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

    private void initRecycler() {
        RecyclerView recyclerView = findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.addOnScrollListener(new SnapCenterListener());

        PageAdapter adapter = new PageAdapter(splitted());
        recyclerView.setAdapter(adapter);
    }

    private List<String> splitted() {
        String text = data();
        List<String> split = new ArrayList<>(Arrays.asList(text.split("\n", -1)));
        split.removeAll(Arrays.asList("", null));
        return split;
    }

    public class PageAdapter extends RecyclerView.Adapter<PageAdapter.ViewHolder> {
        private List<String> pages;

        PageAdapter(List<String> pages) {
            this.pages = pages;
        }

        @Override
        public PageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            TextView v = (TextView) LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.my_text_view, parent, false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.textView.setText(pages.get(position));
        }

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

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView textView;
            ViewHolder(TextView v) {
                super(v);
                textView = v;
            }
        }
    }

    public class SnapCenterListener extends RecyclerView.OnScrollListener {

        @Override
        public void onScrollStateChanged(RecyclerView rv, int state) {
            super.onScrollStateChanged(rv, state);
            if (state != RecyclerView.SCROLL_STATE_IDLE) return;
            LinearLayoutManager lm = (LinearLayoutManager) rv.getLayoutManager();
            setScroll(rv, lm, lm.getOrientation() == LinearLayoutManager.HORIZONTAL);
        }

        private void setScroll(RecyclerView rv, LinearLayoutManager lm, boolean horizontal) {
            int mid = (horizontal)? rv.getWidth() / 2 : rv.getHeight() / 2;
            int minDistance = Integer.MAX_VALUE;
            int position = 0;
            int result = 0;
            for (int i = lm.findFirstVisibleItemPosition(); i <= lm.findLastVisibleItemPosition(); i++) {
                View view = lm.findViewByPosition(i);
                int difference = getDiff(view, mid, horizontal);
                int distance = Math.abs(difference);
                if (distance < minDistance) {
                    minDistance = distance;
                    result = difference;
                    position = lm.getPosition(view);
                }
            }

            if (position == 0 && result < 0 && result > -5) result = 0;
            if (horizontal) rv.smoothScrollBy(result, 0);
            else rv.smoothScrollBy(0, result);
        }

        private int getDiff(View v, int mid, boolean horizontal) {
            return  (horizontal)? (v.getLeft() + (v.getRight() - v.getLeft()) / 2) - mid :
                    (v.getTop() + (v.getBottom() - v.getTop()) / 2) - mid;
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    }

    private String data() {
        return "What is Lorem Ipsum?\n" +
                "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
                "\n" +
                "Why do we use it?\n" +
                "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\n" +
                "\n" +
                "\n" +
                "Where does it come from?\n" +
                "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.\n" +
                "\n" +
                "The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham." + "What is Lorem Ipsum?\\n\" +\n" +
                "            \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"Why do we use it?\\n\" +\n" +
                "            \"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"Where does it come from?\\n\" +\n" +
                "            \"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \\\"de Finibus Bonorum et Malorum\\\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \\\"Lorem ipsum dolor sit amet..\\\", comes from a line in section 1.10.32.\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.Lorem ipsum dolor sit amet, sit nunc ornare primis, pede tempus nibh libero tortor sodales sed, purus maecenas, ad ornare in enim elit. Mauris metus vehicula luctus. Nisl lectus eu sollicitudin at, lectus rhoncus. Quia consectetuer lorem viverra. Quam malesuada non nunc diam phasellus. Ut aliquet aliquam arcu dolor arcu sit, adipiscing pede eget, arcu sit nullam. Eget congue malesuada ullamcorper dolor curabitur neque. Aliquam dignissim tortor dui, velit tempus sed quisque varius sed wisi. Nulla condimentum elit praesent quam. A potenti, nullam consequat libero massa vestibulum erat, dolor nulla nullam. Enim quis pede adipiscing ullamcorper sit. Mauris fusce mus nam dignissimos.\n" +
                "Id justo magna vel. Fusce ridiculus cum imperdiet, sollicitudin malesuada aliquam mollit augue sollicitudin rhoncus, amet enim tincidunt id pede sociis ligula, in felis velit eu vulputate at integer. Ut vulputate orci magna laoreet torquent morbi, maecenas non quam convallis urna quis aliquam, id duis. Augue sit diam, dolor etiam nulla in eu. Et porta et quisque lacinia, non sed eu montes, pede scelerisque ligula. Eu non sit venenatis purus eleifend nec, est felis, consectetuer lorem hymenaeos, in sed magna nunc. Purus pretium. Condimentum felis, faucibus a diam sollicitudin. Quis erat iaculis, ac cras eget vitae pellentesque, phasellus vel sed eu etiam.\n" +
                "Tempor egestas wisi dignissim, ac sapien ac vel velit nam, proin et lorem, quis felis pede lectus neque, donec magna nonummy nec posuere. Potenti eu felis nullam, dis purus, scelerisque eu orci. Turpis vehicula id, felis ullamcorper elementum in ut ipsum nonummy, ipsum interdum vehicula tellus viverra, enim vitae nulla massa quisque rutrum phasellus, id aut. Tempor viverra elementum massa sit euismod eget. Phasellus eros risus tempor a.\n" +
                "Ipsum at et sem, nec litora ipsum, phasellus elit amet erat, sagittis aliquam. Lorem quisque justo erat sed, convallis sed sodales enim, feugiat egestas pretium dignissim ac in ornare. Ante at, turpis morbi, nunc integer augue feugiat quam, orci bibendum nibh in morbi. Eros convallis dis penatibus ipsum laoreet, fermentum nulla mattis nisl, luctus integer ut, fringilla mollis eget, eget fusce donec in. Erat lorem eleifend habitant eros euismod. Metus et justo libero suscipit faucibus, praesent iaculis urna. Purus montes porta et aenean quis vivamus, ut at non fermentum massa, sed lacinia enim, erat quisque. Commodo amet et porta eu et purus, congue elit taciti nisl parturient, vitae porttitor libero, sem rhoncus viverra morbi commodo vulputate, eleifend vivamus.\n" +
                "+";
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="nice.fontaine.pagesplitter.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

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

my_text_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</TextView>
</code>```

Text size

```<code><dimen name="text_size">14sp</dimen>
</code>```

Body:
i have long text and i m separating this text into pages but for the first time it shows but second time it showing blank screen..

i have taken code from this link reference link

2.Problem

if i swiped all the pages to Left so sometimes when i swipe right this won't swipe

Why data only showing for the first time and not not thenAfter ...is this Fragment Proble?

codes are below

public class FeedDetail extends Fragment {
    View view;
    Feeds feeds;
    private ViewPager pagesView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.feed_detail, container, false);

        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        bindViews();
    }

    private void bindViews() {

        pagesView = (ViewPager) view.findViewById(R.id.pages);

        Bundle bundle = getArguments();
        if (bundle != null) {
            feeds = (Feeds) bundle.getSerializable("data");
            if (feeds != null) {
                try {
                    pagesView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            PageSplitter pageSplitter = new PageSplitter(pagesView.getWidth(), pagesView.getHeight(), 1, 0);

                            TextPaint textPaint = new TextPaint();
                            textPaint.setTextSize(getResources().getDimension(R.dimen.text_size));
                            pageSplitter.append(feeds.getDescription(), textPaint);
                            pagesView.setAdapter(new TextPagerAdapter(getActivity().getSupportFragmentManager(), pageSplitter.getPages()));
                            pagesView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    });
                } catch (Exception e) {
                    Log.e("catch", e.toString());
                }

            }

        }

TextPagerAdapter.class

public class TextPagerAdapter extends FragmentPagerAdapter {
private final List<CharSequence> pageTexts;

public TextPagerAdapter(FragmentManager fm, List<CharSequence> pageTexts) {
    super(fm);
    this.pageTexts = pageTexts;
}

@Override
public Fragment getItem(int i) {
    return PageFragment.newInstance(pageTexts.get(i));
}

@Override
public int getCount() {
    return pageTexts.size();
}

}

PagerFragment class

public class PageFragment extends Fragment {
private final static String PAGE_TEXT = "PAGE_TEXT";

public static PageFragment newInstance(CharSequence pageText) {
    PageFragment frag = new PageFragment();
    Bundle args = new Bundle();
    args.putCharSequence(PAGE_TEXT, pageText);
    frag.setArguments(args);
    return frag;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    CharSequence text = getArguments().getCharSequence(PAGE_TEXT);
    TextView pageView = (TextView) inflater.inflate(R.layout.page, container, false);
    pageView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size));
    pageView.setText(text);
    return pageView;
}

}

PageSplitter class

public class PageSplitter {
private final int pageWidth;
private final int pageHeight;
private final float lineSpacingMultiplier;
private final int lineSpacingExtra;
private final List<CharSequence> pages = new ArrayList<CharSequence>();
private SpannableStringBuilder currentLine = new SpannableStringBuilder();
private SpannableStringBuilder currentPage = new SpannableStringBuilder();
private int currentLineHeight;
private int pageContentHeight;
private int currentLineWidth;
private int textLineHeight;

public PageSplitter(int pageWidth, int pageHeight, float lineSpacingMultiplier, int lineSpacingExtra) {
    this.pageWidth = pageWidth;
    this.pageHeight = pageHeight;
    this.lineSpacingMultiplier = lineSpacingMultiplier;
    this.lineSpacingExtra = lineSpacingExtra;
}

public void append(String text, TextPaint textPaint) {
    textLineHeight = (int) Math.ceil(textPaint.getFontMetrics(null) * lineSpacingMultiplier + lineSpacingExtra);
    String[] paragraphs = text.split("\n", -1);
    int i;
    for (i = 0; i < paragraphs.length - 1; i++) {
        appendText(paragraphs[i], textPaint);
        appendNewLine();
    }
    appendText(paragraphs[i], textPaint);
}

private void appendText(String text, TextPaint textPaint) {
    String[] words = text.split(" ", -1);
    int i;
    for (i = 0; i < words.length - 1; i++) {
        appendWord(words[i] + " ", textPaint);
    }
    appendWord(words[i], textPaint);
}

private void appendNewLine() {
    currentLine.append("\n");
    checkForPageEnd();
    appendLineToPage(textLineHeight);
}

private void checkForPageEnd() {
    if (pageContentHeight + currentLineHeight > pageHeight) {
        pages.add(currentPage);
        currentPage = new SpannableStringBuilder();
        pageContentHeight = 0;
    }
}

private void appendWord(String appendedText, TextPaint textPaint) {
    int textWidth = (int) Math.ceil(textPaint.measureText(appendedText));
    if (currentLineWidth + textWidth >= pageWidth) {
        checkForPageEnd();
        appendLineToPage(textLineHeight);
    }
    appendTextToLine(appendedText, textPaint, textWidth);
}

private void appendLineToPage(int textLineHeight) {
    currentPage.append(currentLine);
    pageContentHeight += currentLineHeight;

    currentLine = new SpannableStringBuilder();
    currentLineHeight = textLineHeight;
    currentLineWidth = 0;
}

private void appendTextToLine(String appendedText, TextPaint textPaint, int textWidth) {
    currentLineHeight = Math.max(currentLineHeight, textLineHeight);
    currentLine.append(renderToSpannable(appendedText, textPaint));
    currentLineWidth += textWidth;
}

public List<CharSequence> getPages() {
    List<CharSequence> copyPages = new ArrayList<CharSequence>(pages);
    SpannableStringBuilder lastPage = new SpannableStringBuilder(currentPage);
    if (pageContentHeight + currentLineHeight > pageHeight) {
        copyPages.add(lastPage);
        lastPage = new SpannableStringBuilder();
    }
    lastPage.append(currentLine);
    copyPages.add(lastPage);
    return copyPages;
}

private SpannableString renderToSpannable(String text, TextPaint textPaint) {
    SpannableString spannable = new SpannableString(text);

    if (textPaint.isFakeBoldText()) {
        spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, spannable.length(), 0);
    }
    return spannable;
}

**fragment transaction method

 public void changeFragment(final Fragment fragment, final String fragmenttag) {

    try {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
                fragmentTransaction.replace(R.id.fram, fragment, fragmenttag);
                fragmentTransaction.commit();
                fragmentTransaction.addToBackStack(null);
            }
        }, 50);
    } catch (Exception e) {

    }

}

Body:
Some remarks

I think you shouldn't do the FragmentManager stuff inside another Thread, because all operations related to set Views need to be handled on MainThread.

Your PageSplitter is not working for me or maybe I just don't understand the concept of your splitting. I thought you want to split a whole text by "\n" and additionally you want to apply some TextPaint. Maybe elaborate what you exactly want to achieve.

working example

This example implements a simple splitting instead of your PageSplitter but I think you get an idea what I proposed to your original question. The SnapCenterListener is just a approach to snap horizontally to a certain item of the RecyclerView, there are probably more advanced implementations.

public class MainActivity extends AppCompatActivity {

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

    private void initRecycler() {
        RecyclerView recyclerView = findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.addOnScrollListener(new SnapCenterListener());

        PageAdapter adapter = new PageAdapter(splitted());
        recyclerView.setAdapter(adapter);
    }

    private List<String> splitted() {
        String text = data();
        List<String> split = new ArrayList<>(Arrays.asList(text.split("\n", -1)));
        split.removeAll(Arrays.asList("", null));
        return split;
    }

    public class PageAdapter extends RecyclerView.Adapter<PageAdapter.ViewHolder> {
        private List<String> pages;

        PageAdapter(List<String> pages) {
            this.pages = pages;
        }

        @Override
        public PageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            TextView v = (TextView) LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.my_text_view, parent, false);
            return new ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.textView.setText(pages.get(position));
        }

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

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView textView;
            ViewHolder(TextView v) {
                super(v);
                textView = v;
            }
        }
    }

    public class SnapCenterListener extends RecyclerView.OnScrollListener {

        @Override
        public void onScrollStateChanged(RecyclerView rv, int state) {
            super.onScrollStateChanged(rv, state);
            if (state != RecyclerView.SCROLL_STATE_IDLE) return;
            LinearLayoutManager lm = (LinearLayoutManager) rv.getLayoutManager();
            setScroll(rv, lm, lm.getOrientation() == LinearLayoutManager.HORIZONTAL);
        }

        private void setScroll(RecyclerView rv, LinearLayoutManager lm, boolean horizontal) {
            int mid = (horizontal)? rv.getWidth() / 2 : rv.getHeight() / 2;
            int minDistance = Integer.MAX_VALUE;
            int position = 0;
            int result = 0;
            for (int i = lm.findFirstVisibleItemPosition(); i <= lm.findLastVisibleItemPosition(); i++) {
                View view = lm.findViewByPosition(i);
                int difference = getDiff(view, mid, horizontal);
                int distance = Math.abs(difference);
                if (distance < minDistance) {
                    minDistance = distance;
                    result = difference;
                    position = lm.getPosition(view);
                }
            }

            if (position == 0 && result < 0 && result > -5) result = 0;
            if (horizontal) rv.smoothScrollBy(result, 0);
            else rv.smoothScrollBy(0, result);
        }

        private int getDiff(View v, int mid, boolean horizontal) {
            return  (horizontal)? (v.getLeft() + (v.getRight() - v.getLeft()) / 2) - mid :
                    (v.getTop() + (v.getBottom() - v.getTop()) / 2) - mid;
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    }

    private String data() {
        return "What is Lorem Ipsum?\n" +
                "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n" +
                "\n" +
                "Why do we use it?\n" +
                "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\n" +
                "\n" +
                "\n" +
                "Where does it come from?\n" +
                "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.\n" +
                "\n" +
                "The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham." + "What is Lorem Ipsum?\\n\" +\n" +
                "            \"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"Why do we use it?\\n\" +\n" +
                "            \"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"Where does it come from?\\n\" +\n" +
                "            \"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \\\"de Finibus Bonorum et Malorum\\\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \\\"Lorem ipsum dolor sit amet..\\\", comes from a line in section 1.10.32.\\n\" +\n" +
                "            \"\\n\" +\n" +
                "            \"The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.Lorem ipsum dolor sit amet, sit nunc ornare primis, pede tempus nibh libero tortor sodales sed, purus maecenas, ad ornare in enim elit. Mauris metus vehicula luctus. Nisl lectus eu sollicitudin at, lectus rhoncus. Quia consectetuer lorem viverra. Quam malesuada non nunc diam phasellus. Ut aliquet aliquam arcu dolor arcu sit, adipiscing pede eget, arcu sit nullam. Eget congue malesuada ullamcorper dolor curabitur neque. Aliquam dignissim tortor dui, velit tempus sed quisque varius sed wisi. Nulla condimentum elit praesent quam. A potenti, nullam consequat libero massa vestibulum erat, dolor nulla nullam. Enim quis pede adipiscing ullamcorper sit. Mauris fusce mus nam dignissimos.\n" +
                "Id justo magna vel. Fusce ridiculus cum imperdiet, sollicitudin malesuada aliquam mollit augue sollicitudin rhoncus, amet enim tincidunt id pede sociis ligula, in felis velit eu vulputate at integer. Ut vulputate orci magna laoreet torquent morbi, maecenas non quam convallis urna quis aliquam, id duis. Augue sit diam, dolor etiam nulla in eu. Et porta et quisque lacinia, non sed eu montes, pede scelerisque ligula. Eu non sit venenatis purus eleifend nec, est felis, consectetuer lorem hymenaeos, in sed magna nunc. Purus pretium. Condimentum felis, faucibus a diam sollicitudin. Quis erat iaculis, ac cras eget vitae pellentesque, phasellus vel sed eu etiam.\n" +
                "Tempor egestas wisi dignissim, ac sapien ac vel velit nam, proin et lorem, quis felis pede lectus neque, donec magna nonummy nec posuere. Potenti eu felis nullam, dis purus, scelerisque eu orci. Turpis vehicula id, felis ullamcorper elementum in ut ipsum nonummy, ipsum interdum vehicula tellus viverra, enim vitae nulla massa quisque rutrum phasellus, id aut. Tempor viverra elementum massa sit euismod eget. Phasellus eros risus tempor a.\n" +
                "Ipsum at et sem, nec litora ipsum, phasellus elit amet erat, sagittis aliquam. Lorem quisque justo erat sed, convallis sed sodales enim, feugiat egestas pretium dignissim ac in ornare. Ante at, turpis morbi, nunc integer augue feugiat quam, orci bibendum nibh in morbi. Eros convallis dis penatibus ipsum laoreet, fermentum nulla mattis nisl, luctus integer ut, fringilla mollis eget, eget fusce donec in. Erat lorem eleifend habitant eros euismod. Metus et justo libero suscipit faucibus, praesent iaculis urna. Purus montes porta et aenean quis vivamus, ut at non fermentum massa, sed lacinia enim, erat quisque. Commodo amet et porta eu et purus, congue elit taciti nisl parturient, vitae porttitor libero, sem rhoncus viverra morbi commodo vulputate, eleifend vivamus.\n" +
                "+";
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="nice.fontaine.pagesplitter.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

my_text_view.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</TextView>

Text size

<dimen name="text_size">14sp</dimen>


问:
Navigation Bar and Sliding Tab xamarin android
I want to make a Navigation Bar and Sliding Tab with Fragments in xamarin android. That when you open its Drawer and click a Text inside its drawer it will open a new layout or Fragment. Same in Sliding Tab.

Any Tutorials or File that i can debug. I really want to Learn.

A drawer Like this one:

A Sliding Tab like this:

I'm Pretty new so i would really appreciate the help.

Thanks in Advance!

答:
The Easiest way to do it would be like this :

Navigation Drawer:

http://www.c-sharpcorner.com/article/xamarin-android-create-left-drawer-layout/

http://www.c-sharpcorner.com/article/xamarin-android-create-android-navigation-drawer-layout-using-support-design/

Sliding tab :

http://camposha.info/source/xamarin-android-swipe-tabs-viewpager-fragments-images-actionbartabs/

http://www.c-sharpcorner.com/article/creating-sliding-tab-layout-interface-using-xamarin-android-using-visual-studio/

The code is in xamarin so it would be an easy implementation for you!
Goodluck!


问:
How i can split array in js?
How i can split string in js for result:

```<code>result = ["post_address", "location", "area"]
</code>```

This is problem? Need help with re

```<code>let re = ???
let arr = "post_address[location][area]".split(re)
</code>```

答:
There is the shorter way

It is actually the same as

```<code>'post_address[location][area]'.split(/[^\w]+/).filter(i => i)
</code>```

console.log(
    'post_address[location][area]'.match(/(\w+)/g)
);

console.log(
    'post_address[location][area]'.split(/[^\w]+/).filter(i => i)
);```

Title: How i can split array in js?

Body:
How i can split string in js for result:

result = ["post_address", "location", "area"]

This is problem? Need help with re

let re = ???
let arr = "post_address[location][area]".split(re)

Body:
There is the shorter way

It is actually the same as

'post_address[location][area]'.split(/[^\w]+/).filter(i => i)

console.log(
    'post_address[location][area]'.match(/(\w+)/g)
);

console.log(
    'post_address[location][area]'.split(/[^\w]+/).filter(i => i)
);


问:
CSV parse using aws athena
I am parsing csv file using AWS athena from java code.
Some columns  in csv are of date type and one column has comma in the value.

If  the athena table is created with

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'

then it is unable to parse the column with comma correctly

However it parses correctly if I use

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'

But the issue with OpenCSVSerde is that it requires all columns to be of string data type and I need to carry out date operations in the query so can't use OpenCSVSerde.

Any other solution?
Please help!

答:
That's how this two SerDes are designed, you should only use the LazySimpleSerDe in cases when your data is relatively clean, for example, it does not have values enclosed in quotes or does not have delimiters in the value. And OpenCSVSerde works well for deserializing CSV files that have values enclosed in quotes; however, all columns in the table are of STRING data type. More info here

So in your case, as your data is not clean, the only way to parse it and have loaded into Athena is to use OpenCSVSerde. And if you need to use date operations you need to manually convert/parse the date strings into a date object, which is fairly easy to do with date_parse function.

So say if you have following string data in your date type column:

```<code>11/13/2017
11/14/2017
11/15/2017
11/16/2017
</code>```

You can use the following query to select date in the range

```<code>select * from somedb.sometable where date_parse(createdate, '%m/%d/%Y') between DATE'2017-11-14' and DATE'2017-11-16';
</code>```

Title: CSV parse using aws athena

Body:
That's how this two SerDes are designed, you should only use the LazySimpleSerDe in cases when your data is relatively clean, for example, it does not have values enclosed in quotes or does not have delimiters in the value. And OpenCSVSerde works well for deserializing CSV files that have values enclosed in quotes; however, all columns in the table are of STRING data type. More info here

So in your case, as your data is not clean, the only way to parse it and have loaded into Athena is to use OpenCSVSerde. And if you need to use date operations you need to manually convert/parse the date strings into a date object, which is fairly easy to do with date_parse function.

So say if you have following string data in your date type column:

11/13/2017
11/14/2017
11/15/2017
11/16/2017

You can use the following query to select date in the range

select * from somedb.sometable where date_parse(createdate, '%m/%d/%Y') between DATE'2017-11-14' and DATE'2017-11-16';


问:
Why are only final variables accessible in anonymous class?

a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

        }
    });
}
</code>```

How can I return the 5 * a when it clicked? I mean,

```<code>private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}
</code>```

答:
You can create a class level variable to get returned value. I mean

```<code>class A {
    int k = 0;
    private void f(Button b, int a){
        b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            k = a * 5;
        }
    });
}
</code>```

now you can get value of K and use it where you want.

Answer of your why is :

A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).

Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)

Body:
a can only be final here.  Why?  How can I reassign a in onClick() method without keeping it as private member?

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            int b = a*5;

        }
    });
}

How can I return the 5 * a when it clicked? I mean,

private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             return b; // but return type is void
        }
    });
}

Body:
You can create a class level variable to get returned value. I mean

class A {
    int k = 0;
    private void f(Button b, int a){
        b.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            k = a * 5;
        }
    });
}

now you can get value of K and use it where you want.

Answer of your why is :

A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).

Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)


问:
How to use javascript promises ES6 instead of jQuery ajax call?
I was trying to understand how promises works in javascript but I didn't found clear info about this, I would like to know if it possible and it is so how to do this using promises instead this code (equivalent)

```<code>$.ajax({
    type: 'post',
    cache: false,
    url: 'myfile.php',
    data: { info: info },
    datatype: 'json',

    success: function(response) {
        console.log(response);
    }
});
</code>```

I ask this because I want to use only javascript without any framework or plugins, I have no problem with the other new feautures of ES6 just with this one, I hope you can help me, thanks.

答:
You have to wrap your ajax call with a function that instantiates and returns a promise:

function getSomething() {
  return new Promise((resolve, reject) => {
    $.ajax({
        type: 'post',
        cache: false,
        url: 'myfile.php',
        data: { info: info },
        datatype: 'json',
        success: function(response) {
            resolve(response);
        },
        error: function() {
            reject("some errors");
        }
    });
  });
}```
</div>
</div>
</p>

<p>Then you consume your promise like below:</p>

```getSomething()
    .then(response => console.log(response))
    .catch(err => console.log(err));
```

Body:
I was trying to understand how promises works in javascript but I didn't found clear info about this, I would like to know if it possible and it is so how to do this using promises instead this code (equivalent)

$.ajax({
    type: 'post',
    cache: false,
    url: 'myfile.php',
    data: { info: info },
    datatype: 'json',

    success: function(response) {
        console.log(response);
    }
});

I ask this because I want to use only javascript without any framework or plugins, I have no problem with the other new feautures of ES6 just with this one, I hope you can help me, thanks.

Body:
You have to wrap your ajax call with a function that instantiates and returns a promise:

function getSomething() {
  return new Promise((resolve, reject) => {
    $.ajax({
        type: 'post',
        cache: false,
        url: 'myfile.php',
        data: { info: info },
        datatype: 'json',
        success: function(response) {
            resolve(response);
        },
        error: function() {
            reject("some errors");
        }
    });
  });
}

Then you consume your promise like below:

getSomething()
    .then(response => console.log(response))
    .catch(err => console.log(err));


问:
React App Crashes When Deployed to Heroku
I just deployed my React app to Heroku and while the deployment was successful, the ap crashes and I get an Application Error on the screen. I ran Heroku Logs and it returned this error:

```<code>at=error code=H10 desc="App crashed" method=GET path="/" host=quoriron-
client-app.herokuapp.com request_id=fe82d878-75ce-47b2-a726-
513725e679f2 fwd="65.209.61.114" dyno= connect= service= status=503
bytes= protocol=https
</code>```

Other people have had that error with Node apps and it's seems to usually be an issue with setting the port, but from my understanding the port isn't set the same way in React (or if that's even the problem).

How can I prevent my React app from crashing because of this error?

答:
First sorry for reply this as an answer while it should be a comment...

How did you deploy the React app to Heroku?? Did you use their zero configuration for React apps or did you created your own Node.js that serve the react app?

Also you'll need to add the correctly buildpack to the project.

Body:
I just deployed my React app to Heroku and while the deployment was successful, the ap crashes and I get an Application Error on the screen. I ran Heroku Logs and it returned this error:

at=error code=H10 desc="App crashed" method=GET path="/" host=quoriron-
client-app.herokuapp.com request_id=fe82d878-75ce-47b2-a726-
513725e679f2 fwd="65.209.61.114" dyno= connect= service= status=503
bytes= protocol=https

Other people have had that error with Node apps and it's seems to usually be an issue with setting the port, but from my understanding the port isn't set the same way in React (or if that's even the problem).

How can I prevent my React app from crashing because of this error?


问:
WCF web service returning json format data
I have created a WCF webservice returning json format data. My code is like below:

```<code>String sJSONdata = "";

StreamReader reader = new StreamReader(data);
sJSONdata = reader.ReadToEnd();

//'now convert the JSON into a data table
DataTable dt = GetJSONTable(sJSONdata);
dt.TableName = "Customer";

Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (DataRow rs in dt.Rows)
{
    dict = new Dictionary<string, string>();
    foreach (DataColumn col in dt.Columns)
    {
        dict.Add(col.ColumnName, rs[col].ToString());
    }
}
return (new JavaScriptSerializer().Serialize(dict));
</code>```

And I get the following output:

{ "SampleServiceResult":
  "{\"Id\":\"1\",\"Name\":\"xyz\",\"email\":\"xya@test.com\"}" }

But I want the output as below:

{ "SampleServiceResult":
  {"Id":"1","Name":"xyz","email":"xya@test.com"} }

In the output it adds "\" escape character. How can I remove this and return valid json?

I have tried to replace "\" but it doesn't work.

Thanks

答:
I have got the expected out by applying following changes in my code:

Changed return type from String to Stream

Replaced the below code

return (new JavaScriptSerializer().Serialize(dict));

with

WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(sData));

Thanks everybody for help and support. May it will help someone.

Body:
I have created a WCF webservice returning json format data. My code is like below:

String sJSONdata = "";

StreamReader reader = new StreamReader(data);
sJSONdata = reader.ReadToEnd();

//'now convert the JSON into a data table
DataTable dt = GetJSONTable(sJSONdata);
dt.TableName = "Customer";

Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (DataRow rs in dt.Rows)
{
    dict = new Dictionary<string, string>();
    foreach (DataColumn col in dt.Columns)
    {
        dict.Add(col.ColumnName, rs[col].ToString());
    }
}
return (new JavaScriptSerializer().Serialize(dict));

And I get the following output:

{ "SampleServiceResult":
  "{\"Id\":\"1\",\"Name\":\"xyz\",\"email\":\"xya@test.com\"}" }

But I want the output as below:

{ "SampleServiceResult":
  {"Id":"1","Name":"xyz","email":"xya@test.com"} }

In the output it adds "\" escape character. How can I remove this and return valid json?

I have tried to replace "\" but it doesn't work.

Thanks


问:
Typescript Promise not generic after Version update?
Iam bit confused and could use some help before I deconstruct my whole app again.

I updated my Angular 4 App to Angular 5. And set the Typescript version to 2.4.2
Now my IDEA Editor says "Type Promise is not generic" on such lines e.g.:

```<code>putUserRegister(user: User): Promise<User>
  {...
</code>```

Iam using es5 and it compiles (besides the outdated fullcalendar-another problem).

Do someone know where it comes from and/or how to get rid of it?

Thanks in advance!
Gregor

答:
Using promises can be dependent on your target JavaScript version.

You should be able to solve your problem by targeting a later version:

```<code>{
    "compilerOptions": {
      "target": "ESNext", // <-- Later ES version
      "module": "amd",
      "strict": true,
      "noImplicitAny": true,
      "allowJs": true,
      "sourceMap": true,
      "allowSyntheticDefaultImports": false,
      "moduleResolution": "node",
      "noUnusedLocals": true,
      "noUnusedParameters": false,
      "preserveConstEnums": false,
      "removeComments": false
    },
    "exclude": [
      "node_modules",
      "test",
      ".git"
    ]
}
</code>```

Or by configuring your library includes. Example:

```<code>{
    "compilerOptions": {
      "target": "ES5", // <-- ES5
      "module": "amd",
      "strict": true,
      "noImplicitAny": true,
      "allowJs": true,
      "sourceMap": true,
      "allowSyntheticDefaultImports": false,
      "moduleResolution": "node",
      "noUnusedLocals": true,
      "noUnusedParameters": false,
      "preserveConstEnums": false,
      "removeComments": false,
      "lib": [ // <-- lib config
        "es5",
        "es6",
        "dom",
        "es2015.core",
        "es2015.collection",
        "es2015.generator",
        "es2015.iterable",
        "es2015.promise",
        "es2015.proxy",
        "es2015.reflect",
        "es2015.symbol",
        "es2015.symbol.wellknown",
        "esnext.asynciterable"
      ]
    },
    "exclude": [
      "node_modules",
      "test",
      ".git"
    ]
  }
</code>```

Body:
Iam bit confused and could use some help before I deconstruct my whole app again.

I updated my Angular 4 App to Angular 5. And set the Typescript version to 2.4.2
Now my IDEA Editor says "Type Promise is not generic" on such lines e.g.:

putUserRegister(user: User): Promise<User>
  {...

Iam using es5 and it compiles (besides the outdated fullcalendar-another problem).

Do someone know where it comes from and/or how to get rid of it?

Thanks in advance!
Gregor

Body:
Using promises can be dependent on your target JavaScript version.

You should be able to solve your problem by targeting a later version:

{
    "compilerOptions": {
      "target": "ESNext", // <-- Later ES version
      "module": "amd",
      "strict": true,
      "noImplicitAny": true,
      "allowJs": true,
      "sourceMap": true,
      "allowSyntheticDefaultImports": false,
      "moduleResolution": "node",
      "noUnusedLocals": true,
      "noUnusedParameters": false,
      "preserveConstEnums": false,
      "removeComments": false
    },
    "exclude": [
      "node_modules",
      "test",
      ".git"
    ]
}

Or by configuring your library includes. Example:

{
    "compilerOptions": {
      "target": "ES5", // <-- ES5
      "module": "amd",
      "strict": true,
      "noImplicitAny": true,
      "allowJs": true,
      "sourceMap": true,
      "allowSyntheticDefaultImports": false,
      "moduleResolution": "node",
      "noUnusedLocals": true,
      "noUnusedParameters": false,
      "preserveConstEnums": false,
      "removeComments": false,
      "lib": [ // <-- lib config
        "es5",
        "es6",
        "dom",
        "es2015.core",
        "es2015.collection",
        "es2015.generator",
        "es2015.iterable",
        "es2015.promise",
        "es2015.proxy",
        "es2015.reflect",
        "es2015.symbol",
        "es2015.symbol.wellknown",
        "esnext.asynciterable"
      ]
    },
    "exclude": [
      "node_modules",
      "test",
      ".git"
    ]
  }


问:
How to change color of bootstrap glyphicon .?
How do I change the color of my star glyphicon? My code is

```<code><span  class="glyphicon glyphicon-star-empty " onclick = "addToFav()">      </span>
</code>```

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.

答: If I understand the question correctly, you want to change the star from a black outline to a filled yellow star? If so, then you'll need to change not just the style to set the color, but you'll also need to replace the class glyphicon-star-empty with the class glyphicon-star.

Body:
How do I change the color of my star glyphicon? My code is

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.


问:
generative adversarial network generating image with some random pixels
I am trying to generate images using Generative Adversarial Networks(GANs) on CelebA aligned data set with each image resized to 64*64 in .jpeg format. My network definition is like this

```<code>def my_discriminator(input_var= None):
    net = lasagne.layers.InputLayer(shape= (None, 3,64,64), input_var = input_var)
    net = lasagne.layers.Conv2DLayer(net, 64, filter_size= (6,6 ),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#64*32*32
    net = lasagne.layers.Conv2DLayer(net, 128, filter_size= (6,6),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#128*16*16
    net = lasagne.layers.Conv2DLayer(net, 256, filter_size= (6,6),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#256*8*8
    net = lasagne.layers.Conv2DLayer(net, 512, filter_size= (6,6),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#512*4*4
    net = lasagne.layers.DenseLayer(net, 2048, W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))
    net = lasagne.layers.DenseLayer(net, 1, nonlinearity = lasagne.nonlinearities.sigmoid)

def my_generator(input_var=None):
    gen_net = lasagne.layers.InputLayer(shape = (None, 100), input_var = input_var)
    gen_net = lasagne.layers.DenseLayer(gen_net, 2048, W= lasagne.init.HeUniform())
    gen_net = lasagne.layers.DenseLayer(gen_net, 512*4*4, W= lasagne.init.HeUniform())
    gen_net = lasagne.layers.ReshapeLayer(gen_net, shape = ([0],512,4,4))
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 256,filter_size= (6,6),stride = 2,crop=2, W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.rectify)
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 128,filter_size= (6,6),stride = 2,crop=2, W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.rectify)
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 64, filter_size= (6,6), stride=2,crop=2,W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.rectify)
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 3, filter_size= (6,6),stride = 2,crop=2, nonlinearity= lasagne.nonlinearities.tanh)
</code>```

With the images generated by generator, I am getting some randomly colored pixels and also a "grid" like structure in them as can be seen in the example image:

My question is what are the reasons for these two problems, I also used almost the same architecture with one less Convolution layer in Generator and Discriminator on Cifar-10 datset with 32*32 resolution images in .png format, but there the generated images were not like this. Not sure if the image format could be the reason. I would be very thankful if someone could provide some ideas or ways or links, anything to get rid of such issues.

答:
The reasons for these problems were:-

Random pixels- Normalization of the image data must be in accordance with the activation function of the last layer of the Generator [-1,1] -> tanh

"Grid" in generated images- The way each image's dimensions were changed. So should use 'transpose' function instead of 'reshape', to convert (64,64,3)->(3,64,64)

Body:
I am trying to generate images using Generative Adversarial Networks(GANs) on CelebA aligned data set with each image resized to 64*64 in .jpeg format. My network definition is like this

def my_discriminator(input_var= None):
    net = lasagne.layers.InputLayer(shape= (None, 3,64,64), input_var = input_var)
    net = lasagne.layers.Conv2DLayer(net, 64, filter_size= (6,6 ),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#64*32*32
    net = lasagne.layers.Conv2DLayer(net, 128, filter_size= (6,6),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#128*16*16
    net = lasagne.layers.Conv2DLayer(net, 256, filter_size= (6,6),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#256*8*8
    net = lasagne.layers.Conv2DLayer(net, 512, filter_size= (6,6),stride = 2,pad=2,W = lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))#512*4*4
    net = lasagne.layers.DenseLayer(net, 2048, W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.LeakyRectify(0.2))
    net = lasagne.layers.DenseLayer(net, 1, nonlinearity = lasagne.nonlinearities.sigmoid)

def my_generator(input_var=None):
    gen_net = lasagne.layers.InputLayer(shape = (None, 100), input_var = input_var)
    gen_net = lasagne.layers.DenseLayer(gen_net, 2048, W= lasagne.init.HeUniform())
    gen_net = lasagne.layers.DenseLayer(gen_net, 512*4*4, W= lasagne.init.HeUniform())
    gen_net = lasagne.layers.ReshapeLayer(gen_net, shape = ([0],512,4,4))
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 256,filter_size= (6,6),stride = 2,crop=2, W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.rectify)
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 128,filter_size= (6,6),stride = 2,crop=2, W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.rectify)
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 64, filter_size= (6,6), stride=2,crop=2,W= lasagne.init.HeUniform(), nonlinearity= lasagne.nonlinearities.rectify)
    gen_net = lasagne.layers.Deconv2DLayer(gen_net, 3, filter_size= (6,6),stride = 2,crop=2, nonlinearity= lasagne.nonlinearities.tanh)

With the images generated by generator, I am getting some randomly colored pixels and also a "grid" like structure in them as can be seen in the example image:

My question is what are the reasons for these two problems, I also used almost the same architecture with one less Convolution layer in Generator and Discriminator on Cifar-10 datset with 32*32 resolution images in .png format, but there the generated images were not like this. Not sure if the image format could be the reason. I would be very thankful if someone could provide some ideas or ways or links, anything to get rid of such issues.


答:
As noted in comments, some of this becomes irrelevant in Java 8, where final can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.

It's basically due to the way Java manages closures.

When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)

As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.

Making the variable final removes all these possibilities - as the value can't be changed  at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.

If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)

Title: Why are only final variables accessible in anonymous class?


问:
Cannot install node-sass dependancy
I try to install all dependencies in the project Ive cloned from repo but it fails on node-sass. I use OS Ubuntu 14.04.
This is an error log Ive received:

(

```<code>node) child_process: options.customFds option is deprecated. Use options.stdio instead.
make: Entering directory `/home/maras/Documents/eCodile/debtorcare/client/node_modules/gulp-sass/node_modules/node-sass/build'
  CXX(target) Release/obj.target/binding/binding.o
In file included from ../binding.cpp:7:0:
../sass_context_wrapper.h:10:3: error: ‘uv_work_t’ does not name a type
   uv_work_t request;
   ^
../sass_context_wrapper.h:20:3: error: ‘uv_work_t’ does not name a type
   uv_work_t request;
   ^
../binding.cpp:13:20: error: variable or field ‘WorkOnContext’ declared void
 void WorkOnContext(uv_work_t* req) {
                    ^
../binding.cpp:13:20: error: ‘uv_work_t’ was not declared in this scope
../binding.cpp:13:31: error: ‘req’ was not declared in this scope
 void WorkOnContext(uv_work_t* req) {
                               ^
../binding.cpp:19:22: error: variable or field ‘MakeOldCallback’ declared void
 void MakeOldCallback(uv_work_t* req) {
                      ^
../binding.cpp:19:22: error: ‘uv_work_t’ was not declared in this scope
../binding.cpp:19:33: error: ‘req’ was not declared in this scope
 void MakeOldCallback(uv_work_t* req) {
                                 ^
make: *** [Release/obj.target/binding/binding.o] Error 1
make: Leaving directory `/home/maras/Documents/eCodile/debtorcare/client/node_modules/gulp-sass/node_modules/node-sass/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/maras/.nvm/versions/node/v5.5.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:100:13)
gyp ERR! stack     at ChildProcess.emit (events.js:185:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 3.19.0-58-generic
gyp ERR! command "/home/maras/.nvm/versions/node/v5.5.0/bin/node" "/home/maras/.nvm/versions/node/v5.5.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/maras/Documents/eCodile/debtorcare/client/node_modules/gulp-sass/node_modules/node-sass
gyp ERR! node -v v5.5.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
Build failed
Debtorcare@0.0.0 /home/maras/Documents/eCodile/debtorcare/client
├─┬ gulp-jade@0.3.0
│ └─┬ event-stream@3.0.20
│   ├── map-stream@0.0.6
│   └── split@0.2.10
└─┬ gulp-uglify@0.1.0
  ├── clone@0.1.19
  └─┬ event-stream@3.0.20
    ├── map-stream@0.0.6
    └── split@0.2.10

npm WARN EPACKAGEJSON Debtorcare@0.0.0 No description
npm WARN EPACKAGEJSON Debtorcare@0.0.0 No repository field.
npm WARN EPACKAGEJSON Debtorcare@0.0.0 No license field.
npm ERR! Linux 3.19.0-58-generic
npm ERR! argv "/home/maras/.nvm/versions/node/v5.5.0/bin/node" "/home/maras/.nvm/versions/node/v5.5.0/bin/npm" "install"
npm ERR! node v5.5.0
npm ERR! npm  v3.3.12
npm ERR! code ELIFECYCLE

npm ERR! node-sass@0.7.0 install: `node build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@0.7.0 install script 'node build.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node build.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/maras/Documents/eCodile/debtorcare/client/npm-debug.log
</code>```

I tried to remove .node_modules file , restart etc but It didnt work. Has anyone any ideas what could be wrong here?

答:
I am into the same error and along, I am maintaining multiple versions node using NVM, I resolved this using the following commands,

Clear the cache, using the following command,

```<code>npm cache clear --force
</code>```

Install node-sass dependencies using,

```<code>npm install --save-dev node-sass --unsafe-perm
</code>```

Rebuilds node-sass but only if needed,

```<code>npm rebuild node-sass --unsafe-perm
</code>```

Then, I could make my build successful. Hope this helps.

Title: Cannot install node-sass dependancy

Body:
I try to install all dependencies in the project Ive cloned from repo but it fails on node-sass. I use OS Ubuntu 14.04.
This is an error log Ive received:

(

node) child_process: options.customFds option is deprecated. Use options.stdio instead.
make: Entering directory `/home/maras/Documents/eCodile/debtorcare/client/node_modules/gulp-sass/node_modules/node-sass/build'
  CXX(target) Release/obj.target/binding/binding.o
In file included from ../binding.cpp:7:0:
../sass_context_wrapper.h:10:3: error: ‘uv_work_t’ does not name a type
   uv_work_t request;
   ^
../sass_context_wrapper.h:20:3: error: ‘uv_work_t’ does not name a type
   uv_work_t request;
   ^
../binding.cpp:13:20: error: variable or field ‘WorkOnContext’ declared void
 void WorkOnContext(uv_work_t* req) {
                    ^
../binding.cpp:13:20: error: ‘uv_work_t’ was not declared in this scope
../binding.cpp:13:31: error: ‘req’ was not declared in this scope
 void WorkOnContext(uv_work_t* req) {
                               ^
../binding.cpp:19:22: error: variable or field ‘MakeOldCallback’ declared void
 void MakeOldCallback(uv_work_t* req) {
                      ^
../binding.cpp:19:22: error: ‘uv_work_t’ was not declared in this scope
../binding.cpp:19:33: error: ‘req’ was not declared in this scope
 void MakeOldCallback(uv_work_t* req) {
                                 ^
make: *** [Release/obj.target/binding/binding.o] Error 1
make: Leaving directory `/home/maras/Documents/eCodile/debtorcare/client/node_modules/gulp-sass/node_modules/node-sass/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/maras/.nvm/versions/node/v5.5.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:100:13)
gyp ERR! stack     at ChildProcess.emit (events.js:185:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 3.19.0-58-generic
gyp ERR! command "/home/maras/.nvm/versions/node/v5.5.0/bin/node" "/home/maras/.nvm/versions/node/v5.5.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/maras/Documents/eCodile/debtorcare/client/node_modules/gulp-sass/node_modules/node-sass
gyp ERR! node -v v5.5.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
Build failed
Debtorcare@0.0.0 /home/maras/Documents/eCodile/debtorcare/client
├─┬ gulp-jade@0.3.0
│ └─┬ event-stream@3.0.20
│   ├── map-stream@0.0.6
│   └── split@0.2.10
└─┬ gulp-uglify@0.1.0
  ├── clone@0.1.19
  └─┬ event-stream@3.0.20
    ├── map-stream@0.0.6
    └── split@0.2.10

npm WARN EPACKAGEJSON Debtorcare@0.0.0 No description
npm WARN EPACKAGEJSON Debtorcare@0.0.0 No repository field.
npm WARN EPACKAGEJSON Debtorcare@0.0.0 No license field.
npm ERR! Linux 3.19.0-58-generic
npm ERR! argv "/home/maras/.nvm/versions/node/v5.5.0/bin/node" "/home/maras/.nvm/versions/node/v5.5.0/bin/npm" "install"
npm ERR! node v5.5.0
npm ERR! npm  v3.3.12
npm ERR! code ELIFECYCLE

npm ERR! node-sass@0.7.0 install: `node build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@0.7.0 install script 'node build.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-sass package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node build.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls node-sass
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/maras/Documents/eCodile/debtorcare/client/npm-debug.log

I tried to remove .node_modules file , restart etc but It didnt work. Has anyone any ideas what could be wrong here?

Body:
I am into the same error and along, I am maintaining multiple versions node using NVM, I resolved this using the following commands,

Clear the cache, using the following command,

npm cache clear --force

Install node-sass dependencies using,

npm install --save-dev node-sass --unsafe-perm

Rebuilds node-sass but only if needed,

npm rebuild node-sass --unsafe-perm

Then, I could make my build successful. Hope this helps.