问:
Flutter: Do FutureBuilder Loads everything at the same time?
My app has a book summaries Feature, Now since I don't have money to host an API, I am using Firebase/Firestore database where I add summaries manually and then retrieve data from firebase to App.

I am using FutureBuilder for it.
Now say I have 10 summaries will FutureBuilder first load all 10 of them and then display data on screen(which is a ListView.builder and can show only 2 summaries without scrolling) or it will load only the data which need to be painted on the screen just like simple ListView.builder.

```<code>// code to retrieve data:

Future<QuerySnapshot> getFeedsfromFb() async {
  var data = await Firestore.instance
      .collection('feedItem')
      .orderBy('feedId', descending: true).getDocuments();
  return data;
}

// building widget:

Widget feed() {
  return Container(
    width: deviceWidth,
    height: deviceHeight / 3,
    child: FutureBuilder(
        future: getFeedsfromFb(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: snapshot.data.documents.length > 10
                  ? 10
                  : snapshot.data.documents.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  width: deviceWidth / 2.5,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (BuildContext context) => FeedIntro(
                                  snapshot.data.documents[index]['feedId'])));
                    },
                    child: Card(
                        child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          // width: 150,
                          height: 150,
                          foregroundDecoration: BoxDecoration(
                              image: DecorationImage(
                                  image: NetworkImage(
                                    snapshot.data.documents[index]['feedImage'],
                                  ),
                                  fit: BoxFit.fill)),
                        ),
                        Center(
                            child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(snapshot.data.documents[index]['title']),
                        )),
                      ],
                    )),
                  ),
                );
              },
            );
          } else if (snapshot.hasError) {
            return Center(child: Text('Sorry Something went wrong!'));
          } else {
            return Center(
              child: SizedBox(
                child: CircularProgressIndicator(),
                width: 50,
                height: 50,
              ),
            );
          }
        }),
  );
}
</code>```

答: Your FutureBuilder will load all items at the same, but only needed data by ListView.builder will be painted on the screen.

Body:
My app has a book summaries Feature, Now since I don't have money to host an API, I am using Firebase/Firestore database where I add summaries manually and then retrieve data from firebase to App.

I am using FutureBuilder for it.
Now say I have 10 summaries will FutureBuilder first load all 10 of them and then display data on screen(which is a ListView.builder and can show only 2 summaries without scrolling) or it will load only the data which need to be painted on the screen just like simple ListView.builder.

// code to retrieve data:

Future<QuerySnapshot> getFeedsfromFb() async {
  var data = await Firestore.instance
      .collection('feedItem')
      .orderBy('feedId', descending: true).getDocuments();
  return data;
}

// building widget:

Widget feed() {
  return Container(
    width: deviceWidth,
    height: deviceHeight / 3,
    child: FutureBuilder(
        future: getFeedsfromFb(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: snapshot.data.documents.length > 10
                  ? 10
                  : snapshot.data.documents.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  width: deviceWidth / 2.5,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (BuildContext context) => FeedIntro(
                                  snapshot.data.documents[index]['feedId'])));
                    },
                    child: Card(
                        child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          // width: 150,
                          height: 150,
                          foregroundDecoration: BoxDecoration(
                              image: DecorationImage(
                                  image: NetworkImage(
                                    snapshot.data.documents[index]['feedImage'],
                                  ),
                                  fit: BoxFit.fill)),
                        ),
                        Center(
                            child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(snapshot.data.documents[index]['title']),
                        )),
                      ],
                    )),
                  ),
                );
              },
            );
          } else if (snapshot.hasError) {
            return Center(child: Text('Sorry Something went wrong!'));
          } else {
            return Center(
              child: SizedBox(
                child: CircularProgressIndicator(),
                width: 50,
                height: 50,
              ),
            );
          }
        }),
  );
}


来源: stackexchange

问:
Apply "background-size:cover" to Twitter Bootstrap Carousel slides
I am working with a basic Bootstrap Carousel with three slides. Before I implemented the slider, I had one static image via css background-image of its respective div. In my CSS, I was using background-size:cover, and really liked the way the image responded to different browser widths. Depending on the width of my image, I could get the important section of the image to always stay visibile and centered, while the extra width on either side was only visible on widescreen monitors as an added effect.

I want to retain that same image behavior now that I'm using Bootstrap's Carousel, but even if I assign dimensions to the slide's viewport, I still can't get my background images to show up. I currently have it set up so each slide displays a separate css class, and each one has a different background image so it can scroll between three images.

If this is not possible via background-image, it there another way to manipulate image elements so their display behavior is the same as background-size:cover?

Here's my HTML:

```<code> <div id="myCarousel" class="carousel slide">
  <!-- Carousel items -->
  <div class="carousel-inner">
    <div class="active item ad1">
      <img src="{{ STATIC_URL }}img/TestBannerAd.png">
    </div>
    <div class="item ad2">
      <img src="{{ STATIC_URL }}img/TestBannerAd2.png">
    </div>
    <div class="item ad3">
      <img src="{{ STATIC_URL }}img/TestBannerAd3.png">
    </div>
  </div>
  <!-- Carousel nav -->
  <a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
  <a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
</code>```

And my CSS:

```<code>#myCarousel {
    width: 100%;
}
.carousel-control {
    margin-top: 20px;
}
.carousel-inner {
    width: 100%;
    height: 400px;
}
.ad1 {
    background: url(../img/TestBannerAd.png) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.ad2 {
    background: url(../img/TestBannerAd2.png) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.ad3 {
    background: url(../img/TestBannerAd3.png) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
</code>```

Hopefully this isn't a stupid question and we can figure this out!

答:
Using "background property" in ".item" class and "img" tags is not used

.carousel {
    height: 300px;
}

.carousel-inner {
    height: 100%;
}

.item {
    width: 100%;
    height: 100%;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    background-position: center;
}
/*
img {
    object-fit: cover;
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div id="myCarousel" class="carousel slide">

    <!-- Carousel items -->
    <div class="carousel-inner">

        <div class="item active" style="background-image: url(https://dummyimage.com/300x200/000/fff)" >
<!--            <img src="http://placehold.it/650x450/aaa&text=Item 1" style="width: 100%; height: 100%" /> -->
        </div>

        <div class="item" style="background-image: url(https://dummyimage.com/600x400/000/fff)" >
<!--            <img src="http://placehold.it/350x350/aaa&text=Item 2" style="width: 100%; height: 100%" /> -->
        </div>

        <div class="item" style="background-image: url(https://dummyimage.com/1200x800/000/fff)" >
<!--            <img src="http://placehold.it/350x350/aaa&text=Item 3" style="width: 100%; height: 100%" /> -->
        </div>

    </div>

    <!-- Left and right controls -->

        <span class="glyphicon glyphicon-chevron-left"></span>
        <span class="sr-only">Previous</span>

        <span class="glyphicon glyphicon-chevron-right"></span>
        <span class="sr-only">Next</span>

</div></code>```

Codepen

Editor

Full view

Version of img

ContentLicense: CC BY-SA 3.0

Body:
I am working with a basic Bootstrap Carousel with three slides. Before I implemented the slider, I had one static image via css background-image of its respective div. In my CSS, I was using background-size:cover, and really liked the way the image responded to different browser widths. Depending on the width of my image, I could get the important section of the image to always stay visibile and centered, while the extra width on either side was only visible on widescreen monitors as an added effect.

I want to retain that same image behavior now that I'm using Bootstrap's Carousel, but even if I assign dimensions to the slide's viewport, I still can't get my background images to show up. I currently have it set up so each slide displays a separate css class, and each one has a different background image so it can scroll between three images.

If this is not possible via background-image, it there another way to manipulate image elements so their display behavior is the same as background-size:cover?

Here's my HTML:

  ‹
  ›

And my CSS:

#myCarousel {
    width: 100%;
}
.carousel-control {
    margin-top: 20px;
}
.carousel-inner {
    width: 100%;
    height: 400px;
}
.ad1 {
    background: url(../img/TestBannerAd.png) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.ad2 {
    background: url(../img/TestBannerAd2.png) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.ad3 {
    background: url(../img/TestBannerAd3.png) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Hopefully this isn't a stupid question and we can figure this out!

Body:
Using "background property" in ".item" class and "img" tags is not used

.carousel {
    height: 300px;
}

.carousel-inner {
    height: 100%;
}

.item {
    width: 100%;
    height: 100%;

    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

    background-position: center;
}
/*
img {
    object-fit: cover;
}
*/

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div id="myCarousel" class="carousel slide">

    <!-- Carousel items -->
    <div class="carousel-inner">

        <div class="item active" style="background-image: url(https://dummyimage.com/300x200/000/fff)" >
<!--            <img src="http://placehold.it/650x450/aaa&text=Item 1" style="width: 100%; height: 100%" /> -->
        </div>

        <div class="item" style="background-image: url(https://dummyimage.com/600x400/000/fff)" >
<!--            <img src="http://placehold.it/350x350/aaa&text=Item 2" style="width: 100%; height: 100%" /> -->
        </div>

        <div class="item" style="background-image: url(https://dummyimage.com/1200x800/000/fff)" >
<!--            <img src="http://placehold.it/350x350/aaa&text=Item 3" style="width: 100%; height: 100%" /> -->
        </div>

    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
        <span class="sr-only">Next</span>
    </a>

</div>

Codepen

Editor

Full view

Version of img

ContentLicense: CC BY-SA 4.0


问:
Binding in DynamicResource ResourceKey wpf mvvm
I want to bind the style of button on the basis of if else condition. I have created one string property in the viewmodel and bind to the button's style attribute like this:

```<code><Button x:Name="copd" Content="COPD"
    Command="{Binding COPDReadingsCommand}"
    Style="{DynamicResource ResourceKey={Binding CheckCopd}}"
    HorizontalAlignment="Center" VerticalAlignment="Center"
    Margin="20" FontWeight="Bold" />
</code>```

I am looping through the resourceDictionary and getting all the keys. Using if else i am changing the string property value(CheckCopd) in if else.

I am getting the desired values in if else but style is not getting applied to the button when I execute my application. It only displays the generic button style.

How to bind the DynamicResource ?

Kindly Suggest?

Thank You.

答:
You cannot use bindings on the DynamicResource properties, as it does not derive from DependencyObject. You would either need to set the Style property directly from code-behind, or just use a Binding.

You could use a Style for the Button type, which has a DataTrigger based on a custom property that dynamically changes the look. But in this case, you need a single Style, which changes it's setters based on your condition. It would not allow you to change the Style property itself dynamically.

Body:
I want to bind the style of button on the basis of if else condition. I have created one string property in the viewmodel and bind to the button's style attribute like this:

<Button x:Name="copd" Content="COPD"
    Command="{Binding COPDReadingsCommand}"
    Style="{DynamicResource ResourceKey={Binding CheckCopd}}"
    HorizontalAlignment="Center" VerticalAlignment="Center"
    Margin="20" FontWeight="Bold" />

I am looping through the resourceDictionary and getting all the keys. Using if else i am changing the string property value(CheckCopd) in if else.

I am getting the desired values in if else but style is not getting applied to the button when I execute my application. It only displays the generic button style.

How to bind the DynamicResource ?

Kindly Suggest?

Thank You.


问:
Controlled Inputs not being clear on page refresh (Microsoft Edge)
I have a ReactJS application, and have created a controlled component using a simple  html tag.

The issue is when doing refresh on the page in microsoft edge from the refresh button or pressing F5 (when doing enter from the navbar it works fine) the input values are not being clear properly, they get stuck. If I start typing in any input of my form, then they go away.

Evidence: https://www.screencast.com/t/kJupEbHykZ1X

I've already tried:

- clearing the values on windows.onload

- setting autocomplete='off' on the input tag

- creating timeout functions.

To test I added console.logs everywhere to be sure all the lifecycle methods are called and that the state in each one of them is empty, and it is.

I've also run into this post: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/21174802/

But none of that seem to fixed the issue.

```<code><input
  id={`input-${id}`}
  key={`input-${id}`}
  type={inputType}
  value={value}
  autoComplete="off"
  onChange={this.handleValueChange}
/>
</code>```

答: Internet Explorer and Edge are caching the input tag. On Windows, hit the Ctrl+F5 shortcut to hard refresh. But for me I hit Ctrl+double hit F5 in Edge then it refreshes. You can also refer to this thread.</p>

Body:
I have a ReactJS application, and have created a controlled component using a simple  html tag.

The issue is when doing refresh on the page in microsoft edge from the refresh button or pressing F5 (when doing enter from the navbar it works fine) the input values are not being clear properly, they get stuck. If I start typing in any input of my form, then they go away.

Evidence: https://www.screencast.com/t/kJupEbHykZ1X

I've already tried:

- clearing the values on windows.onload

- setting autocomplete='off' on the input tag

- creating timeout functions.

To test I added console.logs everywhere to be sure all the lifecycle methods are called and that the state in each one of them is empty, and it is.

I've also run into this post: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/21174802/

But none of that seem to fixed the issue.

<input
  id={`input-${id}`}
  key={`input-${id}`}
  type={inputType}
  value={value}
  autoComplete="off"
  onChange={this.handleValueChange}
/>


问:
Make image overlap sections on tablet/desktop but not on mobile
I want my image to overlap two sections on tablet/desktop but not on mobile. Currently, it's doing so but it's causing the image to overlap the text in the first section.

I've tried adding "margin-top: -226px" to the image when the min-width is 768px (but again, it overlaps the text in the first/hero section).

```<code><!-- #HERO -->

  <div class="hero-bg center-text">
    <div class="center-container">
      <h2 class="join">
        <span class="join-the">Join The</span>
        <img class="shelf-squad-logo" src="https://shelfstuff.staging.thisismess.io/wp-content/plugins/readraterewards/static/img/logo-self-squad.svg">
      </h2>
      <h1 class="rate-read-rewards">
        <img class="read-rate-rewards-logo" src="https://shelfstuff.staging.thisismess.io/wp-content/plugins/readraterewards/static/img/logo-read-rate-review.svg">
      </h1>
      <p class="enter-for-a-chance">Enter for a chance to win a Shelf Squad Summer Reading prize pack!</p>
      <p class="read-or-listen-to-excerpt">
        Read or listen to an excerpt of any book below and submit a review for a chance to win. Not able to read or listen? Visit the official rules here on how to send in a write-in entry.
      </p>
    </div>
  </div>

<!-- #PRIZES -->

  <div class="prize-bg center-text">
    <div class="center-container">
      <img class="prize-pack" src="https://storage.googleapis.com/shelfstuff-staging/uploads/2019/05/210d080f-thumbnail-1.jpg">
      <p class="grand-prize">Grand Prize</p>
      <h2 class="grand-prize-desc">One grand prize winner every two weeks will receive a Shelf Squad prize pack including:</h2>
      <ul>
        <li class="prize-bullet">A set of amazing FREE books</li>
        <li class="prize-bullet">1 Shelf Stuff tote bag</li>
        <li class="prize-bullet">1 $50 gift card</li>
        <li class="prize-bullet">1 Shelf Stuff pin</li>
        <li class="prize-bullet">1 Shelf Stuff activity book</li>
      </ul>
    </div>
  </div>
</code>```

```<code>/*------------------------------------*\
  #UNIVERSAL
\*------------------------------------*/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.center-container {
  max-width: 1220px;
  padding: 40px;
  margin: 0 auto;
}

img {
  max-width: 100%;
  height: auto;
}

ul {
  color: white;
  margin-top: 24px;
  font-weight: 700;
  font-size: 18px;
  line-height: 30px;
  list-style: none;
  text-align: left;
}

li {
  padding-left: 18px;
}

/*------------------------------------*\
  #HERO
\*------------------------------------*/

.hero-bg {
  background: blue;
}

.join-the {
  color: white;
  text-transform: uppercase;
  font-size: 21px;
  font-weight: 900;
  display: block;
}

.read-rate-rewards-logo {
  margin: 45px auto 40px auto;
}

.enter-for-a-chance {
  color: white;
  font-size: 36px;
  font-weight: 700;
  line-height: 48px;
  margin: 14px 0;
}

.read-or-listen-to-excerpt {
  color: white;
  font-weight: 700;
  font-size: 20px;
  line-height: 31px;
  max-width: 632px;
  margin: 1em auto;
}

/*------------------------------------*\
  #PRIZES
\*------------------------------------*/

.prize-bg {
  background: orange;
}

.grand-prize {
  color: var(--purple-color);
  text-transform: uppercase;
  margin: 33px auto;
  font-weight: 900;
  font-size: 24px;
}

.grand-prize-desc {
  color: white;
  font-weight: 700;
  font-size: 36px;
  line-height: 55px;
}

/*------------------------------------*\
  #UTILITY
\*------------------------------------*/

.center-text {
  text-align: center;
}

/*------------------------------------*\
  #RESPONSIVE
\*------------------------------------*/

@media only screen and (min-width: 768px) {
  .container {
    max-width: 1300px;
  }

  .prize-pack {
    margin-top: -226px;
  }
}
</code>```

On tablet/desktop, I would like there to be enough room in the first section to fit half of the image. Half of the image should be in the hero and half should be in the prizes section.

this is what I want it to look like

答:
Maybe this code help you

you can add simple padding in the banner section because of the next section you talk the margin-top: -something then it's not expanding height(banner content). so you needed some padding in the banner bottom.

Here the simple code

/*------------------------------------*\
  #UNIVERSAL
\*------------------------------------*/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.center-container {
  max-width: 1220px;
  padding: 40px;
  margin: 0 auto;
}

img {
  max-width: 100%;
  height: auto;
}

ul {
  color: white;
  margin-top: 24px;
  font-weight: 700;
  font-size: 18px;
  line-height: 30px;
  list-style: none;
  text-align: left;
}

li {
  padding-left: 18px;
}

/*------------------------------------*\
  #HERO
\*------------------------------------*/

.hero-bg {
  background: blue;
  padding-bottom: 200px;
}

.join-the {
  color: white;
  text-transform: uppercase;
  font-size: 21px;
  font-weight: 900;
  display: block;
}

.read-rate-rewards-logo {
  margin: 45px auto 40px auto;
}

.enter-for-a-chance {
  color: white;
  font-size: 36px;
  font-weight: 700;
  line-height: 48px;
  margin: 14px 0;
}

.read-or-listen-to-excerpt {
  color: white;
  font-weight: 700;
  font-size: 20px;
  line-height: 31px;
  max-width: 632px;
  margin: 1em auto;
}

/*------------------------------------*\
  #PRIZES
\*------------------------------------*/

.prize-bg {
  background: orange;
}

.grand-prize {
  color: var(--purple-color);
  text-transform: uppercase;
  margin: 33px auto;
  font-weight: 900;
  font-size: 24px;
}

.grand-prize-desc {
  color: white;
  font-weight: 700;
  font-size: 36px;
  line-height: 55px;
}

/*------------------------------------*\
  #UTILITY
\*------------------------------------*/

.center-text {
  text-align: center;
}

/*------------------------------------*\
  #RESPONSIVE
\*------------------------------------*/

@media only screen and (min-width: 768px) {
  .container {
    max-width: 1300px;
  }

  .prize-pack {
    margin-top: -226px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- #HERO -->

  <div class="hero-bg center-text">
    <div class="center-container">
      <h2 class="join">
        <span class="join-the">Join The</span>
        <img class="shelf-squad-logo" src="https://shelfstuff.staging.thisismess.io/wp-content/plugins/readraterewards/static/img/logo-self-squad.svg">
      </h2>
      <h1 class="rate-read-rewards">
        <img class="read-rate-rewards-logo" src="https://shelfstuff.staging.thisismess.io/wp-content/plugins/readraterewards/static/img/logo-read-rate-review.svg">
      </h1>
      <p class="enter-for-a-chance">Enter for a chance to win a Shelf Squad Summer Reading prize pack!</p>
      <p class="read-or-listen-to-excerpt">
        Read or listen to an excerpt of any book below and submit a review for a chance to win. Not able to read or listen? Visit the official rules here on how to send in a write-in entry.
      </p>
    </div>
  </div>

<!-- #PRIZES -->

  <div class="prize-bg center-text">
    <div class="center-container">
      <img class="prize-pack" src="https://storage.googleapis.com/shelfstuff-staging/uploads/2019/05/210d080f-thumbnail-1.jpg">
      <p class="grand-prize">Grand Prize</p>
      <h2 class="grand-prize-desc">One grand prize winner every two weeks will receive a Shelf Squad prize pack including:</h2>
      <ul>
        <li class="prize-bullet">A set of amazing FREE books</li>
        <li class="prize-bullet">1 Shelf Stuff tote bag</li>
        <li class="prize-bullet">1 $50 gift card</li>
        <li class="prize-bullet">1 Shelf Stuff pin</li>
        <li class="prize-bullet">1 Shelf Stuff activity book</li>
      </ul>
    </div>
  </div></code>```

Body:
I want my image to overlap two sections on tablet/desktop but not on mobile. Currently, it's doing so but it's causing the image to overlap the text in the first section.

I've tried adding "margin-top: -226px" to the image when the min-width is 768px (but again, it overlaps the text in the first/hero section).

        Join The

Enter for a chance to win a Shelf Squad Summer Reading prize pack!

        Read or listen to an excerpt of any book below and submit a review for a chance to win. Not able to read or listen? Visit the official rules here on how to send in a write-in entry.

Grand Prize

One grand prize winner every two weeks will receive a Shelf Squad prize pack including:

A set of amazing FREE books

1 Shelf Stuff tote bag

1 $50 gift card

1 Shelf Stuff pin

1 Shelf Stuff activity book

/*------------------------------------*\
  #UNIVERSAL
\*------------------------------------*/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.center-container {
  max-width: 1220px;
  padding: 40px;
  margin: 0 auto;
}

img {
  max-width: 100%;
  height: auto;
}

ul {
  color: white;
  margin-top: 24px;
  font-weight: 700;
  font-size: 18px;
  line-height: 30px;
  list-style: none;
  text-align: left;
}

li {
  padding-left: 18px;
}

/*------------------------------------*\
  #HERO
\*------------------------------------*/

.hero-bg {
  background: blue;
}

.join-the {
  color: white;
  text-transform: uppercase;
  font-size: 21px;
  font-weight: 900;
  display: block;
}

.read-rate-rewards-logo {
  margin: 45px auto 40px auto;
}

.enter-for-a-chance {
  color: white;
  font-size: 36px;
  font-weight: 700;
  line-height: 48px;
  margin: 14px 0;
}

.read-or-listen-to-excerpt {
  color: white;
  font-weight: 700;
  font-size: 20px;
  line-height: 31px;
  max-width: 632px;
  margin: 1em auto;
}

/*------------------------------------*\
  #PRIZES
\*------------------------------------*/

.prize-bg {
  background: orange;
}

.grand-prize {
  color: var(--purple-color);
  text-transform: uppercase;
  margin: 33px auto;
  font-weight: 900;
  font-size: 24px;
}

.grand-prize-desc {
  color: white;
  font-weight: 700;
  font-size: 36px;
  line-height: 55px;
}

/*------------------------------------*\
  #UTILITY
\*------------------------------------*/

.center-text {
  text-align: center;
}

/*------------------------------------*\
  #RESPONSIVE
\*------------------------------------*/

@media only screen and (min-width: 768px) {
  .container {
    max-width: 1300px;
  }

  .prize-pack {
    margin-top: -226px;
  }
}

On tablet/desktop, I would like there to be enough room in the first section to fit half of the image. Half of the image should be in the hero and half should be in the prizes section.

this is what I want it to look like

Body:
Maybe this code help you

you can add simple padding in the banner section because of the next section you talk the margin-top: -something then it's not expanding height(banner content). so you needed some padding in the banner bottom.

Here the simple code

/*------------------------------------*\
  #UNIVERSAL
\*------------------------------------*/

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.center-container {
  max-width: 1220px;
  padding: 40px;
  margin: 0 auto;
}

img {
  max-width: 100%;
  height: auto;
}

ul {
  color: white;
  margin-top: 24px;
  font-weight: 700;
  font-size: 18px;
  line-height: 30px;
  list-style: none;
  text-align: left;
}

li {
  padding-left: 18px;
}

/*------------------------------------*\
  #HERO
\*------------------------------------*/

.hero-bg {
  background: blue;
  padding-bottom: 200px;
}

.join-the {
  color: white;
  text-transform: uppercase;
  font-size: 21px;
  font-weight: 900;
  display: block;
}

.read-rate-rewards-logo {
  margin: 45px auto 40px auto;
}

.enter-for-a-chance {
  color: white;
  font-size: 36px;
  font-weight: 700;
  line-height: 48px;
  margin: 14px 0;
}

.read-or-listen-to-excerpt {
  color: white;
  font-weight: 700;
  font-size: 20px;
  line-height: 31px;
  max-width: 632px;
  margin: 1em auto;
}

/*------------------------------------*\
  #PRIZES
\*------------------------------------*/

.prize-bg {
  background: orange;
}

.grand-prize {
  color: var(--purple-color);
  text-transform: uppercase;
  margin: 33px auto;
  font-weight: 900;
  font-size: 24px;
}

.grand-prize-desc {
  color: white;
  font-weight: 700;
  font-size: 36px;
  line-height: 55px;
}

/*------------------------------------*\
  #UTILITY
\*------------------------------------*/

.center-text {
  text-align: center;
}

/*------------------------------------*\
  #RESPONSIVE
\*------------------------------------*/

@media only screen and (min-width: 768px) {
  .container {
    max-width: 1300px;
  }

  .prize-pack {
    margin-top: -226px;
  }
}

<!-- #HERO -->

  <div class="hero-bg center-text">
    <div class="center-container">
      <h2 class="join">
        <span class="join-the">Join The</span>
        <img class="shelf-squad-logo" src="https://shelfstuff.staging.thisismess.io/wp-content/plugins/readraterewards/static/img/logo-self-squad.svg">
      </h2>
      <h1 class="rate-read-rewards">
        <img class="read-rate-rewards-logo" src="https://shelfstuff.staging.thisismess.io/wp-content/plugins/readraterewards/static/img/logo-read-rate-review.svg">
      </h1>
      <p class="enter-for-a-chance">Enter for a chance to win a Shelf Squad Summer Reading prize pack!</p>
      <p class="read-or-listen-to-excerpt">
        Read or listen to an excerpt of any book below and submit a review for a chance to win. Not able to read or listen? Visit the official rules here on how to send in a write-in entry.
      </p>
    </div>
  </div>

<!-- #PRIZES -->

  <div class="prize-bg center-text">
    <div class="center-container">
      <img class="prize-pack" src="https://storage.googleapis.com/shelfstuff-staging/uploads/2019/05/210d080f-thumbnail-1.jpg">
      <p class="grand-prize">Grand Prize</p>
      <h2 class="grand-prize-desc">One grand prize winner every two weeks will receive a Shelf Squad prize pack including:</h2>
      <ul>
        <li class="prize-bullet">A set of amazing FREE books</li>
        <li class="prize-bullet">1 Shelf Stuff tote bag</li>
        <li class="prize-bullet">1 $50 gift card</li>
        <li class="prize-bullet">1 Shelf Stuff pin</li>
        <li class="prize-bullet">1 Shelf Stuff activity book</li>
      </ul>
    </div>
  </div>


问:
Why it is giving me 'this.state.UserData.map' is not a function?
I am getting an error in my code 'this.state.UserData.map' is not a function . i want get list from the database using fetch. i think i am forgetting something.
please help me remove this error. thanks in advance.
Here is my complete code to show list...</p>

```<code>import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
  constructor(props){
    super(props);
    this.state={ UserData:[] };
    this.headers=[
      {key:1,label:'Name'},
      {key:2,label:'Department'},
      {key:3,label:'Marks'},
    ];
  }

  componentDidMount(){
    fetch("https://www.veomit.com/test/zend/api/fetch.php")
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                })
        .catch(error => {
        console.log(
          "An error occurred while trying to fetch data from Foursquare: " +error
        );
      });
    });
  }
  render(){
    return(
      <div>
      <table className="table table-bordered">
          <thead>
            <tr>
              {
                        this.headers.map(function(h) {
                            return (
                                <th key = {h.key}>{h.label}</th>
                            );
                        })
                        }
            </tr>
          </thead>
          <tbody>
              {
                        this.state.UserData.map(function(item){
                        return (
                                <tr>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                                </tr>
                            );
                        })
                    }
          </tbody>
      </table>
      </div>
    );
  }
}
````````
</code>```

答:
response is not array. You need convert response server to array of object to use map

response must like this. You can tell backend services to change like this or you convert like this to your state

```<code>[{name: 'John Doe', department: 'CEO', marks: 'title' } , {....} ]
</code>```

Body:
I am getting an error in my code 'this.state.UserData.map' is not a function . i want get list from the database using fetch. i think i am forgetting something.
please help me remove this error. thanks in advance.
Here is my complete code to show list...

import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
  constructor(props){
    super(props);
    this.state={ UserData:[] };
    this.headers=[
      {key:1,label:'Name'},
      {key:2,label:'Department'},
      {key:3,label:'Marks'},
    ];
  }

  componentDidMount(){
    fetch("https://www.veomit.com/test/zend/api/fetch.php")
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                })
        .catch(error => {
        console.log(
          "An error occurred while trying to fetch data from Foursquare: " +error
        );
      });
    });
  }
  render(){
    return(

              {
                        this.headers.map(function(h) {
                            return (
                                {h.label}
                            );
                        })
                        }

              {
                        this.state.UserData.map(function(item){
                        return (

                                  {item.name}
                                  {item.department}
                                  {item.marks}

                            );
                        })
                    }

    );
  }
}
````````

Body:
response is not array. You need convert response server to array of object to use map

response must like this. You can tell backend services to change like this or you convert like this to your state

[{name: 'John Doe', department: 'CEO', marks: 'title' } , {....} ]


问:
Unable to find Dir due to credentials not recognized?
I am trying to copy some files from a local location to a network location accessible only via specific user - So far I have

```<code>Import-Module bitstransfer
$username = "domain\user"
$password =  Get-Content 'C:\securestring.txt' | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist ($username, $password)
$sourcePath = 'C:\folder\file.csv', 'C:\folder\file2.csv'
$destPath = '\\server\share$\', '\\server\share$\'
Start-BitsTransfer -Source $sourcePath -Destination $destPath -Credential $cred
</code>```

I am having issues with authentication, script doesn't seem to be able to pass the parameters through

UPDATE: Appears there is a bug with Bits transfer handling -creds as expected, in order to success one must do net use command to manually establish a connection.

Appreciate your input!

答:
Your destination path should have the filenames mentioned:

```<code>Start-BitsTransfer -Source 'C:\folder\file.csv', 'C:\folder\file2.csv' -Destination '\\server\share$\file.csv', '\\server\share$\file2.csv' -Credential $cred
</code>```

Or you need to wrap your variables like this:

```<code>$destPath = "$('\\server\share$\file.csv', '\\server\share$\file2.csv')"
</code>```

Also if you want the file names to be taken dynamically, then this is perfect scenario to use foreach loop and address it.

Hope it helps.

Body:
I am trying to copy some files from a local location to a network location accessible only via specific user - So far I have

Import-Module bitstransfer
$username = "domain\user"
$password =  Get-Content 'C:\securestring.txt' | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist ($username, $password)
$sourcePath = 'C:\folder\file.csv', 'C:\folder\file2.csv'
$destPath = '\\server\share$\', '\\server\share$\'
Start-BitsTransfer -Source $sourcePath -Destination $destPath -Credential $cred

I am having issues with authentication, script doesn't seem to be able to pass the parameters through

UPDATE: Appears there is a bug with Bits transfer handling -creds as expected, in order to success one must do net use command to manually establish a connection.

Appreciate your input!

Body:
Your destination path should have the filenames mentioned:

Start-BitsTransfer -Source 'C:\folder\file.csv', 'C:\folder\file2.csv' -Destination '\\server\share$\file.csv', '\\server\share$\file2.csv' -Credential $cred

Or you need to wrap your variables like this:

$destPath = "$('\\server\share$\file.csv', '\\server\share$\file2.csv')"

Also if you want the file names to be taken dynamically, then this is perfect scenario to use foreach loop and address it.

Hope it helps.


问:
Custom ordering by calculation in Django
Any solutions for custom calculation sorting in Django? I want to create a view that shows the Top Posts in my Blog. The ranking will be calculated by Post's attributes. Let's just say I have 3 IntegerFields called x, y, and z, and the ranking calculation will be x * y / z.

Any ideas? I would like to do Top Post ever, and also other variations filtered by time such as last 24 hours, 7 days, 1 month, etc.

Thanks!

答:
As you can't order querysets by methods and properties in django you have to do the sorting in python.

Consider turning your calculated field into a property on your model and then you can do this in your view:

```<code>sorted_posts = sorted(Post.objects.all(), key=lambda post: post.calculated_field )
</code>```

Finally you can pass sorted_posts to your list-template.

Body:
As you can't order querysets by methods and properties in django you have to do the sorting in python.

Consider turning your calculated field into a property on your model and then you can do this in your view:

sorted_posts = sorted(Post.objects.all(), key=lambda post: post.calculated_field )

Finally you can pass sorted_posts to your list-template.


问:
Implement a group_by_owners dictionary
I made a successful attempt on the TestDome.com Fileowners problem and wanted to see if anyone had suggestions to simplify my answer.  The online IDE uses Python 3.5.1.  If you are trying to do the problem yourself and are just looking for an answer, here's one.  I am by know means a Python expert so this took me quite a while to produce with lots of tinkering.  Any comments at all would be helpful even if its about syntax or general cleanliness.   THANKS!

Implement a group_by_owners function that:

Accepts a dictionary containing the file owner name for each file name.
Returns a dictionary containing a list of file names for each owner name, in any order.
For example, for dictionary {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'} the group_by_owners function should return {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}.

```<code>class FileOwners:

@staticmethod
def group_by_owners(files):
    val = (list(files.values()))                    #get values from dict
    val = set(val)                                  #make values a set to remove duplicates
    val = list(val)                                 #make set a list so we can work with it
    keyst = (list(files.keys()))                    #get keys from dict
    result = {}                                     #creat empty dict for output
    for i in range(len(val)):                       #loop over values(owners)
        for j in range(len(keyst)):                 #loop over keys(files)
            if val[i]==list(files.values())[j]:     #boolean to pick out files for current owner loop
                dummylist = [keyst[j]]              #make string pulled from dict a list so we can add it to the output in the correct format
                if val[i] in result:                #if the owner is already in the output add the new file to the existing dictionary entry
                    result[val[i]].append(keyst[j]) #add the new file
                else:                               #if the owner is NOT already in the output make a new entry
                    result[val[i]] = dummylist      #make a new entry
    return result

files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}

print(FileOwners.group_by_owners(files))
</code>```

Output:

```<code>{'Stan': ['Code.py'], 'Randy': ['Output.txt', 'Input.txt']}
</code>```

答:
I made a dict of owners and their associated list of filenames. To do that i firstly created the dictionary with the values of the passed dictionary files as keys and empty list as values. Then looped through files and appended the empty list with the keys of files

```<code>def group_by_owners(files):
    return_dict = {}
    owner_files = files.keys()
    for f in owner_files:
        return_dict[files[f]] = []
    for f, n in files.items():
        return_dict[n].append(f)
    return return_dict
</code>```

Title: Implement a group_by_owners dictionary

Body:
I made a successful attempt on the TestDome.com Fileowners problem and wanted to see if anyone had suggestions to simplify my answer.  The online IDE uses Python 3.5.1.  If you are trying to do the problem yourself and are just looking for an answer, here's one.  I am by know means a Python expert so this took me quite a while to produce with lots of tinkering.  Any comments at all would be helpful even if its about syntax or general cleanliness.   THANKS!

Implement a group_by_owners function that:

Accepts a dictionary containing the file owner name for each file name.
Returns a dictionary containing a list of file names for each owner name, in any order.
For example, for dictionary {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'} the group_by_owners function should return {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}.

class FileOwners:

@staticmethod
def group_by_owners(files):
    val = (list(files.values()))                    #get values from dict
    val = set(val)                                  #make values a set to remove duplicates
    val = list(val)                                 #make set a list so we can work with it
    keyst = (list(files.keys()))                    #get keys from dict
    result = {}                                     #creat empty dict for output
    for i in range(len(val)):                       #loop over values(owners)
        for j in range(len(keyst)):                 #loop over keys(files)
            if val[i]==list(files.values())[j]:     #boolean to pick out files for current owner loop
                dummylist = [keyst[j]]              #make string pulled from dict a list so we can add it to the output in the correct format
                if val[i] in result:                #if the owner is already in the output add the new file to the existing dictionary entry
                    result[val[i]].append(keyst[j]) #add the new file
                else:                               #if the owner is NOT already in the output make a new entry
                    result[val[i]] = dummylist      #make a new entry
    return result

files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}

print(FileOwners.group_by_owners(files))

Output:

{'Stan': ['Code.py'], 'Randy': ['Output.txt', 'Input.txt']}

Body:
I made a dict of owners and their associated list of filenames. To do that i firstly created the dictionary with the values of the passed dictionary files as keys and empty list as values. Then looped through files and appended the empty list with the keys of files

def group_by_owners(files):
    return_dict = {}
    owner_files = files.keys()
    for f in owner_files:
        return_dict[files[f]] = []
    for f, n in files.items():
        return_dict[n].append(f)
    return return_dict


问:
Android WebView Has started crashing on Android 9
Hello Expert Android Developers:

We have an android app and our basic workflow is as below

User is sent a link via email or text message

User clicks on the link and a page open on Chrome or Android default browser and have a button named JOIN

User clicks on this JOIN button and our app is launched and a page is displayed in webview asking the User to enter the first name, last name and phone/email and then the user clicks on a button named INITIATE

We validate the information - if the user is new, we create a record, it user is existing, we update it etc and then show a popup informing that his session would be recorded.

As soon as the user clicks on OK on the popup and then the control exists the webview and the user is on a native android page.

Problem
As soon as the OK button is tapped on the webview where our native app page would launch normally until a few weeks ago, the app crashes and we would be taken back to the start of the webview page asking us to enter the details.

Please note the below caveats:

First of all, this is happening only in the case of Android 9. We have tested this on Samsung Galaxy S8 and S9. And it doesn't happen every single time but it happens rather regularly, I would say sometimes even 2 out of 3 times. In the best of the times, it has happened 2 out of 10 times but it happens.

This code has been running successfully for the past 1 year or so and we never had this problem. It has only started happening in the last 3-4 weeks.

We also have an iOS app, where the same problem is not observed.

Here is a code snippet that may help - This is how we are loading the webview.

```<code>webview = findViewById(R.id.webview);
    webview.setVisibility(View.VISIBLE);
    final ProgressDialog pd = ProgressDialog.show(ActivtyName.this, "", "Please wait", true);
    webview.setGeolocationEnabled(true);
    webview.setMixedContentAllowed(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setLoadWithOverviewMode(true);

    webview.setWebChromeClient(new WebChromeClient()
</code>```

=======We override a lot of methods here followed by

```<code>webview.setWebViewClient(new WebViewClient()
</code>```

=======We override methods here.

Any idea what might be going on? We have tried looking at the logs while debugging via USB mode, but we don't see much in logs except what is shown on the Android Console like below:

```<code>*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 0, tid: 0 >>> com.a****d.xyzapp <<<
</code>```

backtrace:

```<code>#00  pc 0000000001b61620  /data/app/com.android.chrome-DpcaMBOCm2oa08upmw1Tug==/base.apk
</code>```

Here is the more detailed log as requested:

```<code>2019-05-18 11:58:01.694 23217-23217/com.a**d.xyzapp.debug A/chromium:

[FATAL:crashpad_client_linux.cc(404)] Render process (28925)'s crash wasn't handled by all associated  webviews, triggering application crash.
Fatal signal 5 (SIGTRAP), code 1 (TRAP_BRKPT), fault addr 0x7ab7b9d620 in tid 23217 (atientapp.debug), pid 23217 (atientapp.debug) (edited)
</code>```

答:
This seems like a memory issue, what I can find from few of the threads.

Do this, in your webview fragment/activity override onLowMemory() and add a log.

```<code>@Override
public void onLowMemory() {
    Log.d("TAG_MEMORY", "Memory is Low");
    super.onLowMemory();
}
</code>```

Now try to reproduce the crash, and if onLowMemory() is called then that is the root cause. Maybe some of the webview pages are too much memory.

Body:
Hello Expert Android Developers:

We have an android app and our basic workflow is as below

User is sent a link via email or text message

User clicks on the link and a page open on Chrome or Android default browser and have a button named JOIN

User clicks on this JOIN button and our app is launched and a page is displayed in webview asking the User to enter the first name, last name and phone/email and then the user clicks on a button named INITIATE

We validate the information - if the user is new, we create a record, it user is existing, we update it etc and then show a popup informing that his session would be recorded.

As soon as the user clicks on OK on the popup and then the control exists the webview and the user is on a native android page.

Problem
As soon as the OK button is tapped on the webview where our native app page would launch normally until a few weeks ago, the app crashes and we would be taken back to the start of the webview page asking us to enter the details.

Please note the below caveats:

First of all, this is happening only in the case of Android 9. We have tested this on Samsung Galaxy S8 and S9. And it doesn't happen every single time but it happens rather regularly, I would say sometimes even 2 out of 3 times. In the best of the times, it has happened 2 out of 10 times but it happens.

This code has been running successfully for the past 1 year or so and we never had this problem. It has only started happening in the last 3-4 weeks.

We also have an iOS app, where the same problem is not observed.

Here is a code snippet that may help - This is how we are loading the webview.

webview = findViewById(R.id.webview);
    webview.setVisibility(View.VISIBLE);
    final ProgressDialog pd = ProgressDialog.show(ActivtyName.this, "", "Please wait", true);
    webview.setGeolocationEnabled(true);
    webview.setMixedContentAllowed(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setLoadWithOverviewMode(true);

    webview.setWebChromeClient(new WebChromeClient()

=======We override a lot of methods here followed by

webview.setWebViewClient(new WebViewClient()

=======We override methods here.

Any idea what might be going on? We have tried looking at the logs while debugging via USB mode, but we don't see much in logs except what is shown on the Android Console like below:

*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 0, tid: 0 >>> com.a****d.xyzapp <<<

backtrace:

#00  pc 0000000001b61620  /data/app/com.android.chrome-DpcaMBOCm2oa08upmw1Tug==/base.apk

Here is the more detailed log as requested:

2019-05-18 11:58:01.694 23217-23217/com.a**d.xyzapp.debug A/chromium:

[FATAL:crashpad_client_linux.cc(404)] Render process (28925)'s crash wasn't handled by all associated  webviews, triggering application crash.
Fatal signal 5 (SIGTRAP), code 1 (TRAP_BRKPT), fault addr 0x7ab7b9d620 in tid 23217 (atientapp.debug), pid 23217 (atientapp.debug) (edited)

Body:
This seems like a memory issue, what I can find from few of the threads.

Do this, in your webview fragment/activity override onLowMemory() and add a log.

@Override
public void onLowMemory() {
    Log.d("TAG_MEMORY", "Memory is Low");
    super.onLowMemory();
}

Now try to reproduce the crash, and if onLowMemory() is called then that is the root cause. Maybe some of the webview pages are too much memory.


问:
Appstore takes time based on screens
I have an app, A small app with 4-5 screens, I remember appstore usually takes 1-2 days.

So my question is if i have another app that haves 80 screens, Is the time to be approve is the same or it will take more time ?

答:
First of all App Store usually approves application in 24 hours as per new rules. So all applications with average features will get approval.

Here is an official statement from Apple Team :

On average, 50% of apps are reviewed in 24 hours and over 90% are
  reviewed in 48 hours. If your submission is incomplete, review times
  may be further delayed or your app may be rejected. Once your app has
  been reviewed, its status will be updated and you will be notified.

So the App Store approval time will not vary according to the number of screens application have. But It can be on basis of complexity of features application have. On basis of that it can take time.

I have seen so many apps having 20-30 screens get approval in 24 hours & on the other side some of the applications have hardly 4-5 screens but have some lengthy advance features which needs more detailed review time takes more time.

But still as apple team mentioned in the official statement maximum time in the 90% cases is 48 hours only. So within 2 days they will approve your application even if it has more screens.

Hope this helps to everyone.

Title: Appstore takes time based on screens


问:
How to turn a json object into individual rows
I have a table with a "rules" column that looks like this:

```<code>{"111_abc":0,"222_def":0,"333_abs":0}
</code>```

I'd like to write a postgres query to turn this into something like this:

```<code>rules
111_abc
222_def
333_abs
</code>```

I have tried several renditions of json_extract_path or json_array_element - no luck.

Body:
I have a table with a "rules" column that looks like this:

{"111_abc":0,"222_def":0,"333_abs":0}

I'd like to write a postgres query to turn this into something like this:

rules
111_abc
222_def
333_abs

I have tried several renditions of json_extract_path or json_array_element - no luck.

Body: select * from json_each_text('{"111_abc":0,"222_def":0,"333_abs":0}')


问:
why Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?
System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);

is true.

I understand that integer in Java is 32 bit and can't go above 231-1, but I can't understand why adding 1 to its MAX_VALUE results in MIN_VALUE and not in some kind of exception. Not mentioning something like transparent conversion to a bigger type, like Ruby does.

Is this behavior specified somewhere? Can I rely on it?

答:
Cause overflow and two-compliant nature count goes on "second loop", we was on far most right position 2147483647 and after summing 1, we appeared at far most left position -2147483648, next incrementing goes -2147483647, -2147483646, -2147483645, ... and so forth to the far most right again and on and on, its nature of summing machine on this bit depth.

Some examples:

```<code>int a = 2147483647;

System.out.println(a);
</code>```

gives: 2147483647

```<code>System.out.println(a+1);
</code>```

gives: -2147483648 (cause overflow and two-compliant nature count goes on "second loop", we was on far most right position 2147483647 and after summing 1, we appeared at far most left position -2147483648, next incrementing goes -2147483648, -2147483647, -2147483646, ... and so fores to the far most right again and on and on, its nature of summing machine on this bit depth)

```<code>System.out.println(2-a);
</code>```

gives:-2147483645 (-2147483647+2  seems mathematical logical)

```<code>System.out.println(-2-a);
</code>```

gives: 2147483647 (-2147483647-1 -> -2147483648, -2147483648-1 -> 2147483647  some loop described in previous answers)

```<code>System.out.println(2*a);
</code>```

gives: -2 (2147483647+2147483647 -> -2147483648+2147483646 again mathematical logical)

```<code>System.out.println(4*a);
</code>```

gives: -4 (2147483647+2147483647+2147483647+2147483647 -> -2147483648+2147483646+2147483647+2147483647 -> -2-2 (according to last answer) -> -4)`

Body:
Cause overflow and two-compliant nature count goes on "second loop", we was on far most right position 2147483647 and after summing 1, we appeared at far most left position -2147483648, next incrementing goes -2147483647, -2147483646, -2147483645, ... and so forth to the far most right again and on and on, its nature of summing machine on this bit depth.

Some examples:

int a = 2147483647;

System.out.println(a);

gives: 2147483647

System.out.println(a+1);

gives: -2147483648 (cause overflow and two-compliant nature count goes on "second loop", we was on far most right position 2147483647 and after summing 1, we appeared at far most left position -2147483648, next incrementing goes -2147483648, -2147483647, -2147483646, ... and so fores to the far most right again and on and on, its nature of summing machine on this bit depth)

System.out.println(2-a);

gives:-2147483645 (-2147483647+2  seems mathematical logical)

System.out.println(-2-a);

gives: 2147483647 (-2147483647-1 -> -2147483648, -2147483648-1 -> 2147483647  some loop described in previous answers)

System.out.println(2*a);

gives: -2 (2147483647+2147483647 -> -2147483648+2147483646 again mathematical logical)

System.out.println(4*a);

gives: -4 (2147483647+2147483647+2147483647+2147483647 -> -2147483648+2147483646+2147483647+2147483647 -> -2-2 (according to last answer) -> -4)`


问:
Fitting negative binomial in python
In scipy there is no support for fitting a negative binomial distribution using data
(maybe due to the fact that the negative binomial in scipy is only discrete).

For a normal distribution I would just do:

```<code>from scipy.stats import norm
param = norm.fit(samp)
</code>```

Is there something similar 'ready to use' function in any other library?

Title: Fitting negative binomial in python

Body:
In scipy there is no support for fitting a negative binomial distribution using data
(maybe due to the fact that the negative binomial in scipy is only discrete).

For a normal distribution I would just do:

from scipy.stats import norm
param = norm.fit(samp)

Is there something similar 'ready to use' function in any other library?

Body:
Statsmodels has discrete.discrete_model.NegativeBinomial.fit(), see here:
https://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.NegativeBinomial.fit.html#statsmodels.discrete.discrete_model.NegativeBinomial.fit


问:
How to use popper.js
I have a Laravel project, and I don't want to use bootstrap in it. can I import and use the popper.js plugin without using bootstrap?

When I try to do this, It just shows me the popover title.

答:
It might be two possibilities.
    1) Css wasn't affected.
    2) Some javascript error.
   I am sending a documentation link. Still, you are facing an error. Please send me code snippet.

Popper document link

Title: How to use popper.js


问:
How can I use the Zend library, specifically the twitter class with codeigniter?
I'm trying to use the Zend twitter service in codeigniter.

I have used the following method to integrate zend http://www.beyondcoding.com/2008/02/21/using-zend-framework-with-codeigniter/

I can successfully complete the Oauth authentication and receive a valid access token from twitter, and my callback page works fine, but when I try to make a request I get the following error:

```<code>Message: Undefined offset: 0

Filename: Client/Result.php

Line Number: 232
</code>```

I'm loading the twitter class like this:

```<code>$this->load->library('zend');
$this->zend->load('Zend/Service/Twitter');
</code>```

I'm not sure if there's anything else I should be loading, or what I'm doing wrong.

I'm using Codeigniter 2.0.2 and ZendFramework 1.11.4

Any help would be very much appreciated.

答:
This error doesn't seem to be related directly with CodeIgniter and Zend. Looking at the code on line 232 I can see this

```<code>return (string) $result[0];
</code>```

This is within the following function

```<code>/**
 * toString overload
 *
 * Be sure to only call this when the result is a single value!
 *
 * @return string
 */
public function __toString()
{
    if (!$this->getStatus()) {
        $message = $this->_sxml->xpath('//message');
        return (string) $message[0];
    } else {
        $result = $this->_sxml->xpath('//response');
        if (sizeof($result) > 1) {
            return (string) "An error occured.";
        } else {
            return (string) $result[0];
        }
    }
}
</code>```

It appears that $result is not an array - and to be honest this doesn't seem like a very well thought out function. Try looking into the class in question Zend/Rest/Client/Result.php, seeing what $result is and if the call to Twitter is actually successful.

Hope that helps.

Body:
I'm trying to use the Zend twitter service in codeigniter.

I have used the following method to integrate zend http://www.beyondcoding.com/2008/02/21/using-zend-framework-with-codeigniter/

I can successfully complete the Oauth authentication and receive a valid access token from twitter, and my callback page works fine, but when I try to make a request I get the following error:

Message: Undefined offset: 0

Filename: Client/Result.php

Line Number: 232

I'm loading the twitter class like this:

$this->load->library('zend');
$this->zend->load('Zend/Service/Twitter');

I'm not sure if there's anything else I should be loading, or what I'm doing wrong.

I'm using Codeigniter 2.0.2 and ZendFramework 1.11.4

Any help would be very much appreciated.

Body:
This error doesn't seem to be related directly with CodeIgniter and Zend. Looking at the code on line 232 I can see this

return (string) $result[0];

This is within the following function

/**
 * toString overload
 *
 * Be sure to only call this when the result is a single value!
 *
 * @return string
 */
public function __toString()
{
    if (!$this->getStatus()) {
        $message = $this->_sxml->xpath('//message');
        return (string) $message[0];
    } else {
        $result = $this->_sxml->xpath('//response');
        if (sizeof($result) > 1) {
            return (string) "An error occured.";
        } else {
            return (string) $result[0];
        }
    }
}

It appears that $result is not an array - and to be honest this doesn't seem like a very well thought out function. Try looking into the class in question Zend/Rest/Client/Result.php, seeing what $result is and if the call to Twitter is actually successful.

Hope that helps.


问:
How to duplicate a MySQL database on the same server
I have a large MySQL database, lets call it live_db, which I want to replicate on the same machine to provide a test system to play around with (test_db), including table structure and data.
In regular intervals I want to update the test_db with the content of the live_db; if possible incremental.

Is there some built-in mechanism in MySQL to do that? I think that master-slave replication is not the thing I want since it should be possible to alter data in the test_db. These changes do not have to be preserved, though.

Regards,

CGD

答:
I have been doing this for several years in different contexts, with small to medium databases (1 G to 100 G). The quick and dirty mysqldump works for smaller data sets; the smaller they are, the better it goes.

When you exceed 5-10 GB, depending on the MySQL load, quick and dirty does not cut it anymore.

why mysqldump might not be enough

The problem with MySQLdump is that while it dumps, the live database is either unusable, very awkward to use, or the backup will not be consistent. Unless you have a wide enough time window when the unusability of the live database is not important because the database needs not be in use anyway (for example, late at night).

The default options (here a discussion of the why) make the database next to unusable while it's being dumped, unless the usage is just reading data and little of that. On a busy ecommerce site, you're looking at a client pile-up crash.

So you use InnoDB and the modern options (not defaults, as far as I know)

```<code>--single-transaction --skip-lock-tables
</code>```

which allow the site to run, albeit slower than normal, during the dump. Depending on what the usage is, it might be noticeably slower.

While you're at it, also dump other data which might be important:

```<code>--events --triggers --routines
</code>```

(...oh, and this still won't have dumped user permissions. To use as a test perhaps it wasn't so important).

There is a workaround I've found "advised" (!) as a "great hack", which basically disables transactional integrity allowing the database to run at full speed while it's being dumped. Somewhat like removing the brakes from your car to lighten it and have it run faster, yeah it will work, but it'll have some side effects that you might not notice immediately. You will almost surely notice them sooner or later - and just like brakes, it will be when you'll need them most, and it won't be pretty.

However, for a test database, it could still work.

Xtrabackup

If you have a "serious" database, what's the reason not to have a "serious" backup?

Slave replication

Another possibility if you have space to spare - and, nowadays, 20 Gb is not that much - is that of using an ancillary database.

You can install a second copy of MySQL Server on the same server on a different port, and have it be the slave (the server will take a performance hit, storage-speed-wise). Then you will have two identical databases (live master, live slave). The first time you will still have to run a full dump to get them in sync, with all the problems it involves.

When you need to clone the test database, stop the slave replication - the live slave will now remain "frozen" in time - and backup the live slave to the test db, using MySQLbackup or just copying the data files. Once done, you restart the replication.

The impact on the live master is negligible, and the slave can actually be used for non-update-critical selects.

Body:
I have been doing this for several years in different contexts, with small to medium databases (1 G to 100 G). The quick and dirty mysqldump works for smaller data sets; the smaller they are, the better it goes.

When you exceed 5-10 GB, depending on the MySQL load, quick and dirty does not cut it anymore.

why mysqldump might not be enough

The problem with MySQLdump is that while it dumps, the live database is either unusable, very awkward to use, or the backup will not be consistent. Unless you have a wide enough time window when the unusability of the live database is not important because the database needs not be in use anyway (for example, late at night).

The default options (here a discussion of the why) make the database next to unusable while it's being dumped, unless the usage is just reading data and little of that. On a busy ecommerce site, you're looking at a client pile-up crash.

So you use InnoDB and the modern options (not defaults, as far as I know)

--single-transaction --skip-lock-tables

which allow the site to run, albeit slower than normal, during the dump. Depending on what the usage is, it might be noticeably slower.

While you're at it, also dump other data which might be important:

--events --triggers --routines

(...oh, and this still won't have dumped user permissions. To use as a test perhaps it wasn't so important).

There is a workaround I've found "advised" (!) as a "great hack", which basically disables transactional integrity allowing the database to run at full speed while it's being dumped. Somewhat like removing the brakes from your car to lighten it and have it run faster, yeah it will work, but it'll have some side effects that you might not notice immediately. You will almost surely notice them sooner or later - and just like brakes, it will be when you'll need them most, and it won't be pretty.

However, for a test database, it could still work.

Xtrabackup

If you have a "serious" database, what's the reason not to have a "serious" backup?

Slave replication

Another possibility if you have space to spare - and, nowadays, 20 Gb is not that much - is that of using an ancillary database.

You can install a second copy of MySQL Server on the same server on a different port, and have it be the slave (the server will take a performance hit, storage-speed-wise). Then you will have two identical databases (live master, live slave). The first time you will still have to run a full dump to get them in sync, with all the problems it involves.

When you need to clone the test database, stop the slave replication - the live slave will now remain "frozen" in time - and backup the live slave to the test db, using MySQLbackup or just copying the data files. Once done, you restart the replication.

The impact on the live master is negligible, and the slave can actually be used for non-update-critical selects.


问:
Immutable.js split key of type Map
Consider the following example using Immutable's List and Map collections:

```<code>const Map = Immutable.Map;
const List = Immutable.List;

const origin = List([Map({name: 'element1', groupKey: Map({id1: 'foo', id2: 'bar'})}), Map({name: 'element2', groupKey: Map({id3: 'foo'})})]);

console.log("Origin:", String(origin));

const grouped = origin.groupBy( el => el.get('groupKey'));

console.log("Grouped:", String(grouped));

console.log("Expected", "OrderedMap { 'id1': List [ Map { 'name': 'element1', 'groupKey': Map { 'id1': 'foo', 'id2': 'bar' } } ], 'id2': List [ Map { 'name': 'element1', 'groupKey': Map { 'id1': 'foo', 'id2': 'bar' } } ], 'id3': List [ Map { 'name': 'element2', 'groupKey': Map { 'id3': 'foo' } } ] }");
</code>```

Basically, what I'm searching for is a way to group the contained maps from origin by groupKeyin a way where each of the ids (id1, id2, id3) points to the beloging maps:

```<code>{
 id1: [{'name': 'element1', ...}],
 id2: [{'name': 'element1', ...}],
 id3: [{'name': 'element2', ...}],
}
</code>```

I could not figure out how to split the resulting keys as returned from  groupBy (which are Maps in this case). I tried to use the mapping functions provided by the API but it seems they cannot be used to alter the cardinality as needed.

What would be the cleanest way to achieve this?

答:
The value of el.get('groupKey') is a unique map. Therefore, every element is in it's own group.

The groupBy function cannot group by multiple keys, every element will go in a single group.

```<code>const origin = List([
  Map({name: 'element1', groupKey: 'banana'}),
  Map({name: 'element2', groupKey: 'rocket'}),
  Map({name: 'element3', groupKey: 'rocket'}),
  Map({name: 'element4', groupKey: 'rocket'}),
]);

const groupedMap = origin.groupBy( el => el.get('groupKey'));
// results in:
// "OrderedMap { 'banana': List [ Map { 'name': 'element1', 'groupKey': 'banana' } ], 'rocket': List [ Map { 'name': 'element2', 'groupKey': 'rocket' }, Map { 'name': 'element3', 'groupKey': 'rocket' }, Map { 'name': 'element4', 'groupKey': 'rocket' } ] }"
</code>```

If you want to group by multiple values, as in your example, then you need to write your own grouping function. A list would probably make more sense for the grouping keys, but let's stick to the example:

const Map = Immutable.Map;
const List = Immutable.List;
const OrderedMap = Immutable.OrderedMap;

const origin = List([
  Map({name: 'element1', groupKey: Map({id1: 'foo', id2: 'bar'})}),
  Map({name: 'element2', groupKey: Map({id3: 'foo'})}),
  Map({name: 'element3', groupKey: Map({id99: 'bar'})}),
  Map({name: 'element4'}),
]);

function groupByMap(map, mapKey) {
  const groups = {};
  let keyMap;
  map.forEach(elem => {
    keyMap = elem.get(mapKey);
    if (Immutable.isCollection(keyMap)) {
      keyMap.valueSeq().forEach(k => {
        if (!groups[k]) {
          groups[k] = [elem];
        } else {
          groups[k].push(elem);
        }
      });
    } else if(groups['lost+found']){
      groups['lost+found'].push(elem);
    } else {
      groups['lost+found'] = elem;
    }
  });
  return Immutable.fromJS(groups);
}

const grouped = groupByMap(origin, 'groupKey');
console.log("Grouped:", String(grouped));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script></code>```

Title: Immutable.js split key of type Map

Body:
Consider the following example using Immutable's List and Map collections:

const Map = Immutable.Map;
const List = Immutable.List;

const origin = List([Map({name: 'element1', groupKey: Map({id1: 'foo', id2: 'bar'})}), Map({name: 'element2', groupKey: Map({id3: 'foo'})})]);

console.log("Origin:", String(origin));

const grouped = origin.groupBy( el => el.get('groupKey'));

console.log("Grouped:", String(grouped));

console.log("Expected", "OrderedMap { 'id1': List [ Map { 'name': 'element1', 'groupKey': Map { 'id1': 'foo', 'id2': 'bar' } } ], 'id2': List [ Map { 'name': 'element1', 'groupKey': Map { 'id1': 'foo', 'id2': 'bar' } } ], 'id3': List [ Map { 'name': 'element2', 'groupKey': Map { 'id3': 'foo' } } ] }");

Basically, what I'm searching for is a way to group the contained maps from origin by groupKeyin a way where each of the ids (id1, id2, id3) points to the beloging maps:

{
 id1: [{'name': 'element1', ...}],
 id2: [{'name': 'element1', ...}],
 id3: [{'name': 'element2', ...}],
}

I could not figure out how to split the resulting keys as returned from  groupBy (which are Maps in this case). I tried to use the mapping functions provided by the API but it seems they cannot be used to alter the cardinality as needed.

What would be the cleanest way to achieve this?

Body:
The value of el.get('groupKey') is a unique map. Therefore, every element is in it's own group.

The groupBy function cannot group by multiple keys, every element will go in a single group.

const origin = List([
  Map({name: 'element1', groupKey: 'banana'}),
  Map({name: 'element2', groupKey: 'rocket'}),
  Map({name: 'element3', groupKey: 'rocket'}),
  Map({name: 'element4', groupKey: 'rocket'}),
]);

const groupedMap = origin.groupBy( el => el.get('groupKey'));
// results in:
// "OrderedMap { 'banana': List [ Map { 'name': 'element1', 'groupKey': 'banana' } ], 'rocket': List [ Map { 'name': 'element2', 'groupKey': 'rocket' }, Map { 'name': 'element3', 'groupKey': 'rocket' }, Map { 'name': 'element4', 'groupKey': 'rocket' } ] }"

If you want to group by multiple values, as in your example, then you need to write your own grouping function. A list would probably make more sense for the grouping keys, but let's stick to the example:

const Map = Immutable.Map;
const List = Immutable.List;
const OrderedMap = Immutable.OrderedMap;

const origin = List([
  Map({name: 'element1', groupKey: Map({id1: 'foo', id2: 'bar'})}),
  Map({name: 'element2', groupKey: Map({id3: 'foo'})}),
  Map({name: 'element3', groupKey: Map({id99: 'bar'})}),
  Map({name: 'element4'}),
]);

function groupByMap(map, mapKey) {
  const groups = {};
  let keyMap;
  map.forEach(elem => {
    keyMap = elem.get(mapKey);
    if (Immutable.isCollection(keyMap)) {
      keyMap.valueSeq().forEach(k => {
        if (!groups[k]) {
          groups[k] = [elem];
        } else {
          groups[k].push(elem);
        }
      });
    } else if(groups['lost+found']){
      groups['lost+found'].push(elem);
    } else {
      groups['lost+found'] = elem;
    }
  });
  return Immutable.fromJS(groups);
}

const grouped = groupByMap(origin, 'groupKey');
console.log("Grouped:", String(grouped));

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>


问:
sql query related issue
I have one more question in want to the user between the operator in php. This is my SQL query.

```<code>$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN $start AND $end ");
</code>```

it gives me an error

```<code>$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '26/05/2019' AND '31/05/2019' ");
</code>```

am getting data in this why in the $start and $end am not getting any data

答:
Now it is working. $arr=array(); foreach($results as $single) { $start = $single->trip_start_date; $end = $single->trip_end_date; /* return $sql = "SELECT user_id,day,activity,hotel FROM wp_user_activity WHERE user_id = '$user_id' AND date BETWEEN '$start' AND '$end' "; */ $results=$wpdb->get_results( "SELECT user_id,day,activity,hotel FROM wp_user_activity WHERE user_id = '$user_id' AND date BETWEEN '$start' AND '$end' "); $single->trip_details=$results; $arr[]=$single;

}

Title: sql query related issue

Body:
I have one more question in want to the user between the operator in php. This is my SQL query.

$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN $start AND $end ");

it gives me an error

$results=$wpdb->get_results( "SELECT user_id,day,activity,hotel
FROM wp_user_activity
WHERE user_id = '$user_id' AND date BETWEEN '26/05/2019' AND '31/05/2019' ");

am getting data in this why in the $start and $end am not getting any data


问:
Use floating point button to create menu item
I'm making a counter app want to be able to have a plus button (which I have designed) open up a dialog box that allows the user to enter a title and click add, and then have this new counter automatically add itself to the menu bar (the 3 dashes in the right top corner.)

I have 0 coding experience and don't know how to attempt this, any help or references to videos that I can't find (I've looked) would be greatly appreciated.

```<code>MENU ITEM CODE:
 <item
     android:id="@+id/nav_counter1"
     android:icon="@android:drawable/ic_menu_view"
     android:title="Counter 1" />
 <item

FLOATING POINT BUTTON CODE:
<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:scaleType="fitXY"
        android:tint="@android:color/white"
        app:backgroundTint="#0578C4"
        app:fabCustomSize="80dp"
        app:srcCompat="@android:drawable/ic_input_add"/>
</code>```

This is the code for how I want each menu item to look, but with the user's custom title rather than "Counter X" (X being 1,2,3 etc).

答:
First of all, create an ArrayList with titles (assumed you know how to do that).
You probably need some other class than String, but let assuming a String is enough.

```<code>ArrayList<String> myList = new ArrayList<String>;
</code>```

Then, on "Add" button of your dialog box

```<code>myList.add(theNewInsertedTitle);
invalidateOptionsMenu(); // this will recreate your options menu
</code>```

Then, override your onCreateOptionsMenu from your Activity.

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    for (int i = 0; i < myList.size(); i++) {
        MenuItem mnu = menu.add(Menu.NONE, i, Menu.NONE, myList.get(i));
        mnu.setIcon(android.R.drawable.ic_menu_view);
    }
    // this is needed if you want to show icons on options menu
    if(menu instanceof MenuBuilder) {  //To display sportId on overflow menu
        MenuBuilder m = (MenuBuilder) menu;
        m.setOptionalIconsVisible(true);
     }

    return true;
}
</code>```

That's all...

Body:
I'm making a counter app want to be able to have a plus button (which I have designed) open up a dialog box that allows the user to enter a title and click add, and then have this new counter automatically add itself to the menu bar (the 3 dashes in the right top corner.)

I have 0 coding experience and don't know how to attempt this, any help or references to videos that I can't find (I've looked) would be greatly appreciated.

MENU ITEM CODE:
 <item
     android:id="@+id/nav_counter1"
     android:icon="@android:drawable/ic_menu_view"
     android:title="Counter 1" />
 <item

FLOATING POINT BUTTON CODE:
<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:scaleType="fitXY"
        android:tint="@android:color/white"
        app:backgroundTint="#0578C4"
        app:fabCustomSize="80dp"
        app:srcCompat="@android:drawable/ic_input_add"/>

This is the code for how I want each menu item to look, but with the user's custom title rather than "Counter X" (X being 1,2,3 etc).

Body:
First of all, create an ArrayList with titles (assumed you know how to do that).
You probably need some other class than String, but let assuming a String is enough.

ArrayList<String> myList = new ArrayList<String>;

Then, on "Add" button of your dialog box

myList.add(theNewInsertedTitle);
invalidateOptionsMenu(); // this will recreate your options menu

Then, override your onCreateOptionsMenu from your Activity.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    for (int i = 0; i < myList.size(); i++) {
        MenuItem mnu = menu.add(Menu.NONE, i, Menu.NONE, myList.get(i));
        mnu.setIcon(android.R.drawable.ic_menu_view);
    }
    // this is needed if you want to show icons on options menu
    if(menu instanceof MenuBuilder) {  //To display sportId on overflow menu
        MenuBuilder m = (MenuBuilder) menu;
        m.setOptionalIconsVisible(true);
     }

    return true;
}

That's all...


问:
Open a html file using default web browser
I'm using this to get the path and executable of default web browser:

```<code>public static string DefaultWebBrowser
        {
            get
            {

                string path = @"\http\shell\open\command";

                using (RegistryKey reg = Registry.ClassesRoot.OpenSubKey(path))
                {
                    if (reg != null)
                    {
                        string webBrowserPath = reg.GetValue(String.Empty) as string;

                        if (!String.IsNullOrEmpty(webBrowserPath))
                        {
                            if (webBrowserPath.First() == '"')
                            {
                                return webBrowserPath.Split('"')[1];
                            }

                            return webBrowserPath.Split(' ')[0];
                        }
                    }

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

And:

```<code> protected static bool Run(string FileName, string Args)
        {
            try
            {
                Process proc = new Process();

                processInfo.FileName = FileName;
                 proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

                if(Args != null) proc.StartInfo.Arguments = Args;

                proc.Start();

                return true;
            }
            catch (Exception) { }

            return false;
        }
</code>```

Then I call the web browser: Run(DefaultWebBrowser, "foo.html")

The question is: the above function is calling Firefox and IE (the two web browsers installed on my pc) instead of Internet Explorer, the default web browser. I have no idea how to fix this.

EDIT

I have downloaded and installed the Google Chrome, set it as default web browser, but oddly the above error don't happens with it.

答:
UPDATE 30 April 2022: For .Net Core  better solution is to set UseShellExecute = true as suggested in .Net Core 2.0 Process.Start throws "The specified executable is not a valid application for this OS platform"

Original suggestion:
For .Net Core you need to call (suggested in .Net Core 2.0 Process.Start throws "The specified executable is not a valid application for this OS platform")

```<code> var proc = Process.Start(@"cmd.exe ", @"/c " + pathToHtmlFile);
</code>```

When I tried Process.Start(pathToHtmlFile);,
I've got System.ComponentModel.Win32Exception: The specified executable is not a valid application for this OS platform.

Body:
I'm using this to get the path and executable of default web browser:

public static string DefaultWebBrowser
        {
            get
            {

                string path = @"\http\shell\open\command";

                using (RegistryKey reg = Registry.ClassesRoot.OpenSubKey(path))
                {
                    if (reg != null)
                    {
                        string webBrowserPath = reg.GetValue(String.Empty) as string;

                        if (!String.IsNullOrEmpty(webBrowserPath))
                        {
                            if (webBrowserPath.First() == '"')
                            {
                                return webBrowserPath.Split('"')[1];
                            }

                            return webBrowserPath.Split(' ')[0];
                        }
                    }

                    return null;
                }
            }
        }

And:

 protected static bool Run(string FileName, string Args)
        {
            try
            {
                Process proc = new Process();

                processInfo.FileName = FileName;
                 proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

                if(Args != null) proc.StartInfo.Arguments = Args;

                proc.Start();

                return true;
            }
            catch (Exception) { }

            return false;
        }

Then I call the web browser: Run(DefaultWebBrowser, "foo.html")

The question is: the above function is calling Firefox and IE (the two web browsers installed on my pc) instead of Internet Explorer, the default web browser. I have no idea how to fix this.

EDIT

I have downloaded and installed the Google Chrome, set it as default web browser, but oddly the above error don't happens with it.

Body:
UPDATE 30 April 2022: For .Net Core  better solution is to set UseShellExecute = true as suggested in .Net Core 2.0 Process.Start throws "The specified executable is not a valid application for this OS platform"

Original suggestion:
For .Net Core you need to call (suggested in .Net Core 2.0 Process.Start throws "The specified executable is not a valid application for this OS platform")

 var proc = Process.Start(@"cmd.exe ", @"/c " + pathToHtmlFile);

When I tried Process.Start(pathToHtmlFile);,
I've got System.ComponentModel.Win32Exception: The specified executable is not a valid application for this OS platform.


问:
Download files from SFTP server to local directory
I got a code to download files from remote directory to local directory using python. I want a code that can download can a single file from remote directory to local folder. Please help me to modify this code. All suggestions are welcomed.
I tested this code but it download all the contents of remote directory to local directory,but i want a code that can download a single file from remote to local directory. I am using SFTP server

code i got: (based on Python pysftp get_r from Linux works fine on Linux but not on Windows)

```<code>import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
</code>```

答:
```<code>import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, remotefile, localdir, preserve_mtime=False):
    remotepath = remotedir + "/" + remotefile
    localpath = os.path.join(localdir, remotefile)
     mode = sftp.stat(remotepath).st_mode
     if S_ISDIR(mode):
          try:
              os.mkdir(localpath,mode=777)
          except OSError:
              pass
          get_r_portable(sftp, remotepath, localpath, preserve_mtime)
     elif S_ISREG(mode):
          sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
remote_file=input("enter the remote file: ")

local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, remote_file, local_path, preserve_mtime=False)
</code>```

Body:
I got a code to download files from remote directory to local directory using python. I want a code that can download can a single file from remote directory to local folder. Please help me to modify this code. All suggestions are welcomed.
I tested this code but it download all the contents of remote directory to local directory,but i want a code that can download a single file from remote to local directory. I am using SFTP server

code i got: (based on Python pysftp get_r from Linux works fine on Linux but not on Windows)

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)


问:
Proper steps to migrate PHP 5.6 code into PHP 7.3
we have developed previously in house system based on PHP 5.6 now we want to upgrade same code into PHP 7.3, we have not used any PHP framework we are using core way to write code means we are not using ANY PHP framework. what are the proper steps to migrate PHP 5.6 code into PHP 7.3  </p>

答:
Look through the migration guides at php.net

Have a look particularly at:

Backward incompatible changes

Deprecated features

Changed functions

Go through each of the migration guides and check to make sure that any of the function and extensions that are changed/removed and make sure they are not used in your program.

I would then also test in a testing environment to ensure that all is working correctly still (would turn debugging on for this).


问:
Custom ContextMenu not displaying in MX TextArea
Been tearing my hair out for ages trying to get my custom ContextMenu to apply to a TextArea, It will just display the default (copy, paste ect...).

```<code>        import mx.events.FlexEvent;

        public var nm:NativeMenu = new NativeMenu();
        public var cm:ContextMenu = new ContextMenu();

        protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
        {
            cm.clipboardMenu = true;

            var cmi:ContextMenuItem = new ContextMenuItem("ctest");
            cm.addItem(cmi);

            TA.contextMenu = cm;
        }
</code>```

given TA is an mx TextArea in MXML

i'm really stumped!

答:
Just to put a full set of code for everyone to see:

```<code>var cm:ContextMenu = new ContextMenu();

var menuitem:ContextMenuItem = new ContextMenuItem("Check Spelling");
menuitem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handleContextMenuEvent);
mainMenu.addItem(menuitem);

textArea.contextMenu = mainMenu;
var txt:TextField = textArea.mx_internal::getTextField() as TextField;
txt.contextMenu = mainMenu;
</code>```

Hope this helps!

Body:
Been tearing my hair out for ages trying to get my custom ContextMenu to apply to a TextArea, It will just display the default (copy, paste ect...).

        import mx.events.FlexEvent;

        public var nm:NativeMenu = new NativeMenu();
        public var cm:ContextMenu = new ContextMenu();

        protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
        {
            cm.clipboardMenu = true;

            var cmi:ContextMenuItem = new ContextMenuItem("ctest");
            cm.addItem(cmi);

            TA.contextMenu = cm;
        }

given TA is an mx TextArea in MXML

i'm really stumped!

Body:
Just to put a full set of code for everyone to see:

var cm:ContextMenu = new ContextMenu();

var menuitem:ContextMenuItem = new ContextMenuItem("Check Spelling");
menuitem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handleContextMenuEvent);
mainMenu.addItem(menuitem);

textArea.contextMenu = mainMenu;
var txt:TextField = textArea.mx_internal::getTextField() as TextField;
txt.contextMenu = mainMenu;

Hope this helps!