问:
nth-child with a PHP array
I'm using ACF to post WP posts on a page. But I to be able to control certain CSS properties using nth:child selectors. Heres the PHP which displays every thing fine.  Problem is (I'm assuming) that the "foreach" item is making the nth:child not work, because the are not siblings?</p>

```<code><div class="row">

<?php
        $posts = get_field('projects');
            if ( $posts ) {
                foreach ( $posts as $post ): ?>
            <div class="col-xl-6 no-space">
            <?php
                    setup_postdata($post); ?>
                    <div class="project__wrap">
                      <div class="project__project"><?php echo get_the_post_thumbnail(); ?></div>
                        <div class="project__description__list col-xl-6"><div class="project-content"><a href="<?php echo get_permalink(); ?>"><h2><?php echo get_the_title() ; ?></h2><p><?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 15 ) ); ?></p></a></div>

            <div class="heart"><?php
                $image = get_field('heart_icon');
                if( !empty($image) ): ?>
                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
            <?php endif; ?>
            </div>

                        </div> <!-- .project__description__list -->
                    </div> <!-- .project__wrap -->

                <?php wp_reset_postdata(); ?>
           </div>
                <?php endforeach;
                }
                ?>
</code>```

<p>      </p>

```<code>div.project-content:nth-child(odd) {
  top:0;
  left:0;
}

div.project-content:nth-child(even) {
  bottom:0;
  right:0;
}
</code>```

答:
```<code><?php    $posts = get_field('projects');
 if ( $posts ) {
 $i=0; $k; $class='';
     foreach ( $posts as $post ):
        $k= $i%2;
        if($k==0){ $class='even'; } else { $class='odd'; }?>
        <div class="col-xl-6 no-space">
            <?php setup_postdata($post); ?>
                <div class="project__wrap">
                  <div class="project__project"><?php echo get_the_post_thumbnail(); ?></div>
                    <div class="project__description__list col-xl-6"><div class="project-content <?php echo $class; ?>"><a href="<?php echo get_permalink(); ?>"><h2><?php echo get_the_title() ; ?></h2><p><?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 15 ) ); ?></p></a></div>
                    <div class="heart"><?php  $image = get_field('heart_icon');
                        if( !empty($image) ): ?>
                            <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
                        <?php endif; ?>
                    </div>
                  </div> <!-- .project__description__list -->
                </div> <!-- .project__wrap -->
            <?php wp_reset_postdata(); ?>
        </div>
<?php $i++; endforeach; }   ?>
</code>```

Now you could change your style as :

```<code>div.project-content.odd {
  top:0;
  left:0;
}

div.project-content.even {
  bottom:0;
  right:0;
}
</code>```

Title: nth-child with a PHP array

Body:
I'm using ACF to post WP posts on a page. But I to be able to control certain CSS properties using nth:child selectors. Heres the PHP which displays every thing fine.  Problem is (I'm assuming) that the "foreach" item is making the nth:child not work, because the are not siblings?

<?php
        $posts = get_field('projects');
            if ( $posts ) {
                foreach ( $posts as $post ): ?>

            <?php
                    setup_postdata($post); ?>

<?php echo get_the_post_thumbnail(); ?>

<a href="<?php echo get_permalink(); ?>">
<?php echo get_the_title() ; ?>

<?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 15 ) ); ?>

<?php
                $image = get_field('heart_icon');
                if( !empty($image) ): ?>
                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
            <?php endif; ?>

                <?php wp_reset_postdata(); ?>

                <?php endforeach;
                }
                ?>

div.project-content:nth-child(odd) {
  top:0;
  left:0;
}

div.project-content:nth-child(even) {
  bottom:0;
  right:0;
}

Body:
<?php    $posts = get_field('projects');
 if ( $posts ) {
 $i=0; $k; $class='';
     foreach ( $posts as $post ):
        $k= $i%2;
        if($k==0){ $class='even'; } else { $class='odd'; }?>
        <div class="col-xl-6 no-space">
            <?php setup_postdata($post); ?>
                <div class="project__wrap">
                  <div class="project__project"><?php echo get_the_post_thumbnail(); ?></div>
                    <div class="project__description__list col-xl-6"><div class="project-content <?php echo $class; ?>"><a href="<?php echo get_permalink(); ?>"><h2><?php echo get_the_title() ; ?></h2><p><?php echo apply_filters( 'the_content', wp_trim_words( strip_tags( $post->post_content ), 15 ) ); ?></p></a></div>
                    <div class="heart"><?php  $image = get_field('heart_icon');
                        if( !empty($image) ): ?>
                            <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
                        <?php endif; ?>
                    </div>
                  </div> <!-- .project__description__list -->
                </div> <!-- .project__wrap -->
            <?php wp_reset_postdata(); ?>
        </div>
<?php $i++; endforeach; }   ?>

Now you could change your style as :

div.project-content.odd {
  top:0;
  left:0;
}

div.project-content.even {
  bottom:0;
  right:0;
}


来源: stackexchange

问:
Error deploying shinyapp fatal error: plogr.h: No such file or directory
I'm trying to deploy a Shiny app. When the app is running in RStudio I select the deploy button to republish my updated app.

After a minute or so I receive the following error block in the console:

```<code>/usr/local/lib/R/site-library/dplyr/include/dplyr/main.h:11:19: fatal error: plogr.h: No such file or directory
 #include <plogr.h>
                   ^
compilation terminated.
In file included from /usr/local/lib/R/site-library/dplyr/include/dplyr.h:4:0,
                 from rows-data.cpp:2:
/usr/local/lib/R/site-library/dplyr/include/dplyr/main.h:11:19: fatal error: plogr.h: No such file or directory
 #include <plogr.h>
                   ^
compilation terminated.
make: *** [rows.o] Error 1
make: *** Waiting for unfinished jobs....
make: *** [rows-data.o] Error 1
ERROR: compilation failed for package ‘purrr’
* removing ‘/usr/local/lib/R/site-library/purrr’
################################# End Task Log #################################
Error: Unhandled Exception: Child Task 492377328 failed: Error building image: Error building purrr (0.2.2). Build exited with non-zero status: 1
Execution halted
</code>```

I found this discussion on Google groups. Reading through this discussion I tried to reinstall dplyr with dependencies = T.

Here are the libraries I try to load with my app:

```<code>library(tidyverse)
library(shiny)
library(shinydashboard)
library(shinyjs)
library(lubridate)
library(DT)
library(scales)
</code>```

I also tried to install plogr directly:

```<code>> install.packages("plogr.h")
Warning in install.packages :
  package ‘plogr.h’ is not available (for R version 3.3.3)
</code>```

Does anyone have any advice for deploying my Shinyapp based on this info? What should I do to get around this error?

答:
@Doug Fir I also struggled with this but finally got this working.

1) I first also tried with no luck to

```<code>install.packages("dplyr", dependencies = TRUE)
</code>```

2) So I then took a good look at the error messages on Deploy tab in Rstudio and noticed that it was complaining about another package or two. In this case purrr and Rcpp. So I reinstalled these two as well.

so I:

```<code>install.packages(c("Rcpp","purrr"))
</code>```

3) I noticed Shiny was not up to date (1.0.1 not 1.0.5) so I updated that for good measure.

```<code>install.packages("shiny")
</code>```

4) then quit Rstudio and restarted R.

Shiny app with dplyr then finally redeployed. Not sure if this beats your answer, but at least dplyr 0.7.4 worked without needing to downgrade.

I am posting this to provide clues if someone else has this problem.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to deploy a Shiny app. When the app is running in RStudio I select the deploy button to republish my updated app.

After a minute or so I receive the following error block in the console:

/usr/local/lib/R/site-library/dplyr/include/dplyr/main.h:11:19: fatal error: plogr.h: No such file or directory
 #include <plogr.h>
                   ^
compilation terminated.
In file included from /usr/local/lib/R/site-library/dplyr/include/dplyr.h:4:0,
                 from rows-data.cpp:2:
/usr/local/lib/R/site-library/dplyr/include/dplyr/main.h:11:19: fatal error: plogr.h: No such file or directory
 #include <plogr.h>
                   ^
compilation terminated.
make: *** [rows.o] Error 1
make: *** Waiting for unfinished jobs....
make: *** [rows-data.o] Error 1
ERROR: compilation failed for package ‘purrr’
* removing ‘/usr/local/lib/R/site-library/purrr’
################################# End Task Log #################################
Error: Unhandled Exception: Child Task 492377328 failed: Error building image: Error building purrr (0.2.2). Build exited with non-zero status: 1
Execution halted

I found this discussion on Google groups. Reading through this discussion I tried to reinstall dplyr with dependencies = T.

Here are the libraries I try to load with my app:

library(tidyverse)
library(shiny)
library(shinydashboard)
library(shinyjs)
library(lubridate)
library(DT)
library(scales)

I also tried to install plogr directly:

> install.packages("plogr.h")
Warning in install.packages :
  package ‘plogr.h’ is not available (for R version 3.3.3)

Does anyone have any advice for deploying my Shinyapp based on this info? What should I do to get around this error?

Body:
@Doug Fir I also struggled with this but finally got this working.

1) I first also tried with no luck to

install.packages("dplyr", dependencies = TRUE)

2) So I then took a good look at the error messages on Deploy tab in Rstudio and noticed that it was complaining about another package or two. In this case purrr and Rcpp. So I reinstalled these two as well.

so I:

install.packages(c("Rcpp","purrr"))

3) I noticed Shiny was not up to date (1.0.1 not 1.0.5) so I updated that for good measure.

install.packages("shiny")

4) then quit Rstudio and restarted R.

Shiny app with dplyr then finally redeployed. Not sure if this beats your answer, but at least dplyr 0.7.4 worked without needing to downgrade.

I am posting this to provide clues if someone else has this problem.


问:
What's the best state machine gem to mongoid?
What's the best state machine gem to use with mongoid?</p>

答: The state_machine gem https://github.com/pluginaweek/state_machine should work with mongoid as it uses active_model</p>

ContentLicense: CC BY-SA 2.5


问:
Reducing memory when manipulating images Excel VBA
I have an Excel sheet that downloads satellite imagery for helicopter landing sites and places them in to tabs with the site code. There are 166 to be exact each of those has 2 static map images for a total of 332 images and I need to manipulate them in several ways.

I have no issue downloading them and placing them but when I am manipulating them I run out of memory. The manipulations are to help our pilots see better at night when looking at the maps since they are displayed on a screen.

I typed out the following code and it works until about sheet 100 and then I run out of ram due to being restricted to a 32 bit Excel. is there a way to reduce the amount of memory being used?

```<code>Public Sub SwitchtoNight()
    Dim oWS As Worksheet
    For i = 5 To ThisWorkbook.Sheets.Count
        Set oWS = ThisWorkbook.Sheets(i)
        With oWS
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0 'Saturation
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(1).Value = -0.35  'Brightness
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.75  'Contrast

            .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0 'Saturation
            .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.35  'Contrast
        End With
        Set oWS = Nothing
    Next i
End Sub
</code>```

The images are about 400px X 400px here is an example

With the following code I get to sheet 140 before I run out of ram

```<code>Public Sub SwitchtoNight()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

    Dim oWS As Worksheet
    For i = 5 To ThisWorkbook.Sheets.Count
        Set oWS = ThisWorkbook.Sheets(i)
        oWS.DisplayPageBreaks = False
        With oWS
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0: .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(1).Value = -0.35: .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.75
            .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0: .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.35
        End With
        Set oWS = Nothing
    Next I

    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub
</code>```

答:
Downloading the images as a Night Map will help, as will saving as JPG instead of PNG.  I think Excel just isn't meant to handle image manipulation on this scale, although saving, closing & re-opening partway through the process will free up some memory.

There are a number of free options (online or downloadable) for batch photo editing in this way, such as ImBatch or BatchPhoto, which will do the job in no time.

Note that PictureEffects is basically saving a new "layer" with each manipulation, sucking up memory along with it. (In my case, about 2000kb per change.)

If you do choose to stick with Excel, use the ShapeRange.PictureFormat Property instead of the PictureEffects Object.

Also if you're using the API, note that Stack Overflow has a tag just for you!  google-static-maps  If you add that tag to your question, you might get further help from people more familiar with that API than I.

Check out this link (note the adjustments than can be handled directly in the URL):

http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyADV4Wfi9-4ET5GG52Cw_l0_Bkt8W5vwvM&center=43.597586,-79.746689&zoom=14&markers=icon:http://www.xmeasures.com/images/planMapPin.png|43.597586,-79.746689&format=png32&sensor=false&size=480x480&scale=4&markers=color:black|&maptype=roadmap&style=feature|element:geometry|hue:0xwhite|saturation:-100%|lightness:100|visibility:off&style=feature:road|element:geometry|hue:0xblack|saturation:-100%|lightness:-20|visibility:on&style=feature:road.path|element:labels|hue:0xblack|saturation:-100%|lightness:-20|visibility:off&style=feature:labels|element:geometry|hue:0xblack|saturation:-100%|lightness:-20|visibility:off&style=feature:water|element:geometry|hue:0xblack|saturation:-100%|lightness:-40|visibility:on&style=element:labels.text.stroke|visibility:off&style=element:labels.text.fill|visibility:off&style=feature:road|hue:0xblack|saturation:-100%|lightness:-100|element:labels.text.fill|visibility:on&style=feature:transit|visibility:off&style=feature:poi|visibility:off&style=feature:landscape|visibility:off&key=AIzaSyADV4Wfi9-4ET5GG52Cw_l0_Bkt8W5vwvM|
  (Source)

Try something like:

```<code>    Dim oWS As Worksheet, sh As Shape
</code>```

…

```<code>    Set oWS = ThisWorkbook.Sheets(I)
    Set sh = oWS.Shapes("GoogleMap1")
    With sh
        .PictureFormat.Brightness = -0.35
        .PictureFormat.Contrast = 0.75

        With sh.Fill.PictureEffects
            .Delete (1)
            .Insert(msoEffectSaturation).EffectParameters(1).Value = 0
        End With
    End With
    Set sh = Nothing
    Set oWS = Nothing
</code>```

…

I didn't test this but there are examples here and here

Body:
I have an Excel sheet that downloads satellite imagery for helicopter landing sites and places them in to tabs with the site code. There are 166 to be exact each of those has 2 static map images for a total of 332 images and I need to manipulate them in several ways.

I have no issue downloading them and placing them but when I am manipulating them I run out of memory. The manipulations are to help our pilots see better at night when looking at the maps since they are displayed on a screen.

I typed out the following code and it works until about sheet 100 and then I run out of ram due to being restricted to a 32 bit Excel. is there a way to reduce the amount of memory being used?

Public Sub SwitchtoNight()
    Dim oWS As Worksheet
    For i = 5 To ThisWorkbook.Sheets.Count
        Set oWS = ThisWorkbook.Sheets(i)
        With oWS
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0 'Saturation
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(1).Value = -0.35  'Brightness
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.75  'Contrast

            .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0 'Saturation
            .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.35  'Contrast
        End With
        Set oWS = Nothing
    Next i
End Sub

The images are about 400px X 400px here is an example

With the following code I get to sheet 140 before I run out of ram

Public Sub SwitchtoNight()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

    Dim oWS As Worksheet
    For i = 5 To ThisWorkbook.Sheets.Count
        Set oWS = ThisWorkbook.Sheets(i)
        oWS.DisplayPageBreaks = False
        With oWS
            .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0: .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(1).Value = -0.35: .Shapes("GoogleMap1").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.75
            .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectSaturation).EffectParameters(1).Value = 0: .Shapes("GoogleMap2").Fill.PictureEffects.Insert(msoEffectBrightnessContrast).EffectParameters(2).Value = 0.35
        End With
        Set oWS = Nothing
    Next I

    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Body:
Downloading the images as a Night Map will help, as will saving as JPG instead of PNG.  I think Excel just isn't meant to handle image manipulation on this scale, although saving, closing & re-opening partway through the process will free up some memory.

There are a number of free options (online or downloadable) for batch photo editing in this way, such as ImBatch or BatchPhoto, which will do the job in no time.

Note that PictureEffects is basically saving a new "layer" with each manipulation, sucking up memory along with it. (In my case, about 2000kb per change.)

If you do choose to stick with Excel, use the ShapeRange.PictureFormat Property instead of the PictureEffects Object.

Also if you're using the API, note that Stack Overflow has a tag just for you!  google-static-maps  If you add that tag to your question, you might get further help from people more familiar with that API than I.

Check out this link (note the adjustments than can be handled directly in the URL):

<a href="http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyADV4Wfi9-4ET5GG52Cw_l0_Bkt8W5vwvM&center=43.597586,-79.746689&zoom=14&markers=icon:http://www.xmeasures.com/images/planMapPin.png|43.597586,-79.746689&format=png32&sensor=false&size=480x480&scale=4&markers=color:black|&maptype=roadmap&style=feature|element:geometry|hue:0xwhite|saturation:-100%|lightness:100|visibility:off&style=feature:road|element:geometry|hue:0xblack|saturation:-100%|lightness:-20|visibility:on&style=feature:road.path|element:labels|hue:0xblack|saturation:-100%|lightness:-20|visibility:off&style=feature:labels|element:geometry|hue:0xblack|saturation:-100%|lightness:-20|visibility:off&style=feature:water|element:geometry|hue:0xblack|saturation:-100%|lightness:-40|visibility:on&style=element:labels.text.stroke|visibility:off&style=element:labels.text.fill|visibility:off&style=feature:road|hue:0xblack|saturation:-100%|lightness:-100|element:labels.text.fill|visibility:on&style=feature:transit|visibility:off&style=feature:poi|visibility:off&style=feature:landscape|visibility:off&key=AIzaSyADV4Wfi9-4ET5GG52Cw_l0_Bkt8W5vwvM|" rel="nofollow noreferrer">http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyADV4Wfi9-4ET5GG52Cw_l0_Bkt8W5vwvM&center=43.597586,-79.746689&zoom=14&markers=icon:http://www.xmeasures.com/images/planMapPin.png|43.597586,-79.746689&format=png32&sensor=false&size=480x480&scale=4&markers=color:black|&maptype=roadmap&style=feature|element:geometry|hue:0xwhite|saturation:-100%|lightness:100|visibility:off&style=feature:road|element:geometry|hue:0xblack|saturation:-100%|lightness:-20|visibility:on&style=feature:road.path|element:labels|hue:0xblack|saturation:-100%|lightness:-20|visibility:off&style=feature:labels|element:geometry|hue:0xblack|saturation:-100%|lightness:-20|visibility:off&style=feature:water|element:geometry|hue:0xblack|saturation:-100%|lightness:-40|visibility:on&style=element:labels.text.stroke|visibility:off&style=element:labels.text.fill|visibility:off&style=feature:road|hue:0xblack|saturation:-100%|lightness:-100|element:labels.text.fill|visibility:on&style=feature:transit|visibility:off&style=feature:poi|visibility:off&style=feature:landscape|visibility:off&key=AIzaSyADV4Wfi9-4ET5GG52Cw_l0_Bkt8W5vwvM|
  (Source)

Try something like:

    Dim oWS As Worksheet, sh As Shape

…

    Set oWS = ThisWorkbook.Sheets(I)
    Set sh = oWS.Shapes("GoogleMap1")
    With sh
        .PictureFormat.Brightness = -0.35
        .PictureFormat.Contrast = 0.75

        With sh.Fill.PictureEffects
            .Delete (1)
            .Insert(msoEffectSaturation).EffectParameters(1).Value = 0
        End With
    End With
    Set sh = Nothing
    Set oWS = Nothing

…

I didn't test this but there are examples here and here


问:
Variables are not initialized in if statement
I was trying the following code out.

```<code>    int index, use, comp;
    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
    }
    for (index = 0; index < 3; index++)
    {
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
    }
    int sum = comp + use;
</code>```

At the line int sum = comp + use;, I am getting an error saying that variables comp and use are not initialized. How can I store the values I had gotten during the execution of the loop in these variables?

答:
You need to calculate the sum inside the for loop, otherwise, the two variables will be accessible (outside of the loop).</p>

```<code> int index;
 int sum = 0;
 int comp= 0;
 int use = 0;
 //would've been better if you specified what these variables are for though.

    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
        sum = comp + use;
    }
</code>```

Body:
I was trying the following code out.

    int index, use, comp;
    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
    }
    for (index = 0; index < 3; index++)
    {
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
    }
    int sum = comp + use;

At the line int sum = comp + use;, I am getting an error saying that variables comp and use are not initialized. How can I store the values I had gotten during the execution of the loop in these variables?

Body:
You need to calculate the sum inside the for loop, otherwise, the two variables will be accessible (outside of the loop).

 int index;
 int sum = 0;
 int comp= 0;
 int use = 0;
 //would've been better if you specified what these variables are for though.

    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
        sum = comp + use;
    }


问:
App Engine Java Deployment Error: java.lang.NoSuchMethodError: com.google.common.reflect.TypeToken.isSubtypeOf
We are getting following error on deploying on app engine server since last 4-5 days.  Sometimes deployment works, but most of the time it gives following errors.

Log snippet 1:

```<code>Error for /_ah/api/agentEndPoint/v1/addLead
java.lang.NoSuchMethodError: com.google.common.reflect.TypeToken.isSubtypeOf(Ljava/lang/reflect/Type;)Z
    at com.google.api.server.spi.config.model.Types.getArrayItemType(Types.java:138)
    at com.google.api.server.spi.SystemService.registerService(SystemService.java:185)
    at com.google.api.server.spi.SystemService$Builder.build(SystemService.java:524)
    at com.google.api.server.spi.EndpointsServlet.createSystemService(EndpointsServlet.java:130)
</code>```

Log snippet 2:

```<code>/_ah/api/taskEndPoint/v1/gettaskdetailresponse/TCB-16327
java.lang.NullPointerException
    at com.google.api.server.spi.EndpointsServlet.service(EndpointsServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
</code>```

答:
Change in build.gradle

```<code>classpath 'com.google.cloud.tools:endpoints-framework-gradle-plugin:1.0.1'
</code>```

changed to

```<code>classpath 'com.google.cloud.tools:endpoints-framework-gradle-plugin:1.0.2'
</code>```

Worked for me.

Also extra gradle clean remove the error

https://github.com/GoogleCloudPlatform/endpoints-framework-gradle-plugin/blob/master/ANDROID_README.md

Body:
We are getting following error on deploying on app engine server since last 4-5 days.  Sometimes deployment works, but most of the time it gives following errors.

Log snippet 1:

Error for /_ah/api/agentEndPoint/v1/addLead
java.lang.NoSuchMethodError: com.google.common.reflect.TypeToken.isSubtypeOf(Ljava/lang/reflect/Type;)Z
    at com.google.api.server.spi.config.model.Types.getArrayItemType(Types.java:138)
    at com.google.api.server.spi.SystemService.registerService(SystemService.java:185)
    at com.google.api.server.spi.SystemService$Builder.build(SystemService.java:524)
    at com.google.api.server.spi.EndpointsServlet.createSystemService(EndpointsServlet.java:130)

Log snippet 2:

/_ah/api/taskEndPoint/v1/gettaskdetailresponse/TCB-16327
java.lang.NullPointerException
    at com.google.api.server.spi.EndpointsServlet.service(EndpointsServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Body:
Change in build.gradle

classpath 'com.google.cloud.tools:endpoints-framework-gradle-plugin:1.0.1'

changed to

classpath 'com.google.cloud.tools:endpoints-framework-gradle-plugin:1.0.2'

Worked for me.

Also extra gradle clean remove the error

https://github.com/GoogleCloudPlatform/endpoints-framework-gradle-plugin/blob/master/ANDROID_README.md


问:
regex segfault when compiling with clang, possible compiler bug?
let's start with the minimal code to reproduce the error:

```<code>#include <cxxabi.h>
#include <iostream>
#include <regex>

int main()
{

  std::string realname("My amazing string with trailing whitespace ");

  std::string ret = std::regex_replace(
      realname.data(), std::regex{"My amazing string with trailing whitespace ?"},
      "std::string" );

  std::cout << ret << std::endl;
}
</code>```

If you compile this with clang:

clang++ -O2 -g -std=c++14 test.cpp -o crash

This will produce a segmentation fault.

Using -O1 or less will work, using gcc works in all cases, and not passing the char* but just passing realname as std::string will work as well.

However the original code only has the char* so I would have to perform a copy to get the std::string.

So let's focus on the version with clang -O2 and char*.

I have done some debugging and it seems to crash in the standard library regex parts.
To be more precise in regex.tcc line 501 reads:

```<code>return _M_pregex == __rhs._M_pregex
      && _M_begin == __rhs._M_begin
      && _M_end == __rhs._M_end
      && _M_flags == __rhs._M_flags
      && _M_match[0] == __rhs._M_match[0];
</code>```

When stepping through a binary that doesn't segfault it will perform these checks in order and stop after _M_end == __rhs._M_end, however, in the crashing binary we will see it checking _M_match[0] == __rhs._M_match[0] first which results in a crash.

I'd be happy to get some input on this, as I'm not quite sure if I am missing something here...

But if not I would assume this is a bug in the clang optimizer, no?

Edit: clang version is clang version 5.0.0 (trunk 296300)

答:
Apologies for the noise, after noticing that the provided clang5 on our system is as posted above actually not a release version I tried it with the release and clang3.9 and it works.

Must have been a regression during development...

Again, sorry for the noise!

Body:
let's start with the minimal code to reproduce the error:

#include <cxxabi.h>
#include <iostream>
#include <regex>

int main()
{

  std::string realname("My amazing string with trailing whitespace ");

  std::string ret = std::regex_replace(
      realname.data(), std::regex{"My amazing string with trailing whitespace ?"},
      "std::string" );

  std::cout << ret << std::endl;
}

If you compile this with clang:

clang++ -O2 -g -std=c++14 test.cpp -o crash

This will produce a segmentation fault.

Using -O1 or less will work, using gcc works in all cases, and not passing the char* but just passing realname as std::string will work as well.

However the original code only has the char* so I would have to perform a copy to get the std::string.

So let's focus on the version with clang -O2 and char*.

I have done some debugging and it seems to crash in the standard library regex parts.
To be more precise in regex.tcc line 501 reads:

return _M_pregex == __rhs._M_pregex
      && _M_begin == __rhs._M_begin
      && _M_end == __rhs._M_end
      && _M_flags == __rhs._M_flags
      && _M_match[0] == __rhs._M_match[0];

When stepping through a binary that doesn't segfault it will perform these checks in order and stop after _M_end == __rhs._M_end, however, in the crashing binary we will see it checking _M_match[0] == __rhs._M_match[0] first which results in a crash.

I'd be happy to get some input on this, as I'm not quite sure if I am missing something here...

But if not I would assume this is a bug in the clang optimizer, no?

Edit: clang version is clang version 5.0.0 (trunk 296300)


问:
How to implement jQuery range slider in AngularJS
I am trying to use anuglar-slider in my existing AngularJS app.

I followed the author's comments here

I downloaded below files (in Head tag) from author's github and added in my index.html

HTML code:

```<code><head>

<link rel="stylesheet" href="css/angular-slider.css">
<script src="js/vendor/angular-slider.js"></script>

</head>
<body>

  <slider floor="10" ceiling="60" ng-model-low="lowValue" ng-model-high="highValue"></slider>

</body>
</code>```

App.js (Angular code) . I added second line as per Author's instructions, I suspect I did do something wrong there

```<code>var app = angular.module('myApp', [])
angular.module('uiSlider', []);

app.constant('Config',
{
    baseURL : "http://blah",
    httpTimeout : 36000
});
app.config(function($logProvider) {
    $logProvider.debugEnabled(true);
});
 //and some other app specific code follows
</code>```

I don't see any slider rendering in browser. However, the older Angular specific functionality in the app still works and there is no error in browser's console.

If you cannot find problem above, feel free to suggest any other way to implement range slider in AngularJS app.

I am fairly new to AngularJS

Let me know if you like me to post Author's library file code here as well.

答:
Recently I have used RANGE SLIDER in angularJS.
If you want to use fancy slider or slider directive. You will get it from below.

AngularJS slider directive with no external dependencies There are many types of sliders like

Simple slider

Range slider

Slider with custom style

Slider with dynamic selection bar color

Slider with custom floor/ceil/step

Slider with ticks

It's very easy to use, mobile friendly and customizable.

I have used simple slider using jQuery. Code is given below.

```<code><form>
    <div class="choose_industry">
        <div class="form-group">
            <label class="control-label col-xs-12 col-sm-4 col-md-2 col-lg-2 " for="name">What Industry?</label>
            <div class="col-xs-12 col-sm-8 col-md-10 col-lg-10">
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio1" value="cdl" ng-model="leg_ser.industry">
                    <label for="radio1">
                        Commercial Trucking Transportation
                    </label>
                </div>
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio2" value="non_cdl" ng-model="leg_ser.industry">
                    <label for="radio2">
                        Other Industries
                    </label>
                </div>
            </div>
        </div>
    </div>

    <div class="employee_counting">
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Number of Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-user"></i></span>
                <input type="number" class="form-control" placeholder="Employees" name="Number of Employees" ng-model="leg_ser.num_of_emp">
                <!-- <span>Total Number of Employees</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0</span>
                <span class="pull-right">25k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="25000" value="0" class="slider" id="myRange" ng-model="leg_ser.num_of_emp">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Enrollment Percentage (%)?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-percent"></i></span>
                <input type="number" class="form-control" placeholder="Percentage" name="Enrollment Percentage" ng-model="leg_ser.enroll_per">
                <!-- <span>Estimated Percentage that will enroll</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0%</span>
                <span class="pull-right">100%</span>
                <div id="slidecontainer">
                    <input type="range" min="1" max="100" value="1" class="slider" id="myRange" ng-model="leg_ser.enroll_per">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Annual Cost per Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-dollar"></i></span>
                <input type="number" class="form-control" placeholder="Cost" name="Annual Cost per Employees" ng-model="leg_ser.annual_cost">
                <!-- <span>Avarage Salary and benifits per Employee</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">$0</span>
                <span class="pull-right">$300k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="300000" value="0" class="slider" id="myRange" ng-model="leg_ser.annual_cost">
                </div>
            </div>
        </div>
    </div>
</form>
</code>```

Add following code in the script tag

```<code><!-- RANGE SLIDER JS START -->
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>
<!-- RANGE SLIDER JS OVER -->
</code>```

Above script working good for me, should work for you too.

Body:
I am trying to use anuglar-slider in my existing AngularJS app.

I followed the author's comments here

I downloaded below files (in Head tag) from author's github and added in my index.html

HTML code:

<link rel="stylesheet" href="css/angular-slider.css">

  <slider floor="10" ceiling="60" ng-model-low="lowValue" ng-model-high="highValue"></slider>

App.js (Angular code) . I added second line as per Author's instructions, I suspect I did do something wrong there

var app = angular.module('myApp', [])
angular.module('uiSlider', []);

app.constant('Config',
{
    baseURL : "http://blah",
    httpTimeout : 36000
});
app.config(function($logProvider) {
    $logProvider.debugEnabled(true);
});
 //and some other app specific code follows

I don't see any slider rendering in browser. However, the older Angular specific functionality in the app still works and there is no error in browser's console.

If you cannot find problem above, feel free to suggest any other way to implement range slider in AngularJS app.

I am fairly new to AngularJS

Let me know if you like me to post Author's library file code here as well.

Body:
Recently I have used RANGE SLIDER in angularJS.
If you want to use fancy slider or slider directive. You will get it from below.

AngularJS slider directive with no external dependencies There are many types of sliders like

Simple slider

Range slider

Slider with custom style

Slider with dynamic selection bar color

Slider with custom floor/ceil/step

Slider with ticks

It's very easy to use, mobile friendly and customizable.

I have used simple slider using jQuery. Code is given below.

<form>
    <div class="choose_industry">
        <div class="form-group">
            <label class="control-label col-xs-12 col-sm-4 col-md-2 col-lg-2 " for="name">What Industry?</label>
            <div class="col-xs-12 col-sm-8 col-md-10 col-lg-10">
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio1" value="cdl" ng-model="leg_ser.industry">
                    <label for="radio1">
                        Commercial Trucking Transportation
                    </label>
                </div>
                <div class="radio  col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <input type="radio" name="radio1" id="radio2" value="non_cdl" ng-model="leg_ser.industry">
                    <label for="radio2">
                        Other Industries
                    </label>
                </div>
            </div>
        </div>
    </div>

    <div class="employee_counting">
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Number of Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-user"></i></span>
                <input type="number" class="form-control" placeholder="Employees" name="Number of Employees" ng-model="leg_ser.num_of_emp">
                <!-- <span>Total Number of Employees</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0</span>
                <span class="pull-right">25k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="25000" value="0" class="slider" id="myRange" ng-model="leg_ser.num_of_emp">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Enrollment Percentage (%)?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-percent"></i></span>
                <input type="number" class="form-control" placeholder="Percentage" name="Enrollment Percentage" ng-model="leg_ser.enroll_per">
                <!-- <span>Estimated Percentage that will enroll</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">0%</span>
                <span class="pull-right">100%</span>
                <div id="slidecontainer">
                    <input type="range" min="1" max="100" value="1" class="slider" id="myRange" ng-model="leg_ser.enroll_per">
                </div>
            </div>
        </div>
        <div class="form-group col-xs-12 col-sm-4 col-md-4 col-lg-4">
            <label class="control-label" for="name">Annual Cost per Employees?</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-dollar"></i></span>
                <input type="number" class="form-control" placeholder="Cost" name="Annual Cost per Employees" ng-model="leg_ser.annual_cost">
                <!-- <span>Avarage Salary and benifits per Employee</span> -->
            </div>

            <div class="range_slider">
                <span class="pull-left">$0</span>
                <span class="pull-right">$300k</span>
                <div id="slidecontainer">
                    <input type="range" min="0" max="300000" value="0" class="slider" id="myRange" ng-model="leg_ser.annual_cost">
                </div>
            </div>
        </div>
    </div>
</form>

Add following code in the script tag

<!-- RANGE SLIDER JS START -->
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>
<!-- RANGE SLIDER JS OVER -->

Above script working good for me, should work for you too.


问:
Android displaying Multiple markers on Map Fragment
Im having trouble zooming the start point (green marker) and end point (red marker), My code zoom in just on the end point. see the picture below

enter image description here

im getting my first and last data by using this:

```<code>   public void createMarker(int index, Double latitude, Double longitude, String location, String remarks) {

    double latitudeStart, longitudeStart;
    double latitudeEnd, longitudeEnd;

    index = index + 1;
    String text = String.valueOf(index);

    BitmapDescriptor image = BitmapDescriptorFactory.fromResource(index);

    IconGenerator tc = new IconGenerator(getContext());

    if (index == 1) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_green);
        latitudeStart =latitude;
        longitudeStart = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));

    } else if (index == response_last.body().getAsJsonArray().size()) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_red);
        latitudeEnd =latitude;
        longitudeEnd = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));
    } else {

    }

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    builder.include(new LatLng(latitudeStart,longitudeStart));
    builder.include(new LatLng(latitudeEnd,longitudeEnd));
    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

    mMapSnailTrail.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    });
}
</code>```

the data latitude and longitude is coming from API which im getting them by this code:

```<code>String lati = jo.get("lat").toString();
                    String latiString = lati;
                    latiString = latiString.replace("\"", "");
                    String lat = String.valueOf(latiString);

                    String longi = jo.get("lng").toString();
                    String longiString = longi;
                    longiString = longiString.replace("\"", "");
                    String lng = String.valueOf(longiString);
</code>```

and lastly this is the create marker that I've been using:

```<code> LatLngBounds.Builder builder = new LatLngBounds.Builder();
    //starting point
    builder.include(new LatLng(latitude,longitude));
        //end point
    builder.include(new LatLng(latitude,longitude));

    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
</code>```

i really need your help to accomplish this task. I'm searching on the internet but i can't find a solution. thanks guys!

答:
Seems, you use same LatLng coords LatLng(latitude,longitude) for zooming:

```<code>//starting point
builder.include(new LatLng(latitude,longitude));
//end point
builder.include(new LatLng(latitude,longitude));
</code>```

May be

```<code> //starting point
 builder.include(new LatLng(latitudeStart,longitudeStart));
 //end point
 builder.include(new LatLng(latitudeEnd,longitudeEnd));
</code>```

where (latitudeStart,longitudeStart) - coords of start point (green marker) and (latitudeEnd,longitudeEnd) - coords of end point (red marker), solve the issue. You can get latitudeStart, longitudeStart, latitudeEnd and longitudeEnd this way (updated):

```<code>// wrong code:
// LatLng latitudeStart, longitudeStart;
// LatLng latitudeEnd, longitudeEnd;

// update2: global variables
double latitudeMin = 1000, longitudeMin = 1000;   // better get first value of lat/lon, not 1000
double latitudeMax = -1000, longitudeMax = -1000;  // better get first value of lat/lon, not -1000

...

// test current latitude is min or max
if (latitude < latitudeMin) {
    latitudeMin = latitude;
} else {
    if (latitude > latitudeMax) {
        latitudeMax = latitude;
    }
}

// test current longitude is min or max
if (longitude< longitudeMin) {
    longitudeMin = longitude;
} else {
    if (longitude> longitudeMax) {
        longitudeMax = longitude;
    }
}

if (index == 1) {

    image = BitmapDescriptorFactory.fromResource(R.drawable.pin_green);
    mMapSnailTrail.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .anchor(0.5f, 0.5f)
            .title(location)
            .snippet(remarks)
            .icon(image));

} else if (index == response_last.body().getAsJsonArray().size()) {
    image = BitmapDescriptorFactory.fromResource(R.drawable.pin_red);
    mMapSnailTrail.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .anchor(0.5f, 0.5f)
            .title(location)
            .snippet(remarks)
            .icon(image));
} else {

}

...
</code>```

then, outside of createMarker():

```<code>LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(new LatLng(latitudeMin,longitudeMin));
builder.include(new LatLng(latitudeMax,longitudeMax));
LatLngBounds bounds = builder.build();
mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
</code>```

Body:
Im having trouble zooming the start point (green marker) and end point (red marker), My code zoom in just on the end point. see the picture below

enter image description here

im getting my first and last data by using this:

   public void createMarker(int index, Double latitude, Double longitude, String location, String remarks) {

    double latitudeStart, longitudeStart;
    double latitudeEnd, longitudeEnd;

    index = index + 1;
    String text = String.valueOf(index);

    BitmapDescriptor image = BitmapDescriptorFactory.fromResource(index);

    IconGenerator tc = new IconGenerator(getContext());

    if (index == 1) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_green);
        latitudeStart =latitude;
        longitudeStart = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));

    } else if (index == response_last.body().getAsJsonArray().size()) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_red);
        latitudeEnd =latitude;
        longitudeEnd = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));
    } else {

    }

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    builder.include(new LatLng(latitudeStart,longitudeStart));
    builder.include(new LatLng(latitudeEnd,longitudeEnd));
    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

    mMapSnailTrail.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    });
}

the data latitude and longitude is coming from API which im getting them by this code:

String lati = jo.get("lat").toString();
                    String latiString = lati;
                    latiString = latiString.replace("\"", "");
                    String lat = String.valueOf(latiString);

                    String longi = jo.get("lng").toString();
                    String longiString = longi;
                    longiString = longiString.replace("\"", "");
                    String lng = String.valueOf(longiString);

and lastly this is the create marker that I've been using:

 LatLngBounds.Builder builder = new LatLngBounds.Builder();
    //starting point
    builder.include(new LatLng(latitude,longitude));
        //end point
    builder.include(new LatLng(latitude,longitude));

    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));

i really need your help to accomplish this task. I'm searching on the internet but i can't find a solution. thanks guys!

Body:
Seems, you use same LatLng coords LatLng(latitude,longitude) for zooming:

//starting point
builder.include(new LatLng(latitude,longitude));
//end point
builder.include(new LatLng(latitude,longitude));

May be

 //starting point
 builder.include(new LatLng(latitudeStart,longitudeStart));
 //end point
 builder.include(new LatLng(latitudeEnd,longitudeEnd));

where (latitudeStart,longitudeStart) - coords of start point (green marker) and (latitudeEnd,longitudeEnd) - coords of end point (red marker), solve the issue. You can get latitudeStart, longitudeStart, latitudeEnd and longitudeEnd this way (updated):

// wrong code:
// LatLng latitudeStart, longitudeStart;
// LatLng latitudeEnd, longitudeEnd;

// update2: global variables
double latitudeMin = 1000, longitudeMin = 1000;   // better get first value of lat/lon, not 1000
double latitudeMax = -1000, longitudeMax = -1000;  // better get first value of lat/lon, not -1000

...

// test current latitude is min or max
if (latitude < latitudeMin) {
    latitudeMin = latitude;
} else {
    if (latitude > latitudeMax) {
        latitudeMax = latitude;
    }
}

// test current longitude is min or max
if (longitude< longitudeMin) {
    longitudeMin = longitude;
} else {
    if (longitude> longitudeMax) {
        longitudeMax = longitude;
    }
}

if (index == 1) {

    image = BitmapDescriptorFactory.fromResource(R.drawable.pin_green);
    mMapSnailTrail.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .anchor(0.5f, 0.5f)
            .title(location)
            .snippet(remarks)
            .icon(image));

} else if (index == response_last.body().getAsJsonArray().size()) {
    image = BitmapDescriptorFactory.fromResource(R.drawable.pin_red);
    mMapSnailTrail.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .anchor(0.5f, 0.5f)
            .title(location)
            .snippet(remarks)
            .icon(image));
} else {

}

...

then, outside of createMarker():

LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(new LatLng(latitudeMin,longitudeMin));
builder.include(new LatLng(latitudeMax,longitudeMax));
LatLngBounds bounds = builder.build();
mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));


问:
Script required
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

```<code>Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)
</code>```

I tried as below, where its incrementing the values rows by rows.

```<code>select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1
</code>```

Output should be:

```<code>ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40
</code>```

Can anyone here me, how to do that.

答:
try the below query </p>

```<code>select ID,Name,Series,(series - (select top 1 series from #temp1)) as abc from #temp1
</code>```

Title: Script required

Body:
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)

I tried as below, where its incrementing the values rows by rows.

select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1

Output should be:

ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40

Can anyone here me, how to do that.

Body:
try the below query

select ID,Name,Series,(series - (select top 1 series from #temp1)) as abc from #temp1


问:
Bot framework dialogs error handling
I need to handle errors withing bot framework dialogs, where I have IDialogContext to send a message or to call another dialog.
At the moment I have

```<code>try
{
    await Conversation.SendAsync();
}
catch (Exception e)
{
    HandleExceptions(e, activity);
}
</code>```

in MessagesController, but at this level the Microsoft.Bot.Builder.Dialogs.DefaultIfException already sends error message back to user.
Where and how can intercept an error before DefaultIfException, handle it and propagate unhandled to DefaultIfException.

答:
You can use your exception Layer to capture bot exception. Below code will help you to guide to proceed further. I was using that and it was working fine.

```<code>try
   {
      // your code
   }
   catch (Exception ex)
   {
      await BotException.GenerateBotException(message.From.Name, ex);
   }
</code>```

After that you need to create a Exception class to capture log in your custom DB or send email notification with exception details.

```<code>using System;
using GPP.Bot.DataAccessLayer;
using System.Collections.Generic;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web.Configuration;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;

namespace Gpp.Bot.ExceptionHandling
{
    public class BotException
    {
        public static List<ErrorLogProperties> BOTErrorLog(string Environment, string exceptionStack, string exceptionSource, string fullException, string loggedInUser, string exceptionDateTime)
        {
            // this code to capture data in Cutome DB
            return DbHelper.ExecuteList<ErrorLogProperties>(
                new Command { ComandText = "Your Stored Procedure" },
                new Parameter<string, object>("Environment", Environment),
                new Parameter<string, object>("exceptionStack", exceptionStack),
                new Parameter<string, object>("exceptionSource", exceptionSource),
                new Parameter<string, object>("fullException", fullException),
                new Parameter<string, object>("loggedInUser", loggedInUser),
                new Parameter<string, object>("exceptionDateTime", exceptionDateTime)
                );

        }

        public static async Task GenerateBotException(string LLID, Exception ex)
        {
           BotExceptionNotification(LLID.Split('*')[1], ex.StackTrace, ex.Source, ex.Message,LLID.Split('*')[0], DateTime.Now.ToString());
           BOTErrorLog(LLID.Split('*')[1], ex.StackTrace, ex.Source, ex.Message,LLID.Split('*')[0], DateTime.Now.ToString());
        }

        public static void BotExceptionNotification(string Environment, string exceptionStack, string exceptionSource,
            string fullException, string loggedInUser, string exceptionDateTime)
        {
          // Send email code goes here using above peramaeters in you html
        }

    }
}
</code>```

Do let me know in case you required more help

Title: Bot framework dialogs error handling

Body:
I need to handle errors withing bot framework dialogs, where I have IDialogContext to send a message or to call another dialog.
At the moment I have

try
{
    await Conversation.SendAsync();
}
catch (Exception e)
{
    HandleExceptions(e, activity);
}

in MessagesController, but at this level the Microsoft.Bot.Builder.Dialogs.DefaultIfException already sends error message back to user.
Where and how can intercept an error before DefaultIfException, handle it and propagate unhandled to DefaultIfException.

Body:
You can use your exception Layer to capture bot exception. Below code will help you to guide to proceed further. I was using that and it was working fine.

try
   {
      // your code
   }
   catch (Exception ex)
   {
      await BotException.GenerateBotException(message.From.Name, ex);
   }

After that you need to create a Exception class to capture log in your custom DB or send email notification with exception details.

using System;
using GPP.Bot.DataAccessLayer;
using System.Collections.Generic;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web.Configuration;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;

namespace Gpp.Bot.ExceptionHandling
{
    public class BotException
    {
        public static List<ErrorLogProperties> BOTErrorLog(string Environment, string exceptionStack, string exceptionSource, string fullException, string loggedInUser, string exceptionDateTime)
        {
            // this code to capture data in Cutome DB
            return DbHelper.ExecuteList<ErrorLogProperties>(
                new Command { ComandText = "Your Stored Procedure" },
                new Parameter<string, object>("Environment", Environment),
                new Parameter<string, object>("exceptionStack", exceptionStack),
                new Parameter<string, object>("exceptionSource", exceptionSource),
                new Parameter<string, object>("fullException", fullException),
                new Parameter<string, object>("loggedInUser", loggedInUser),
                new Parameter<string, object>("exceptionDateTime", exceptionDateTime)
                );

        }

        public static async Task GenerateBotException(string LLID, Exception ex)
        {
           BotExceptionNotification(LLID.Split('*')[1], ex.StackTrace, ex.Source, ex.Message,LLID.Split('*')[0], DateTime.Now.ToString());
           BOTErrorLog(LLID.Split('*')[1], ex.StackTrace, ex.Source, ex.Message,LLID.Split('*')[0], DateTime.Now.ToString());
        }

        public static void BotExceptionNotification(string Environment, string exceptionStack, string exceptionSource,
            string fullException, string loggedInUser, string exceptionDateTime)
        {
          // Send email code goes here using above peramaeters in you html
        }

    }
}

Do let me know in case you required more help


问:
How to manage connected users over websocket using Vert.x 3?
To convince some people to switch from old school tech, I need to build a chat demo application that manages more than 10K concurrent connections using Java (like Node.Js stuff).

I have tested Netty 5.0 which is awesome but requires lot of work to be done; on the other hand Jetty 9.3 is great but is slow compared to other competitors.

After some search I found the Vert.x 3 toolkit which is based on Netty with a plethora of great tools (no need to reinvent the wheel), I have seen the examples in git and I was able to build a websocket server, etc.

public void start() throws Exception {
    vertx.createHttpServer().websocketHandler(new Handler<ServerWebSocket>() {
        @Override
        public void handle(ServerWebSocket e) {
           // business stuff in the old style not yet lambda
        }
    }).listen(port);
}
```

<p>Being new to the <em>Vert.x</em> world, I could not figure out how to manage connected users using it, normally the old fashion way is to use something like: </p>

<pre class="lang-java prettyprint-override"><code>HashMap<UUID,ServerWebSocket> connectedUsers;
</code>```

When a connection is established I check if it exists; if not I add it as a new  entry and do some functions to send, broadcast, retrieve through the collection and so on.

My question is does Vert.x 3 have something to deal with connections to track them and remove those who left (ping pong), broadcast, etc. or should I implement them from scratch using cookies, session, ....)

I could not find any real example using Vert.x 3.

答:
Basically, the scope of the websocketHandler represents a connection. In your example this is your anonymous class. I created a little websocket chat example where I use the Vert.x event bus to distribute the messages to all the clients.

In the start method of the server we handle the websocket connections. You can implement the closeHandler to monitor client disconnection. There are also handlers for exceptions, ping-pong, etc. You can identify a specific connection by using the textHandlerID, but you have also access to the remote address.

```<code> public void start() throws Exception {
        vertx.createHttpServer().websocketHandler(handler -> {
            System.out.println("client connected: "+handler.textHandlerID());

            vertx.eventBus().consumer(CHAT_CHANNEL, message -> {
                handler.writeTextMessage((String)message.body());
            });

            handler.textMessageHandler(message -> {
               vertx.eventBus().publish(CHAT_CHANNEL,message);
            });

            handler.closeHandler(message ->{
                System.out.println("client disconnected "+handler.textHandlerID());
            });

        }).listen(8080);
    }
</code>```

The client example is also written in Java. It just prints all the received messages on the websocket connection to the console. After connection it sends a message.

```<code>public void start() throws Exception {
        HttpClient client = vertx.createHttpClient();

        client.websocket(8080, "localhost", "", websocket -> {
            websocket.handler(data -> System.out.println(data.toString("ISO-8859-1")));
            websocket.writeTextMessage(NAME+ ":hello from client");
        });

    }
</code>```

Body:
To convince some people to switch from old school tech, I need to build a chat demo application that manages more than 10K concurrent connections using Java (like Node.Js stuff).

I have tested Netty 5.0 which is awesome but requires lot of work to be done; on the other hand Jetty 9.3 is great but is slow compared to other competitors.

After some search I found the Vert.x 3 toolkit which is based on Netty with a plethora of great tools (no need to reinvent the wheel), I have seen the examples in git and I was able to build a websocket server, etc.

public void start() throws Exception {
    vertx.createHttpServer().websocketHandler(new Handler<ServerWebSocket>() {
        @Override
        public void handle(ServerWebSocket e) {
           // business stuff in the old style not yet lambda
        }
    }).listen(port);
}

Being new to the Vert.x world, I could not figure out how to manage connected users using it, normally the old fashion way is to use something like:

HashMap<UUID,ServerWebSocket> connectedUsers;

When a connection is established I check if it exists; if not I add it as a new  entry and do some functions to send, broadcast, retrieve through the collection and so on.

My question is does Vert.x 3 have something to deal with connections to track them and remove those who left (ping pong), broadcast, etc. or should I implement them from scratch using cookies, session, ....)

I could not find any real example using Vert.x 3.

Body:
Basically, the scope of the websocketHandler represents a connection. In your example this is your anonymous class. I created a little websocket chat example where I use the Vert.x event bus to distribute the messages to all the clients.

In the start method of the server we handle the websocket connections. You can implement the closeHandler to monitor client disconnection. There are also handlers for exceptions, ping-pong, etc. You can identify a specific connection by using the textHandlerID, but you have also access to the remote address.

 public void start() throws Exception {
        vertx.createHttpServer().websocketHandler(handler -> {
            System.out.println("client connected: "+handler.textHandlerID());

            vertx.eventBus().consumer(CHAT_CHANNEL, message -> {
                handler.writeTextMessage((String)message.body());
            });

            handler.textMessageHandler(message -> {
               vertx.eventBus().publish(CHAT_CHANNEL,message);
            });

            handler.closeHandler(message ->{
                System.out.println("client disconnected "+handler.textHandlerID());
            });

        }).listen(8080);
    }

The client example is also written in Java. It just prints all the received messages on the websocket connection to the console. After connection it sends a message.

public void start() throws Exception {
        HttpClient client = vertx.createHttpClient();

        client.websocket(8080, "localhost", "", websocket -> {
            websocket.handler(data -> System.out.println(data.toString("ISO-8859-1")));
            websocket.writeTextMessage(NAME+ ":hello from client");
        });

    }


问:
VBA Excel array writing all values as 0 in cells
I have the below code:

```<code>Private Sub UpdateButton_Click()

    Dim uniqueID As Integer
    uniqueID = 0

    Dim notInOrder As Boolean
    notInOrder = False

    Dim inOrder As Boolean
    inOrder = False

    Dim employeeNumber As String

    Dim week As Integer

    Dim tdate As Date
    tdate = Now

    Dim qtyWelds As Integer
    qtyWelds = 26

    Dim totalOfWeldsInOrder As Integer
    totalOfWeldsInOrder = 0

    Dim qtyGridsInspected As Integer
    qtyGridsInspected = 1

    Dim s1 As Integer
    Dim s2 As Integer
    Dim s3 As Integer
    Dim s4 As Integer
    Dim s5 As Integer
    Dim s6 As Integer
    Dim s7 As Integer
    Dim s8 As Integer
    Dim s9 As Integer
    Dim s10 As Integer
    Dim s11 As Integer
    Dim s12 As Integer
    Dim s13 As Integer
    Dim s14 As Integer
    Dim s15 As Integer
    Dim s16 As Integer
    Dim s17 As Integer
    Dim s18 As Integer
    Dim s19 As Integer
    Dim s20 As Integer
    Dim s21 As Integer
    Dim s22 As Integer
    Dim s23 As Integer
    Dim s24 As Integer
    Dim s25 As Integer
    Dim s26 As Integer

    If ThisWorkbook.Worksheets(2).Shapes("cBox1").OLEFormat.Object.Value = 0 Then
        totalOfWeldsInOrder = totalOfWeldsInOrder + 1
        s1 = 0
        notInOrder = True
    End If

        .....

    If ThisWorkbook.Worksheets(2).Shapes("cBox26").OLEFormat.Object.Value = 0 Then
        totalOfWeldsInOrder = totalOfWeldsInOrder + 1
        s26 = 0
        notInOrder = True
    End If

    Dim sInOrder As Integer

    If inOrder = True Then
        sInOrder = 1
    Else
        sInOder = 0
    End If

    Dim snotInOrder As Integer

    If notInOrder = True Then
        snotInOrder = 1
    Else
        snotInOrder = 0
    End If

    Dim rowArray(1 To 35) As String

    uniqueID = GetLastRow() - 1

    rowArray(1) = uniqueID

        .....

    rowArray(35) = s26

    Dim lastRow As Long

    lastRow = GetLastRow()

    Debug.Print "Last Row: ", lastRow

    InsertRow lastRow, rowArray

End Sub
Public Function GetLastRow() As Long

    Dim wbshtSelect         As Worksheet
    Dim LR_wbSelectNew      As Long

    Set wbshtSelect = Sheets("Data")

    ' find last row with data in Column AI9 at current regioun starting at cell AI9
    With wbshtSelect.Range("AI9").CurrentRegion
        LR_wbSelectNew = .Rows(.Rows.Count).Row
    End With

    Dim rng         As Range
    Set rng = wbshtSelect.Range("AI9:AI" & LR_wbSelectNew)

    ' find last row inside the range, ignore values inside formulas
    LR_wbSelectNew = rng.Find(What:="*", _
                        After:=Range("AI9"), _
                        LookAt:=xlPart, _
                        LookIn:=xlValues, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row

    GetLastRow = LR_wbSelectNew

End Function

Function InsertRow(lastRow As Long, List() As String)

    Dim newRow As Range
    Dim rowArray As Variant

    Dim wsData As Worksheet
    Set wsData = Sheets("Data")

    rowArray = List()

    lastRow = lastRow + 1

        For Each c In wsData.Range("A" & lastRow & ":AI" & lastRow)
                For Each s In rowArray
                    c.Value = s
                Next s
        Next c

    Debug.Print "New Row: ", lastRow

End Function
</code>```

I have a button and when I click the Button the macro runs the above code. The code will get the last filled row, and insert data from an array (in code) in the next row. The array is getting populated correctly, however when it comes to writing it to cell all values are returned as 0.

I tried converting the values using CStr(variable) with no success (still saved as 0).

The function that writes values to row:

```<code>Function InsertRow(lastRow As Long, List() As String)

    Dim newRow As Range
    Dim rowArray As Variant

    Dim wsData As Worksheet
    Set wsData = Sheets("Data")

    rowArray = List()

    lastRow = lastRow + 1

        For Each c In wsData.Range("A" & lastRow & ":AI" & lastRow)
                For Each s In rowArray
                    c.Value = s
                Next s
        Next c

    Debug.Print "New Row: ", lastRow

End Function
</code>```

Any idea what I am doing wrong?

NOTE1: I am using Office 2007 (Excel)

NOTE2: I have removed some of the repetitive code. (denoted as .... in code)

答:
Fixed it. I wanted to write an array to a range. The below is what worked:</p>

```<code>Function InsertRow(lastRow As Long, List() As String)

    Dim newRow As Range
    Dim rowArray As Variant
    Dim i As Long

    Dim wsData As Worksheet
    Set wsData = Sheets("Data")

    rowArray = List()

    lastRow = lastRow + 1

    wsData.Range("A" & lastRow & ":AI" & lastRow) = rowArray

    Debug.Print "New Row: ", lastRow

End Function
</code>```

Body:
I have the below code:

Private Sub UpdateButton_Click()

    Dim uniqueID As Integer
    uniqueID = 0

    Dim notInOrder As Boolean
    notInOrder = False

    Dim inOrder As Boolean
    inOrder = False

    Dim employeeNumber As String

    Dim week As Integer

    Dim tdate As Date
    tdate = Now

    Dim qtyWelds As Integer
    qtyWelds = 26

    Dim totalOfWeldsInOrder As Integer
    totalOfWeldsInOrder = 0

    Dim qtyGridsInspected As Integer
    qtyGridsInspected = 1

    Dim s1 As Integer
    Dim s2 As Integer
    Dim s3 As Integer
    Dim s4 As Integer
    Dim s5 As Integer
    Dim s6 As Integer
    Dim s7 As Integer
    Dim s8 As Integer
    Dim s9 As Integer
    Dim s10 As Integer
    Dim s11 As Integer
    Dim s12 As Integer
    Dim s13 As Integer
    Dim s14 As Integer
    Dim s15 As Integer
    Dim s16 As Integer
    Dim s17 As Integer
    Dim s18 As Integer
    Dim s19 As Integer
    Dim s20 As Integer
    Dim s21 As Integer
    Dim s22 As Integer
    Dim s23 As Integer
    Dim s24 As Integer
    Dim s25 As Integer
    Dim s26 As Integer

    If ThisWorkbook.Worksheets(2).Shapes("cBox1").OLEFormat.Object.Value = 0 Then
        totalOfWeldsInOrder = totalOfWeldsInOrder + 1
        s1 = 0
        notInOrder = True
    End If

        .....

    If ThisWorkbook.Worksheets(2).Shapes("cBox26").OLEFormat.Object.Value = 0 Then
        totalOfWeldsInOrder = totalOfWeldsInOrder + 1
        s26 = 0
        notInOrder = True
    End If

    Dim sInOrder As Integer

    If inOrder = True Then
        sInOrder = 1
    Else
        sInOder = 0
    End If

    Dim snotInOrder As Integer

    If notInOrder = True Then
        snotInOrder = 1
    Else
        snotInOrder = 0
    End If

    Dim rowArray(1 To 35) As String

    uniqueID = GetLastRow() - 1

    rowArray(1) = uniqueID

        .....

    rowArray(35) = s26

    Dim lastRow As Long

    lastRow = GetLastRow()

    Debug.Print "Last Row: ", lastRow

    InsertRow lastRow, rowArray

End Sub
Public Function GetLastRow() As Long

    Dim wbshtSelect         As Worksheet
    Dim LR_wbSelectNew      As Long

    Set wbshtSelect = Sheets("Data")

    ' find last row with data in Column AI9 at current regioun starting at cell AI9
    With wbshtSelect.Range("AI9").CurrentRegion
        LR_wbSelectNew = .Rows(.Rows.Count).Row
    End With

    Dim rng         As Range
    Set rng = wbshtSelect.Range("AI9:AI" & LR_wbSelectNew)

    ' find last row inside the range, ignore values inside formulas
    LR_wbSelectNew = rng.Find(What:="*", _
                        After:=Range("AI9"), _
                        LookAt:=xlPart, _
                        LookIn:=xlValues, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row

    GetLastRow = LR_wbSelectNew

End Function

Function InsertRow(lastRow As Long, List() As String)

    Dim newRow As Range
    Dim rowArray As Variant

    Dim wsData As Worksheet
    Set wsData = Sheets("Data")

    rowArray = List()

    lastRow = lastRow + 1

        For Each c In wsData.Range("A" & lastRow & ":AI" & lastRow)
                For Each s In rowArray
                    c.Value = s
                Next s
        Next c

    Debug.Print "New Row: ", lastRow

End Function

I have a button and when I click the Button the macro runs the above code. The code will get the last filled row, and insert data from an array (in code) in the next row. The array is getting populated correctly, however when it comes to writing it to cell all values are returned as 0.

I tried converting the values using CStr(variable) with no success (still saved as 0).

The function that writes values to row:

Function InsertRow(lastRow As Long, List() As String)

    Dim newRow As Range
    Dim rowArray As Variant

    Dim wsData As Worksheet
    Set wsData = Sheets("Data")

    rowArray = List()

    lastRow = lastRow + 1

        For Each c In wsData.Range("A" & lastRow & ":AI" & lastRow)
                For Each s In rowArray
                    c.Value = s
                Next s
        Next c

    Debug.Print "New Row: ", lastRow

End Function

Any idea what I am doing wrong?

NOTE1: I am using Office 2007 (Excel)

NOTE2: I have removed some of the repetitive code. (denoted as .... in code)

Body:
Fixed it. I wanted to write an array to a range. The below is what worked:

Function InsertRow(lastRow As Long, List() As String)

    Dim newRow As Range
    Dim rowArray As Variant
    Dim i As Long

    Dim wsData As Worksheet
    Set wsData = Sheets("Data")

    rowArray = List()

    lastRow = lastRow + 1

    wsData.Range("A" & lastRow & ":AI" & lastRow) = rowArray

    Debug.Print "New Row: ", lastRow

End Function


问:
Why does Subversion fail to flag a modified Microsoft Excel spreadsheet file?
I have encountered some behaviour I didn't expect from Subversion, and discovered this almost accidentally: A modified file is not being flagged as modified.

I have a unit test involving a Microsoft Excel spreadsheet as an input file. The unit test calculates a CRC checksum; my test started failing due to the checksum changing.

The test file is stored in SVN, and has MIME type "application/octet-stream", and is therefore considered as binary by SVN.

I get the same behaviour from TortoiseSVN and the SVN command line client, in this case both based on SVN 1.6: When the file is opened in Excel, the fact that it is open must be encoded in the file itself; SVN shows that the file is modified. However, when the file is closed again (without saving), it seems to return to its unmodified state: that is, svn status does not list the Excel file; svn diff produces no output anyway due to the data being binary.

The catch is that the file does not now binary compare with the file stored in the repository. (If a fresh copy is exported, it does not binary compare with the opened-and-closed copy.) The file is apparently unchanged from the user's point of view, so in a semantic sense, the SVN response is reasonable. But not syntactically; and SVN is essentially syntactic.

The part for which I can't find a reason is why SVN does not flag the file as modified. I can't imagine SVN has any special handling for Excel files (and in any case the MIME type is not specifically one associated with MS Excel); there is no SNV keyword property defined. Likewise, I can imagine Excel knows anything about the contents of the hidden .svn subdirectory in which the SVN working copy information is stored.

Do you have any clues as to what is going on here?

Thanks, Rob.

答:
Subversion assumes that the "last modification" time stamp is not lying. If the timestamp is unchanged, the content of the file is not checked for changes. I think all version control system do this, checking for local modifications would be unbearably slow otherwise.

edit: for the details of how SVN works in this regard, questions.c in the source of the SVN working copy library is a good start.


问:
Why is there such a performance difference on Raspberry pi between Open and Oracle JDK?
On my Raspberry I did some Performance Tests like CaffeineMark and SciMark with both JVMs. There is a huge performance difference between them even though  I have heard that the differences are very small. I also tried calculating with floating numbers and the Oracle JDK got a better Score even though both should support the hard float abi.

I use Linux raspberrypi 3.18.11-v7+ as OS.

```<code>OpenJDK:
java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-1~deb7u1+rpi1)
OpenJDK Zero VM (build 24.79-b02, mixed mode)

OracleJDK:
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) Client VM (build 24.0-b56, mixed mode)

SciMark results:

                 OpenJDK            OracleJDK
Composite Score 14.280735577363213  || 32.24948180361924
FFT (1024)      9.482866845055302   || 26.447121360843663
SOR (100x100)   27.14938943220646   || 59.68022533004399
Monte Carlo     3.6298604956147384  || 10.561671865446971
Sparse matmult  15.603809523809524  || 26.64931580928407
LU (100x100)    15.53775159013005   || 37.90907465247749
</code>```

I used a program that counts a float in 0.1 steps to 600000. I tried to test the performance of the JVM on handling floats.

OpenJDK: 257ms

OracleJDK: 151ms

0.1 steps to 1200000:

OpenJDK: 457ms

OracleJDK: 263ms

```<code>public class Testing {

    /**
     * @param args
     */
    public static long Test()
    {
        float counter=0.0f;
        long startTime = System.currentTimeMillis();
        while (counter <= 1_200_000.0f)
        {
            counter += 0.1f;
        }
        return System.currentTimeMillis() - startTime;
    }

    public static void main(String[] args){
        System.out.println(Test());
    }

}
</code>```

I tried the enhancements mentioned from SlipperySeal and put the test in the loop. I also tried to use the c2 compiler but the results were not different.

答:
An update for April 2018.

I run a Java Whetstone off-line benchmark on Raspberry Pi 3 with Raspbian Stretch. The source code can be found here in file Raspberry_Pi_Benchmarks/java/source code/whetstone-off-line/whetstc.java.

The conclusion is that openjdk-9-jre is faster than openjdk-8-jre (tested version 1.8.0_162), which is in turn faster than oracle-java8-jdk (tested version 1.8.0_65). Note also that I used an older kernel with oracle-java8-jdk.

openjdk-9-jdk from Raspbian repos:

```<code>$ java -version
openjdk version "9-Raspbian"
OpenJDK Runtime Environment (build 9-Raspbian+0-9b181-4bpo9rpt1)
OpenJDK Server VM (build 9-Raspbian+0-9b181-4bpo9rpt1, mixed mode)

$ java whetstc
   Whetstone Benchmark Java Version, apr. 26 2018, 23:15:40

                                                     1 Pass
Test                  Result       MFLOPS     MOPS  millisecs

N1 floating point  -1,124750137    333,22             0,0576
N2 floating point  -1,131330490    293,19             0,4584
N3 if then else     1,000000000             185,95    0,5566
N4 fixed point     12,000000000             412,95    0,7628
N5 sin,cos etc.     0,499110132              22,40    3,7140
N6 floating point   0,999999821    212,70             2,5360
N7 assignments      3,000000000             105,66    1,7490
N8 exp,sqrt etc.    0,825148463              16,70    2,2280

MWIPS                              829,02            12,0624

Operating System    Linux, Arch. arm, Version 4.14.34-v7+
Java Vendor         Oracle Corporation, Version  9-Raspbian
CPU null
</code>```

openjdk-8-jdk from Raspbian repos:

```<code>$ java -version
openjdk version "1.8.0_162"
OpenJDK Runtime Environment (build 1.8.0_162-8u162-b12-1~deb9u1-b12)
OpenJDK Client VM (build 25.162-b12, mixed mode)

$ java whetstc
   Whetstone Benchmark Java Version, Apr 27 2018, 13:13:26

                                                     1 Pass
Test                  Result       MFLOPS     MOPS  millisecs

N1 floating point  -1.124750137    181.82             0.1056
N2 floating point  -1.131330490    175.92             0.7640
N3 if then else     1.000000000              88.61    1.1680
N4 fixed point     12.000000000             389.85    0.8080
N5 sin,cos etc.     0.499110132               9.35    8.8980
N6 floating point   0.999999821     76.27             7.0720
N7 assignments      3.000000000             275.82    0.6700
N8 exp,sqrt etc.    0.825148463               7.15    5.2060

MWIPS                              405.00            24.6916

Operating System    Linux, Arch. arm, Version 4.14.34-v7+
Java Vendor         Oracle Corporation, Version  1.8.0_162
CPU null
</code>```

oracle-java8-jdk from Raspbian repos:

```<code>$ java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) Client VM (build 25.65-b01, mixed mode)`

$ java whetstc
   Whetstone Benchmark Java Version, Nov 15 2017, 11:16:37

                                                     1 Pass
Test                  Result       MFLOPS     MOPS  millisecs

N1 floating point  -1.124750137     91.52             0.2098
N2 floating point  -1.131330490     89.01             1.5100
N3 if then else     1.000000000              44.27    2.3380
N4 fixed point     12.000000000             229.76    1.3710
N5 sin,cos etc.     0.499110103               3.01   27.6400
N6 floating point   0.999999821     44.95            12.0000
N7 assignments      3.000000000             137.09    1.3480
N8 exp,sqrt etc.    0.751108646               0.58   63.9100

MWIPS                               90.64           110.3268

Operating System    Linux, Arch. arm, Version 4.9.35-v7+
Java Vendor         Oracle Corporation, Version  1.8.0_65
CPU null
</code>```

Body:
On my Raspberry I did some Performance Tests like CaffeineMark and SciMark with both JVMs. There is a huge performance difference between them even though  I have heard that the differences are very small. I also tried calculating with floating numbers and the Oracle JDK got a better Score even though both should support the hard float abi.

I use Linux raspberrypi 3.18.11-v7+ as OS.

OpenJDK:
java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-1~deb7u1+rpi1)
OpenJDK Zero VM (build 24.79-b02, mixed mode)

OracleJDK:
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) Client VM (build 24.0-b56, mixed mode)

SciMark results:

                 OpenJDK            OracleJDK
Composite Score 14.280735577363213  || 32.24948180361924
FFT (1024)      9.482866845055302   || 26.447121360843663
SOR (100x100)   27.14938943220646   || 59.68022533004399
Monte Carlo     3.6298604956147384  || 10.561671865446971
Sparse matmult  15.603809523809524  || 26.64931580928407
LU (100x100)    15.53775159013005   || 37.90907465247749

I used a program that counts a float in 0.1 steps to 600000. I tried to test the performance of the JVM on handling floats.

OpenJDK: 257ms

OracleJDK: 151ms

0.1 steps to 1200000:

OpenJDK: 457ms

OracleJDK: 263ms

public class Testing {

    /**
     * @param args
     */
    public static long Test()
    {
        float counter=0.0f;
        long startTime = System.currentTimeMillis();
        while (counter <= 1_200_000.0f)
        {
            counter += 0.1f;
        }
        return System.currentTimeMillis() - startTime;
    }

    public static void main(String[] args){
        System.out.println(Test());
    }

}

I tried the enhancements mentioned from SlipperySeal and put the test in the loop. I also tried to use the c2 compiler but the results were not different.

Body:
An update for April 2018.

I run a Java Whetstone off-line benchmark on Raspberry Pi 3 with Raspbian Stretch. The source code can be found here in file Raspberry_Pi_Benchmarks/java/source code/whetstone-off-line/whetstc.java.

The conclusion is that openjdk-9-jre is faster than openjdk-8-jre (tested version 1.8.0_162), which is in turn faster than oracle-java8-jdk (tested version 1.8.0_65). Note also that I used an older kernel with oracle-java8-jdk.

openjdk-9-jdk from Raspbian repos:

$ java -version
openjdk version "9-Raspbian"
OpenJDK Runtime Environment (build 9-Raspbian+0-9b181-4bpo9rpt1)
OpenJDK Server VM (build 9-Raspbian+0-9b181-4bpo9rpt1, mixed mode)

$ java whetstc
   Whetstone Benchmark Java Version, apr. 26 2018, 23:15:40

                                                     1 Pass
Test                  Result       MFLOPS     MOPS  millisecs

N1 floating point  -1,124750137    333,22             0,0576
N2 floating point  -1,131330490    293,19             0,4584
N3 if then else     1,000000000             185,95    0,5566
N4 fixed point     12,000000000             412,95    0,7628
N5 sin,cos etc.     0,499110132              22,40    3,7140
N6 floating point   0,999999821    212,70             2,5360
N7 assignments      3,000000000             105,66    1,7490
N8 exp,sqrt etc.    0,825148463              16,70    2,2280

MWIPS                              829,02            12,0624

Operating System    Linux, Arch. arm, Version 4.14.34-v7+
Java Vendor         Oracle Corporation, Version  9-Raspbian
CPU null

openjdk-8-jdk from Raspbian repos:

$ java -version
openjdk version "1.8.0_162"
OpenJDK Runtime Environment (build 1.8.0_162-8u162-b12-1~deb9u1-b12)
OpenJDK Client VM (build 25.162-b12, mixed mode)

$ java whetstc
   Whetstone Benchmark Java Version, Apr 27 2018, 13:13:26

                                                     1 Pass
Test                  Result       MFLOPS     MOPS  millisecs

N1 floating point  -1.124750137    181.82             0.1056
N2 floating point  -1.131330490    175.92             0.7640
N3 if then else     1.000000000              88.61    1.1680
N4 fixed point     12.000000000             389.85    0.8080
N5 sin,cos etc.     0.499110132               9.35    8.8980
N6 floating point   0.999999821     76.27             7.0720
N7 assignments      3.000000000             275.82    0.6700
N8 exp,sqrt etc.    0.825148463               7.15    5.2060

MWIPS                              405.00            24.6916

Operating System    Linux, Arch. arm, Version 4.14.34-v7+
Java Vendor         Oracle Corporation, Version  1.8.0_162
CPU null

oracle-java8-jdk from Raspbian repos:

$ java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) Client VM (build 25.65-b01, mixed mode)`

$ java whetstc
   Whetstone Benchmark Java Version, Nov 15 2017, 11:16:37

                                                     1 Pass
Test                  Result       MFLOPS     MOPS  millisecs

N1 floating point  -1.124750137     91.52             0.2098
N2 floating point  -1.131330490     89.01             1.5100
N3 if then else     1.000000000              44.27    2.3380
N4 fixed point     12.000000000             229.76    1.3710
N5 sin,cos etc.     0.499110103               3.01   27.6400
N6 floating point   0.999999821     44.95            12.0000
N7 assignments      3.000000000             137.09    1.3480
N8 exp,sqrt etc.    0.751108646               0.58   63.9100

MWIPS                               90.64           110.3268

Operating System    Linux, Arch. arm, Version 4.9.35-v7+
Java Vendor         Oracle Corporation, Version  1.8.0_65
CPU null


问:
file_get_contents() Breaks Up UTF-8 Characters
I am loading a HTML from an external server. The HTML markup has UTF-8 encoding and contains characters such as ľ,š,č,ť,ž etc. When I load the HTML with file_get_contents() like this:

```<code>$html = file_get_contents('http://example.com/foreign.html');
</code>```

It messes up the UTF-8 characters and loads Å, ¾, ¤ and similar nonsense instead of proper UTF-8 characters.

How can I solve this?

UPDATE:

I tried both saving the HTML to a file and outputting it with UTF-8 encoding. Both doesn't work so it means file_get_contents() is already returning broken HTML.

UPDATE2:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="sk" lang="sk">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Language" content="sk" />
<title>Test</title>

</head>
<body>

<?php

$html = file_get_contents('http://example.com');
echo htmlentities($html);

?>

</body>
</html>
</code>```

答:
I am working with 35000 lines of data.

```<code>$f=fopen("veri1.txt","r");
$i=0;
while(!feof($f)){
    $i++;
    $line=mb_convert_encoding(fgets($f), 'HTML-ENTITIES', "UTF-8");
    echo $line;
}
</code>```

This code convert my strange characters into normal.

Body:
I am loading a HTML from an external server. The HTML markup has UTF-8 encoding and contains characters such as ľ,š,č,ť,ž etc. When I load the HTML with file_get_contents() like this:

$html = file_get_contents('http://example.com/foreign.html');

It messes up the UTF-8 characters and loads Å, ¾, ¤ and similar nonsense instead of proper UTF-8 characters.

How can I solve this?

UPDATE:

I tried both saving the HTML to a file and outputting it with UTF-8 encoding. Both doesn't work so it means file_get_contents() is already returning broken HTML.

UPDATE2:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Language" content="sk" />
<title>Test</title>

<?php

$html = file_get_contents('http://example.com');
echo htmlentities($html);

?>

Body:
I am working with 35000 lines of data.

$f=fopen("veri1.txt","r");
$i=0;
while(!feof($f)){
    $i++;
    $line=mb_convert_encoding(fgets($f), 'HTML-ENTITIES', "UTF-8");
    echo $line;
}

This code convert my strange characters into normal.