问:
Response: Status 406 - spring
When I do request I get 406 with message:

"org.springframework.web.server.NotAcceptableStatusException: 406
  NOT_ACCEPTABLE \"Could not find acceptable representation\"\n\tat
  org.springframework.web.reactive.result.method.annotation.AbstractMessageWriterResultHandler.writeBody(AbstractMessageWriterResultHandler.java:156)

I don't know how to fix it. Can you tell me why it doesn't work?

```<code>@PostMapping("/sign-in")
fun signIn(@RequestBody request: SignInRequest): Mono<ServerResponse> {
    return userService.findByEmail(request.email)
            .flatMap {
                return@flatMap if (it != null && passwordEncoder.encode(it.password.toString()) == request.password) {
                    println("ok")
                    ok().body(BodyInserters.fromObject(AuthResponse(jwtUtil.generateToken(it))))
                } else {
                    println("no ok")
                    notFound().build()
                }
            }
}
</code>```

答:
I found a solution. This is it:</p>

```<code>@PostMapping("/sign-in")
fun signIn(@RequestBody request: SignInRequest): Mono<ResponseEntity<*>> {
    return userService.findByEmail(request.email).map {
        return@map if (it != null && passwordEncoder.encode(request.password) == it.password) {
            ResponseEntity.ok(AuthResponse(jwtUtil.generateToken(it)))
        } else {
            ResponseEntity.status(HttpStatus.UNAUTHORIZED).build<String>()
        }
    }.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build<String>())
}
</code>```

Title: Response: Status 406 - spring

Body:
When I do request I get 406 with message:

"org.springframework.web.server.NotAcceptableStatusException: 406
  NOT_ACCEPTABLE \"Could not find acceptable representation\"\n\tat
  org.springframework.web.reactive.result.method.annotation.AbstractMessageWriterResultHandler.writeBody(AbstractMessageWriterResultHandler.java:156)

I don't know how to fix it. Can you tell me why it doesn't work?

@PostMapping("/sign-in")
fun signIn(@RequestBody request: SignInRequest): Mono<ServerResponse> {
    return userService.findByEmail(request.email)
            .flatMap {
                return@flatMap if (it != null && passwordEncoder.encode(it.password.toString()) == request.password) {
                    println("ok")
                    ok().body(BodyInserters.fromObject(AuthResponse(jwtUtil.generateToken(it))))
                } else {
                    println("no ok")
                    notFound().build()
                }
            }
}

Body:
I found a solution. This is it:

@PostMapping("/sign-in")
fun signIn(@RequestBody request: SignInRequest): Mono<ResponseEntity<*>> {
    return userService.findByEmail(request.email).map {
        return@map if (it != null && passwordEncoder.encode(request.password) == it.password) {
            ResponseEntity.ok(AuthResponse(jwtUtil.generateToken(it)))
        } else {
            ResponseEntity.status(HttpStatus.UNAUTHORIZED).build<String>()
        }
    }.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build<String>())
}


来源: stackexchange

问:
SELECT subCategory which equals parentCategory = value from outer table
I have a products table and I need to put discount on some products from a given sub category, which has parent category in another table.

```<code>TABLE products:

category_id      sku      discount
-----------------------------------
8             3141          NULL
7             4333          NULL
7             601           NULL
3             405           NULL

TABLE product_category:

id      parent_id           slug
-----------------------------------
8             18          somename
7             3           somename
</code>```

It's a pretty simple question but I can't figure out how to use the parent_id column to update my products table simply, instead of writing down every subcategory id like this:

```<code>UPDATE products
SET discount = 25
WHERE category_id IN (1,4,5,6 etc..);
</code>```

I want to update the products table by selecting the subcategory's parent id from the product_category table.

答:
Consider an UPDATE + JOIN:

```<code>UPDATE products p
INNER JOIN product_category c ON p.category_id = c.id
SET p.discount = 25 ;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a products table and I need to put discount on some products from a given sub category, which has parent category in another table.

TABLE products:

category_id      sku      discount
-----------------------------------
8             3141          NULL
7             4333          NULL
7             601           NULL
3             405           NULL

TABLE product_category:

id      parent_id           slug
-----------------------------------
8             18          somename
7             3           somename

It's a pretty simple question but I can't figure out how to use the parent_id column to update my products table simply, instead of writing down every subcategory id like this:

UPDATE products
SET discount = 25
WHERE category_id IN (1,4,5,6 etc..);

I want to update the products table by selecting the subcategory's parent id from the product_category table.

Body:
Consider an UPDATE + JOIN:

UPDATE products p
INNER JOIN product_category c ON p.category_id = c.id
SET p.discount = 25 ;


问:
What is my context and where do I find it?
I asked a similar question earlier but i don't understand what to do, I also have read other solutions like: What is a NullPointerException, and how do I fix it?
I still don't know what to do, please help:

According to what I understand is that my context = null; and I am not sure why, and how to fix it...

I wrote a UniversImageLoader.class to be able to load images over several activities. Now I have initiated it in all my activities, but in my UIL class, I need to pass a context.

```<code>public class UniversalImageLoader {

    private static final int defaultImage = R.drawable.ic_android;
    private Context mContext;

    public UniversalImageLoader(Context context) {
        mContext = context;
    }

    public ImageLoaderConfiguration getConfig(){
        //File cacheDir = StorageUtils.getCacheDirectory(mContext);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext)//<--the error is in this line
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(mContext)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();

        return config;
    }
</code>```

in HomeActivity:[in every Activity I call it like this]

```<code>private void initImageLoader(){
        UniversalImageLoader universalImageLoader = new UniversalImageLoader(mContext);
        ImageLoader.getInstance().init(universalImageLoader.getConfig());
    }
</code>```

and in all those activities I call it in the OnCreate method like this:

```<code>initImageLoader();
</code>```

So I have read up, looked at other solutions but can't find an understandable answer...your guidance will be highly appreciated!

答:
Use this.mContext = context; in constructor so it will pass your context to the context of current class.

And pass getApplicationContext or yourActivityName.this where you are using this class.

If you are using it in fragment use getActivity or getContext.

Body:
I asked a similar question earlier but i don't understand what to do, I also have read other solutions like: What is a NullPointerException, and how do I fix it?
I still don't know what to do, please help:

According to what I understand is that my context = null; and I am not sure why, and how to fix it...

I wrote a UniversImageLoader.class to be able to load images over several activities. Now I have initiated it in all my activities, but in my UIL class, I need to pass a context.

public class UniversalImageLoader {

    private static final int defaultImage = R.drawable.ic_android;
    private Context mContext;

    public UniversalImageLoader(Context context) {
        mContext = context;
    }

    public ImageLoaderConfiguration getConfig(){
        //File cacheDir = StorageUtils.getCacheDirectory(mContext);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext)//<--the error is in this line
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(mContext)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();

        return config;
    }

in HomeActivity:[in every Activity I call it like this]

private void initImageLoader(){
        UniversalImageLoader universalImageLoader = new UniversalImageLoader(mContext);
        ImageLoader.getInstance().init(universalImageLoader.getConfig());
    }

and in all those activities I call it in the OnCreate method like this:

initImageLoader();

So I have read up, looked at other solutions but can't find an understandable answer...your guidance will be highly appreciated!


问:
Is has_shortcode() or get_post_meta() fatser?
I want to add a body_class to pages, if the page has a specific shortcode.

Which of the following methods would be the most efficient one when it comes to performance?

Use has_shortcode() like

```<code>function my_body_class($classes) {
    $post_id = get_the_ID();
    if( isset($post_id) && has_shortcode( $post->post_content, 'my_shortocde' ) ) {
        $classes = array_merge( $classes, array( 'my-body-tag' ));
    }
    return $classes;
}
add_filter( 'body_class', 'my_body_class', 10, 1 );
</code>```

Presume that the post_meta table for the page has a custom meta_key with meta_value of true added somewhere else in the code when updating a page and you use get_post_meta() like

```<code>function my_body_class($classes) {
    $post_id = get_the_ID();
    if( isset($post_id) && get_post_meta($post_id, '_my_shortocde_is_used') ) {
        $classes = array_merge( $classes, array( 'my_body_tag' ));
    }
    return $classes;
}
add_filter( 'body_class', 'my_body_class', 10, 1 );
</code>```

What would be faster? The regex that has_shortcode does or the query that get_post_meta does? Which one would you use?

UPDATE: Wall clock timing results as suggested by @Rimarx

Option 1: Using has_shortcode()

```<code>Wall clock time: 8.66254170735685E-06 = 0.00000866254170735685
</code>```

Option 2: Using get_post_meta()

```<code>Wall clock time: 2.88486480712892E-05 = 0.00002884864807128920
</code>```

Using has_shorcode wins.

Side note: in this test the mysql db is on the same server as wordpress.

答:
You can check speed like that:

```<code><?php
$start = microtime(true);
//Your code
echo 'The script time: ' . (microtime(true) - $start) . ' seconds';
?>
</code>```

As an option:

```<code>function my_body_class($classes) {
    $start = microtime(true);

    $post_id = get_the_ID();
    if( isset($post_id) && has_shortcode( $post->post_content, 'my_shortocde' ) ) {
        $classes = array_merge( $classes, array( 'my-body-tag' ));
    }

    return 'The script time: ' . (microtime(true) - $start) . ' seconds';
}
add_filter( 'body_class', 'my_body_class', 10, 1 );
</code>```

Write the results if you try this :)

Body:
I want to add a body_class to pages, if the page has a specific shortcode.

Which of the following methods would be the most efficient one when it comes to performance?

Use has_shortcode() like

function my_body_class($classes) {
    $post_id = get_the_ID();
    if( isset($post_id) && has_shortcode( $post->post_content, 'my_shortocde' ) ) {
        $classes = array_merge( $classes, array( 'my-body-tag' ));
    }
    return $classes;
}
add_filter( 'body_class', 'my_body_class', 10, 1 );

Presume that the post_meta table for the page has a custom meta_key with meta_value of true added somewhere else in the code when updating a page and you use get_post_meta() like

function my_body_class($classes) {
    $post_id = get_the_ID();
    if( isset($post_id) && get_post_meta($post_id, '_my_shortocde_is_used') ) {
        $classes = array_merge( $classes, array( 'my_body_tag' ));
    }
    return $classes;
}
add_filter( 'body_class', 'my_body_class', 10, 1 );

What would be faster? The regex that has_shortcode does or the query that get_post_meta does? Which one would you use?

UPDATE: Wall clock timing results as suggested by @Rimarx

Option 1: Using has_shortcode()

Wall clock time: 8.66254170735685E-06 = 0.00000866254170735685

Option 2: Using get_post_meta()

Wall clock time: 2.88486480712892E-05 = 0.00002884864807128920

Using has_shorcode wins.

Side note: in this test the mysql db is on the same server as wordpress.

Body:
You can check speed like that:

<?php
$start = microtime(true);
//Your code
echo 'The script time: ' . (microtime(true) - $start) . ' seconds';
?>

As an option:

function my_body_class($classes) {
    $start = microtime(true);

    $post_id = get_the_ID();
    if( isset($post_id) && has_shortcode( $post->post_content, 'my_shortocde' ) ) {
        $classes = array_merge( $classes, array( 'my-body-tag' ));
    }

    return 'The script time: ' . (microtime(true) - $start) . ' seconds';
}
add_filter( 'body_class', 'my_body_class', 10, 1 );

Write the results if you try this :)


问:
XAMPP MySQL Access Denied ** ONLY if not connected to Internet **
My apologies in advance if this is a dup. Seems like it should be but I'm not able to find anyone else with the same question.

I'm using XAMPP - MySQL. Everything works fine unless I am not connected to the Internet.

If and ONLY if I am not connected to the Internet do I get the message:

Access denied for user 'jon'@'localhost' (using password:YES)

...where 'Jon' is my user name. There is no further information in the log.

Again - all I have to do to fix this is connect to the Internet - but I am not always able to do this and need to work even if there is no Internet.

Thanks - Jon

答: I never figured out the cause, but the work-around was to delete the user account and re-add it. It seems odd because the problem only happened when no Internet connection. But it's working now. </p>


问:
Reactive or observe in dynamic filtering
I have a working app that uses multiple filters to plot some data and i want the filters to be dynamic and dependent on the filter above by only showing available options for the selection.  For instance if the Location_Id == 1 then only 'Bike' User_Type is available in the 'User Type' filter.  This all works when the app starts with the filters all constrained by the initial Location_ID starting value but as soon as i change the initial input (Location_Id) nothing is getting updated automatically and i have to do an Select All to see which data is available for the new selected Location Id.  I have been reading all morning and it seems i need to perhaps include a reactive() somewhere in the server but its not clear how then i update the ui and if i need a render type function somewhere.    </p>

```<code>

#Example for stack overflow
library(shiny)
library(datasets)
library(dplyr)
library(shinyWidgets)
library(lubridate)
#Create test data
set.seed(10)
Dates. <- sample(c(seq(as.Date("2017-01-01"),as.Date("2017-12-28"),1),seq(as.Date("2018-01-01"),as.Date("2019-12-28"),1)),1000)
Facility_Type. <- sample(c("Bikelane","No facility"),length(Dates.),replace = T)
Data.. <- data.frame(Date = Dates., Facility_Type = Facility_Type.)
Data..$User_Type_Desc<- sample(c("Bike","Pedestrian"),nrow(Data..),replace = T)
Data..$Counts <- sample(1:100,nrow(Data..),replace = T)
Data..$Location_Id <- sample(c("01","02","03","04"),nrow(Data..),replace = T)
Data..$Month <- months(Data..$Date)
Data..$Year <- year(Data..$Date)
Data..$User_Type_Desc <- as.character(Data..$User_Type_Desc)
Data..$Facility_Type <- as.character(Data..$Facility_Type)

#Force some changes on data to highlight problem
Data..$User_Type_Desc[Data..$Location_Id%in%"01"] <- "Bike"
Data..$User_Type_Desc[Data..$Location_Id%in%"04"] <- "Pedestrian"

ui <-
  #shinyUI(fluidPage(
  navbarPage(title = "Bend Bike/PedTraffic Counts",
             #Graphics panel
             tabPanel("Charting",
                      #headerPanel(title = "Bend Traffic Count Data Viewer"),
                      sidebarLayout(
                        sidebarPanel(
                          #Select Location Id
                          selectInput("Location_Id","Select a Location Id",choices = unique(Data..$Location_Id)),

                          #Select Year
                          pickerInput(inputId = "Year", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE),
                          #Select Month
                          pickerInput(inputId = "Month", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE),
                          #Location details
                          ##################
                          #Select User Types
                          pickerInput(inputId = "User_Type", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE),
                          #Select Facility Types
                          pickerInput(inputId = "Facility_Type", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE)
                          #dateRangeInput("Date", "Input date range")
                          #selectInput("Date","Select a Product",choices = NULL)

                          #Panel end
                        ),
                        mainPanel( plotOutput("location_plot"))
                        #Sidebar panel layout end
                      )
                      # Sidebar panel end
             )
             #PAge end
  )

server <-
  #print(str(product_list))
  shinyServer(function(session,input,output) {

    #Create selection menus
    ##########################
    #Year selection with choices constrained by Location_Id
    observe({
      Years. <- unique(Data..$Year[Data..$Location_Id%in%input$Location_Id])
      updatePickerInput(session,"Year","Select Year(s)",choices = Years.,selected = Years.[1])
    })
    #Month selection  with Year choices
    observe({
      Months. <- unique(Data..$Month[Data..$Year%in%input$Year])
      updatePickerInput(session,"Month","Select Month(s)",choices = Months., selected = Months.[1]  )

    })
    #User Type
    observe({
      User_Type. <- unique(Data..$User_Type_Desc[Data..$Year%in%input$Year & Data..$Month%in%input$Month])
      updatePickerInput(session,"User_Type","Select User Type(s)",choices = User_Type., selected = User_Type.[1])

    })
    #Facility Type
    observe({
      Facility_Type. <- unique(Data..$Facility_Type[Data..$Year%in%input$Year & Data..$Month%in%input$Month
                                                    & Data..$User_Type_Desc%in%input$User_Type])
      updatePickerInput(session,"Facility_Type","Select Facility Type(s)",choices = Facility_Type., selected = Facility_Type.[1])

    })

    #Plot data
    ##########################
    #Select final data and chart
    output$location_plot <- renderPlot({
      #Select data
      dat <- Data..[Data..$Location_Id%in%input$Location_Id & Data..$Month%in%input$Month &
                      Data..$Year%in%input$Year & Data..$User_Type_Desc%in%input$User_Type,]
      #Initialze chart
      ggplot(data = dat, x=Date, y = Counts) +
        geom_bar(aes(x = Date,y = Counts),color = "black", position = "dodge", stat = "identity")+
        facet_wrap(Facility_Type~User_Type_Desc)

    })
  })

#Run App

shinyApp(ui,server)

</code>```

答:
I have developed a solution for the above problem that started this issue (making filters update with proper reactive-ness) but now that i have added a map the app tends to break after making selections in the first selector, in this example that would be the state.

I created a new example below that answers the above question but poses a new one: Why is my app crashing and does it have to do with improper way i handle the reactive-ness?

In order to get the app to crash you have to select a couple of different states and let it render.  It seems to do it on California so it makes me wonder if its a matter of the amount of data the map is attempting to render.  Unfortunately there is no error given RStudio just crashes.  Not sure if this is the proper way to pose this question but if the reactive-ness is the problem with the RStudio crash i think its still relevant to this thread.  Thx for any help!

```<code>library(shiny)    # for shiny apps
library(ggplot2)
library(plotly)
library(dplyr)
library(shinyWidgets)
library(tigris)
library(mapview)
library(leaflet)
library(raster)
library(rgeos)

# Load(Create) data
State_01_Tracts_Sp <- tracts("01")
State_02_Tracts_Sp <- tracts("02")
State_04_Tracts_Sp <- tracts("04")
State_05_Tracts_Sp <- tracts("05")
State_06_Tracts_Sp <- tracts("06")
Tracts_Sp <- rbind(State_01_Tracts_Sp ,State_02_Tracts_Sp, State_04_Tracts_Sp,
State_05_Tracts_Sp , State_06_Tracts_Sp  )

#Decode fips into descriptive state and county names
Tracts_Sp@data$State <-
fips_codes$state_name[match(Tracts_Sp@data$STATEFP,fips_codes$state_code)]
Tracts_Sp@data$County <-
fips_codes$county[match(Tracts_Sp@data$COUNTYFP,fips_codes$county_code)]
#Create a copy of the spatial data's data frame
Data.. <- Tracts_Sp@data

#Set up User Interface
   ui <- fluidPage(
    titlePanel("Census Viewer Test"),
  tabsetPanel(
    #Daily Counts Panel
    ##############
    #Hourly Counts Panel
    #######################
    tabPanel("Tab 1",
             #Call plot
             fluidRow(column(width = 12,plotlyOutput("county_plot" ))),
             #Location Details
             fluidRow(
               column(3,
                      h4("Select Details"),
                      uiOutput("State_selector"),
                      uiOutput("County_selector"),
                      uiOutput("Tract_selector")),
               column(6,
                      #h4("Selected Location"),
                      leafletOutput("map_plot",height = 500))
               #Close row
             )
             #Close panel
    )
    #Close setPanel
  )
  #PAge end
)

#Set up Server
#---------------------------
server <- shinyServer(function(session,input,output){
  #Temporal Details
  ##################
  #State
  output$State_selector <- renderUI({
    selectInput(inputId = "State",
                label = "State", multiple = FALSE,
                choices = c( unique(Data..$State)),
                selected =  unique(Data..$State)[1])
  })
  #County selection----
  output$County_selector <- renderUI({
    available0 <- as.character(unique(Data..$County[Data..$State %in% input$State ]
))
    pickerInput(inputId = "County", label = "Select/deselect all + format selected",
choices = as.character(unique(available0)),
                options = list(`actions-box` = TRUE, size = 10,`selected-text-format`
= "count > 3"), multiple = TRUE,selected = as.character(unique(available0)))
  })
  #Tract selection----
  output$Tract_selector <- renderUI({
    available1 <- as.character(unique(Data..$GEOID[Data..$State %in% input$State ] ))
    pickerInput(inputId = "Tract", label = "Select/deselect all + format selected",
  choices = as.character(unique(available1)),
                options = list(`actions-box` = TRUE, size = 10,`selected-text-format`
= "count > 3"), multiple = TRUE,selected = as.character(unique(available1)))
  })

#Graphics
#Select final data and chart-----

  output$county_plot <- renderPlotly({
    #Select data
    dat <- Data..[Data..$State%in%input$State & Data..$County%in%input$County &
Data..$GEOID%in%input$Tract ,]
    #Set up axis parameters depending on amount of data
    angle = 90

    #Initialze chart
    ggplotly(ggplot(data = dat, x=GEOID, y = ALAND, fill = State) +
               geom_bar(aes(x=GEOID, y = ALAND, fill = State),color = "black",
position = "dodge", stat = "identity")+
                ggtitle(paste("Land Area of Select Counties
",unique(dat$State),sep="")) +
               #Center plot
               theme(plot.title = element_text(hjust = 0.5)) +
               ylab("LAnd Area") +
               xlab("") +
               guides(color=guide_legend("State")) +
               theme(axis.text.x = element_text(angle = angle, hjust =
1),plot.background = element_rect(fill = "darkseagreen"))) %>% layout(dragmode =
"select")

  })
  #Select final data and map-----
  output$map_plot <- renderLeaflet({
    #Select data
    Map_Data_Sp <- Tracts_Sp[Tracts_Sp@data$State%in%input$State,]
    class(Map_Data_Sp )
    #Create map
    Map <- mapview(Map_Data_Sp, map.types = "OpenStreetMap", legend = FALSE,
col.regions = "red",color = "black",cex = 10)
    Map@map

    #Close map
  })

})
#Run App
shinyApp(ui,server)
</code>```

Body:
I have a working app that uses multiple filters to plot some data and i want the filters to be dynamic and dependent on the filter above by only showing available options for the selection.  For instance if the Location_Id == 1 then only 'Bike' User_Type is available in the 'User Type' filter.  This all works when the app starts with the filters all constrained by the initial Location_ID starting value but as soon as i change the initial input (Location_Id) nothing is getting updated automatically and i have to do an Select All to see which data is available for the new selected Location Id.  I have been reading all morning and it seems i need to perhaps include a reactive() somewhere in the server but its not clear how then i update the ui and if i need a render type function somewhere.

#Example for stack overflow
library(shiny)
library(datasets)
library(dplyr)
library(shinyWidgets)
library(lubridate)
#Create test data
set.seed(10)
Dates. <- sample(c(seq(as.Date("2017-01-01"),as.Date("2017-12-28"),1),seq(as.Date("2018-01-01"),as.Date("2019-12-28"),1)),1000)
Facility_Type. <- sample(c("Bikelane","No facility"),length(Dates.),replace = T)
Data.. <- data.frame(Date = Dates., Facility_Type = Facility_Type.)
Data..$User_Type_Desc<- sample(c("Bike","Pedestrian"),nrow(Data..),replace = T)
Data..$Counts <- sample(1:100,nrow(Data..),replace = T)
Data..$Location_Id <- sample(c("01","02","03","04"),nrow(Data..),replace = T)
Data..$Month <- months(Data..$Date)
Data..$Year <- year(Data..$Date)
Data..$User_Type_Desc <- as.character(Data..$User_Type_Desc)
Data..$Facility_Type <- as.character(Data..$Facility_Type)

#Force some changes on data to highlight problem
Data..$User_Type_Desc[Data..$Location_Id%in%"01"] <- "Bike"
Data..$User_Type_Desc[Data..$Location_Id%in%"04"] <- "Pedestrian"

ui <-
  #shinyUI(fluidPage(
  navbarPage(title = "Bend Bike/PedTraffic Counts",
             #Graphics panel
             tabPanel("Charting",
                      #headerPanel(title = "Bend Traffic Count Data Viewer"),
                      sidebarLayout(
                        sidebarPanel(
                          #Select Location Id
                          selectInput("Location_Id","Select a Location Id",choices = unique(Data..$Location_Id)),

                          #Select Year
                          pickerInput(inputId = "Year", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE),
                          #Select Month
                          pickerInput(inputId = "Month", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE),
                          #Location details
                          ##################
                          #Select User Types
                          pickerInput(inputId = "User_Type", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE),
                          #Select Facility Types
                          pickerInput(inputId = "Facility_Type", label = "Select/deselect all + format selected", choices = NULL,
                                      options = list(`actions-box` = TRUE, size = 10,`selected-text-format` = "count > 3"), multiple = TRUE)
                          #dateRangeInput("Date", "Input date range")
                          #selectInput("Date","Select a Product",choices = NULL)

                          #Panel end
                        ),
                        mainPanel( plotOutput("location_plot"))
                        #Sidebar panel layout end
                      )
                      # Sidebar panel end
             )
             #PAge end
  )

server <-
  #print(str(product_list))
  shinyServer(function(session,input,output) {

    #Create selection menus
    ##########################
    #Year selection with choices constrained by Location_Id
    observe({
      Years. <- unique(Data..$Year[Data..$Location_Id%in%input$Location_Id])
      updatePickerInput(session,"Year","Select Year(s)",choices = Years.,selected = Years.[1])
    })
    #Month selection  with Year choices
    observe({
      Months. <- unique(Data..$Month[Data..$Year%in%input$Year])
      updatePickerInput(session,"Month","Select Month(s)",choices = Months., selected = Months.[1]  )

    })
    #User Type
    observe({
      User_Type. <- unique(Data..$User_Type_Desc[Data..$Year%in%input$Year & Data..$Month%in%input$Month])
      updatePickerInput(session,"User_Type","Select User Type(s)",choices = User_Type., selected = User_Type.[1])

    })
    #Facility Type
    observe({
      Facility_Type. <- unique(Data..$Facility_Type[Data..$Year%in%input$Year & Data..$Month%in%input$Month
                                                    & Data..$User_Type_Desc%in%input$User_Type])
      updatePickerInput(session,"Facility_Type","Select Facility Type(s)",choices = Facility_Type., selected = Facility_Type.[1])

    })

    #Plot data
    ##########################
    #Select final data and chart
    output$location_plot <- renderPlot({
      #Select data
      dat <- Data..[Data..$Location_Id%in%input$Location_Id & Data..$Month%in%input$Month &
                      Data..$Year%in%input$Year & Data..$User_Type_Desc%in%input$User_Type,]
      #Initialze chart
      ggplot(data = dat, x=Date, y = Counts) +
        geom_bar(aes(x = Date,y = Counts),color = "black", position = "dodge", stat = "identity")+
        facet_wrap(Facility_Type~User_Type_Desc)

    })
  })

#Run App

shinyApp(ui,server)

Body:
I have developed a solution for the above problem that started this issue (making filters update with proper reactive-ness) but now that i have added a map the app tends to break after making selections in the first selector, in this example that would be the state.

I created a new example below that answers the above question but poses a new one: Why is my app crashing and does it have to do with improper way i handle the reactive-ness?

In order to get the app to crash you have to select a couple of different states and let it render.  It seems to do it on California so it makes me wonder if its a matter of the amount of data the map is attempting to render.  Unfortunately there is no error given RStudio just crashes.  Not sure if this is the proper way to pose this question but if the reactive-ness is the problem with the RStudio crash i think its still relevant to this thread.  Thx for any help!

library(shiny)    # for shiny apps
library(ggplot2)
library(plotly)
library(dplyr)
library(shinyWidgets)
library(tigris)
library(mapview)
library(leaflet)
library(raster)
library(rgeos)

# Load(Create) data
State_01_Tracts_Sp <- tracts("01")
State_02_Tracts_Sp <- tracts("02")
State_04_Tracts_Sp <- tracts("04")
State_05_Tracts_Sp <- tracts("05")
State_06_Tracts_Sp <- tracts("06")
Tracts_Sp <- rbind(State_01_Tracts_Sp ,State_02_Tracts_Sp, State_04_Tracts_Sp,
State_05_Tracts_Sp , State_06_Tracts_Sp  )

#Decode fips into descriptive state and county names
Tracts_Sp@data$State <-
fips_codes$state_name[match(Tracts_Sp@data$STATEFP,fips_codes$state_code)]
Tracts_Sp@data$County <-
fips_codes$county[match(Tracts_Sp@data$COUNTYFP,fips_codes$county_code)]
#Create a copy of the spatial data's data frame
Data.. <- Tracts_Sp@data

#Set up User Interface
   ui <- fluidPage(
    titlePanel("Census Viewer Test"),
  tabsetPanel(
    #Daily Counts Panel
    ##############
    #Hourly Counts Panel
    #######################
    tabPanel("Tab 1",
             #Call plot
             fluidRow(column(width = 12,plotlyOutput("county_plot" ))),
             #Location Details
             fluidRow(
               column(3,
                      h4("Select Details"),
                      uiOutput("State_selector"),
                      uiOutput("County_selector"),
                      uiOutput("Tract_selector")),
               column(6,
                      #h4("Selected Location"),
                      leafletOutput("map_plot",height = 500))
               #Close row
             )
             #Close panel
    )
    #Close setPanel
  )
  #PAge end
)

#Set up Server
#---------------------------
server <- shinyServer(function(session,input,output){
  #Temporal Details
  ##################
  #State
  output$State_selector <- renderUI({
    selectInput(inputId = "State",
                label = "State", multiple = FALSE,
                choices = c( unique(Data..$State)),
                selected =  unique(Data..$State)[1])
  })
  #County selection----
  output$County_selector <- renderUI({
    available0 <- as.character(unique(Data..$County[Data..$State %in% input$State ]
))
    pickerInput(inputId = "County", label = "Select/deselect all + format selected",
choices = as.character(unique(available0)),
                options = list(`actions-box` = TRUE, size = 10,`selected-text-format`
= "count > 3"), multiple = TRUE,selected = as.character(unique(available0)))
  })
  #Tract selection----
  output$Tract_selector <- renderUI({
    available1 <- as.character(unique(Data..$GEOID[Data..$State %in% input$State ] ))
    pickerInput(inputId = "Tract", label = "Select/deselect all + format selected",
  choices = as.character(unique(available1)),
                options = list(`actions-box` = TRUE, size = 10,`selected-text-format`
= "count > 3"), multiple = TRUE,selected = as.character(unique(available1)))
  })

#Graphics
#Select final data and chart-----

  output$county_plot <- renderPlotly({
    #Select data
    dat <- Data..[Data..$State%in%input$State & Data..$County%in%input$County &
Data..$GEOID%in%input$Tract ,]
    #Set up axis parameters depending on amount of data
    angle = 90

    #Initialze chart
    ggplotly(ggplot(data = dat, x=GEOID, y = ALAND, fill = State) +
               geom_bar(aes(x=GEOID, y = ALAND, fill = State),color = "black",
position = "dodge", stat = "identity")+
                ggtitle(paste("Land Area of Select Counties
",unique(dat$State),sep="")) +
               #Center plot
               theme(plot.title = element_text(hjust = 0.5)) +
               ylab("LAnd Area") +
               xlab("") +
               guides(color=guide_legend("State")) +
               theme(axis.text.x = element_text(angle = angle, hjust =
1),plot.background = element_rect(fill = "darkseagreen"))) %>% layout(dragmode =
"select")

  })
  #Select final data and map-----
  output$map_plot <- renderLeaflet({
    #Select data
    Map_Data_Sp <- Tracts_Sp[Tracts_Sp@data$State%in%input$State,]
    class(Map_Data_Sp )
    #Create map
    Map <- mapview(Map_Data_Sp, map.types = "OpenStreetMap", legend = FALSE,
col.regions = "red",color = "black",cex = 10)
    Map@map

    #Close map
  })

})
#Run App
shinyApp(ui,server)


问:
Upgrade Angular 7 -> 8 runs out of memory
When I am running ng update to upgrade Angular 7 to 8, I am getting "Out of memory" error during @angular/core migration:

```<code>FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
</code>```

which is not particularly surprising - I am getting Out of memory when I run ng build as well. As a solution, we run npm run build which is configured as node --max_old_space_size=10240 ./node_modules/@angular/cli/bin/ng build

So, my question is how do I configure migration for the package @angular/core to use more memory?

UPDATE: as suggested, I reran the update

```<code>node --max_old_space_size=10240 ./node_modules/.bin/ng update @angular/core --from 7 --to 8 --migrate-only
</code>```

but I am getting an error:

```<code>basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
      ^^^^^^^

SyntaxError: missing ) after argument list
</code>```

Seems like the quotes are for Linux environment and break on Windows...

答:
Try this command node --max_old_space_size=10240 node_modules/.bin/ng update as explained in this GitHub issue.

Update:

Looks like you can also customize ng command invocation as explained in this post.

Or you can upgrade node to the version 12, which should automatically adjust memory required to run the command.

Body:
When I am running ng update to upgrade Angular 7 to 8, I am getting "Out of memory" error during @angular/core migration:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

which is not particularly surprising - I am getting Out of memory when I run ng build as well. As a solution, we run npm run build which is configured as node --max_old_space_size=10240 ./node_modules/@angular/cli/bin/ng build

So, my question is how do I configure migration for the package @angular/core to use more memory?

UPDATE: as suggested, I reran the update

node --max_old_space_size=10240 ./node_modules/.bin/ng update @angular/core --from 7 --to 8 --migrate-only

but I am getting an error:

basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
      ^^^^^^^

SyntaxError: missing ) after argument list

Seems like the quotes are for Linux environment and break on Windows...


问:
How do I use bitwise shifts with cout?
I'm trying to do something similar to this:

```<code>#include <iostream>

int main()
{
    std::cout << 1 << 5 << std::endl;
}
</code>```

I expect 32 (1 shifted left by 5), but I get 15.

I am trying to use a macro like this:

```<code>#define BIT_SHIFT(x,y) x << y
...
cout << BIT_SHIFT(1, 5) << std::endl;
</code>```

and this happens.

Why? How do I fix this?

答:
I'm trying to do something similar to this:

```<code>#include <iostream>

int main()
{
   std::cout << 1 << 5 << std::endl;
}
</code>```

You're right. You are trying to do something similar to that. However, the problem has nothing to do with the macro (I mean, that's a problem too, but more on that later). The problem is your goal isn't what you mean. You don't mean std::cout << 1 << 5 << std::endl;, you mean std::cout << (1 << 5) << std::endl; The difference is that the first breaks down into something like this:

```<code>std::cout << 1;
std::cout << 5;
std::cout << std::endl;
</code>```

While what you want is something like this:

```<code>int i = 1 << 5;

std::cout << i;
std::cout << std::endl;

</code>```

Or something to that effect.

The answer is simple: either use parenthesis in your cout statement, or put it in your macro (the better option):

```<code>// either
cout << (BIT_SHIFT(1, 5)) << std::endl;
// or
#define BIT_SHIFT(x,y) (x << y)
...
cout << BIT_SHIFT(1, 5) << std::endl;
</code>```

Also, as someone else suggested, you can even go a step further if you like and do this:

```<code>#define BIT_SHIFT(x,y) ((x) << (y))
...
cout << BIT_SHIFT(1, 5) << std::endl;
</code>```

That way, if you do something weird in x or y, your code doesn't break.

Title: How do I use bitwise shifts with cout?

Body:
I'm trying to do something similar to this:

#include <iostream>

int main()
{
    std::cout << 1 << 5 << std::endl;
}

I expect 32 (1 shifted left by 5), but I get 15.

I am trying to use a macro like this:

#define BIT_SHIFT(x,y) x << y
...
cout << BIT_SHIFT(1, 5) << std::endl;

and this happens.

Why? How do I fix this?

Body:
I'm trying to do something similar to this:

#include <iostream>

int main()
{
   std::cout << 1 << 5 << std::endl;
}

You're right. You are trying to do something similar to that. However, the problem has nothing to do with the macro (I mean, that's a problem too, but more on that later). The problem is your goal isn't what you mean. You don't mean std::cout << 1 << 5 << std::endl;, you mean std::cout << (1 << 5) << std::endl; The difference is that the first breaks down into something like this:

std::cout << 1;
std::cout << 5;
std::cout << std::endl;

While what you want is something like this:

int i = 1 << 5;

std::cout << i;
std::cout << std::endl;

Or something to that effect.

The answer is simple: either use parenthesis in your cout statement, or put it in your macro (the better option):

// either
cout << (BIT_SHIFT(1, 5)) << std::endl;
// or
#define BIT_SHIFT(x,y) (x << y)
...
cout << BIT_SHIFT(1, 5) << std::endl;

Also, as someone else suggested, you can even go a step further if you like and do this:

#define BIT_SHIFT(x,y) ((x) << (y))
...
cout << BIT_SHIFT(1, 5) << std::endl;

That way, if you do something weird in x or y, your code doesn't break.


问:
Java library for creating straight skeleton?
I have as an input a 2D polygon with holes, and I need to find it's straight skeleton, like in the picture:

(source: cgal.org)

Maybe there is a good Java library for it?

And if not, can you point me to the good explanation of the algorithm, so I could implement it myself? (I haven't found good resources on Google)

答:
Edit:
Ah.  I see that "Straight Skeleton" is a technical term.  The wikipedia article references several algorithms.  Have you looked at those?

As I understand it, you have a (convex?) polygon.  From it, you subtract 1 or more (potentially non-convex) polygons. You want to turn the result into a set of polygons without holes.  Are there extra rules that you're trying to apply?

I have a hard time coming up with a set of rules from the example that you provided.  The outer polygons are non-convex; so it doesn't seem like you're trying to find a convex set to represent the result (which is a relatively common task).

If you could use the breakdown shown below, the algorithm is pretty simple.  Can you clarify?

ContentLicense: CC BY-SA 3.0


问:
GoogleCredentials does not work and paralyzes the application
I followed the steps of the documentation https://firebase.google.com/docs/admin/setup?authuser=0

But the "GoogleCredentials.fromStream(serviceAccount)" part of the code ; it stops the application and does not return anything, not even an error message.

I have included the following libraries

firebase-admin-6.8.1.jar

google-auth-library-credentials-0.15.0.jar

google-auth-library-oauth2-http-0.15.0.jar

appengine-api-1.0-sdk-1.9.74.jar

Please give me some help, thanks

```<code>        String token=null;
        FirebaseOptions options=null;
        FileInputStream serviceAccount=null;
        try {
            serviceAccount = new FileInputStream(Aplicacion.ruta_firebase_js);
        }catch(FileNotFoundException ex) {
            log("Ruta de clave de firebase no encontrada: "+ex.getMessage());
        }

        if(serviceAccount!=null){
            try {

                GoogleCredentials gc=GoogleCredentials.fromStream(serviceAccount);
                log(gc.toString());
                options = new FirebaseOptions.Builder()
                        .setCredentials(gc)
                        .setDatabaseUrl("https://xxxxx-xxxxxx.firebaseio.com")
                        .build();
            } catch(FileNotFoundException ex) {
                log("Ruta de clave de firebase no encontrada: "+ex.getMessage());
            }catch (IOException ex){
                log("Error autenticando en Firebase: "+ex.getMessage());
            }
        }

        if(options!=null){
            FirebaseApp.initializeApp(options);
            try {
                String uid = "Rocco-ergvrw98";
                token = FirebaseAuth.getInstance().createCustomToken(uid);
                HashMap p=new HashMap();
                p.put("accion", "tokenfirebase");
                p.put("token", token);
                Rocco.servidor_enlinealizate.enviar(indice, p);

            } catch (FirebaseAuthException ex) {
                log("Error obtenmiendo token: "+ex.getMessage());
            };
        }
        return token;
    }
</code>```

答:
Solved! I had to include these bookstores in my project

api-common-1.8.1

commons-logging-1.2

firebase-admin-6.8.1

google-api-client-1.29.0

google-http-client-1.29.1

google-http-client-gson-1.29.1

google-http-client-jackson2-1.29.1

google-oauth-client-1.29.0

gson-2.8.5

guava-27.1-jre

httpclient-4.5.8

httpcore-4.4.11

jackson-core-2.9.9

jackson-core-asl-1.9.13

jsr305-3.0.2

protobuf-java-3.8.0

slf4j-api-1.7.26

slf4j-simple-1.7.26

xpp3-1.1.6

Whose updated versions are available in https://mvnrepository.com/

Body:
I followed the steps of the documentation https://firebase.google.com/docs/admin/setup?authuser=0

But the "GoogleCredentials.fromStream(serviceAccount)" part of the code ; it stops the application and does not return anything, not even an error message.

I have included the following libraries

firebase-admin-6.8.1.jar

google-auth-library-credentials-0.15.0.jar

google-auth-library-oauth2-http-0.15.0.jar

appengine-api-1.0-sdk-1.9.74.jar

Please give me some help, thanks

        String token=null;
        FirebaseOptions options=null;
        FileInputStream serviceAccount=null;
        try {
            serviceAccount = new FileInputStream(Aplicacion.ruta_firebase_js);
        }catch(FileNotFoundException ex) {
            log("Ruta de clave de firebase no encontrada: "+ex.getMessage());
        }

        if(serviceAccount!=null){
            try {

                GoogleCredentials gc=GoogleCredentials.fromStream(serviceAccount);
                log(gc.toString());
                options = new FirebaseOptions.Builder()
                        .setCredentials(gc)
                        .setDatabaseUrl("https://xxxxx-xxxxxx.firebaseio.com")
                        .build();
            } catch(FileNotFoundException ex) {
                log("Ruta de clave de firebase no encontrada: "+ex.getMessage());
            }catch (IOException ex){
                log("Error autenticando en Firebase: "+ex.getMessage());
            }
        }

        if(options!=null){
            FirebaseApp.initializeApp(options);
            try {
                String uid = "Rocco-ergvrw98";
                token = FirebaseAuth.getInstance().createCustomToken(uid);
                HashMap p=new HashMap();
                p.put("accion", "tokenfirebase");
                p.put("token", token);
                Rocco.servidor_enlinealizate.enviar(indice, p);

            } catch (FirebaseAuthException ex) {
                log("Error obtenmiendo token: "+ex.getMessage());
            };
        }
        return token;
    }


问:
Black color for a style font clips through original line
the purpose of shadow() is to create a line where a color that the user picks is followed by a black line. However, when the user drags the line across the canvas, particularly from right to left, the black line stutters over the original color

I implemented the same method used to create a line on canvas to create the trailing black line in shadow(), only changing the properties shadowOffset, lineJoin, and lineCap in order to create the black line effect.

#c {
  border: 1px solid black;

table{
    float:left;
}
```

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Canvas</title>
  <link href="canvas.css" rel="stylesheet">
</head>

<body>
   <h2>STYLES:</h2>
    <form>
    <input type="button" value="shadow" onclick="shadow()">
    </form>

    <canvas id="c"></canvas>
</body>

<script src="canvas.js"></script>
<script src="colors.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</html>
</code>```

```<code>const c = document.querySelector("#c");
c.height = window.innerHeight;
c.width = window.innerWidth;
const ctx = c.getContext("2d");
//default settings
ctx.strokeStyle = "black";
ctx.lineWidth = 15;

let confirmButton = document.querySelector(".confirm");

window.addEventListener('load', () => {

  let painting = false;

  //when mouse is clicked; paint
  function mousedown(b) {
    painting = true;
    //allows for paint to appear without nedding to drag mouse
    mousemove(b);
  }
  //when mouse is not clicked; don't paint
  function mouseup() {
    painting = false;
    //resets path each time so multiple can be created
    ctx.beginPath();
  }

  function mousemove(b) {
    //Get correct mouse position
    var pos = getMousePos(c, b);
    //if not holding down the mouse; nothing happens
    if (!painting) return;
    //roundness of paint
    ctx.lineCap = 'round';

    //create paint wherever the mouse goes: ctx[on the canvas].lineTo[move the line to]()
    ctx.lineTo(pos.x, pos.y);
    //end the stroke and visualize paint
    ctx.stroke();
    //begins a new paint so that everything doesn't just stick to a fat line
    ctx.beginPath();
    //move the new line to wherever the mouse goes
    ctx.moveTo(pos.x, pos.y);
  }

  //starting posistion of paint line
  c.addEventListener('mousedown', mousedown);
  //ending posistion of paint line
  c.addEventListener('mouseup', mouseup);
  //whenever the mouse is moving; paint
  c.addEventListener('mousemove', mousemove);

  confirmButton.addEventListener('click', size);
});

function size() {
   numS = document.getElementById("sizeInput").value;
  ctx.lineWidth = numS;
  console.log("blah "+ ctx.lineWidth)
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

function shadow(){

  let sc =  ctx.shadowColor = 'rgb(0, 0, 0)';

  let painting = false;

  //when mouse is clicked; paint
  function mousedown(b) {
    painting = true;
    sc = true;
    //allows for paint to appear without nedding to drag mouse
    mousemove(b);
  }
  //when mouse is not clicked; don't paint
  function mouseup() {
    painting = false;
    sc = false;
    //resets path each time so multiple can be created
    ctx.beginPath();
  }

  function mousemove(b) {
    //Get correct mouse position
    var pos = getMousePos(c, b);
    //if not holding down the mouse; nothing happens
    if (!painting) return;
    ctx.lineJoin = "round";
    ctx.lineCap = "round";
    ctx.shadowOffsetX = 10;
    ctx.shadowOffsetY = 10;

    //create paint wherever the mouse goes: ctx[on the canvas].lineTo[move the line to]()
    ctx.lineTo(pos.x, pos.y,);
    //end the stroke and visualize paint
    ctx.stroke();
    //begins a new paint so that everything doesn't just stick to a fat line
    ctx.beginPath();
    //move the new line to wherever the mouse goes
    ctx.moveTo(pos.x, pos.y,);
  }

  //starting posistion of paint line
  c.addEventListener('mousedown', mousedown);
  //ending posistion of paint line
  c.addEventListener('mouseup', mouseup);
  //whenever the mouse is moving; paint
  c.addEventListener('mousemove', mousemove);
}
</code>```

What occurs is that the trailing black line clips through the original color line, creating a stutter effect. I showed code only relevant to this question, but for clarity I have re-created the project on plunker:
https://plnkr.co/edit/0gP32ZSf0ZlOVguTj51X?p=preview

file color.js is not relevant to this question

答:
You have a mess of functions on your canvas.js I could not figure out what your are doing there...

Here is a simple canvas with a shadow button

const c = document.querySelector("#c");
const ctx = c.getContext("2d");

ctx.strokeStyle = "red";
ctx.lineWidth = 6;

window.addEventListener('load', () => {
  function mousemove(b) {
    var pos = getMousePos(c, b);
    ctx.lineTo(pos.x, pos.y);
    ctx.clearRect(0,0,c.width,c.height);
    ctx.stroke();
  }

  c.addEventListener('mousemove', mousemove);
});

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

function shadow() {
  ctx.shadowBlur = 2;
  ctx.shadowOffsetX = 6
  ctx.shadowColor = 'black';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas><br>
<input type="button" value="shadow" onclick="shadow()"></code>```

Body:
the purpose of shadow() is to create a line where a color that the user picks is followed by a black line. However, when the user drags the line across the canvas, particularly from right to left, the black line stutters over the original color

I implemented the same method used to create a line on canvas to create the trailing black line in shadow(), only changing the properties shadowOffset, lineJoin, and lineCap in order to create the black line effect.

#c {
  border: 1px solid black;

table{
    float:left;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Canvas</title>
  <link href="canvas.css" rel="stylesheet">

STYLES:

    <form>
    <input type="button" value="shadow" onclick="shadow()">
    </form>

    <canvas id="c"></canvas>

const c = document.querySelector("#c");
c.height = window.innerHeight;
c.width = window.innerWidth;
const ctx = c.getContext("2d");
//default settings
ctx.strokeStyle = "black";
ctx.lineWidth = 15;

let confirmButton = document.querySelector(".confirm");

window.addEventListener('load', () => {

  let painting = false;

  //when mouse is clicked; paint
  function mousedown(b) {
    painting = true;
    //allows for paint to appear without nedding to drag mouse
    mousemove(b);
  }
  //when mouse is not clicked; don't paint
  function mouseup() {
    painting = false;
    //resets path each time so multiple can be created
    ctx.beginPath();
  }

  function mousemove(b) {
    //Get correct mouse position
    var pos = getMousePos(c, b);
    //if not holding down the mouse; nothing happens
    if (!painting) return;
    //roundness of paint
    ctx.lineCap = 'round';

    //create paint wherever the mouse goes: ctx[on the canvas].lineTo[move the line to]()
    ctx.lineTo(pos.x, pos.y);
    //end the stroke and visualize paint
    ctx.stroke();
    //begins a new paint so that everything doesn't just stick to a fat line
    ctx.beginPath();
    //move the new line to wherever the mouse goes
    ctx.moveTo(pos.x, pos.y);
  }

  //starting posistion of paint line
  c.addEventListener('mousedown', mousedown);
  //ending posistion of paint line
  c.addEventListener('mouseup', mouseup);
  //whenever the mouse is moving; paint
  c.addEventListener('mousemove', mousemove);

  confirmButton.addEventListener('click', size);
});

function size() {
   numS = document.getElementById("sizeInput").value;
  ctx.lineWidth = numS;
  console.log("blah "+ ctx.lineWidth)
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

function shadow(){

  let sc =  ctx.shadowColor = 'rgb(0, 0, 0)';

  let painting = false;

  //when mouse is clicked; paint
  function mousedown(b) {
    painting = true;
    sc = true;
    //allows for paint to appear without nedding to drag mouse
    mousemove(b);
  }
  //when mouse is not clicked; don't paint
  function mouseup() {
    painting = false;
    sc = false;
    //resets path each time so multiple can be created
    ctx.beginPath();
  }

  function mousemove(b) {
    //Get correct mouse position
    var pos = getMousePos(c, b);
    //if not holding down the mouse; nothing happens
    if (!painting) return;
    ctx.lineJoin = "round";
    ctx.lineCap = "round";
    ctx.shadowOffsetX = 10;
    ctx.shadowOffsetY = 10;

    //create paint wherever the mouse goes: ctx[on the canvas].lineTo[move the line to]()
    ctx.lineTo(pos.x, pos.y,);
    //end the stroke and visualize paint
    ctx.stroke();
    //begins a new paint so that everything doesn't just stick to a fat line
    ctx.beginPath();
    //move the new line to wherever the mouse goes
    ctx.moveTo(pos.x, pos.y,);
  }

  //starting posistion of paint line
  c.addEventListener('mousedown', mousedown);
  //ending posistion of paint line
  c.addEventListener('mouseup', mouseup);
  //whenever the mouse is moving; paint
  c.addEventListener('mousemove', mousemove);
}

What occurs is that the trailing black line clips through the original color line, creating a stutter effect. I showed code only relevant to this question, but for clarity I have re-created the project on plunker:
https://plnkr.co/edit/0gP32ZSf0ZlOVguTj51X?p=preview

file color.js is not relevant to this question

Body:
You have a mess of functions on your canvas.js I could not figure out what your are doing there...

Here is a simple canvas with a shadow button

const c = document.querySelector("#c");
const ctx = c.getContext("2d");

ctx.strokeStyle = "red";
ctx.lineWidth = 6;

window.addEventListener('load', () => {
  function mousemove(b) {
    var pos = getMousePos(c, b);
    ctx.lineTo(pos.x, pos.y);
    ctx.clearRect(0,0,c.width,c.height);
    ctx.stroke();
  }

  c.addEventListener('mousemove', mousemove);
});

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

function shadow() {
  ctx.shadowBlur = 2;
  ctx.shadowOffsetX = 6
  ctx.shadowColor = 'black';
}

<canvas id="c"></canvas><br>
<input type="button" value="shadow" onclick="shadow()">


问:
Gitlab CI - Add custom label/badge to pipeline after completing a certain stage
Is it possible to add a custom label/badge to a pipeline if a specific stage is successfully finished? This is how it normally looks:

As you can see the pipeline #1410 has the "latest" badge. I want to add a simular badge "last deploy" (maybe in another color) to pipeline #1409 when the latest stage successfully is finished. But only one pipeline can have this badge. Like this:

答:
It's not possible to add custom badges. Gitlab is part open source, so theoretically you could build this yourself and try to get it merged.

Have a look at the Environment that Gitlab is providing https://docs.gitlab.com/ee/ci/environments.html#viewing-environments-and-deployments This is basically what you're looking for: Tracking which pipeline / commit hash is currently deployed.


问:
Import .csv file through SSIS Package without double Quotes
SQL 2005

I am importing .csv file to SQL Table through SSIS Package !! On doing so, I am getting double quotes on every column header or field value !!

How to remove double quotes, while importing .csv file ???

答:
Add " as the Text Qualifier when choosing the source (csv file)

http://twitpic.com/4k3ok8/full


问:
C# Exception error while running SQL Server query
I'm building simple library application. I'm using C# and SQL Server 2017.

While running a function to check if the book already exists I'm getting an error near "Name".

```<code>        public bool DoesItExist()
        {
            mainSet mset = new mainSet();
            string query = "SELECT * FROM [Library].[dbo].[ViewBook] WHERE " +
                "Title = '" + this.title + "' AND " +
                "DateOfFirstRelease = " + this.release_date + " AND " +
                "Name = '" + this.author_name + "' AND " +
                "2Name= '" + this.author_2name + "' AND " +
                "Surname = '" + this.author_surname + "' AND " +
                "Category = '" + this.category + "' AND " +
                "Publishing = '" + this.Publishing+ "' ";

            SqlConnection cnn = new SqlConnection(mset.dataBaseConect);
            SqlCommand cmd = new SqlCommand(query, cnn);
            cnn.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows) return true;
            else return false;
        }
</code>```

All "this." are are parameters in "Title" class.

All parameters are type:string except "DateOfRelease" which is type:int

[ViewBook] is a view in [Library] database.

Error I'm getting:

```<code>System.Data.SqlClient.SqlException:

An expression of non-boolean type specified in a context where a condition is expected, near 'Name'.”
</code>```

Example of the cmd query:

```<code>"SELECT * FROM [Library].[dbo].[ViewBook] WHERE Title = 'Book Name' AND DateOfFirstRelease = 2004 AND Name = 'George' AND 2Name= '' AND Surname = 'Martin' AND Category = 'Economy' AND Publishing = 'PublishingTest' "
</code>```

答:
There is a big caveat with this answer; I'm not a c# coder so I have not tested this. I very rarely go near C#, and only when I do it's because I'm assisting our developers at work with their SQL Server requirements (as I'm a DBA/SQL Developer). What did I do though? I used the documentation (SqlCommand.Parameters Property & SqlDbType Enum) to write a properly parametrised query which should work (I added a comment as to why I believe your query failed as well):

```<code>string query = "SELECT * FROM Library.dbo.ViewBook" +
                " WHERE Title = @Title" +
                " AND DateOfFirstRelease = @ReleaseDate" +
                " AND [Name] = @AuthorName" + //Name is a keyword, so I prefer to quote it
                " AND [2Name] = @AuthorName2" + //Quoted as a column that begins with a number needs to be delimit identified
                " AND Surname = @Surname" +
                " AND Category = @Category" +
                " AND Publishing = @Publishing;";

    using (SqlConnection cnn = new SqlConnection(mset.dataBaseConect))
    {
        SqlCommand cmd = new SqlCommand(query, cnn);

        cmd.Parameters.Add("@Title",SqlDbType,VarChar,50); //Guessed datatype
        cmd.Parameters["@Title"].Value = this.title;

        cmd.Parameters.Add("@ReleaseDate",SqlDbType.Date); //Guessed datatype
        cmd.Parameters["@ReleaseDate"].Value = this.release_date;

        cmd.Parameters.Add("@AuthorName",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@AuthorName"].Value = this.author_name;

        cmd.Parameters.Add("@AuthorName2",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@AuthorName2"].Value = this.author_2name;

        cmd.Parameters.Add("@Surname",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@Surname"].Value = this.author_surname;

        cmd.Parameters.Add("@Category",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@Category"].Value = this.category;

        cmd.Parameters.Add("@Publishing",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@Publishing"].Value = this.Publishing;

        cnn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
    }
</code>```

Body:
I'm building simple library application. I'm using C# and SQL Server 2017.

While running a function to check if the book already exists I'm getting an error near "Name".

        public bool DoesItExist()
        {
            mainSet mset = new mainSet();
            string query = "SELECT * FROM [Library].[dbo].[ViewBook] WHERE " +
                "Title = '" + this.title + "' AND " +
                "DateOfFirstRelease = " + this.release_date + " AND " +
                "Name = '" + this.author_name + "' AND " +
                "2Name= '" + this.author_2name + "' AND " +
                "Surname = '" + this.author_surname + "' AND " +
                "Category = '" + this.category + "' AND " +
                "Publishing = '" + this.Publishing+ "' ";

            SqlConnection cnn = new SqlConnection(mset.dataBaseConect);
            SqlCommand cmd = new SqlCommand(query, cnn);
            cnn.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows) return true;
            else return false;
        }

All "this." are are parameters in "Title" class.

All parameters are type:string except "DateOfRelease" which is type:int

[ViewBook] is a view in [Library] database.

Error I'm getting:

System.Data.SqlClient.SqlException:

An expression of non-boolean type specified in a context where a condition is expected, near 'Name'.”

Example of the cmd query:

"SELECT * FROM [Library].[dbo].[ViewBook] WHERE Title = 'Book Name' AND DateOfFirstRelease = 2004 AND Name = 'George' AND 2Name= '' AND Surname = 'Martin' AND Category = 'Economy' AND Publishing = 'PublishingTest' "

Body:
There is a big caveat with this answer; I'm not a c# coder so I have not tested this. I very rarely go near C#, and only when I do it's because I'm assisting our developers at work with their SQL Server requirements (as I'm a DBA/SQL Developer). What did I do though? I used the documentation (SqlCommand.Parameters Property & SqlDbType Enum) to write a properly parametrised query which should work (I added a comment as to why I believe your query failed as well):

string query = "SELECT * FROM Library.dbo.ViewBook" +
                " WHERE Title = @Title" +
                " AND DateOfFirstRelease = @ReleaseDate" +
                " AND [Name] = @AuthorName" + //Name is a keyword, so I prefer to quote it
                " AND [2Name] = @AuthorName2" + //Quoted as a column that begins with a number needs to be delimit identified
                " AND Surname = @Surname" +
                " AND Category = @Category" +
                " AND Publishing = @Publishing;";

    using (SqlConnection cnn = new SqlConnection(mset.dataBaseConect))
    {
        SqlCommand cmd = new SqlCommand(query, cnn);

        cmd.Parameters.Add("@Title",SqlDbType,VarChar,50); //Guessed datatype
        cmd.Parameters["@Title"].Value = this.title;

        cmd.Parameters.Add("@ReleaseDate",SqlDbType.Date); //Guessed datatype
        cmd.Parameters["@ReleaseDate"].Value = this.release_date;

        cmd.Parameters.Add("@AuthorName",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@AuthorName"].Value = this.author_name;

        cmd.Parameters.Add("@AuthorName2",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@AuthorName2"].Value = this.author_2name;

        cmd.Parameters.Add("@Surname",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@Surname"].Value = this.author_surname;

        cmd.Parameters.Add("@Category",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@Category"].Value = this.category;

        cmd.Parameters.Add("@Publishing",SqlDbType.VarChar,50); //Guessed datatype
        cmd.Parameters["@Publishing"].Value = this.Publishing;

        cnn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
    }


问:
What incorrect Metadata-Flavor header at GoogleAuth means?
I´m trying to write to firestore from a onCall firebase function

functions.js

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

console.log('initialing functions at ' , new Date().toString())

exports.getLinks = functions.runWith({ timeoutSeconds: 540 }).https.onCall( (data,context) => {

    console.log('starting to get links ' , new Date().toString())
    console.log('data' , data.query, data.limit, data.country, data.uid)
    console.log('context auth', context.auth, 'context.auth.uid', context.auth.uid)
    // is there anything like admin.setCredentials(context.auth) necessary here?
    const queries = admin.firestore().collection('queries');
    let uid = data.uid
    console.log('uid', uid);
    console.log('queries ref', queries)
    //probably when trying to write here is not being allowed
    queries.doc(uid).set({LinksArrayLength: 'starting'})
        .then( r => console.log('writing to firestore 1 result', r))
        .catch( err => console.error('writing to firestore 2 error', err))
</code>```

The console output is like this

starting to get links  Fri May 31 2019 19:01:10 GMT-0300 (GMT-03:00)

data sells anywhere 2 com fwfwqe
     context auth {
       uid: 'f23oij2ioafOIJOeofiwjOIJ',
       token: {
         iss: 'https://securetoken.google.com/was98oinr-fa4c9',
         aud: 'was234r-f32c9',
         auth_time: 1559327744,
         user_id: 'f23oij2ioafOIJOeofiwjOIJ',
         sub: 'f23oij2ioafOIJOeofiwjOIJ',
         iat: 1559338208,
         exp: 1559341808,
         email: 'awef3h@gmail.com',
         email_verified: false,
         firebase: { identities: [Object], sign_in_provider: 'password' },
         uid: 'f23oij2ioafOIJOeofiwjOIJ'
       }
     } context.auth.uid f23oij2ioafOIJOeofiwjOIJ
     uid f1EMxzwjJlTaH3u7RAYsySx0MZV2
     queries ref CollectionReference {
       _firestore: Firestore {
         _settings: {
           projectId: 'xxx',
           firebaseVersion: '7.0.0',
           libName: 'gccl',
           libVersion: '1.3.0 fire/7.0.0'
         },

and then the not allowed write request to firestore ?

```<code>writing to firestore 2 error Error: Unexpected error determining execution environment: Invalid response from metadata service: incorrect Metadata-Flavor header.
>      at GoogleAuth.<anonymous> (H:\nprojetos\whats_app_sender\firebase_sender\vue_sender\wa_sender\functions\node_modules\google-auth-library\build\src\auth\googleauth.js:164:23)
>      at Generator.throw (<anonymous>)
>      at rejected (H:\nprojetos\whats_app_sender\firebase_sender\vue_sender\wa_sender\functions\node_modules\google-auth-library\build\src\auth\googleauth.js:20:65)
>      at processTicksAndRejections (internal/process/task_queues.js:89:5)
</code>```

How could I ensure that the request.auth.uid is being sent to the firestore write request?

Firestore rules

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;//: if request.auth.uid != null;
// even when commented and allowing all requests still giving the error //message
    }
  }
}
</code>```

Even when fully allowed is continues to give the error.

I´m trying to write to firestore to update the client side when something is being written to the the collections('queries') ... so that the  client gets notified of the function progress...
Is there is a better way of doing that also?

On the client side the code goes like this

client-side

```<code>fireApp.firestore().collection('queries').doc(this.getUser.uid).onSnapshot(snap => {
                    debugger
                    console.log('snap', snap)

                    snap.exists ?
                    snap.docChanges().forEach(async change => {
                        if (change.type === "modified") {
                         _vue.updating = true // the function is in progress
</code>```

答:
Solved
It just required propper initialization

```<code>const credential = require('./xxxxx.json')

admin.initializeApp({credential: admin.credential.cert(credential),
databaseURL: "https://xxx.xxx.firebaseio.com"
});
</code>```

this link (https://www.youtube.com/watch?v=Z87OZtIYC_0)
explains how to initialize it properly

Body:
I´m trying to write to firestore from a onCall firebase function

functions.js

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

console.log('initialing functions at ' , new Date().toString())

exports.getLinks = functions.runWith({ timeoutSeconds: 540 }).https.onCall( (data,context) => {

    console.log('starting to get links ' , new Date().toString())
    console.log('data' , data.query, data.limit, data.country, data.uid)
    console.log('context auth', context.auth, 'context.auth.uid', context.auth.uid)
    // is there anything like admin.setCredentials(context.auth) necessary here?
    const queries = admin.firestore().collection('queries');
    let uid = data.uid
    console.log('uid', uid);
    console.log('queries ref', queries)
    //probably when trying to write here is not being allowed
    queries.doc(uid).set({LinksArrayLength: 'starting'})
        .then( r => console.log('writing to firestore 1 result', r))
        .catch( err => console.error('writing to firestore 2 error', err))

The console output is like this

starting to get links  Fri May 31 2019 19:01:10 GMT-0300 (GMT-03:00)

data sells anywhere 2 com fwfwqe
     context auth {
       uid: 'f23oij2ioafOIJOeofiwjOIJ',
       token: {
         iss: 'https://securetoken.google.com/was98oinr-fa4c9',
         aud: 'was234r-f32c9',
         auth_time: 1559327744,
         user_id: 'f23oij2ioafOIJOeofiwjOIJ',
         sub: 'f23oij2ioafOIJOeofiwjOIJ',
         iat: 1559338208,
         exp: 1559341808,
         email: 'awef3h@gmail.com',
         email_verified: false,
         firebase: { identities: [Object], sign_in_provider: 'password' },
         uid: 'f23oij2ioafOIJOeofiwjOIJ'
       }
     } context.auth.uid f23oij2ioafOIJOeofiwjOIJ
     uid f1EMxzwjJlTaH3u7RAYsySx0MZV2
     queries ref CollectionReference {
       _firestore: Firestore {
         _settings: {
           projectId: 'xxx',
           firebaseVersion: '7.0.0',
           libName: 'gccl',
           libVersion: '1.3.0 fire/7.0.0'
         },

and then the not allowed write request to firestore ?

writing to firestore 2 error Error: Unexpected error determining execution environment: Invalid response from metadata service: incorrect Metadata-Flavor header.
>      at GoogleAuth.<anonymous> (H:\nprojetos\whats_app_sender\firebase_sender\vue_sender\wa_sender\functions\node_modules\google-auth-library\build\src\auth\googleauth.js:164:23)
>      at Generator.throw (<anonymous>)
>      at rejected (H:\nprojetos\whats_app_sender\firebase_sender\vue_sender\wa_sender\functions\node_modules\google-auth-library\build\src\auth\googleauth.js:20:65)
>      at processTicksAndRejections (internal/process/task_queues.js:89:5)

How could I ensure that the request.auth.uid is being sent to the firestore write request?

Firestore rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;//: if request.auth.uid != null;
// even when commented and allowing all requests still giving the error //message
    }
  }
}

Even when fully allowed is continues to give the error.

I´m trying to write to firestore to update the client side when something is being written to the the collections('queries') ... so that the  client gets notified of the function progress...
Is there is a better way of doing that also?

On the client side the code goes like this

client-side

fireApp.firestore().collection('queries').doc(this.getUser.uid).onSnapshot(snap => {
                    debugger
                    console.log('snap', snap)

                    snap.exists ?
                    snap.docChanges().forEach(async change => {
                        if (change.type === "modified") {
                         _vue.updating = true // the function is in progress

Body:
Solved
It just required propper initialization

const credential = require('./xxxxx.json')

admin.initializeApp({credential: admin.credential.cert(credential),
databaseURL: "https://xxx.xxx.firebaseio.com"
});

this link (https://www.youtube.com/watch?v=Z87OZtIYC_0)
explains how to initialize it properly


问:
How to define integral arguments in R? (argument "a" is missing, with no default)
I am trying to recreate a python code in R, but no matter what I try I get the error message.

This is my python code which works

def Cp(T,a,b,c):
    return a+b*T+c*(T**2)
a = np.array([26.63, 20.04, 13.39])
b = np.array([0.183, 0.0945, 0.077])
c = -np.array([45.86, 30.95, 18.71])*(10**(-6))
Tp = 298
Tk = 1035
RE = np.array([0, 1, 2])
Cps1 = [(1/(Tk-Tp))*si.romberg(Cp, Tp, Tk, args=(a[i], b[i], c[i])) for  i in RE]
Cps1
```

<p>This is how I have tried to do this in R</p>

```Cp <- function(Te,a,b,c) a+b*Te+c*(Te**2)
a1 <- c(26.63, 20.04, 13.39)
b1 <- c(0.183, 0.0945, 0.077)
c1 <- -c(45.86, 30.95, 18.71)*(10**(-6))
Tp <- 298
Tk <- 1035
require(pracma)
for(i in seq(1,3,1)){
  Cps1[i] <- (1/(Tk-Tp))*integral(Cp, Tp, Tk, a=a1[i], b=b1[i], c=c1[i])
}
Cps1
```

<p>In python I get this </p>

```[126.15165675333331, 67.87464798333333, 55.55221070333332]
```

But in R I get an error:

argument "a" is missing, with no default

Body:
I am trying to recreate a python code in R, but no matter what I try I get the error message.

This is my python code which works

def Cp(T,a,b,c):
    return a+b*T+c*(T**2)
a = np.array([26.63, 20.04, 13.39])
b = np.array([0.183, 0.0945, 0.077])
c = -np.array([45.86, 30.95, 18.71])*(10**(-6))
Tp = 298
Tk = 1035
RE = np.array([0, 1, 2])
Cps1 = [(1/(Tk-Tp))*si.romberg(Cp, Tp, Tk, args=(a[i], b[i], c[i])) for  i in RE]
Cps1

This is how I have tried to do this in R

Cp <- function(Te,a,b,c) a+b*Te+c*(Te**2)
a1 <- c(26.63, 20.04, 13.39)
b1 <- c(0.183, 0.0945, 0.077)
c1 <- -c(45.86, 30.95, 18.71)*(10**(-6))
Tp <- 298
Tk <- 1035
require(pracma)
for(i in seq(1,3,1)){
  Cps1[i] <- (1/(Tk-Tp))*integral(Cp, Tp, Tk, a=a1[i], b=b1[i], c=c1[i])
}
Cps1

In python I get this

[126.15165675333331, 67.87464798333333, 55.55221070333332]

But in R I get an error:

argument "a" is missing, with no default

Body:
You can vary the extra parameter inputs explicitly in the loop, and change your original function

require(pracma)

Cp <- function(Te) {
  a + b * Te + c * (Te**2)
}

a1 <- c(26.63, 20.04, 13.39)
b1 <- c(0.183, 0.0945, 0.077)
c1 <- -c(45.86, 30.95, 18.71) * (10**(-6))
Tp <- 298
Tk <- 1035
Cps1 = NA

for(i in 1:3){
  a = a1[i]
  b = b1[i]
  c = c1[i]
  Cps1[i] = (1 / (Tk - Tp)) * integral(Cp, Tp, Tk)
t}

Cps1

[1] 126.15166  67.87465  55.55221


问:
Google MyMaps to Google Maps API
I am trying to recreate the following map, made using Google MyMaps, by using Google Maps API

Anyone know the best way to do this? Have the following code at the moment but doesn't look great

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Search for up to 200 places with Radar Search</title>

```

答: use a saved google my maps and share it from your google drive</p>

Title: Google MyMaps to Google Maps API


问:
Error: Selection does not contain a main type
I am trying to run some java files in a new project. So I make the project, put the files in it and I try to run the main file so my game starts.

I get an error that says selection does not contain a main type.

I have tried several ways to run it:

Some say to launch eclipse again, tried this a dozen times.

Somewhere else someone pointed to open a new project and make a build path to the old project.

Didn't work either.

I am pretty sure it must work because I ran it a few hours ago at school. How do I get this working?  Thank you in advance!

答:
I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions:
Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked.
Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem

Conclusion:
Eclipse and/or the lombok plugin have/has a bug.


答:
Like user @StéphaneLaurent says in his answer, I also believe it's because argument a is matching abstol.

Another way of solving this problem is to change the Cp function argument name to A.

```<code>Cp <- function(x, A, b, c) A + b*x + c*(x**2)

Cps1 <- numeric(3)
for(i in seq(1, 3, 1)){
  res <- integral(Cp, xmin = Tp, xmax = Tk, method = "Kronrod",
                  A = a1[i], b = b1[i], c = c1[i])
  Cps1[i] <- (1/(Tk-Tp))*res
}

Cps1
#[1] 126.15166  67.87465  55.55221
</code>```

Title: How to define integral arguments in R? (argument "a" is missing, with no default)

Body:
Like user @StéphaneLaurent says in his answer, I also believe it's because argument a is matching abstol.

Another way of solving this problem is to change the Cp function argument name to A.

Cp <- function(x, A, b, c) A + b*x + c*(x**2)

Cps1 <- numeric(3)
for(i in seq(1, 3, 1)){
  res <- integral(Cp, xmin = Tp, xmax = Tk, method = "Kronrod",
                  A = a1[i], b = b1[i], c = c1[i])
  Cps1[i] <- (1/(Tk-Tp))*res
}

Cps1
#[1] 126.15166  67.87465  55.55221


问:
Python logging - new log file each loop iteration
I would like to generate a new log file on each iteration of a loop in Python using the logging module. I am analysing data in a for loop, where each iteration of the loop contains information on a new object. I would like to generate a log file per object.

I looked at the docs for the logging module and there is capability to change log file on time intervals or when the log file fills up, but I cannot see how to iteratively generate a new log file with a new name. I know ahead of time how many objects are in the loop.

My imagined pseudo code would be:

import logging

for target in targets:
    logfile_name = f"{target}.log"
    logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s',
                        datefmt='%Y-%m/%dT%H:%M:%S',
                        filename=logfile_name,
                        level=logging.DEBUG)

    # analyse target infomation
    logging.info('log target info...')

```

However, the logging information is always appended to the fist log file for target 1.

Is there a way to force a new log file at the beginning of each loop?

答:
This is not necessarily the best answer but worked for my case, and just wanted to put it here for future references. I created a function that looks as follows:

```<code>def logger(filename, level=None, format=None):
    """A wrapper to the logging python module

    This module is useful for cases where we need to log in a for loop
    different files. It also will allow more flexibility later on how the
    logging format could evolve.

    Parameters
    ----------
    filename : str
        Name of logfile.
    level : str, optional
        Level of logging messages, by default 'info'. Supported are: 'info'
        and 'debug'.
    format : str, optional
        Format of logging messages, by default '%(message)s'.

    Returns
    -------
    logger
        A logger object.
    """

    levels = {"info": logging.INFO, "debug": logging.DEBUG}

    if level is None:
        level = levels["info"]
    else:
        level = levels[level.lower()]

    if format is None:
        format = "%(message)s"

    # https://stackoverflow.com/a/12158233/1995261
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)

    logger = logging.basicConfig(filename=filename, level=level, format=format)

    return logger
</code>```

As you can see (you might need to scroll down the code above to see the return logger line), I am using logging.basicConfig(). All modules I have in my package that log stuff, have the following at the beginning of the files:

```<code>import logging
import other stuff

logger = logging.getLogger()

class SomeClass(object):
    def some_method(self):
        logger.info("Whatever")
        .... stuff
</code>```

When doing a loop, I have call things this way:

```<code>if __name__ == "__main__":
    for i in range(1, 11, 1):
        directory = "_{}".format(i)

        if not os.path.exists(directory):
            os.makedirs(directory)
        filename = directory + "/training.log"
        logger(filename=filename)
</code>```

I hope this is helpful.

Body:
I would like to generate a new log file on each iteration of a loop in Python using the logging module. I am analysing data in a for loop, where each iteration of the loop contains information on a new object. I would like to generate a log file per object.

I looked at the docs for the logging module and there is capability to change log file on time intervals or when the log file fills up, but I cannot see how to iteratively generate a new log file with a new name. I know ahead of time how many objects are in the loop.

My imagined pseudo code would be:

import logging

for target in targets:
    logfile_name = f"{target}.log"
    logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s',
                        datefmt='%Y-%m/%dT%H:%M:%S',
                        filename=logfile_name,
                        level=logging.DEBUG)

    # analyse target infomation
    logging.info('log target info...')

However, the logging information is always appended to the fist log file for target 1.

Is there a way to force a new log file at the beginning of each loop?

Body:
This is not necessarily the best answer but worked for my case, and just wanted to put it here for future references. I created a function that looks as follows:

def logger(filename, level=None, format=None):
    """A wrapper to the logging python module

    This module is useful for cases where we need to log in a for loop
    different files. It also will allow more flexibility later on how the
    logging format could evolve.

    Parameters
    ----------
    filename : str
        Name of logfile.
    level : str, optional
        Level of logging messages, by default 'info'. Supported are: 'info'
        and 'debug'.
    format : str, optional
        Format of logging messages, by default '%(message)s'.

    Returns
    -------
    logger
        A logger object.
    """

    levels = {"info": logging.INFO, "debug": logging.DEBUG}

    if level is None:
        level = levels["info"]
    else:
        level = levels[level.lower()]

    if format is None:
        format = "%(message)s"

    # https://stackoverflow.com/a/12158233/1995261
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)

    logger = logging.basicConfig(filename=filename, level=level, format=format)

    return logger

As you can see (you might need to scroll down the code above to see the return logger line), I am using logging.basicConfig(). All modules I have in my package that log stuff, have the following at the beginning of the files:

import logging
import other stuff

logger = logging.getLogger()

class SomeClass(object):
    def some_method(self):
        logger.info("Whatever")
        .... stuff

When doing a loop, I have call things this way:

if __name__ == "__main__":
    for i in range(1, 11, 1):
        directory = "_{}".format(i)

        if not os.path.exists(directory):
            os.makedirs(directory)
        filename = directory + "/training.log"
        logger(filename=filename)

I hope this is helpful.


问:
Concurrent Modification Exception in Array list of users
I was done this code to the show each user, who chat with the logged in user. this code gives me an error of ConcurrentModificationException.this happens when I reply to the message.

I used Array lists for store data that are retrieved from the firebase. the error causes in the code line of " for (User user1 : users) { ". How to fix this issue.

```<code> private void readChats() {

        users = new ArrayList<>();

        reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                users.clear();

                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    User user = snapshot.getValue(User.class);

                    // Display each user from the chats
                    for (String id : usersList) {
                        if (user.getId().equals(id)) {
                            if (users.size() != 0) {
                                for (User user1 : users) { // getting error
                                    if (!user.getId().equals(user1.getId())){
                                        users.add(user);
                                    }
                                }
                            } else {
                                users.add(user);
                            }
                        }
                    }
                }

                usersAdapter= new UsersAdapter(getContext(), users);
                recyclerView.setAdapter(usersAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }
</code>```

This giving following error messages.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.dasun96.vreyedoctor, PID: 20759
    java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.next(ArrayList.java:860)
        at com.dasun96.vreyedoctor.ChatsFragment$2.onDataChange(ChatsFragment.java:93)
        at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source:13)
        at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source:2)
        at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source:71)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
</code>```

答:
Can you please try users = new CopyOnWriteArrayList<>(); instead of users = new ArrayList<>();?

ArrayLists are fail-fast, meaning they will throw out an exception when you try to do an illegal operation. An example of an illegal operation may be adding/removing from an ArrayList while iteration through it (without an iterator).

Long story short, use a CopyOnWriteArrayList and you won't have any more headaches.

Body:
I was done this code to the show each user, who chat with the logged in user. this code gives me an error of ConcurrentModificationException.this happens when I reply to the message.

I used Array lists for store data that are retrieved from the firebase. the error causes in the code line of " for (User user1 : users) { ". How to fix this issue.

 private void readChats() {

        users = new ArrayList<>();

        reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                users.clear();

                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    User user = snapshot.getValue(User.class);

                    // Display each user from the chats
                    for (String id : usersList) {
                        if (user.getId().equals(id)) {
                            if (users.size() != 0) {
                                for (User user1 : users) { // getting error
                                    if (!user.getId().equals(user1.getId())){
                                        users.add(user);
                                    }
                                }
                            } else {
                                users.add(user);
                            }
                        }
                    }
                }

                usersAdapter= new UsersAdapter(getContext(), users);
                recyclerView.setAdapter(usersAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

This giving following error messages.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.dasun96.vreyedoctor, PID: 20759
    java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.next(ArrayList.java:860)
        at com.dasun96.vreyedoctor.ChatsFragment$2.onDataChange(ChatsFragment.java:93)
        at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source:13)
        at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source:2)
        at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source:71)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)


问:
Array of pointers - memory allocation
I'm new into array of pointers (putting functions into array) and allocating memory for it using malloc. Can you help me with this piece of code? Have functions: int comp_int(int a, int b); int comp_int_abs(int a, int b); int comp_int_length(int a, int b); int comp_int_digits_sum(int a, int b);
and would like to put pointers to these functions in array of pointers. Firstly would like to dynamically allocate memory for the array and put functions' pointers into it. Stuck in this place, what am I doing wrong?

```<code>int (**funcs)(int, int) = malloc(4*sizeof(int));

if(!*funcs)
{
    printf("Failed to allocate memory");
    return 8;
}

*funcs={add_int, sub_int, div_int, mul_int};
</code>```

答:
First, change the allocation from:

```<code>int (**funcs)(int, int)=malloc(4*sizeof(int));
</code>```

to

```<code>int (**funcs)(int, int)=malloc(4*sizeof(*funcs));
</code>```

Change

```<code>*funcs={add_int, sub_int, div_int, mul_int};
</code>```

to

```<code>funcs[0]=add_int;
funcs[1]=sub_int;
funcs[2]=div_int;
funcs[3]=mul_int;
</code>```

The notation with braces, {} can only be used upon initializations and not assignments. If you use an array instead of a pointer, you can do this:

```<code>int (*funcs[4])(int, int)={add_int, sub_int, div_int, mul_int};
</code>```

Title: Array of pointers - memory allocation

Body:
I'm new into array of pointers (putting functions into array) and allocating memory for it using malloc. Can you help me with this piece of code? Have functions: int comp_int(int a, int b); int comp_int_abs(int a, int b); int comp_int_length(int a, int b); int comp_int_digits_sum(int a, int b);
and would like to put pointers to these functions in array of pointers. Firstly would like to dynamically allocate memory for the array and put functions' pointers into it. Stuck in this place, what am I doing wrong?

int (**funcs)(int, int) = malloc(4*sizeof(int));

if(!*funcs)
{
    printf("Failed to allocate memory");
    return 8;
}

*funcs={add_int, sub_int, div_int, mul_int};

Body:
First, change the allocation from:

int (**funcs)(int, int)=malloc(4*sizeof(int));

to

int (**funcs)(int, int)=malloc(4*sizeof(*funcs));

Change

*funcs={add_int, sub_int, div_int, mul_int};

to

funcs[0]=add_int;
funcs[1]=sub_int;
funcs[2]=div_int;
funcs[3]=mul_int;

The notation with braces, {} can only be used upon initializations and not assignments. If you use an array instead of a pointer, you can do this:

int (*funcs[4])(int, int)={add_int, sub_int, div_int, mul_int};