问:
Format a vector of rows in italic and red font in R DT (datatable)
A bit similar to this question: How to give color to a given interval of rows of a DT table?

but in my case I would like to let the user select rows in the table, then on click of a button deselect the rows, and turn the previously selected rows that are now part of the list of rows submitted for removal grayed out font (color: light gray) and in italic. This to indicate that these will be excluded from further analysis.
Secondly a button to undo the entire selection should change all rows back to normal format

I've gotten as far as recording the selected rows and adding the deselect feature, but to then restyle the rows before resetting them escapes me....

Output that I hope to achieve:

Not sure whether it is the right approach, but my thought was to use both
values$selected_rows and values$removed_rows, where the first holds the selection until it is submitted, and removed holds the potentially growing list of rows selected for removal if the user decides to remove more rows on another submit

removed_rows is then also the list of rows that need to be styled (grayed out in italic)

```<code>library(shiny)
library(DT)

ui <- fluidPage(
    actionButton('SubmitRemoval', 'Exclude selected rows'),
    actionButton('UndoRemoval', 'Include full data'),
  verbatimTextOutput('Printresult'),
    DT::dataTableOutput('mytable')

)

server <- function(input, output,session) {

  values <- reactiveValues()

  observe({
    values$selected_rows <- input$mytable_rows_selected
  })

  observeEvent(input$SubmitRemoval, {
        values$removed_rows <- c(values$removed_rows,input$mytable_rows_selected)

    dataTableProxy('mytable') %>% selectRows(NULL)
    values$selected_rows <- NULL
    removeTab("tabs", "mytable")
    })

  Remaining_mtcars <- reactive({
    req( values$removed_rows)
    mtcarsR <- mtcars[-c(values$removed_rows), ]
    mtcarsR
    })

  output$Printresult <- renderText({ nrow(Remaining_mtcars()) })

  observeEvent(input$UndoRemoval, {
    values$removed_rows <- NULL

    })

  output$mytable <- DT::renderDataTable({
    DT::datatable(mtcars,
                  extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                  options = list(pageLength = 25,
                                 selection = c('multiple'),
                                 dom = 'frtipB'
    )
  )
  })
}
runApp(list(ui = ui, server = server))
</code>```

UPDATE
@SL: I tried to move your javascript functions for submit and undo inside the DT::JS() part of embedded buttons, but I could not get it to work. I guess i'm close, but no idea where the problem is.

The table output code would follow this structure:

```<code> output[["mytable"]] <- renderDT({
    datatable(dat,
              escape = -2,
              extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
              callback = JS(callback),
              options = list(
                dom = 'frtipB',
                initComplete = JS(initComplete),
                rowId = JS(sprintf("function(data){return data[%d];}", ncol(dat))),
                columnDefs = list(
                  list(visible = FALSE, targets = ncol(dat)),
                  list(className = "dt-center", targets = "_all")
                ),
                buttons = list('copy', 'csv',
                               list(
                                 extend = "collection",
                                 text = 'Deselect',
                                 action = DT::JS("function ( e, dt, node, config ) {
                                       Shiny.setInputValue('SubmitRemoval', true, {priority: 'event'});
                                     }")
                                   ## move the submit javascript here
                                ),
                               list(
                                 extend = "collection",
                                 text = 'Restore',
                                 action = DT::JS("function ( e, dt, node, config ) {
                                       Shiny.setInputValue('UndoRemoval', true, {priority: 'event'});
 ## move the undo removal javascript here
                                     }")
                               )
                )
              )
    )
  })
</code>```

答:
Here is a variant. Instead of using a button to mark the selected rows as removed, the user clicks on the icons.

```<code>library(shiny)
library(DT)

callback <- c(
  "table.on('click', 'td:nth-child(2)', function(){",
  "  var td = this;",
  "  var cell = table.cell(td);",
  "  if(cell.data() === 'ok'){",
  "    cell.data('remove');",
  "  } else {",
  "    cell.data('ok');",
  "  }",
  "  var $row = $(td).closest('tr');",
  "  $row.toggleClass('excluded');",
  "  var excludedRows = [];",
  "  table.$('tr').each(function(i, row){",
  "    if($(this).hasClass('excluded')){",
  "      excludedRows.push(parseInt($(row).attr('id')));",
  "    }",
  "  });",
  "  Shiny.setInputValue('excludedRows', excludedRows);",
  "})"
)

restore <- c(
  "function(e, table, node, config) {",
  "  table.$('tr').removeClass('excluded').each(function(){",
  "    var td = $(this).find('td').eq(1)[0];",
  "    var cell = table.cell(td);",
  "    cell.data('ok');",
  "  });",
  "  Shiny.setInputValue('excludedRows', null);",
  "}"
)

render <- c(
  'function(data, type, row, meta){',
  '  if(type === "display"){',
  '    return "<span style=\\\"color:red; font-size:18px\\\"><i class=\\\"glyphicon glyphicon-" + data + "\\\"></i></span>";',
  '  } else {',
  '    return data;',
  '  }',
  '}'
)

ui <- fluidPage(
  tags$head(
    tags$style(HTML(
      ".excluded { color: rgb(211,211,211); font-style: italic; }"
    ))
  ),
  fluidRow(
    column(
      6,
      tags$label("Excluded rows"),
      verbatimTextOutput("excludedRows")
    ),
    column(
      6,
      tags$label("Included rows"),
      verbatimTextOutput("includedRows")
    )
  ),
  br(),
  DTOutput('mytable')
)

server <- function(input, output,session) {

  dat <- cbind(Selected = "ok", mtcars[1:6,], id = 1:6)

  output[["mytable"]] <- renderDT({
    datatable(dat,
              extensions = c("Select", "Buttons"),
              selection = "none",
              callback = JS(callback),
              options = list(
                rowId = JS(sprintf("function(data){return data[%d];}", ncol(dat))),
                columnDefs = list(
                  list(visible = FALSE, targets = ncol(dat)),
                  list(className = "dt-center", targets = "_all"),
                  list(className = "notselectable", targets = 1),
                  list(targets = 1, render = JS(render))
                ),
                dom = "Bt",
                buttons = list("copy", "csv",
                               list(
                                 extend = "collection",
                                 text = 'Select all rows',
                                 action = JS(restore)
                               )
                ),
                select = list(style = "single", selector = "td:not(.notselectable)")
              )
    )
  }, server = FALSE)

    output$excludedRows <- renderPrint({
      input[["excludedRows"]]
    })

    output$includedRows <- renderPrint({
      setdiff(1:nrow(dat), input[["excludedRows"]])
    })

}

shinyApp(ui, server)
</code>```

Body:
A bit similar to this question: How to give color to a given interval of rows of a DT table?

but in my case I would like to let the user select rows in the table, then on click of a button deselect the rows, and turn the previously selected rows that are now part of the list of rows submitted for removal grayed out font (color: light gray) and in italic. This to indicate that these will be excluded from further analysis.
Secondly a button to undo the entire selection should change all rows back to normal format

I've gotten as far as recording the selected rows and adding the deselect feature, but to then restyle the rows before resetting them escapes me....

Output that I hope to achieve:

Not sure whether it is the right approach, but my thought was to use both
values$selected_rows and values$removed_rows, where the first holds the selection until it is submitted, and removed holds the potentially growing list of rows selected for removal if the user decides to remove more rows on another submit

removed_rows is then also the list of rows that need to be styled (grayed out in italic)

library(shiny)
library(DT)

ui <- fluidPage(
    actionButton('SubmitRemoval', 'Exclude selected rows'),
    actionButton('UndoRemoval', 'Include full data'),
  verbatimTextOutput('Printresult'),
    DT::dataTableOutput('mytable')

)

server <- function(input, output,session) {

  values <- reactiveValues()

  observe({
    values$selected_rows <- input$mytable_rows_selected
  })

  observeEvent(input$SubmitRemoval, {
        values$removed_rows <- c(values$removed_rows,input$mytable_rows_selected)

    dataTableProxy('mytable') %>% selectRows(NULL)
    values$selected_rows <- NULL
    removeTab("tabs", "mytable")
    })

  Remaining_mtcars <- reactive({
    req( values$removed_rows)
    mtcarsR <- mtcars[-c(values$removed_rows), ]
    mtcarsR
    })

  output$Printresult <- renderText({ nrow(Remaining_mtcars()) })

  observeEvent(input$UndoRemoval, {
    values$removed_rows <- NULL

    })

  output$mytable <- DT::renderDataTable({
    DT::datatable(mtcars,
                  extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
                  options = list(pageLength = 25,
                                 selection = c('multiple'),
                                 dom = 'frtipB'
    )
  )
  })
}
runApp(list(ui = ui, server = server))

UPDATE
@SL: I tried to move your javascript functions for submit and undo inside the DT::JS() part of embedded buttons, but I could not get it to work. I guess i'm close, but no idea where the problem is.

The table output code would follow this structure:

 output[["mytable"]] <- renderDT({
    datatable(dat,
              escape = -2,
              extensions = c('Buttons', 'ColReorder', 'FixedHeader', 'Scroller'),
              callback = JS(callback),
              options = list(
                dom = 'frtipB',
                initComplete = JS(initComplete),
                rowId = JS(sprintf("function(data){return data[%d];}", ncol(dat))),
                columnDefs = list(
                  list(visible = FALSE, targets = ncol(dat)),
                  list(className = "dt-center", targets = "_all")
                ),
                buttons = list('copy', 'csv',
                               list(
                                 extend = "collection",
                                 text = 'Deselect',
                                 action = DT::JS("function ( e, dt, node, config ) {
                                       Shiny.setInputValue('SubmitRemoval', true, {priority: 'event'});
                                     }")
                                   ## move the submit javascript here
                                ),
                               list(
                                 extend = "collection",
                                 text = 'Restore',
                                 action = DT::JS("function ( e, dt, node, config ) {
                                       Shiny.setInputValue('UndoRemoval', true, {priority: 'event'});
 ## move the undo removal javascript here
                                     }")
                               )
                )
              )
    )
  })

Body:
Here is a variant. Instead of using a button to mark the selected rows as removed, the user clicks on the icons.

library(shiny)
library(DT)

callback <- c(
  "table.on('click', 'td:nth-child(2)', function(){",
  "  var td = this;",
  "  var cell = table.cell(td);",
  "  if(cell.data() === 'ok'){",
  "    cell.data('remove');",
  "  } else {",
  "    cell.data('ok');",
  "  }",
  "  var $row = $(td).closest('tr');",
  "  $row.toggleClass('excluded');",
  "  var excludedRows = [];",
  "  table.$('tr').each(function(i, row){",
  "    if($(this).hasClass('excluded')){",
  "      excludedRows.push(parseInt($(row).attr('id')));",
  "    }",
  "  });",
  "  Shiny.setInputValue('excludedRows', excludedRows);",
  "})"
)

restore <- c(
  "function(e, table, node, config) {",
  "  table.$('tr').removeClass('excluded').each(function(){",
  "    var td = $(this).find('td').eq(1)[0];",
  "    var cell = table.cell(td);",
  "    cell.data('ok');",
  "  });",
  "  Shiny.setInputValue('excludedRows', null);",
  "}"
)

render <- c(
  'function(data, type, row, meta){',
  '  if(type === "display"){',
  '    return "<span style=\\\"color:red; font-size:18px\\\"><i class=\\\"glyphicon glyphicon-" + data + "\\\"></i></span>";',
  '  } else {',
  '    return data;',
  '  }',
  '}'
)

ui <- fluidPage(
  tags$head(
    tags$style(HTML(
      ".excluded { color: rgb(211,211,211); font-style: italic; }"
    ))
  ),
  fluidRow(
    column(
      6,
      tags$label("Excluded rows"),
      verbatimTextOutput("excludedRows")
    ),
    column(
      6,
      tags$label("Included rows"),
      verbatimTextOutput("includedRows")
    )
  ),
  br(),
  DTOutput('mytable')
)

server <- function(input, output,session) {

  dat <- cbind(Selected = "ok", mtcars[1:6,], id = 1:6)

  output[["mytable"]] <- renderDT({
    datatable(dat,
              extensions = c("Select", "Buttons"),
              selection = "none",
              callback = JS(callback),
              options = list(
                rowId = JS(sprintf("function(data){return data[%d];}", ncol(dat))),
                columnDefs = list(
                  list(visible = FALSE, targets = ncol(dat)),
                  list(className = "dt-center", targets = "_all"),
                  list(className = "notselectable", targets = 1),
                  list(targets = 1, render = JS(render))
                ),
                dom = "Bt",
                buttons = list("copy", "csv",
                               list(
                                 extend = "collection",
                                 text = 'Select all rows',
                                 action = JS(restore)
                               )
                ),
                select = list(style = "single", selector = "td:not(.notselectable)")
              )
    )
  }, server = FALSE)

    output$excludedRows <- renderPrint({
      input[["excludedRows"]]
    })

    output$includedRows <- renderPrint({
      setdiff(1:nrow(dat), input[["excludedRows"]])
    })

}

shinyApp(ui, server)


来源: stackexchange

问:
Dynamic name for react-final-form Field
I have 2 forms. When I choose an option on 1st form, the 2nd form is added to the page with the parameters retrieved from backend. Now how can I set the parameter names as react-final-form Field names?

I could not find a way to do this. Where to pass the parameter names?

```<code>  <Form
    onSubmit={onSubmit}
    validate={validate}
</code>```

答:
React Final Form calls your onSubmit function with the values from all the fields in your form. It's totally up to you to transmit the values to your server.

If you're asking how to build the second form, you just add the fields you need to add. So, say you got back from the server that you needed three fields: [ 'name', 'startTime', 'endTime' ]. You'd just loop through that array and add the fields.

```<code><Form onSubmit={onSubmit}>({handleSubmit}) => (
  <form onSubmit={handleSubmit}>
    {fieldsFromServer.map(fieldName => (
      <div key={fieldName}>
        <label>{fieldName}</label>
        <Field name={fieldName} component="input"/>
      </div>
    ))}
  </form>
)}<Form>
</code>```

Does that help? You don't have to "pass parameters to the form", you just add the Field components that you need.

ContentLicense: CC BY-SA 4.0

Title: Dynamic name for react-final-form Field

Body:
I have 2 forms. When I choose an option on 1st form, the 2nd form is added to the page with the parameters retrieved from backend. Now how can I set the parameter names as react-final-form Field names?

I could not find a way to do this. Where to pass the parameter names?

  <Form
    onSubmit={onSubmit}
    validate={validate}

Body:
React Final Form calls your onSubmit function with the values from all the fields in your form. It's totally up to you to transmit the values to your server.

If you're asking how to build the second form, you just add the fields you need to add. So, say you got back from the server that you needed three fields: [ 'name', 'startTime', 'endTime' ]. You'd just loop through that array and add the fields.

<Form onSubmit={onSubmit}>({handleSubmit}) => (
  <form onSubmit={handleSubmit}>
    {fieldsFromServer.map(fieldName => (
      <div key={fieldName}>
        <label>{fieldName}</label>
        <Field name={fieldName} component="input"/>
      </div>
    ))}
  </form>
)}<Form>

Does that help? You don't have to "pass parameters to the form", you just add the Field components that you need.


问:
Forms/AD Authentication with Sharepoint
All,

I'm configuring Sharepoint to use forms authentication with LDAP/Active Directory. I'm new to Sharepoint, so if this is obvious, please point me in the right direction.

Whenever I attempt to log in with a bad account or password, I get the very friendly (and correct) error message,

The server could not sign you in. Make
  sure your user name and password are
  correct, and then try again.

... which implies that Sharepoint is able to communicate with AD. If I log in with a valid account, I get a page that says:

alt text http://img63.imageshack.us/img63/6053/sharepointerror.png

(I added the grey bar to cover up the login name)

Any suggestions? The account I'm logging in with is an administrator and has been granted full control in central administration.

Also, interesting note: If I click the "sign in as a different user" link, and attempt to sign in using with the same credentials I just used, the site just redirects back to the login page, with no error or status message. If I then manually enter the site url, it again shows the "Error: Access Denied" page. Argh.

答:
Go to site action of the actual site and add user in the format of
:loginid
It should resolve and show it underlined then try login in back to application that should fix it.
Your AD connection is working fine just need to add to sharepoint users list

yourprovider:userid
Yourprovider name is the name you gave to the user provider in web config

And you can add this user from parent site that is windows protected and you have all

ContentLicense: CC BY-SA 2.5

Title: Forms/AD Authentication with Sharepoint

ContentLicense: CC BY-SA 3.0


问:
what is major difference between dotnet publish and dotnet pack
What is the major difference between dotnet pack and publish?

From Microsoft's description, my understanding is that pack creates a package while publish creates package + DLL.

Is this correct?
If so, why not just always use publish and not use the DLL file if it is not needed.

答:
Basically, when we use the pack command, it creates a package; when we use the publish command, it creates a folder that can be copied and executed from anywhere.

What makes pack command unique is that the package gets updated to the nuget server without uploading its dependencies. Its dependencies are updated in the project which fetches the package when we run dotnet restore. This is not with the case of dotnet publish, as it contains third-party dependencies packed in the bundle.


问:
How to generate arm64-v8a 64bit shared object from c++ code?
I've been using a c++ library on my android app for some time now but it has been using 32-bit. I'm trying to compile now the c++ library to a 64bit .so file but every time I do ndk-build I do see the armeabi-v7a get generated successfully, but when the arm64-v8a tries to compile, it fails and gives me the following error message:

libfftw3.a: error adding symbols: File in wrong format
collect2: error: ld returned 1 exit status

I'm going to place below my Application.mk and Android.mk respectively to show what I've done to try to do this properly.

Application.mk

```<code>APP_STL := gnustl_static
NDK_TOOLCHAIN_VERSION=4.9
APP_CPPFLAGS += -frtti
APP_PLATFORM := android-23
APP_CPPFLAGS += -std=c++11
APP_ABI := armeabi-v7a arm64-v8a
APP_MODULES := SCCpp
</code>```

Android.mk

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
CXXFLAGS += -arch x86_64 -arch i386
LOCAL_MODULE := fftw3
LOCAL_SRC_FILES := ../lib/libfftw3.a
LOCAL_EXPORT_C_INCLUDES = $(LOCAL_PATH)/..
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)

GLOBAL_C_INCLUDES := \
  $(LOCAL_PATH)/../src

LOCAL_SRC_FILES += ../src/d/re.cpp
LOCAL_SRC_FILES += ../src/d/me.cpp
LOCAL_SRC_FILES += ../src/d/ev.cpp
LOCAL_SRC_FILES += ../src/d/fe.cpp
LOCAL_SRC_FILES += ../src/fft/fourier.cpp
LOCAL_SRC_FILES += ../src/nu/ac.cpp
LOCAL_SRC_FILES += ../src/nu/st.cpp
LOCAL_SRC_FILES += ../src/utils/converter.cpp
LOCAL_SRC_FILES += ../src/sci.cpp

LOCAL_MODULE := SCCpp
LOCAL_MODULE_FILENAME := libSCCpp

LOCAL_STATIC_LIBRARIES := fftw3

LOCAL_CPP_FEATURES += exceptions
LOCAL_CFLAGS += -fopenmp
LOCAL_CFLAGS += -Ofast
LOCAL_LDFLAGS += -fopenmp -t
LOCAL_CPPFLAGS :=  -std=c++11
LOCAL_LDLIBS += -latomic -llog
LOCAL_C_INCLUDES := $(GLOBAL_C_INCLUDES) $(LOCAL_PATH)/../../../3rdParty/fftw-3.3.4-dll32/
LOCAL_EXPORT_CPPFLAGS := -fexceptions -frtti

include $(BUILD_SHARED_LIBRARY)

</code>```

I'm really unfamiliar with this whole process so I'm at a dead end especially since the logs don't really tell me anything at all. I thought that by just adding in the arm64-v8a would automatically generate the 64bit shared object. Is there a missing step?

If there's any missing information that I should provide, please ask in the comments so I can give more details, but as of now in my current position, this is all that I have touched in the code base for the c++ library so I'm not quite sure where all the pieces are at the moment.

答:
You use a prebuilt library at

```<code>../lib/libfftw3.a
</code>```

You must build fftw3 for arm64, too. Usually we have

```<code> LOCAL_SRC_FILES := ../lib/$(TARGET_ARCH_ABI)/libfftw3.a
</code>```

so that ndk-build can choose the right variant of the 3rd party lib.

The instructions to build fftw3 for arm64 are available on GitHub.

Body:
I've been using a c++ library on my android app for some time now but it has been using 32-bit. I'm trying to compile now the c++ library to a 64bit .so file but every time I do ndk-build I do see the armeabi-v7a get generated successfully, but when the arm64-v8a tries to compile, it fails and gives me the following error message:

libfftw3.a: error adding symbols: File in wrong format
collect2: error: ld returned 1 exit status

I'm going to place below my Application.mk and Android.mk respectively to show what I've done to try to do this properly.

Application.mk

APP_STL := gnustl_static
NDK_TOOLCHAIN_VERSION=4.9
APP_CPPFLAGS += -frtti
APP_PLATFORM := android-23
APP_CPPFLAGS += -std=c++11
APP_ABI := armeabi-v7a arm64-v8a
APP_MODULES := SCCpp

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
CXXFLAGS += -arch x86_64 -arch i386
LOCAL_MODULE := fftw3
LOCAL_SRC_FILES := ../lib/libfftw3.a
LOCAL_EXPORT_C_INCLUDES = $(LOCAL_PATH)/..
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)

GLOBAL_C_INCLUDES := \
  $(LOCAL_PATH)/../src

LOCAL_SRC_FILES += ../src/d/re.cpp
LOCAL_SRC_FILES += ../src/d/me.cpp
LOCAL_SRC_FILES += ../src/d/ev.cpp
LOCAL_SRC_FILES += ../src/d/fe.cpp
LOCAL_SRC_FILES += ../src/fft/fourier.cpp
LOCAL_SRC_FILES += ../src/nu/ac.cpp
LOCAL_SRC_FILES += ../src/nu/st.cpp
LOCAL_SRC_FILES += ../src/utils/converter.cpp
LOCAL_SRC_FILES += ../src/sci.cpp

LOCAL_MODULE := SCCpp
LOCAL_MODULE_FILENAME := libSCCpp

LOCAL_STATIC_LIBRARIES := fftw3

LOCAL_CPP_FEATURES += exceptions
LOCAL_CFLAGS += -fopenmp
LOCAL_CFLAGS += -Ofast
LOCAL_LDFLAGS += -fopenmp -t
LOCAL_CPPFLAGS :=  -std=c++11
LOCAL_LDLIBS += -latomic -llog
LOCAL_C_INCLUDES := $(GLOBAL_C_INCLUDES) $(LOCAL_PATH)/../../../3rdParty/fftw-3.3.4-dll32/
LOCAL_EXPORT_CPPFLAGS := -fexceptions -frtti

include $(BUILD_SHARED_LIBRARY)

I'm really unfamiliar with this whole process so I'm at a dead end especially since the logs don't really tell me anything at all. I thought that by just adding in the arm64-v8a would automatically generate the 64bit shared object. Is there a missing step?

If there's any missing information that I should provide, please ask in the comments so I can give more details, but as of now in my current position, this is all that I have touched in the code base for the c++ library so I'm not quite sure where all the pieces are at the moment.

Body:
You use a prebuilt library at

../lib/libfftw3.a

You must build fftw3 for arm64, too. Usually we have

 LOCAL_SRC_FILES := ../lib/$(TARGET_ARCH_ABI)/libfftw3.a

so that ndk-build can choose the right variant of the 3rd party lib.

The instructions to build fftw3 for arm64 are available on GitHub.


问:
Executable generated by cl runs extremely slowly the first time
When I try to compile and run simple C++ programs from the command line using the Developer Prompt for VS 2019 and VS 2017, my executables run extremely slowly the first time I run them, but are back to being fast as normal the second time onwards. Even a simple "Hello World!" program takes 10-15 seconds to finish from the time I call hello.exe the first time. It seems like there is some sort of overhead the first time I call the executable, and I'm not sure what it is. What gives?

This originally happened to me with VS 2017, so I thought it could have been a VS 2017 bug and I installed VS 2019. However, the problem persists.

For a precise example, I made a file called "test.cpp" with the following content:

```<code>#include <iostream>
#include <ctime>

int main(int argc, char *argv[]) {
    clock_t t;
    t = clock();
    std::cout << "Why is this happening?" << "\n";
    std::cout << clock() - t << "\n";
    return 0;
}
</code>```

Then in the VS Developer Prompt I run "cl /EHsc test.cpp", and this finishes quickly. However, when I run "test.exe", it takes about 10-15 seconds for the output to show up. Of course the clock output is 0; there is nothing weird happening inside the main function. Also, I haven't been able to find anyone who has experienced this same issue.

答: Do you have antivirus enabled? If yes try with out antivirus</p>

Body:
When I try to compile and run simple C++ programs from the command line using the Developer Prompt for VS 2019 and VS 2017, my executables run extremely slowly the first time I run them, but are back to being fast as normal the second time onwards. Even a simple "Hello World!" program takes 10-15 seconds to finish from the time I call hello.exe the first time. It seems like there is some sort of overhead the first time I call the executable, and I'm not sure what it is. What gives?

This originally happened to me with VS 2017, so I thought it could have been a VS 2017 bug and I installed VS 2019. However, the problem persists.

For a precise example, I made a file called "test.cpp" with the following content:

#include <iostream>
#include <ctime>

int main(int argc, char *argv[]) {
    clock_t t;
    t = clock();
    std::cout << "Why is this happening?" << "\n";
    std::cout << clock() - t << "\n";
    return 0;
}

Then in the VS Developer Prompt I run "cl /EHsc test.cpp", and this finishes quickly. However, when I run "test.exe", it takes about 10-15 seconds for the output to show up. Of course the clock output is 0; there is nothing weird happening inside the main function. Also, I haven't been able to find anyone who has experienced this same issue.


问:
Will ClickOnce be ported to .NET Core 3 or .NET 5 as well as WinForms?
Now that Winforms is being ported to .NET Core 3, what technology will be used for deploying those apps?  Will ClickOnce also be ported?

Many of the properties used by ClickOnce are currently stored in the .csproj file, but those project files change significantly between .NET Framework and .NET Core, so presumably this would require changes to Microsoft's ClickOnce code to make it work?

Has there been any official word from Microsoft on this, I can't find anything in the documentation?

答: There is no mention of anything about .net core 3 winforms working with Clickonce. The answer provided above had a link that had Scott Hunter who redirected to Microsoft's MSIX technology. Based on my readings the only way to deploy to end users without using the Microsoft store is to "sideload" your application and that seems to involve many steps that may make the user hesitant even if you sign the package it seems that users have to enable sideloading first. Not my idea of user friendly. </p>


问:
Displaying list of foreign key values Asp Net Web Api
JsonError

Working on my Gym managment application I've encountered with displaying collection of data related to Client model.

The problem is related to following models:

```<code>public class Client
{
    [Key]
    public int Id { get; set; }

    public int CardId { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }

    public string PersonalInfo => "ID: " + CardId + ": " + Name + " " + Surname;

    public int? GymEntries { get; set; }
    public int? MartialArtsEntries { get; set; }

    public int? GymEntriesLeft { get; set; }
    public int? MartialArtsEntriesLeft { get; set; }

    public DateTime? ClientJoined { get; set; }
    public DateTime? SubscriptionExpires { get; set; }

    public int? SubscriptionId { get; set; }
    public virtual Subscription Subscription { get; set; }

    public bool? IsDeleted { get; set; }

    public virtual ICollection<Payment> Payments { get; set; }
}

public class Payment
{
    [Key]
    public int Id { get; set; }

    public int ClientId { get; set; }
    public virtual Client Client { get; set; }

    public int? SubscriptionId { get; set; }
    public virtual Subscription Subscription { get; set; }

    public int CashRegistered { get; set; }
    public string AdditionalInformation { get; set; }

    public DateTime? PaymentRegistered { get; set; }
    public DateTime? SubscriptionExpires { get; set; }

}
</code>```

Everything works fine, until I want my Client controller, when given get/id request, to return all Client data including all payments related to client id from Payment. Json result in Postman doesn't return proper format, it misses payments list.

That's the way I try to do that in my Controller

```<code>[HttpGet("{id}")]
public async Task<ActionResult<Client>> GetClient(int id)
{
   var client = await _context.Client.FindAsync(id);
   var subscription = await _context.Subscription.FindAsync(client.SubscriptionId);
   var payments = await _context.Payment.Where(p => p.Client == client).ToListAsync();

   client.Subscription = subscription;
   client.Payments = payments;

   if (client == null)
   {
       return NotFound();
   }

   if (client.IsDeleted == true)
   {
       return NotFound();
   }

   return client;
}
</code>```

答:
Try that:

```<code>var payments = await _context.Payment.Where(p => p.ClientId == client.Id).ToListAsync();
</code>```

You should use your Id's to select entities but not entire entities.

UPD:

Try to set attribute [JsonIgnore] on public virtual Client Client { get; set; } in your Payment class. To prevent json serializer from endless loop.

Also you can stop Self referencing loop due to the proxies while you converting the entity to JSON as follows:

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}
</code>```

Body:
JsonError

Working on my Gym managment application I've encountered with displaying collection of data related to Client model.

The problem is related to following models:

public class Client
{
    [Key]
    public int Id { get; set; }

    public int CardId { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }

    public string PersonalInfo => "ID: " + CardId + ": " + Name + " " + Surname;

    public int? GymEntries { get; set; }
    public int? MartialArtsEntries { get; set; }

    public int? GymEntriesLeft { get; set; }
    public int? MartialArtsEntriesLeft { get; set; }

    public DateTime? ClientJoined { get; set; }
    public DateTime? SubscriptionExpires { get; set; }

    public int? SubscriptionId { get; set; }
    public virtual Subscription Subscription { get; set; }

    public bool? IsDeleted { get; set; }

    public virtual ICollection<Payment> Payments { get; set; }
}

public class Payment
{
    [Key]
    public int Id { get; set; }

    public int ClientId { get; set; }
    public virtual Client Client { get; set; }

    public int? SubscriptionId { get; set; }
    public virtual Subscription Subscription { get; set; }

    public int CashRegistered { get; set; }
    public string AdditionalInformation { get; set; }

    public DateTime? PaymentRegistered { get; set; }
    public DateTime? SubscriptionExpires { get; set; }

}

Everything works fine, until I want my Client controller, when given get/id request, to return all Client data including all payments related to client id from Payment. Json result in Postman doesn't return proper format, it misses payments list.

That's the way I try to do that in my Controller

[HttpGet("{id}")]
public async Task<ActionResult<Client>> GetClient(int id)
{
   var client = await _context.Client.FindAsync(id);
   var subscription = await _context.Subscription.FindAsync(client.SubscriptionId);
   var payments = await _context.Payment.Where(p => p.Client == client).ToListAsync();

   client.Subscription = subscription;
   client.Payments = payments;

   if (client == null)
   {
       return NotFound();
   }

   if (client.IsDeleted == true)
   {
       return NotFound();
   }

   return client;
}

Body:
Try that:

var payments = await _context.Payment.Where(p => p.ClientId == client.Id).ToListAsync();

You should use your Id's to select entities but not entire entities.

UPD:

Try to set attribute [JsonIgnore] on public virtual Client Client { get; set; } in your Payment class. To prevent json serializer from endless loop.

Also you can stop Self referencing loop due to the proxies while you converting the entity to JSON as follows:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}


问:
Python PyGame delay
I have a function like this:

```<code>  def valami() :
        pygame.draw.rect(screen, (0, 255, 0), (0, 0, 20, 20))
        pygame.draw.rect(screen, (0, 255, 0), (100, 100, 120, 120))
        pygame.draw.rect(screen, (0, 255, 0), (200, 200, 220, 220))
</code>```

And this is my main while loop:

```<code>  while True:
        valami()
</code>```

I want to draw these 3 rectangles one by one every 5 seconds.

答:
Define an array of rectangles and a counter:

rects = [(0, 0, 20, 20), (100, 100, 120, 120), (200, 200, 220, 220)]
counter = 0
```

<p>Draw the rectangle dependent on <code>counter</code> in <code>valami</code>:</p>

<pre class="lang-py prettyprint-override"><code>def valami() :
    pygame.draw.rect(screen, (0, 255, 0), rects[counter % len(rects)])
</code>```

Define a user event see (pygame.event) and start a timer with an interval of 5000 milliseconds (5 seconds) before the main loop, See pygame.time.set_timer():

mytimerevent = pygame.USEREVENT + 1
pygame.time.set_timer(mytimerevent, 5000) # 5000 milliseconds
```

<p>Increment <code>counter</code> when the timer elapse. A timer can be stopped by calling <code>pygame.time.set_timer()</code> with an interval of 0:</p>

<pre class="lang-py prettyprint-override"><code>run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == mytimerevent: # timer event
            counter += 1
            if counter == 2:
                pygame.time.set_timer(mytimerevent, 0) # stop timer

    screen.fill(0)
    valami()
    pygame.display.flip()
</code>```

Note, the modulom (%) operator calculates the rest (remainder) of an integral division.

Because of rects[counter % len(rects)] the rectangles will be drawn on by one in a loop, if you don't stop the timer.

Title: Python PyGame delay

Body:
I have a function like this:

  def valami() :
        pygame.draw.rect(screen, (0, 255, 0), (0, 0, 20, 20))
        pygame.draw.rect(screen, (0, 255, 0), (100, 100, 120, 120))
        pygame.draw.rect(screen, (0, 255, 0), (200, 200, 220, 220))

And this is my main while loop:

  while True:
        valami()

I want to draw these 3 rectangles one by one every 5 seconds.

Body:
Define an array of rectangles and a counter:

rects = [(0, 0, 20, 20), (100, 100, 120, 120), (200, 200, 220, 220)]
counter = 0

Draw the rectangle dependent on counter in valami:

def valami() :
    pygame.draw.rect(screen, (0, 255, 0), rects[counter % len(rects)])

Define a user event see (pygame.event) and start a timer with an interval of 5000 milliseconds (5 seconds) before the main loop, See pygame.time.set_timer():

mytimerevent = pygame.USEREVENT + 1
pygame.time.set_timer(mytimerevent, 5000) # 5000 milliseconds

Increment counter when the timer elapse. A timer can be stopped by calling pygame.time.set_timer() with an interval of 0:

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == mytimerevent: # timer event
            counter += 1
            if counter == 2:
                pygame.time.set_timer(mytimerevent, 0) # stop timer

    screen.fill(0)
    valami()
    pygame.display.flip()

Note, the modulom (%) operator calculates the rest (remainder) of an integral division.

Because of rects[counter % len(rects)] the rectangles will be drawn on by one in a loop, if you don't stop the timer.


问:
How do I replace infoLabel description with a Poster image?
I need to convert a code like the following so that "infoLabel" will show a picture instead of text.

This code reads from an XML string that had a field id of 'posteruri' instead of 'description'

I have and example of the working script with the Label/description.  And my attempt to convert to a poster, which does not work.

My attempt doesn't return an error, however nothing shows but a blank rectangle.

<?xml version="1.0" encoding="utf-8" ?>

<component name="categoryinfoPanel" extends="Panel" >

<interface>
   <field id="description" type="string" onChange="showdescription" />
</interface>

<children>

<Rectangle
  id = "infoRectangle"
  translation = "[0,40]"
  height = "420"
  width = "520"
  color = "0x00000099" >

</Rectangle>

</children>

</component>
```

<p>I have tried simply replacing the field id, and replacing Label with Poster at the bottom to no avail.</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>

<component name="categoryinfoPoster" extends="Panel" >

<interface>
   <field id="posteruri" type="string" onChange="showdescription" />
</interface>

<script type="text/brightscript" >
<![CDATA[

sub init()
  m.top.panelSize = "medium"
  m.top.focusable = true
  m.top.hasNextPanel = true

  m.infoposter= m.top.findNode("infoPoster")
end sub

sub showdescription()
  m.infoposter.uri = m.top.poster
end sub

]]>
</script>

<children>

<Rectangle
 id = "infoRectangle"
 translation = "[0,40]"
  height = "420"
  width = "520"
  color = "0x00000099" >

  <Label
    id = "infoPoster"
    translation = "[15,15]"
    height = "400"
    width = "510" />

</Rectangle>

</children>

</component>
</code>```

Currently text shows up onChange.  I would like for an image to show up onChange.

答:
```<code>    <?xml version="1.0" encoding="utf-8" ?>

<component name="categoryinfoPoster" extends="Panel" >

<interface>
   <field id="posteruri" type="string" onChange="showdescription" />
</interface>

<script type="text/brightscript" >
<![CDATA[

sub init()
  m.top.panelSize = "medium"
  m.top.focusable = true
  m.top.hasNextPanel = true

  m.infoposter= m.top.findNode("infoPoster")
end sub

sub showdescription()
  m.infoposter.uri = m.top.poster
end sub

]]>
</script>

<children>

<Rectangle
 id = "infoRectangle"
 translation = "[0,40]"
  height = "420"
  width = "520"
  color = "0x00000099" >

  <Poster
    id = "infoPoster"
    translation = "[15,15]"
    height = "400"
    width = "510" />

</Rectangle>

</children>

</component>
</code>```

You need to replace "Label" node with "poster" node in "rectangle" node.
It looks like You did everything except that. So You are passing "uri" to a "label" node and that's why you did not see the image.
I also assume that You got some error in the debugger because of it.

Body:
I need to convert a code like the following so that "infoLabel" will show a picture instead of text.

This code reads from an XML string that had a field id of 'posteruri' instead of 'description'

I have and example of the working script with the Label/description.  And my attempt to convert to a poster, which does not work.

My attempt doesn't return an error, however nothing shows but a blank rectangle.

<?xml version="1.0" encoding="utf-8" ?>

<component name="categoryinfoPanel" extends="Panel" >

<interface>
   <field id="description" type="string" onChange="showdescription" />
</interface>

<children>

<Rectangle
  id = "infoRectangle"
  translation = "[0,40]"
  height = "420"
  width = "520"
  color = "0x00000099" >

</Rectangle>

</children>

</component>

I have tried simply replacing the field id, and replacing Label with Poster at the bottom to no avail.

<?xml version="1.0" encoding="utf-8" ?>

<component name="categoryinfoPoster" extends="Panel" >

<interface>
   <field id="posteruri" type="string" onChange="showdescription" />
</interface>

<children>

<Rectangle
 id = "infoRectangle"
 translation = "[0,40]"
  height = "420"
  width = "520"
  color = "0x00000099" >

</Rectangle>

</children>

</component>

Currently text shows up onChange.  I would like for an image to show up onChange.

Body:
    <?xml version="1.0" encoding="utf-8" ?>

<component name="categoryinfoPoster" extends="Panel" >

<interface>
   <field id="posteruri" type="string" onChange="showdescription" />
</interface>

<script type="text/brightscript" >
<![CDATA[

sub init()
  m.top.panelSize = "medium"
  m.top.focusable = true
  m.top.hasNextPanel = true

  m.infoposter= m.top.findNode("infoPoster")
end sub

sub showdescription()
  m.infoposter.uri = m.top.poster
end sub

]]>
</script>

<children>

<Rectangle
 id = "infoRectangle"
 translation = "[0,40]"
  height = "420"
  width = "520"
  color = "0x00000099" >

  <Poster
    id = "infoPoster"
    translation = "[15,15]"
    height = "400"
    width = "510" />

</Rectangle>

</children>

</component>

You need to replace "Label" node with "poster" node in "rectangle" node.
It looks like You did everything except that. So You are passing "uri" to a "label" node and that's why you did not see the image.
I also assume that You got some error in the debugger because of it.


问:
Disable Context Menu in WebBrowser .NET CF 3.5
I'm using a WebBrowser control in .NET CF 3.5 for a Windows CE device application, and for security reasons need to disable the Context Menu.  I've tried a variety of things, none of which seem to work for mobile devices with .NET CF 3.5:

I've tried placing a pictureBox over the WebBrowser, and setting it to be transparent.  Unfortunately, the transparency doesn't work and this ends up being a white box over my browser.

I've tried implementing a new custom transparent control to place over the web browser, similar to this.

I've tried editing the OnContextMenu element in the html, no luck.

I've tried overriding the CreateParams to make a transparent PictureBox over the browser, noted as one of the solutions here.

There seems to be many solutions for this online, but none of them seem to work for windows CE with .NET CF 3.5.  I believe this is because the WebBrowser has a much simpler implementation than the full .NET 3.5.  So my question is thus: is there any way to disable the context menu for the WebBrowser control?

答: Does WebBrowser control implementation in .NET CF not contain property IsWebBrowserContextMenuEnabled?


问:
How can I secure the use of my dll by other applications
I made some UI controls by WPF and wrap it into a DLL.

As we know, everyone can reference the DLL easily but I don't want it being like that.

I want only the program which I made to use it.

In my opinion, I think I can add something such a password when the user creates the control. However, I don't know if it is a good idea.

I want to know more about that. Would you please tell me? Thank you.

答:
I'd suggest a license key or some form of token that needs to be passed to some method in your DLL to allow any subsequent calls to be made. Without the license key, your controls could be set to some evaluation mode, or just totally disabled. It's really up to you.

Maybe browse some sites of companies that do this for a living like DevExpress or any number of other companies that make user control libraries and get a feel for the types of ways they ensure people license their products prior to use.

I realise your requirement may not be around licensing, but you could still restrict access via a similar mechanism.


问:
Is there a way to push key value pairs in google earth engine in a loop that is using the map() function?
I am doing a spatiotemporal analysis of LULC on google earth engine.
For this, I have imported Landsat 5 tier 1 TOA reflectance images and filtered them by my preference. Following this I was able to extract the id values of the features in the filtered image collection, I need to create a dictionary in order to be able to assign the unique names from ID extracted by slicing the ID's and assign a value(id itself) to each pair.

The id obtained of images in an image collection is of the type: LANDSAT/LT05/C01/T1_TOA/LT05_148045_19890509
in this,
key:19890509
value:LT05_148045_19890509

both of which can be obtained from slicing the obtained ID

I have filtered the image collection and tried to create a dictionary as follows but it creates an empty dictionary.

```<code>// Create a list of image objects.
var imageList = Collection.toList(100);
print('imageList', imageList);

// Extract the ID of each image object.
var dicty = ee.Dictionary({}); //def dict for names
var id_list = imageList.map(function(item) {
    var list_nm = ee.Image(item).id();
    var lst_nm_slice = ee.Image(item).id().slice(-8,-1);
    dicty.lst_nm_slice = list_nm;
    return dicty;
});//end of map function
</code>```

I expect the output of dicty to be a dictionary of key-value pairs with each key value getting assigned dynamically in the aforementioned loop so that I can call the images by using the dictionary key value pairs.

答:
Generally speaking, you want to provide an iterable object to .map() and you get out an iterable like object with the original length (that function applied to each item). Earth Engine processes the function provided into .map() in parallel making it difficult to push values to a single variable in memory within that function. So, a solution to this is to set the ID values that you extract within the function to each image in the collection as a property and then outside of the function get the names and ids of the image into a dictionary. Here is a working code example:

```<code>// Create an ImageCollection and filter by space and time
var Collection = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
  .filterDate('1990-01-01','1991-01-01')
  .filterBounds(ee.Geometry.Point([86.5861,34.7304]));

print('LT5 Image Collection', Collection);

// Extract the ID of each image object and set as property
// within for each image in the collection
var Collection = Collection.map(function(img) {
    var img_id = img.id();
    var id_slice = img_id.slice(-8);
    return img.set('id',id_slice);
});//end of map function

// Get the image IDs and names as lists from the collection
var ids = ee.List(Collection.aggregate_array('id'));
var names = ee.List(Collection.aggregate_array('system:index'));

// Build dictionary from each image ID and name
var out_dict = ee.Dictionary.fromLists(ids,names);
print('Output Dictionary',out_dict);
</code>```

Body:
I am doing a spatiotemporal analysis of LULC on google earth engine.
For this, I have imported Landsat 5 tier 1 TOA reflectance images and filtered them by my preference. Following this I was able to extract the id values of the features in the filtered image collection, I need to create a dictionary in order to be able to assign the unique names from ID extracted by slicing the ID's and assign a value(id itself) to each pair.

The id obtained of images in an image collection is of the type: LANDSAT/LT05/C01/T1_TOA/LT05_148045_19890509
in this,
key:19890509
value:LT05_148045_19890509

both of which can be obtained from slicing the obtained ID

I have filtered the image collection and tried to create a dictionary as follows but it creates an empty dictionary.

// Create a list of image objects.
var imageList = Collection.toList(100);
print('imageList', imageList);

// Extract the ID of each image object.
var dicty = ee.Dictionary({}); //def dict for names
var id_list = imageList.map(function(item) {
    var list_nm = ee.Image(item).id();
    var lst_nm_slice = ee.Image(item).id().slice(-8,-1);
    dicty.lst_nm_slice = list_nm;
    return dicty;
});//end of map function

I expect the output of dicty to be a dictionary of key-value pairs with each key value getting assigned dynamically in the aforementioned loop so that I can call the images by using the dictionary key value pairs.

Body:
Generally speaking, you want to provide an iterable object to .map() and you get out an iterable like object with the original length (that function applied to each item). Earth Engine processes the function provided into .map() in parallel making it difficult to push values to a single variable in memory within that function. So, a solution to this is to set the ID values that you extract within the function to each image in the collection as a property and then outside of the function get the names and ids of the image into a dictionary. Here is a working code example:

// Create an ImageCollection and filter by space and time
var Collection = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
  .filterDate('1990-01-01','1991-01-01')
  .filterBounds(ee.Geometry.Point([86.5861,34.7304]));

print('LT5 Image Collection', Collection);

// Extract the ID of each image object and set as property
// within for each image in the collection
var Collection = Collection.map(function(img) {
    var img_id = img.id();
    var id_slice = img_id.slice(-8);
    return img.set('id',id_slice);
});//end of map function

// Get the image IDs and names as lists from the collection
var ids = ee.List(Collection.aggregate_array('id'));
var names = ee.List(Collection.aggregate_array('system:index'));

// Build dictionary from each image ID and name
var out_dict = ee.Dictionary.fromLists(ids,names);
print('Output Dictionary',out_dict);


问:
How to retain cursor position when using :%!filtercmd in vim?
When I issue a vim command that starts with :%!, such as :%!sort to sort all lines in the buffer, the cursor moves to the first line. How do I preserve the cursor position?

Ultimately, I want to use this command in an autocmd, such as:

```<code>augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :%!sort
augroup END
</code>```

Will the same method work in both places?

答:
You can use a mark to remember the current line number (but note that the line contents could change):</p>

```<code>augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :kk
    autocmd BufWrite *.xxx :%!sort
    autocmd BufWrite *.xxx :'k
augroup END
</code>```

Body:
When I issue a vim command that starts with :%!, such as :%!sort to sort all lines in the buffer, the cursor moves to the first line. How do I preserve the cursor position?

Ultimately, I want to use this command in an autocmd, such as:

augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :%!sort
augroup END

Will the same method work in both places?

Body:
You can use a mark to remember the current line number (but note that the line contents could change):

augroup filetype_xxx
    autocmd!
    autocmd BufWrite *.xxx :kk
    autocmd BufWrite *.xxx :%!sort
    autocmd BufWrite *.xxx :'k
augroup END


问:
Writing code to help the compiler to do optimizations
Does anyone know if there is a list of what a compiler do to optimize a source code? I prefer GCC as example.

I want to know what a programmer should do with the code to get good optimization and help the compiler to optimize it. Some optimizations by programmer may avoid the compiler to do better optimizations.

Examples:

```<code>replace
for (int i = 0; i < n - 1; i++ )
by
int n2 = n - 1;
for (int i = 0; i < n2; i++ )

for (int i = 0; i < n/2; i++ )
by
int n2 = n/2;
for (int i = 0; i < n2; i++ )

for (int i = 0; i < obj.calc_value(); i++ ) //calc_value() will return the same result with obj remaining unchanged.
by
int y = obj.calc_value()
for (int i = 0; i < y; i++ )
</code>```

It is important to keep the code simple to read and understand.

Thanks

Edit:

Other examples:

Inline functions

Remove recursion

答:
No matter what the "don't optimizers" here tell you it is always possible to help the (C in my case) compiler produce better code.

The compiler will be better than most programmers at tactically ordering code to make the most optimal use of available pipelines and execution units. Having said that, it is also important to point out that the compiler is not as good at the strategic programming level, i e the level above individual procedures.

Poorly-performing software is far more common than well-performing. One thing the "don't optimizers" seldom admit (and definitely not in the answers to your post) is that since it is (obviously) possible to write low-performing software it is also (obviously) possible to write well-performing. Compilers are not alchemy: feed them garbage source code and they will produce garbage machine code. Feed them competent source code and they will certainly produce competent machine code.

I'm ambivalent on the subject of optimisation. On the one hand if a performance issue has been pinpointed (most often when development is nearing completion) it is usually too late to get any significant improvement (say 100% or greater) because that requires work at the strategic level (which there is no time for). On the other, if it's done earlier the "complete performance picture" is not available so the "don't optimizers" will say it's too early to optimize because there is no valid data. Optimisation is all too often something that is done in panic to salvage some poorly-constructed software or perhaps as life-support through acceptance tests. Optimisation in a positive context (making good code execute more efficiently) is more or less unheard of (at least here?).

I enjoy the challenges of writing code which performs well. My code is readable but from first-hand experience I choose certain code constructs because I know they will perform better. Also I instrument my applications from the very beginning of development such that they measure themselves and then I can keep an eye on performance as development moves along.

Body:
Does anyone know if there is a list of what a compiler do to optimize a source code? I prefer GCC as example.

I want to know what a programmer should do with the code to get good optimization and help the compiler to optimize it. Some optimizations by programmer may avoid the compiler to do better optimizations.

Examples:

replace
for (int i = 0; i < n - 1; i++ )
by
int n2 = n - 1;
for (int i = 0; i < n2; i++ )

for (int i = 0; i < n/2; i++ )
by
int n2 = n/2;
for (int i = 0; i < n2; i++ )

for (int i = 0; i < obj.calc_value(); i++ ) //calc_value() will return the same result with obj remaining unchanged.
by
int y = obj.calc_value()
for (int i = 0; i < y; i++ )

It is important to keep the code simple to read and understand.

Thanks

Edit:

Other examples:

Inline functions

Remove recursion


问:
Getting distorted WAV files after using scipy.io.wavfile.write, librosa.output.write_wav
The first one returns a WAV file with alien like sound(the original sounds more like simple techno beat)

The second returns a WAV file only when set with np.float32, also with distortion.

rate, signal = wavfile.read('audio/0b0bd019.wav')

wavfile.write(filename = 'clean/0af9f0b4.wav', rate =rate , data=signal)

librosa.output.write_wav(path = 'clean/0af9f0b4.wav',y=signal.astype(np.float32), sr=rate)

Expecting to return the same WAV sound as the original.

答:
I recommend using: https://pysoundfile.readthedocs.io/en/0.9.0/
I am not sure why your formulation didn't work but this package worked for me.</p>


问:
I want to display placeholder date as current date
I'm using date picker and when I open by default it will be the current date. But now I want to display placeholder date also as current date.

```<code>private func showDatePicker(_ sender: UITextField){
    datePickerView.datePickerMode = UIDatePicker.Mode.date
    sender.inputView = datePickerView
    let toolbar = UIToolbar();
    toolbar.sizeToFit()
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donedatePicker));
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker));
    toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false) sender.inputAccessoryView = toolbar sender.inputView = datePickerView;
}

@objc func donedatePicker(){
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yy"
    if (selectedDateField == 1){
        datePickerView.minimumDate = NSDate() as Date
        sOdateTxt.text = formatter.string(from:datePickerView.date)
        sOdateTxt.placeholder=formatter.string(from:datePickerView.date)
    } else if (selectedDateField == 2){
        datePickerView.minimumDate = NSDate() as Date
        sRdateTxt.text = formatter.string(from:datePickerView.date)
    } else if (selectedDateField == 3){
        datePickerView.minimumDate = NSDate() as Date
        sRecordedTxt.text = formatter.string(from:datePickerView.date)
    }
    self.view.endEditing(true)
}
@objc func cancelDatePicker(){
    self.view.endEditing(true)
}
</code>```

placeholder date should be as the current date

答:
```<code>extension Date {
    func toString(format:String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}
</code>```

Usage

yourtextfield.placeholder = Date().toString(format:"dd-MM-yyyy")

Body:
I'm using date picker and when I open by default it will be the current date. But now I want to display placeholder date also as current date.

private func showDatePicker(_ sender: UITextField){
    datePickerView.datePickerMode = UIDatePicker.Mode.date
    sender.inputView = datePickerView
    let toolbar = UIToolbar();
    toolbar.sizeToFit()
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donedatePicker));
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker));
    toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false) sender.inputAccessoryView = toolbar sender.inputView = datePickerView;
}

@objc func donedatePicker(){
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yy"
    if (selectedDateField == 1){
        datePickerView.minimumDate = NSDate() as Date
        sOdateTxt.text = formatter.string(from:datePickerView.date)
        sOdateTxt.placeholder=formatter.string(from:datePickerView.date)
    } else if (selectedDateField == 2){
        datePickerView.minimumDate = NSDate() as Date
        sRdateTxt.text = formatter.string(from:datePickerView.date)
    } else if (selectedDateField == 3){
        datePickerView.minimumDate = NSDate() as Date
        sRecordedTxt.text = formatter.string(from:datePickerView.date)
    }
    self.view.endEditing(true)
}
@objc func cancelDatePicker(){
    self.view.endEditing(true)
}

placeholder date should be as the current date

Body:
extension Date {
    func toString(format:String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

Usage

yourtextfield.placeholder = Date().toString(format:"dd-MM-yyyy")


问:
Can you tell me what's wrong in the query I'm using to retrieve info on when a customer last placed an order?
I'm trying to write a query on MySQL workbench that shows me when a customer last ordered from my client's website. I'm using two tables for this purpose. One is called "orders", which is updated with order time whenever a new order is placed and assigns a unique id to each new order. The other table is called "orders_customers_details", which is also updated whenever a new order is placed and contains the unique id (based on a combination of customer's email address and phone number) of the customer placing the order, as well as a key which corresponds to the orders table's id.

My problem is that the query I'm using is not returning every customer's most recent order. In the case of some customers, I'm being given the date of their fourth or fifth most recent order.

I'm left joining orders on orders_customer_details:

```<code>left join orders o
on ocd.id = o.customer_details_id
</code>```

I've also tried using a left outer join, and the following join:

```<code>from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
</code>```

In order to retrieve the most recent order only, I'm grouping by customer_id HAVING max(order.id). FYI, order.id increases with the placement of each new order, so the order with the highest id is the most recent order.

I've also tried

```<code> SELECT customer_id, MAX(order.id)
</code>```

and then grouped by customer_id, but to no avail.

Here's the entire code:

```<code>select customer_id, o.id as id_of_last_order, date(order_date) as
last_ordered, timestampdiff(day, order_date, now()) as
days_since_last_ordered
from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
group by customer_id having max(o.id)
order by customer_id;
</code>```

答:
Using a correlated sub query in the where clause to find the most recent order by customer and tidying up the code then something like this

```<code>select customer_id, o.id as id_of_last_order, date(order_date) as last_ordered,
        timestampdiff(day, order_date, now()) as days_since_last_ordered
from orders_customers_details ocd
join orders o on  o.customer_details_id = ocd.id
where ocd_id = (select max(ocd_id) from orders_customers_details ocd1 where ocd1.customer_id = ocd_customer_id);
</code>```

Though I cannot be certain without table definitions sample data etc..

Body:
I'm trying to write a query on MySQL workbench that shows me when a customer last ordered from my client's website. I'm using two tables for this purpose. One is called "orders", which is updated with order time whenever a new order is placed and assigns a unique id to each new order. The other table is called "orders_customers_details", which is also updated whenever a new order is placed and contains the unique id (based on a combination of customer's email address and phone number) of the customer placing the order, as well as a key which corresponds to the orders table's id.

My problem is that the query I'm using is not returning every customer's most recent order. In the case of some customers, I'm being given the date of their fourth or fifth most recent order.

I'm left joining orders on orders_customer_details:

left join orders o
on ocd.id = o.customer_details_id

I've also tried using a left outer join, and the following join:

from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id

In order to retrieve the most recent order only, I'm grouping by customer_id HAVING max(order.id). FYI, order.id increases with the placement of each new order, so the order with the highest id is the most recent order.

I've also tried

 SELECT customer_id, MAX(order.id)

and then grouped by customer_id, but to no avail.

Here's the entire code:

select customer_id, o.id as id_of_last_order, date(order_date) as
last_ordered, timestampdiff(day, order_date, now()) as
days_since_last_ordered
from orders o, orders_customers_details ocd
where o.customer_details_id = ocd.id
group by customer_id having max(o.id)
order by customer_id;

Body:
Using a correlated sub query in the where clause to find the most recent order by customer and tidying up the code then something like this

select customer_id, o.id as id_of_last_order, date(order_date) as last_ordered,
        timestampdiff(day, order_date, now()) as days_since_last_ordered
from orders_customers_details ocd
join orders o on  o.customer_details_id = ocd.id
where ocd_id = (select max(ocd_id) from orders_customers_details ocd1 where ocd1.customer_id = ocd_customer_id);

Though I cannot be certain without table definitions sample data etc..


问:
Authenticate Operation Before Each Action In Spring Boot Effectively
I have a code block like below. For each method, I call action authentication. Is it possible to do with annotation or other thing effectively?

```<code>@GetMapping
public ResponseEntity getAction(@PrincipalUser user, Long actionId)
{
   repository.checkUserForAction(user.getId(), actionId);
   implement actions...
   return service call;
}
@PostMapping
public ResponseEntity addAction(@PrincipalUser user)
{
   repository.checkUserForAction(user.getId());
   implement actions...
   return service call;
}
@DeleteMapping
public ResponseEntity addAction(@PrincipalUser user, Long actionId)
{
   repository.checkUserForAction(user.getId(), actionId);
   implement actions...
   return service call;
}
</code>```

Actually, in here my other problem is that I call repository method each time and I know this is not an effective way.

答:
You could use Spring Security and @PreAuthorize annotation.

Example:

```<code>@PreAuthorize("@authorizationService.check(#actionId)")
@DeleteMapping
public ResponseEntity performAction(Long actionId) {
implement actions...
}
</code>```

And encapsulate authorization logic inside authorizationService, moreover authorizationService must be a bean and @EnableGlobalMethodSecurity(prePostEnabled = true) must be set.

Body:
I have a code block like below. For each method, I call action authentication. Is it possible to do with annotation or other thing effectively?

@GetMapping
public ResponseEntity getAction(@PrincipalUser user, Long actionId)
{
   repository.checkUserForAction(user.getId(), actionId);
   implement actions...
   return service call;
}
@PostMapping
public ResponseEntity addAction(@PrincipalUser user)
{
   repository.checkUserForAction(user.getId());
   implement actions...
   return service call;
}
@DeleteMapping
public ResponseEntity addAction(@PrincipalUser user, Long actionId)
{
   repository.checkUserForAction(user.getId(), actionId);
   implement actions...
   return service call;
}

Actually, in here my other problem is that I call repository method each time and I know this is not an effective way.

Body:
You could use Spring Security and @PreAuthorize annotation.

Example:

@PreAuthorize("@authorizationService.check(#actionId)")
@DeleteMapping
public ResponseEntity performAction(Long actionId) {
implement actions...
}

And encapsulate authorization logic inside authorizationService, moreover authorizationService must be a bean and @EnableGlobalMethodSecurity(prePostEnabled = true) must be set.


问:
RegEx for finding matches between quotes
Here i am trying to find String within double quotes .

```<code>   List<String> getList(String value){
    String regex = "\"[^\"]*\"|[^,]+";
    List<String> allMatches = new ArrayList<String>();
    if (StringUtils.isNotBlank(value)) {
        Matcher m = Pattern.compile(regex).matcher(value);
        while (m.find() && StringUtils.isNotBlank(m.group())) {
            String str=m.group().replaceAll("^\"|\"$", "");
            allMatches.add(str.trim());
        }
    }
    return allMatches;
  }

  result = getList(400,test,\"don't split, this\",15);
  result have [400,test,don't split, this,15] all comma seperated string except inside quotes.
</code>```

It is working well for pattern "" but not for “” .  "foo,bar", is different than "foo,bar"  here is not working regex

答:
If the different quotes should match but should not be mixed, you could use an alternation to match either of the formats. If you don't want to match newlines, that can be added to the negated character class.

```<code>(?:“[^“”]+”|"[^"]+"|(?<=,|^)[^“”,"]+(?=(?:,|$)))
</code>```

Explanation

(?: Non capturing group

“[^“”]+” Match variant “, then not “ or ” and match variant ”

| Or

"[^"]+" Match, ", then not " and again "

| Or

(?<=,|^) Asert what on the left is comma or start of string

[^“”,"]+ Match any char that is not in the character class

(?=(?:,|$)) Assert what on the right is a comma or end of the string

) Close non capturing group

Regex demo | Java demo

The whole pattern is an alternation which has 3 options. The first 2 options match from an opening till a closing quote.

The third option matches all except any of the type of quotes or comma, but makes sure that at the start and the end of the match there is either a comma or the start or end of the string.

Body:
Here i am trying to find String within double quotes .

   List<String> getList(String value){
    String regex = "\"[^\"]*\"|[^,]+";
    List<String> allMatches = new ArrayList<String>();
    if (StringUtils.isNotBlank(value)) {
        Matcher m = Pattern.compile(regex).matcher(value);
        while (m.find() && StringUtils.isNotBlank(m.group())) {
            String str=m.group().replaceAll("^\"|\"$", "");
            allMatches.add(str.trim());
        }
    }
    return allMatches;
  }

  result = getList(400,test,\"don't split, this\",15);
  result have [400,test,don't split, this,15] all comma seperated string except inside quotes.

It is working well for pattern "" but not for “” .  "foo,bar", is different than "foo,bar"  here is not working regex

Body:
If the different quotes should match but should not be mixed, you could use an alternation to match either of the formats. If you don't want to match newlines, that can be added to the negated character class.

(?:“[^“”]+”|"[^"]+"|(?<=,|^)[^“”,"]+(?=(?:,|$)))

Explanation

(?: Non capturing group

“[^“”]+” Match variant “, then not “ or ” and match variant ”

| Or

"[^"]+" Match, ", then not " and again "

| Or

(?<=,|^) Asert what on the left is comma or start of string

[^“”,"]+ Match any char that is not in the character class

(?=(?:,|$)) Assert what on the right is a comma or end of the string

) Close non capturing group

Regex demo | Java demo

The whole pattern is an alternation which has 3 options. The first 2 options match from an opening till a closing quote.

The third option matches all except any of the type of quotes or comma, but makes sure that at the start and the end of the match there is either a comma or the start or end of the string.


问:
Find and replace white spaces in html
I'm trying to find and replace all white spaces in a html file. Here's my code so far:

```<code>html.replace(@ (?![^<]*>|[^<>]*</)@g," ")
</code>```

But above expression throws error as not a valid expression. How do I make it work?

答:
Regexes are delimited by /, not @.

```<code>html.replace(/ (?![^<]*>|[^<>]*<\/)/g," ")
</code>```

Here's another regex that literally replaces every white space with a non-breaking space:

```<code>html.replace(/\s+/g, " ");
</code>```

Title: Find and replace white spaces in html

Body:
I'm trying to find and replace all white spaces in a html file. Here's my code so far:

html.replace(@ (?![^<]*>|[^<>]*</)@g," ")

But above expression throws error as not a valid expression. How do I make it work?

Body:
Regexes are delimited by /, not @.

html.replace(/ (?![^<]*>|[^<>]*<\/)/g,"&nbsp;")

Here's another regex that literally replaces every white space with a non-breaking space:

html.replace(/\s+/g, "&nbsp;");


问:
Multidimensional Array - Illegal String Offset
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

```<code>$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);
</code>```

I am trying to get the value of end in the date array. I have tried this:

```<code>foreach($fields as $field) {
  echo $field['end'];
}
</code>```

this outputs the data but also the illegal offset error.

I have tried this:

```<code>foreach($fields as $key => $value) {
  echo $value['end'];
}
</code>```

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

```<code>foreach($fields['date'] as $field) {
    $field['end'];
  }
</code>```

This is just an error.

And finally

```<code>foreach($fields as $field) {
  $field['date']['end'];
}
</code>```

just an error.

答:
You don't need to loop the array since you wanna get specific key value:

First method :

```<code>echo $fields['date']['end'];
</code>```

second method :
 this little bit ugly the method.

```<code>echo array_column($fields,'end'))[0];
</code>```

Body:
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);

I am trying to get the value of end in the date array. I have tried this:

foreach($fields as $field) {
  echo $field['end'];
}

this outputs the data but also the illegal offset error.

I have tried this:

foreach($fields as $key => $value) {
  echo $value['end'];
}

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

foreach($fields['date'] as $field) {
    $field['end'];
  }

This is just an error.

And finally

foreach($fields as $field) {
  $field['date']['end'];
}

just an error.

Body:
You don't need to loop the array since you wanna get specific key value:

First method :

echo $fields['date']['end'];

second method :
 this little bit ugly the method.

echo array_column($fields,'end'))[0];


问:
How to avoid setState in useEffect hook causing second render
I'm writing a custom hook that takes an id as input and then should do the following tasks:

get data for that id synchronously from a store

subscribe to changes in this store and update data accordingly

I came up with the following implementation which has the downside that I am setting state directly from inside the effect hook, causing a second render.

```<code>function useData({id}) {
    // set initial data on first render
    const [data, setData] = useState(Store.getData(id));

    useEffect(() => {
        // when id changes, set data to whatever is in store at the moment
        // here we call setData directly from inside useEffect, causing a second render
        setData(Store.getData(id));
        // subscribe to changes to update data whenever it changes in the store
        return Store.onChange(id, setData);
    }, [id]);

    return data;
}
</code>```

A second approach I tried was to add a dummy state that is only there to cause a re-render. In this approach I am directly returning the data received from Store.getData(). This ensures that I will get the freshest data with every render and the useEffect ensures that every onChange trigger will cause a new render.

```<code>function useData({id}) {
    // adding some dummy state that we only use to force a render
    const [, setDummy] = useState({});
    const refresh = useCallback(() => {
        setDummy({});
    }, []);

    useEffect(() => {
        // subscribe to changes cause a refresh on every change
        return Store.onChange(id, refresh);
    }, [id, refresh]);

    return Store.getData[id];
}
</code>```

The second approach works well but it feels weird to add this dummy state. Sure, I could put this into another useRefresh hook but I am not sure if this would really be a good practice.

Is there any better way of implementing this, without calling setData directly from inside useEffect and without relying on some unused dummy state?

答:
So by now you use useState inside your hook just to re-trigger rendering of host component once store is changed. How about taking change handler from the outside?

```<code>function useData(id, onChanged) {
  useEffect(() => {
    return store.onChange(id, onChanged);
  }, [id, onChanged]);

 return store.getData(id);
}
</code>```

Body:
I'm writing a custom hook that takes an id as input and then should do the following tasks:

get data for that id synchronously from a store

subscribe to changes in this store and update data accordingly

I came up with the following implementation which has the downside that I am setting state directly from inside the effect hook, causing a second render.

function useData({id}) {
    // set initial data on first render
    const [data, setData] = useState(Store.getData(id));

    useEffect(() => {
        // when id changes, set data to whatever is in store at the moment
        // here we call setData directly from inside useEffect, causing a second render
        setData(Store.getData(id));
        // subscribe to changes to update data whenever it changes in the store
        return Store.onChange(id, setData);
    }, [id]);

    return data;
}

A second approach I tried was to add a dummy state that is only there to cause a re-render. In this approach I am directly returning the data received from Store.getData(). This ensures that I will get the freshest data with every render and the useEffect ensures that every onChange trigger will cause a new render.

function useData({id}) {
    // adding some dummy state that we only use to force a render
    const [, setDummy] = useState({});
    const refresh = useCallback(() => {
        setDummy({});
    }, []);

    useEffect(() => {
        // subscribe to changes cause a refresh on every change
        return Store.onChange(id, refresh);
    }, [id, refresh]);

    return Store.getData[id];
}

The second approach works well but it feels weird to add this dummy state. Sure, I could put this into another useRefresh hook but I am not sure if this would really be a good practice.

Is there any better way of implementing this, without calling setData directly from inside useEffect and without relying on some unused dummy state?

Body:
So by now you use useState inside your hook just to re-trigger rendering of host component once store is changed. How about taking change handler from the outside?

function useData(id, onChanged) {
  useEffect(() => {
    return store.onChange(id, onChanged);
  }, [id, onChanged]);

 return store.getData(id);
}


问:
Sending a SOAP query to reactome.org with curl
(Note: this question was cross-posted on Biostar)

Hi all,

I'm trying to send a RPC-encoded SOAP query to Reactome (a biological pathways database),  using curl:

I want to call the remote method
queryPathwaysForReferenceIdentifiers defined in http://www.reactome.org:8080/caBIOWebApp/services/caBIOService?wsdl

I created the following SOAP/XML file: soap.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:r="http://www.reactome.org:8080/caBIOWebApp/services/caBIOService" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:reactome="http://www.reactome.org/caBIOWebApp/schema">
<SOAP-ENV:Body>
<r:queryPathwaysForReferenceIdentifiers>
<r:referenceIdentifiers>
<soapenc:Array soapenc:arrayType="soapenc:string[3]">
<soapenc:string>Q9Y266</soapenc:string>
<soapenc:string>P17480</soapenc:string>
<soapenc:string>P2048</soapenc:string>
</soapenc:Array>
</r:referenceIdentifiers>
</r:queryPathwaysForReferenceIdentifiers>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

and I sent it with curl using the following command:

```<code>curl -d @soap.xml \
      -H "Content-Type: application/soap+xml" \
      -H 'SOAPAction: ""' \
      "http://www.reactome.org:8080/caBIOWebApp/services/caBIOService"
</code>```

But the response is empty, whereas I expected a result.

```<code><?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">
  <soapenv:Body>
    <ns1:queryPathwaysForReferenceIdentifiersResponse xmlns:ns1="http://www.reactome.org:8080/caBIOWebApp/services/caBIOService" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <queryPathwaysForReferenceIdentifiersReturn xmlns:ns2="http://www.reactome.org/caBIOWebApp/schema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" soapenc:arrayType="ns2:Pathway[0]" xsi:type="soapenc:Array"/>
    </ns1:queryPathwaysForReferenceIdentifiersResponse>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

is there an error in my Request ? where ?

Many thanks !

Pierre

答: the question was answered on Biostar: http://biostar.stackexchange.com/questions/5511</p>

Body:
(Note: this question was cross-posted on Biostar)

Hi all,

I'm trying to send a RPC-encoded SOAP query to Reactome (a biological pathways database),  using curl:

I want to call the remote method
queryPathwaysForReferenceIdentifiers defined in http://www.reactome.org:8080/caBIOWebApp/services/caBIOService?wsdl

I created the following SOAP/XML file: soap.xml

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:r="http://www.reactome.org:8080/caBIOWebApp/services/caBIOService" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:reactome="http://www.reactome.org/caBIOWebApp/schema">
<SOAP-ENV:Body>
<r:queryPathwaysForReferenceIdentifiers>
<r:referenceIdentifiers>
<soapenc:Array soapenc:arrayType="soapenc:string[3]">
<soapenc:string>Q9Y266</soapenc:string>
<soapenc:string>P17480</soapenc:string>
<soapenc:string>P2048</soapenc:string>
</soapenc:Array>
</r:referenceIdentifiers>
</r:queryPathwaysForReferenceIdentifiers>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

and I sent it with curl using the following command:

curl -d @soap.xml \
      -H "Content-Type: application/soap+xml" \
      -H 'SOAPAction: ""' \
      "http://www.reactome.org:8080/caBIOWebApp/services/caBIOService"

But the response is empty, whereas I expected a result.

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">
  <soapenv:Body>
    <ns1:queryPathwaysForReferenceIdentifiersResponse xmlns:ns1="http://www.reactome.org:8080/caBIOWebApp/services/caBIOService" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <queryPathwaysForReferenceIdentifiersReturn xmlns:ns2="http://www.reactome.org/caBIOWebApp/schema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" soapenc:arrayType="ns2:Pathway[0]" xsi:type="soapenc:Array"/>
    </ns1:queryPathwaysForReferenceIdentifiersResponse>
  </soapenv:Body>
</soapenv:Envelope>

is there an error in my Request ? where ?

Many thanks !

Pierre