问:
Shiny input variables are selectively ignored by ggplot
I want my shiny app to be able to plot data frames with a varying number of columns. Since I don't expect the data to contain more than 5 columns, I wrote an explicit list of all possible cases for the ggplot object. I also want the size of the first object to be variable using a slider on the UI.

The problem is that the value of that slider is only recognized for data with more than one column.

To test this here is example data with one data column:
https://drive.google.com/file/d/182Qi-2I37OscSeLir_AyXdoedstIxx6D/view?usp=sharing

And here with two:
https://drive.google.com/file/d/1eB0eKvgfj94xIp80P0SG3QnoGZJ1Zq9a/view?usp=sharing

This is my first question here and I'm not to sure how to ideally provide examples for shiny apps using a fileInput. Please let me know if there is a better way than this.

```<code>#The ui

shinyUI(

  pageWithSidebar(

    headerPanel(""),

    sidebarPanel(

      fileInput(inputId = "file", label = "Choose an Excel (.xlsx) File",
                multiple = FALSE,
                accept = c("text/xlsx", "text/microsoft-excel-pen-XML-format-spreadsheet-file", ".xlsx"),
                width = NULL, buttonLabel = "Find...",
                placeholder = "No File selected"
      ),

      sliderInput(inputId = "width", label = "width", min = 0.01, max = 0.4, value = 0.2, step = 0.01)),

    mainPanel(plotOutput("graph"), height = "600px", quoted = TRUE)
  )
)

</code>```

```<code>#and the server

library(shiny)
library(ggplot2)
library(readxl)

shinyServer(function(input, output, session) {

  data <- reactive({
            data.frame(read_xlsx(input$file$datapath))
           })

  output$graph <- renderPlot({

      print(

        #somehow the interactive heigth setting is now muted within the expression
        ggplot(data(), aes(x = data()[,1], y = "", fill = as.factor(data()[2:ncol(data())])) ) +
        {if(ncol(data()) >= 2)geom_tile(aes(x = data()[,1], y = 0, fill = as.factor(data()[,2])), data(), width = 0.2, height = input$width, size = 2)} +
        {if(ncol(data()) >= 3)geom_tile(aes(x = data()[,1], y = 0.125, fill = as.factor(data()[,3])), data(), width = 0.2, height = 0.02, size = 2)} +
        {if(ncol(data()) >= 4)geom_tile(aes(x = data()[,1], y = -0.125, fill = as.factor(data()[,4])), data(), width = 0.2, height = 0.02, size = 2)} +
        {if(ncol(data()) == 5)geom_tile(aes(x = data()[,1], y = -0.145, fill = as.factor(data()[,5])), data(), width = 0.2, height = 0.02, size = 2)}

          scale_y_continuous(breaks = NULL, labels = NULL)
          )

  })
})
</code>```

答: So, I finally found the error. The problem is that scale_y_continuousautomatically rescales the y-axis to the size of the plot elements. In my case, this didn't show up if I added fixed-size plot elements (as is done by the program, if the data contains more than one column) that also set limits to the size of the y-axis. The solution in this particular case for me was to use ylim(-0.2005, 0.2005)instead, hence fixing y-axis size.

Body:
I want my shiny app to be able to plot data frames with a varying number of columns. Since I don't expect the data to contain more than 5 columns, I wrote an explicit list of all possible cases for the ggplot object. I also want the size of the first object to be variable using a slider on the UI.

The problem is that the value of that slider is only recognized for data with more than one column.

To test this here is example data with one data column:
https://drive.google.com/file/d/182Qi-2I37OscSeLir_AyXdoedstIxx6D/view?usp=sharing

And here with two:
https://drive.google.com/file/d/1eB0eKvgfj94xIp80P0SG3QnoGZJ1Zq9a/view?usp=sharing

This is my first question here and I'm not to sure how to ideally provide examples for shiny apps using a fileInput. Please let me know if there is a better way than this.

#The ui

shinyUI(

  pageWithSidebar(

    headerPanel(""),

    sidebarPanel(

      fileInput(inputId = "file", label = "Choose an Excel (.xlsx) File",
                multiple = FALSE,
                accept = c("text/xlsx", "text/microsoft-excel-pen-XML-format-spreadsheet-file", ".xlsx"),
                width = NULL, buttonLabel = "Find...",
                placeholder = "No File selected"
      ),

      sliderInput(inputId = "width", label = "width", min = 0.01, max = 0.4, value = 0.2, step = 0.01)),

    mainPanel(plotOutput("graph"), height = "600px", quoted = TRUE)
  )
)

#and the server

library(shiny)
library(ggplot2)
library(readxl)

shinyServer(function(input, output, session) {

  data <- reactive({
            data.frame(read_xlsx(input$file$datapath))
           })

  output$graph <- renderPlot({

      print(

        #somehow the interactive heigth setting is now muted within the expression
        ggplot(data(), aes(x = data()[,1], y = "", fill = as.factor(data()[2:ncol(data())])) ) +
        {if(ncol(data()) >= 2)geom_tile(aes(x = data()[,1], y = 0, fill = as.factor(data()[,2])), data(), width = 0.2, height = input$width, size = 2)} +
        {if(ncol(data()) >= 3)geom_tile(aes(x = data()[,1], y = 0.125, fill = as.factor(data()[,3])), data(), width = 0.2, height = 0.02, size = 2)} +
        {if(ncol(data()) >= 4)geom_tile(aes(x = data()[,1], y = -0.125, fill = as.factor(data()[,4])), data(), width = 0.2, height = 0.02, size = 2)} +
        {if(ncol(data()) == 5)geom_tile(aes(x = data()[,1], y = -0.145, fill = as.factor(data()[,5])), data(), width = 0.2, height = 0.02, size = 2)}

          scale_y_continuous(breaks = NULL, labels = NULL)
          )

  })
})


来源: stackexchange

问:
How do I find all the files that were created today in Unix/Linux?
How do I find all the files that were create only today and not in 24 hour period in unix/linux</p>

答:
This worked for me. Lists the files created on May 30 in the current directory.</p>

```<code>ls -lt | grep 'May 30'
</code>```

OwnerDisplayName: kevin

ContentLicense: CC BY-SA 3.0

Body:
This worked for me. Lists the files created on May 30 in the current directory.

ls -lt | grep 'May 30'

ContentLicense: CC BY-SA 4.0


问:
How to print PDF files in Android?
I have some PDF files in the app and I want to enable users to print them.

I have seen PrinterManager class but it looks like too much boilerplate code.

Is there some kind of Intent that will open some system screen to handle printing like choosing printer and printing?

I have used a few PDF apps and they are opening this screen for printing.

How I can make something like this?

答:
If you don't want create your own code to print the document in your app.

You could try to implement an Intent to launch Chrome or other browser passing the path of the file as Uri and open the PDF in the browser, then the user could print the document using the browser.

Launching the intent:

```<code>//Launch the intent to open the file with default browser.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(path_to_file));
startActivity(i);
</code>```

You can print using Chrome: Settings -> Share -> Choose Print and select your printer.

I hope it can helps you.

Title: How to print PDF files in Android?

Body:
If you don't want create your own code to print the document in your app.

You could try to implement an Intent to launch Chrome or other browser passing the path of the file as Uri and open the PDF in the browser, then the user could print the document using the browser.

Launching the intent:

//Launch the intent to open the file with default browser.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(path_to_file));
startActivity(i);

You can print using Chrome: Settings -> Share -> Choose Print and select your printer.

I hope it can helps you.


问:
ViewModel refetches data when fragment is recreated
I am using Bottom Navigation with Navigation Architecture Component. When the user navigates from one item to another(via Bottom navigation) and back again view model call repository function to fetch data again. So if the user goes back and forth 10 times the same data will be fetched 10 times. How to avoid re-fetching when the fragment is recreated data is already there?.

Fragment

```<code>class HomeFragment : Fragment() {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    private lateinit var productsViewModel: ProductsViewModel
    private lateinit var productsAdapter: ProductsAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initViewModel()
        initAdapters()
        initLayouts()
        getData()
    }

    private fun initViewModel() {
        (activity!!.application as App).component.inject(this)

        productsViewModel = activity?.run {
            ViewModelProviders.of(this, viewModelFactory).get(ProductsViewModel::class.java)
        }!!
    }

    private fun initAdapters() {
        productsAdapter = ProductsAdapter(this.context!!, From.HOME_FRAGMENT)
    }

    private fun initLayouts() {
        productsRecyclerView.layoutManager = LinearLayoutManager(this.activity)
        productsRecyclerView.adapter = productsAdapter
    }

    private fun getData() {
        val productsFilters = ProductsFilters.builder().sortBy(SortProductsBy.NEWEST).build()

        //Products filters
        productsViewModel.setInput(productsFilters, 2)

        //Observing products data
        productsViewModel.products.observe(viewLifecycleOwner, Observer {
            it.products()?.let { products -> productsAdapter.setData(products) }
        })

        //Observing loading
        productsViewModel.networkState.observe(viewLifecycleOwner, Observer {
            //Todo showing progress bar
        })
    }
}
</code>```

ViewModel

```<code>class ProductsViewModel
@Inject constructor(private val repository: ProductsRepository) : ViewModel() {

    private val _input = MutableLiveData<PInput>()

    fun setInput(filters: ProductsFilters, limit: Int) {
        _input.value = PInput(filters, limit)
    }

    private val getProducts = map(_input) {
        repository.getProducts(it.filters, it.limit)
    }

    val products = switchMap(getProducts) { it.data }
    val networkState = switchMap(getProducts) { it.networkState }
}

data class PInput(val filters: ProductsFilters, val limit: Int)
</code>```

Repository

```<code>@Singleton
class ProductsRepository @Inject constructor(private val api: ApolloClient) {

    val networkState = MutableLiveData<NetworkState>()

    fun getProducts(filters: ProductsFilters, limit: Int): ApiResponse<ProductsQuery.Data> {
        val products = MutableLiveData<ProductsQuery.Data>()

        networkState.postValue(NetworkState.LOADING)

        val request = api.query(ProductsQuery
                .builder()
                .filters(filters)
                .limit(limit)
                .build())

        request.enqueue(object : ApolloCall.Callback<ProductsQuery.Data>() {
            override fun onFailure(e: ApolloException) {
                networkState.postValue(NetworkState.error(e.localizedMessage))
            }

            override fun onResponse(response: Response<ProductsQuery.Data>) = when {
                response.hasErrors() -> networkState.postValue(NetworkState.error(response.errors()[0].message()))
                else -> {
                    networkState.postValue(NetworkState.LOADED)
                    products.postValue(response.data())
                }
            }
        })

        return ApiResponse(data = products, networkState = networkState)
    }
}
</code>```

Navigation main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation.xml"
    app:startDestination="@id/home">

    <fragment
        android:id="@+id/home"
        android:name="com.nux.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home"/>
    <fragment
        android:id="@+id/search"
        android:name="com.nux.ui.search.SearchFragment"
        android:label="@string/title_search"
        tools:layout="@layout/fragment_search" />
    <fragment
        android:id="@+id/my_profile"
        android:name="com.nux.ui.user.MyProfileFragment"
        android:label="@string/title_profile"
        tools:layout="@layout/fragment_profile" />
</navigation>
</code>```

ViewModelFactory

```<code>@Singleton
class ViewModelFactory @Inject
constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val creator = viewModels[modelClass]
                ?: viewModels.asIterable().firstOrNull { modelClass.isAssignableFrom(it.key) }?.value
                ?: throw IllegalArgumentException("unknown model class $modelClass")
        return try {
            creator.get() as T
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}
</code>```

答:
In onActivityCreated(), you are calling getData(). In there, you have:

```<code>productsViewModel.setInput(productsFilters, 2)
</code>```

This, in turn, changes the value of _input in your ProductsViewModel. And, every time that _input changes, the getProducts lambda expression will be evaluated, calling your repository.

So, every onActivityCreated() call triggers a call to your repository.

I do not know enough about your app to tell you what you need to change. Here are some possibilities:

Switch from onActivityCreated() to other lifecycle methods. initViewModel() could be called in onCreate(), while the rest should be in onViewCreated().

Reconsider your getData() implementation. Do you really need to call setInput() every time we navigate to this fragment? Or, should that be part of initViewModel() and done once in onCreate()? Or, since productsFilters does not seem to be tied to the fragment at all, should productsFilters and the setInput() call be part of the init block of ProductsViewModel, so it only happens once?

Body:
I am using Bottom Navigation with Navigation Architecture Component. When the user navigates from one item to another(via Bottom navigation) and back again view model call repository function to fetch data again. So if the user goes back and forth 10 times the same data will be fetched 10 times. How to avoid re-fetching when the fragment is recreated data is already there?.

Fragment

class HomeFragment : Fragment() {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    private lateinit var productsViewModel: ProductsViewModel
    private lateinit var productsAdapter: ProductsAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initViewModel()
        initAdapters()
        initLayouts()
        getData()
    }

    private fun initViewModel() {
        (activity!!.application as App).component.inject(this)

        productsViewModel = activity?.run {
            ViewModelProviders.of(this, viewModelFactory).get(ProductsViewModel::class.java)
        }!!
    }

    private fun initAdapters() {
        productsAdapter = ProductsAdapter(this.context!!, From.HOME_FRAGMENT)
    }

    private fun initLayouts() {
        productsRecyclerView.layoutManager = LinearLayoutManager(this.activity)
        productsRecyclerView.adapter = productsAdapter
    }

    private fun getData() {
        val productsFilters = ProductsFilters.builder().sortBy(SortProductsBy.NEWEST).build()

        //Products filters
        productsViewModel.setInput(productsFilters, 2)

        //Observing products data
        productsViewModel.products.observe(viewLifecycleOwner, Observer {
            it.products()?.let { products -> productsAdapter.setData(products) }
        })

        //Observing loading
        productsViewModel.networkState.observe(viewLifecycleOwner, Observer {
            //Todo showing progress bar
        })
    }
}

ViewModel

class ProductsViewModel
@Inject constructor(private val repository: ProductsRepository) : ViewModel() {

    private val _input = MutableLiveData<PInput>()

    fun setInput(filters: ProductsFilters, limit: Int) {
        _input.value = PInput(filters, limit)
    }

    private val getProducts = map(_input) {
        repository.getProducts(it.filters, it.limit)
    }

    val products = switchMap(getProducts) { it.data }
    val networkState = switchMap(getProducts) { it.networkState }
}

data class PInput(val filters: ProductsFilters, val limit: Int)

Repository

@Singleton
class ProductsRepository @Inject constructor(private val api: ApolloClient) {

    val networkState = MutableLiveData<NetworkState>()

    fun getProducts(filters: ProductsFilters, limit: Int): ApiResponse<ProductsQuery.Data> {
        val products = MutableLiveData<ProductsQuery.Data>()

        networkState.postValue(NetworkState.LOADING)

        val request = api.query(ProductsQuery
                .builder()
                .filters(filters)
                .limit(limit)
                .build())

        request.enqueue(object : ApolloCall.Callback<ProductsQuery.Data>() {
            override fun onFailure(e: ApolloException) {
                networkState.postValue(NetworkState.error(e.localizedMessage))
            }

            override fun onResponse(response: Response<ProductsQuery.Data>) = when {
                response.hasErrors() -> networkState.postValue(NetworkState.error(response.errors()[0].message()))
                else -> {
                    networkState.postValue(NetworkState.LOADED)
                    products.postValue(response.data())
                }
            }
        })

        return ApiResponse(data = products, networkState = networkState)
    }
}

Navigation main.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation.xml"
    app:startDestination="@id/home">

    <fragment
        android:id="@+id/home"
        android:name="com.nux.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home"/>
    <fragment
        android:id="@+id/search"
        android:name="com.nux.ui.search.SearchFragment"
        android:label="@string/title_search"
        tools:layout="@layout/fragment_search" />
    <fragment
        android:id="@+id/my_profile"
        android:name="com.nux.ui.user.MyProfileFragment"
        android:label="@string/title_profile"
        tools:layout="@layout/fragment_profile" />
</navigation>

ViewModelFactory

@Singleton
class ViewModelFactory @Inject
constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val creator = viewModels[modelClass]
                ?: viewModels.asIterable().firstOrNull { modelClass.isAssignableFrom(it.key) }?.value
                ?: throw IllegalArgumentException("unknown model class $modelClass")
        return try {
            creator.get() as T
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}

Body:
In onActivityCreated(), you are calling getData(). In there, you have:

productsViewModel.setInput(productsFilters, 2)

This, in turn, changes the value of _input in your ProductsViewModel. And, every time that _input changes, the getProducts lambda expression will be evaluated, calling your repository.

So, every onActivityCreated() call triggers a call to your repository.

I do not know enough about your app to tell you what you need to change. Here are some possibilities:

Switch from onActivityCreated() to other lifecycle methods. initViewModel() could be called in onCreate(), while the rest should be in onViewCreated().

Reconsider your getData() implementation. Do you really need to call setInput() every time we navigate to this fragment? Or, should that be part of initViewModel() and done once in onCreate()? Or, since productsFilters does not seem to be tied to the fragment at all, should productsFilters and the setInput() call be part of the init block of ProductsViewModel, so it only happens once?


问:
How to serve static files in Flask
So this is embarrassing. I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation Flask describes returning static files. Yes, I could use render_template but I know the data is not templatized. I'd have thought send_file or url_for was the right thing, but I could not get those to work. In the meantime, I am opening the files, reading content, and rigging up a Response with appropriate mimetype:

```<code>import os.path

from flask import Flask, Response

app = Flask(__name__)
app.config.from_object(__name__)

def root_dir():  # pragma: no cover
    return os.path.abspath(os.path.dirname(__file__))

def get_file(filename):  # pragma: no cover
    try:
        src = os.path.join(root_dir(), filename)
        # Figure out how flask returns static files
        # Tried:
        # - render_template
        # - send_file
        # This should not be so non-obvious
        return open(src).read()
    except IOError as exc:
        return str(exc)

@app.route('/', methods=['GET'])
def metrics():  # pragma: no cover
    content = get_file('jenkins_analytics.html')
    return Response(content, mimetype="text/html")

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def get_resource(path):  # pragma: no cover
    mimetypes = {
        ".css": "text/css",
        ".html": "text/html",
        ".js": "application/javascript",
    }
    complete_path = os.path.join(root_dir(), path)
    ext = os.path.splitext(path)[1]
    mimetype = mimetypes.get(ext, "text/html")
    content = get_file(complete_path)
    return Response(content, mimetype=mimetype)

if __name__ == '__main__':  # pragma: no cover
    app.run(port=80)
</code>```

Someone want to give a code sample or url for this? I know this is going to be dead simple.

答:
One of the simple way to do. Cheers!

demo.py

```<code>from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)
</code>```

Now create folder name called templates.
Add your index.html file inside of templates folder

index.html

```<code><!DOCTYPE html>
<html>
<head>
    <title>Python Web Application</title>
</head>
<body>
    <div>
         <p>
            Welcomes You!!
         </p>
    </div>
</body>
</html>
</code>```

Project Structure

```<code>-demo.py
-templates/index.html
</code>```

Title: How to serve static files in Flask

Body:
So this is embarrassing. I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation Flask describes returning static files. Yes, I could use render_template but I know the data is not templatized. I'd have thought send_file or url_for was the right thing, but I could not get those to work. In the meantime, I am opening the files, reading content, and rigging up a Response with appropriate mimetype:

import os.path

from flask import Flask, Response

app = Flask(__name__)
app.config.from_object(__name__)

def root_dir():  # pragma: no cover
    return os.path.abspath(os.path.dirname(__file__))

def get_file(filename):  # pragma: no cover
    try:
        src = os.path.join(root_dir(), filename)
        # Figure out how flask returns static files
        # Tried:
        # - render_template
        # - send_file
        # This should not be so non-obvious
        return open(src).read()
    except IOError as exc:
        return str(exc)

@app.route('/', methods=['GET'])
def metrics():  # pragma: no cover
    content = get_file('jenkins_analytics.html')
    return Response(content, mimetype="text/html")

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def get_resource(path):  # pragma: no cover
    mimetypes = {
        ".css": "text/css",
        ".html": "text/html",
        ".js": "application/javascript",
    }
    complete_path = os.path.join(root_dir(), path)
    ext = os.path.splitext(path)[1]
    mimetype = mimetypes.get(ext, "text/html")
    content = get_file(complete_path)
    return Response(content, mimetype=mimetype)

if __name__ == '__main__':  # pragma: no cover
    app.run(port=80)

Someone want to give a code sample or url for this? I know this is going to be dead simple.

Body:
One of the simple way to do. Cheers!

demo.py

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)

Now create folder name called templates.
Add your index.html file inside of templates folder

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Python Web Application</title>
</head>
<body>
    <div>
         <p>
            Welcomes You!!
         </p>
    </div>
</body>
</html>

Project Structure

-demo.py
-templates/index.html


问:
Vuetify toolbar is not collapsing on mobile view
I am reading the official docs of Vuetify toolbar, I want to use the toolbar provided in the example but when I use the mobile view from dev tools and click the menu icon to expand it, it doesn't expand.

Here is the example provided by official docs

Here is the code itself

```<code><div id="app">
  <v-app id="inspire">
    <v-toolbar>
      <v-toolbar-side-icon></v-toolbar-side-icon>
      <v-toolbar-title>Title</v-toolbar-title>
      <v-spacer></v-spacer>
      <v-toolbar-items class="hidden-sm-and-down">
        <v-btn flat>Link One</v-btn>
        <v-btn flat>Link Two</v-btn>
        <v-btn flat>Link Three</v-btn>
      </v-toolbar-items>
    </v-toolbar>
  </v-app>
</div>
</code>```

and

```<code>new Vue({
  el: '#app',

})
</code>```

答:
Inside the example you linked, the menu bar does not open either because there is no method to implement it.

In this vuetify example, the menu bar that opens and closes correctly in desktop and mobile.

What they did was implement @click right there in the HTML

```<code>    <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon>
</code>```

Body:
I am reading the official docs of Vuetify toolbar, I want to use the toolbar provided in the example but when I use the mobile view from dev tools and click the menu icon to expand it, it doesn't expand.

Here is the example provided by official docs

Here is the code itself

  <v-app id="inspire">
    <v-toolbar>
      <v-toolbar-side-icon></v-toolbar-side-icon>
      <v-toolbar-title>Title</v-toolbar-title>
      <v-spacer></v-spacer>
      <v-toolbar-items class="hidden-sm-and-down">
        <v-btn flat>Link One</v-btn>
        <v-btn flat>Link Two</v-btn>
        <v-btn flat>Link Three</v-btn>
      </v-toolbar-items>
    </v-toolbar>
  </v-app>

and

new Vue({
  el: '#app',

})

Body:
Inside the example you linked, the menu bar does not open either because there is no method to implement it.

In this vuetify example, the menu bar that opens and closes correctly in desktop and mobile.

What they did was implement @click right there in the HTML

    <v-toolbar-side-icon @click.stop="drawer = !drawer"></v-toolbar-side-icon>


问:
DropzoneJS: How to get PHP response after upload success?
I'm trying to implement Dropzone on my site. I want to listen for the "success" event and then take the server response and add some info from it to a form on the same page as the DropZone after the upload is completed.

the info i want to get in the server response is a direct link to the file.

the website of dropzone: http://www.dropzonejs.com/

my project website:

```<code>http://37.34.62.131/test/
</code>```

so i completed this in a older version of my project but i cant figure it out how to do it with dropzone.js

working example:

```<code>http://37.34.62.131/test/uploader%201.0/
</code>```

what i try to do is when a file has been uploaded i want to get the php response back on the same page with the download links as shown below.

i can also send you my source codes so you can look for yourself.

my php code i want to see in the response:

```<code>        print '<h2>Picture Uploaded Successfuly!!!!</h2> <p id="codes">

      <img src="'.$imgurl.'" height="300" alt="Uploaded Picture" >
        <label for="codebb">BBCode:</label>
        <input type="text" id="codebb" value="[URL='.$siteurl.'][IMG]'.$dlurl.'[/IMG][/URL]" onclick="javascript:this.focus();this.select();" readonly="true" /><br />
        <label for="codehtml">HTML Code: </label>
        <input type="text" id="codehtml" value=\'<a href="'.$siteurl.'"><img src="'.$dlurl.'" alt="'.$alt.'" />&lt/a>\' onclick="javascript:this.focus();this.select();" readonly="true" /><br />
        <label for="codedirect">Direct Link:</label>
        <input type="text" id="codedirect" value="'.$dlurl.'" onclick="javascript:this.focus();this.select();" readonly="true" /></p>';
        echo ".$newname";
</code>```

Can anyone help me understand what I'm missing?

答:
Note that there is an issue with chunked uploads and never get back the response from the server on success. All the previous answers will not work in that case. Solution could be by manually parsing XHR response like so:

```<code>const galleryZone = new Dropzone(".dropzone-gallery", {
    url: your_upload_url_in_here,
    chunking: true,
    forceChunking: true,
    chunkSize: 2000000,
    success: (file, response) => {
        console.log(JSON.parse(file.xhr.response));
    }
});
</code>```

Alse you could check the issue at Dropzone's repository in here https://gitlab.com/meno/dropzone/issues/51#note_47553173

Body:
I'm trying to implement Dropzone on my site. I want to listen for the "success" event and then take the server response and add some info from it to a form on the same page as the DropZone after the upload is completed.

the info i want to get in the server response is a direct link to the file.

the website of dropzone: http://www.dropzonejs.com/

my project website:

http://37.34.62.131/test/

so i completed this in a older version of my project but i cant figure it out how to do it with dropzone.js

working example:

http://37.34.62.131/test/uploader%201.0/

what i try to do is when a file has been uploaded i want to get the php response back on the same page with the download links as shown below.

i can also send you my source codes so you can look for yourself.

my php code i want to see in the response:

        print '
Picture Uploaded Successfuly!!!!

        BBCode:
        <input type="text" id="codebb" value="[URL='.$siteurl.'][IMG]'.$dlurl.'[/IMG][/URL]" onclick="javascript:this.focus();this.select();" readonly="true" />

        HTML Code:
        <input type="text" id="codehtml" value=\'&lt/a>\' onclick="javascript:this.focus();this.select();" readonly="true" />

        Direct Link:
        <input type="text" id="codedirect" value="'.$dlurl.'" onclick="javascript:this.focus();this.select();" readonly="true" />
';
        echo ".$newname";

Can anyone help me understand what I'm missing?

Body:
Note that there is an issue with chunked uploads and never get back the response from the server on success. All the previous answers will not work in that case. Solution could be by manually parsing XHR response like so:

const galleryZone = new Dropzone(".dropzone-gallery", {
    url: your_upload_url_in_here,
    chunking: true,
    forceChunking: true,
    chunkSize: 2000000,
    success: (file, response) => {
        console.log(JSON.parse(file.xhr.response));
    }
});

Alse you could check the issue at Dropzone's repository in here https://gitlab.com/meno/dropzone/issues/51#note_47553173


答:
Why are you using window functions, when you seem to want a simple aggregation?

```<code>SELECT u.[FirstName] + ' ' + u.[LastName] AS EmployeeName
       min(e.LoggedTime) as first
       max(e.LoggedTime) as last
FROM [ProtegeGX].[dbo].[Users] u JOIN
     [ProtegeGXEvents].[dbo].[Events] e
     ON e.RecordIndex1 = u.UserID JOIN
     [ProtegeGX].[dbo].[EventTypes] et
     on e.EventTypeID = et.EventTypeID
WHERE e.LoggedTime Between '2019-05-29' AND '2019-05-31' AND
      u.userid = 97
GROUP BY u.[FirstName] + ' ' + u.[LastName];
</code>```

I changed the JOINs to inner joins, because the WHERE clause is limiting them anyway.

If you want this per day, then:

```<code>SELECT u.[FirstName] + ' ' + u.[LastName] AS EmployeeName,
       CONVERT(DATE, e.loggedTime) as theday,
       min(e.LoggedTime) as first
       max(e.LoggedTime) as last
FROM [ProtegeGX].[dbo].[Users] u JOIN
     [ProtegeGXEvents].[dbo].[Events] e
     ON e.RecordIndex1 = u.UserID JOIN
     [ProtegeGX].[dbo].[EventTypes] et
     on e.EventTypeID = et.EventTypeID
WHERE e.LoggedTime Between '2019-05-29' AND '2019-05-31' AND
      u.userid = 97
GROUP BY u.[FirstName] + ' ' + u.[LastName],
         CONVERT(DATE, e.loggedTime);
</code>```

Title: How can i get first and last record for all users per day by date range selected

Body:
I would like to get as the title states, A list of all users first and last swipe time per day, for a selected date range(this can be selected by the user). Right now I am returning every time a user swipes.

Mike Donati  2019-05-29 09:21:01.673    2019-05-29 09:21:01.673
Mike Donati  2019-05-29 09:21:10.207    2019-05-29 09:21:10.207
Mike Donati  2019-05-29 09:23:21.737    2019-05-29 09:23:21.737
Mike Donati  2019-05-29 09:23:30.430    2019-05-29 09:23:30.430
Mike Donati  2019-05-29 09:33:17.640    2019-05-29 09:33:17.640
Mike Donati  2019-05-29 09:33:21.587    2019-05-29 09:33:21.587
Mike Donati  2019-05-29 09:36:16.687    2019-05-29 09:36:16.687
Mike Donati  2019-05-29 09:36:25.083    2019-05-29 09:36:25.083
Mike Donati  2019-05-29 10:00:30.820    2019-05-29 10:00:30.820
Mike Donati  2019-05-29 10:01:07.313    2019-05-29 10:01:07.313
Mike Donati  2019-05-29 10:42:13.057    2019-05-29 10:42:13.057
Mike Donati  2019-05-29 10:42:15.410    2019-05-29 10:42:15.410
Mike Donati  2019-05-29 16:16:51.493    2019-05-29 16:16:51.493
Mike Donati  2019-05-29 16:16:57.637    2019-05-29 16:16:57.637
Mike Donati  2019-05-30 07:49:33.710    2019-05-30 07:49:33.710
Mike Donati  2019-05-30 07:51:56.003    2019-05-30 07:51:56.003
Mike Donati  2019-05-30 08:24:29.797    2019-05-30 08:24:29.797
Mike Donati  2019-05-30 08:24:38.743    2019-05-30 08:24:38.743

SELECT
     u.[FirstName] + ' ' + u.[LastName] AS EmployeeName
    ,min(e.LoggedTime) OVER(PARTITION BY e.LoggedTime) as first
    ,max(e.LoggedTime) OVER(PARTITION BY e.LoggedTime) as last

FROM [ProtegeGX].[dbo].[Users] AS u
LEFT JOIN [ProtegeGXEvents].[dbo].[Events] AS e ON e.RecordIndex1=u.UserID
LEFT JOIN [ProtegeGX].[dbo].[EventTypes] AS et on e.EventTypeID = et.EventTypeID
WHERE  e.LoggedTime Between '2019-05-29'and '2019-05-31' and u.userid = 97
GROUP BY
    u.[FirstName] + ' ' + u.[LastName]
    ,(e.LoggedTime)
ORDER BY
    u.[FirstName] + ' ' + u.[LastName]

I would like the initial swipe in time and last swipe time per day per user

user               first swipe             last swipe
Mike Donati  2019-05-29 09:21:01.673   2019-05-29 16:16:57.637
Mike Donati  2019-05-30 07:49:33.710   2019-05-30 08:24:38.743

Body:
Why are you using window functions, when you seem to want a simple aggregation?

SELECT u.[FirstName] + ' ' + u.[LastName] AS EmployeeName
       min(e.LoggedTime) as first
       max(e.LoggedTime) as last
FROM [ProtegeGX].[dbo].[Users] u JOIN
     [ProtegeGXEvents].[dbo].[Events] e
     ON e.RecordIndex1 = u.UserID JOIN
     [ProtegeGX].[dbo].[EventTypes] et
     on e.EventTypeID = et.EventTypeID
WHERE e.LoggedTime Between '2019-05-29' AND '2019-05-31' AND
      u.userid = 97
GROUP BY u.[FirstName] + ' ' + u.[LastName];

I changed the JOINs to inner joins, because the WHERE clause is limiting them anyway.

If you want this per day, then:

SELECT u.[FirstName] + ' ' + u.[LastName] AS EmployeeName,
       CONVERT(DATE, e.loggedTime) as theday,
       min(e.LoggedTime) as first
       max(e.LoggedTime) as last
FROM [ProtegeGX].[dbo].[Users] u JOIN
     [ProtegeGXEvents].[dbo].[Events] e
     ON e.RecordIndex1 = u.UserID JOIN
     [ProtegeGX].[dbo].[EventTypes] et
     on e.EventTypeID = et.EventTypeID
WHERE e.LoggedTime Between '2019-05-29' AND '2019-05-31' AND
      u.userid = 97
GROUP BY u.[FirstName] + ' ' + u.[LastName],
         CONVERT(DATE, e.loggedTime);


问:
Custom defined form Constraint throws a null pointer exception
I have a problem with defining a custom Constraint on my form. This is my form:

val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply)
```

<p>If I do the following:</p>

<pre class="lang-scala prettyprint-override"><code>val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply).verifying("my constraint", f => f.field == true)
</code>```

then it works fine. However, if I try to use the following custom defined Constraint , then a null pointer exception is thrown and I do not knowing why:

val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply).verifying(myconstraint)

val myconstraint : Constraint[MyForm] = Constraint("myconstraint")({
   form =>
      if(form.field == true){
          Valid
      }else {
        Invalid(Seq(ValidationError("problem")))
      }
})
```

I tried to use println to debug but I nothing is printed in the console.

答:
Try moving myconstraint definition above the form definition like so

```<code>val myconstraint : Constraint[MyForm] = Constraint("myconstraint")({ ...
...
val form = Form( ...
</code>```

due to possible forward reference problem where we end up referencing an uninitialised value.

Body:
I have a problem with defining a custom Constraint on my form. This is my form:

val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply)

If I do the following:

val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply).verifying("my constraint", f => f.field == true)

then it works fine. However, if I try to use the following custom defined Constraint , then a null pointer exception is thrown and I do not knowing why:

val form = Form(
  mapping(
    "field" -> boolean
)(MyForm.apply)(MyForm.unapply).verifying(myconstraint)

val myconstraint : Constraint[MyForm] = Constraint("myconstraint")({
   form =>
      if(form.field == true){
          Valid
      }else {
        Invalid(Seq(ValidationError("problem")))
      }
})

I tried to use println to debug but I nothing is printed in the console.

Body:
Try moving myconstraint definition above the form definition like so

val myconstraint : Constraint[MyForm] = Constraint("myconstraint")({ ...
...
val form = Form( ...

due to possible forward reference problem where we end up referencing an uninitialised value.


问:
Validate array of strings with joi, must be strings
I need to validate an array to check if it's elements are strings using joi. It always sends the error of "Inavlid tag".</p>

```<code>// returned array from req.body
let tags = ["Vue", "React", "Angular"]

// joi shema
const schema = {
     tags: Joi.array().items(Joi.string()),
};

const { error, value } = Joi.validate(tags, schema);

if (error) {
     return res.status(400).send({ tagError: "Invalid tag" });
}
</code>```

答:
Joi was recently changed to @hapi/joi (literally 2 weeks ago), so make sure first and foremost that you've switched out the NPM package properly:npm uninstall joi and npm i -s @hapi/joi. Make sure to change your require statements for this change, also.

To define your schema in this new package, you would use:

```<code>const schema = Joi.array().items(Joi.string());
</code>```

Body:
I need to validate an array to check if it's elements are strings using joi. It always sends the error of "Inavlid tag".

// returned array from req.body
let tags = ["Vue", "React", "Angular"]

// joi shema
const schema = {
     tags: Joi.array().items(Joi.string()),
};

const { error, value } = Joi.validate(tags, schema);

if (error) {
     return res.status(400).send({ tagError: "Invalid tag" });
}

Body:
Joi was recently changed to @hapi/joi (literally 2 weeks ago), so make sure first and foremost that you've switched out the NPM package properly:npm uninstall joi and npm i -s @hapi/joi. Make sure to change your require statements for this change, also.

To define your schema in this new package, you would use:

const schema = Joi.array().items(Joi.string());


问:
Select highest value from column and corresponding value from another column in multiple columns

I want to return the group which has the highest value in the columns Value1, Value2, Value3 as well as their name and numerical ID for the name. I do not know where to start since I have little SQL and Google Sheets experience. Preferably the solution would be in Google Sheets but I am open to other software alternatives. Just a pointer in the right direction would be very helpful.

Link to the spreadsheet.

答:
paste in H3 cell:

```<code>=UNIQUE(A2:B)
</code>```

paste in J3 cell and drag down:

```<code>=QUERY(A:F, "select max(D),max(E),max(F)
             where A="&H3&"
             label max(D)'',max(E)'',max(F)''")
</code>```

paste in H3 cell:

```<code>=UNIQUE(A2:B)
</code>```

paste in J3 cell and drag to the right then drag down:

```<code>=ARRAYFORMULA(IFERROR(VLOOKUP(QUERY({$A:$F},
 "select max(Col"&COLUMN(D$1)&")
  where Col1="&$H3&"
  label max(Col"&COLUMN(D$1)&")''"),
 QUERY(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(LEN($C$2:$C),
 "♥"&$A$2:$A&"♦"&D$2:D&"♦"&$C$2:$C, )),,999^99)),,999^99), "♥")), "♦"),
 "select Col2,Col3
  where Col1="&$H3), 2, 0)))
</code>```

Body:
paste in H3 cell:

=UNIQUE(A2:B)

paste in J3 cell and drag down:

=QUERY(A:F, "select max(D),max(E),max(F)
             where A="&H3&"
             label max(D)'',max(E)'',max(F)''")

paste in H3 cell:

=UNIQUE(A2:B)

paste in J3 cell and drag to the right then drag down:

=ARRAYFORMULA(IFERROR(VLOOKUP(QUERY({$A:$F},
 "select max(Col"&COLUMN(D$1)&")
  where Col1="&$H3&"
  label max(Col"&COLUMN(D$1)&")''"),
 QUERY(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(IF(LEN($C$2:$C),
 "♥"&$A$2:$A&"♦"&D$2:D&"♦"&$C$2:$C, )),,999^99)),,999^99), "♥")), "♦"),
 "select Col2,Col3
  where Col1="&$H3), 2, 0)))


问:
how to disable/enable dropdown angular 4
How can I enable/disable a dropdown based on the selection of another dropdown menu?

I tried this but it doesn't seem to work:

```<code><select class="custom-select" id="abc">
    <option value="" hidden>Select</option>
    <option *ngFor="let data of datay"
            [ngValue]="data.code"
            [attr.disabled]="true">
        {{data.name}}
    </option>
</select>
</code>```

Any sample code is appreciated.

答:
Here is example with reactive forms as answer with template-driven forms is already posted:

```<code><form [formGroup]="form">
  <select name="field1" formControlName="field1">
    <option *ngFor="let value of [1, 2, 3]" [value]="value">{{value}}</option>
  </select>
</form>

<form [formGroup]="form">
  <select name="field1" formControlName="field2">
    <option *ngFor="let value of [1, 2, 3]" [value]="value">{{value}}</option>
  </select>
</form>
</code>```

TS:

```<code>  form;

  ngOnInit(): void {
    this.form = new FormGroup({
      field1: new FormControl(),
      field2: new FormControl()
    });

    this.form.controls.field1.valueChanges.subscribe(value => {
      value === '2' ? this.form.controls.field2.disable() : this.form.controls.field2.enable();
    });
  }
</code>```

Body:
How can I enable/disable a dropdown based on the selection of another dropdown menu?

I tried this but it doesn't seem to work:

<select class="custom-select" id="abc">
    <option value="" hidden>Select</option>
    <option *ngFor="let data of datay"
            [ngValue]="data.code"
            [attr.disabled]="true">
        {{data.name}}
    </option>
</select>

Any sample code is appreciated.

Body:
Here is example with reactive forms as answer with template-driven forms is already posted:

<form [formGroup]="form">
  <select name="field1" formControlName="field1">
    <option *ngFor="let value of [1, 2, 3]" [value]="value">{{value}}</option>
  </select>
</form>

<form [formGroup]="form">
  <select name="field1" formControlName="field2">
    <option *ngFor="let value of [1, 2, 3]" [value]="value">{{value}}</option>
  </select>
</form>

TS:

  form;

  ngOnInit(): void {
    this.form = new FormGroup({
      field1: new FormControl(),
      field2: new FormControl()
    });

    this.form.controls.field1.valueChanges.subscribe(value => {
      value === '2' ? this.form.controls.field2.disable() : this.form.controls.field2.enable();
    });
  }


问:
All of my .json files have problems loading reference/schema from schemastore.azurewebsites.net
I'm working in VS Code and started getting this error yesterday.  All of my json files have this error, not just a few.  If I remember right there was an update to the program yesterday or the day before.  Did the update break something or reset a setting that I forgot I had set?

When looking this up, people are talking about downloading the schema and using it locally, but I would prefer not to have to do that and would instead like to find out why this broke?

I am using a proxy, but as far as I know that hasn't changed.  Here's the exact error I'm getting.

Problems loading reference 'https://schemastore.azurewebsites.net/schemas/json/package.json': Unable to load schema from 'https://schemastore.azurewebsites.net/schemas/json/package.json': Unable to connect to https://schemastore.azurewebsites.net/schemas/json/package.json. Error: connect ECONNREFUSED 168.62.224.13:443

答:
I'm behind my company's proxy which I don't know the details because it's everything automatic, and this problem have bug me for some time.

I'm not sure whether this is an universal solution but according to this issue, the http.proxySupport setting is defaulting to "override".

I turn this setting off and the errors disappeared:

```<code>"http.proxySupport": "off"
</code>```

Body:
I'm behind my company's proxy which I don't know the details because it's everything automatic, and this problem have bug me for some time.

I'm not sure whether this is an universal solution but according to this issue, the http.proxySupport setting is defaulting to "override".

I turn this setting off and the errors disappeared:

"http.proxySupport": "off"


问:
Regex conditional lookout
My input text file is like

```<code>A={5,6},B={2},C={3}
B={2,4}
A={5},B={1},C={3}
A={5},B={2},C={3,4,QWERT},D={TXT}
</code>```

I would like to match all the lines where A=5,B=2 and C=3. The catch is, if variable is not mentioned, then that variable can take any value and hence that line also needs to be matched.

Above should match line 1,2 & 4.

I tried

```<code>.*?(?:(?=A)A\{.*?5).*?(?:(?=B)B\{.*?2).*?(?:(?=C)C\{.*?3)
</code>```

https://regex101.com/r/NN9qk5/1

But, it is not working

I shall be using this regex in a python 3.6 code.

答:
If you want to solve it with a regex, you may use

```<code>^
 (?!.*\bA={(?![^{}]*\b5\b))
 (?!.*\bB={(?![^{}]*\b2\b))
 (?!.*\bC={(?![^{}]*\b3\b))
.*
</code>```

See the regex demo

The point is to fail a match if there is a key that contains no given number value inside braces.

E.g. (?!.*\bA={(?![^{}]*\b5\b)) is a negative lookahead that fails the match if, immediately to the right of the current location, there is no
 - .* - any 0+ chars other than line break chars
 - \bA - a whole word A
 - ={ - ={ substring
 - (?![^{}]*\b5\b) - that is not followed with any 0+ chars other than { and } and then followed with 5 as a whole word.

Sample usage in Python 3.6:

```<code>import re
s = """A={5,6},B={2},C={3}
B={2,4}
A={5},B={1},C={3}
A={5},B={2},C={3,4,QWERT},D={TXT}"""
given = { 'A': '5', 'B': '2', 'C': '3'}

reg_pattern = ''
for key,val in given.items():
    reg_pattern += r"(?!.*\b{}={{(?![^{{}}]*\b{}\b))".format(key,val)

reg = re.compile(reg_pattern)

for line in s.splitlines():
    if reg.match(line):
        print(line)
</code>```

Output:

```<code>A={5,6},B={2},C={3}
B={2,4}
A={5},B={2},C={3,4,QWERT},D={TXT}
</code>```

Note the use of re.match, this method only searches for a match at the start of the string, so, no need adding ^ anchor (that matches string start).

Title: Regex conditional lookout

Body:
My input text file is like

A={5,6},B={2},C={3}
B={2,4}
A={5},B={1},C={3}
A={5},B={2},C={3,4,QWERT},D={TXT}

I would like to match all the lines where A=5,B=2 and C=3. The catch is, if variable is not mentioned, then that variable can take any value and hence that line also needs to be matched.

Above should match line 1,2 & 4.

I tried

.*?(?:(?=A)A\{.*?5).*?(?:(?=B)B\{.*?2).*?(?:(?=C)C\{.*?3)

https://regex101.com/r/NN9qk5/1

But, it is not working

I shall be using this regex in a python 3.6 code.

Body:
If you want to solve it with a regex, you may use

^
 (?!.*\bA={(?![^{}]*\b5\b))
 (?!.*\bB={(?![^{}]*\b2\b))
 (?!.*\bC={(?![^{}]*\b3\b))
.*

See the regex demo

The point is to fail a match if there is a key that contains no given number value inside braces.

E.g. (?!.*\bA={(?![^{}]*\b5\b)) is a negative lookahead that fails the match if, immediately to the right of the current location, there is no
 - .* - any 0+ chars other than line break chars
 - \bA - a whole word A
 - ={ - ={ substring
 - (?![^{}]*\b5\b) - that is not followed with any 0+ chars other than { and } and then followed with 5 as a whole word.

Sample usage in Python 3.6:

import re
s = """A={5,6},B={2},C={3}
B={2,4}
A={5},B={1},C={3}
A={5},B={2},C={3,4,QWERT},D={TXT}"""
given = { 'A': '5', 'B': '2', 'C': '3'}

reg_pattern = ''
for key,val in given.items():
    reg_pattern += r"(?!.*\b{}={{(?![^{{}}]*\b{}\b))".format(key,val)

reg = re.compile(reg_pattern)

for line in s.splitlines():
    if reg.match(line):
        print(line)

Output:

A={5,6},B={2},C={3}
B={2,4}
A={5},B={2},C={3,4,QWERT},D={TXT}

Note the use of re.match, this method only searches for a match at the start of the string, so, no need adding ^ anchor (that matches string start).


问:
C++ creating new operators and overloading the current ones
I am writing code for transposing a matrix as a part of learning C++. What I am doing is operator overloading. But, usually the notation for transposing a matrix is '.

Is ' even an operator? I understand if it is between ' ' you notate a character, and if you use " " you notate a string. But are these operators or not? Can I overload them as individual characters or even as whole?

Can I make new operators in C++ that only work on an object of a specific class? The trick I've used is overloading the known operators like +, -, ^, ... and then with #define I change how the preprocessor processes the text, but in the end I would still override an existing operator and I cannot use any of the special symbols but rather letters.

答:
Operator overloading is limited to the existing set of C++ operators. It's operator overloading, not creation. You cannot make new operators like @, nor can you turn non-operator characters like ' into operators.

Can I make new operators in C++ that only work on an object of a specific class?

You can't make new operators. You can only repurpose existing ones.

...then with #define I change how the preprocessor processes the text...

You probably shouldn't be doing that. Stay away from the preprocessor. It's a tool of last resort.


问:
aws lambda fails with jdk 11
I am trying to  build an spring boot application with jdk 11 on   aws lambda.

I followed tutorial on https://dzone.com/articles/aws-lambda-with-spring-boot and code base of  https://github.com/gemerick/spring-boot-lambda/tree/lambda. It worked fine with java 8. Then I changed the
Runtime: java8 to java11 in sam.yaml but deploy failed with following reason

```<code>        "ResourceStatusReason": "Value java11 at 'runtime' failed to satisfy constraint:
Member must satisfy enum value set:
    [java8, nodejs6.10, nodejs8.10, python2.7, python3.6, dotnetcore1.0, dotnetcore2.0, dotnetcore2.1, go1.x] or
    be a valid ARN (Service: AWSLambdaInternal; Status Code: 400; Error Code: InvalidParameterValueException;)
</code>```

As far as I understood aws lambda, does not support jdk 11.  Then I read that corretto 11 is out https://aws.amazon.com/about-aws/whats-new/2019/03/amazon-corretto-11-is-now-generally-available/

Does the release of corretto 11 means that aws-lambda support java 11? I could not see  any official doc about it. It was my first application with aws lambda. Therefore I am bit confused.

Can anyone please point me about support of jdk 11 with aws lambda

答:
Only Java 8 is currently supported in lambda. See https://docs.aws.amazon.com/lambda/latest/dg/java-programming-model.html

Edit: you can check out how to use Java 11 as a custom runtime. See https://stackoverflow.com/a/54799017/4814697

Title: aws lambda fails with jdk 11

Body:
I am trying to  build an spring boot application with jdk 11 on   aws lambda.

I followed tutorial on https://dzone.com/articles/aws-lambda-with-spring-boot and code base of  https://github.com/gemerick/spring-boot-lambda/tree/lambda. It worked fine with java 8. Then I changed the
Runtime: java8 to java11 in sam.yaml but deploy failed with following reason

        "ResourceStatusReason": "Value java11 at 'runtime' failed to satisfy constraint:
Member must satisfy enum value set:
    [java8, nodejs6.10, nodejs8.10, python2.7, python3.6, dotnetcore1.0, dotnetcore2.0, dotnetcore2.1, go1.x] or
    be a valid ARN (Service: AWSLambdaInternal; Status Code: 400; Error Code: InvalidParameterValueException;)

As far as I understood aws lambda, does not support jdk 11.  Then I read that corretto 11 is out https://aws.amazon.com/about-aws/whats-new/2019/03/amazon-corretto-11-is-now-generally-available/

Does the release of corretto 11 means that aws-lambda support java 11? I could not see  any official doc about it. It was my first application with aws lambda. Therefore I am bit confused.

Can anyone please point me about support of jdk 11 with aws lambda


答:
You cannot create operators that don't exist as part of the C++ standard. They would not be part of the grammar and would lead to syntax errors.

So operator possibilities are linked to what the language syntax and grammar authorize (see @afenster answer for a link to the list).

On a side note, this operator issue is also a true in other languages like Python, where the committee needs to decide whether adding a new operator (like @ for matrix multiplication) makes sense for the language or not. Lots of operators are derived from mathematical expressions, so adding new operators that don't have this mathematical background would not make sense (exceptions are *, (), for instance)

Title: C++ creating new operators and overloading the current ones

Body:
I am writing code for transposing a matrix as a part of learning C++. What I am doing is operator overloading. But, usually the notation for transposing a matrix is '.

Is ' even an operator? I understand if it is between ' ' you notate a character, and if you use " " you notate a string. But are these operators or not? Can I overload them as individual characters or even as whole?

Can I make new operators in C++ that only work on an object of a specific class? The trick I've used is overloading the known operators like +, -, ^, ... and then with #define I change how the preprocessor processes the text, but in the end I would still override an existing operator and I cannot use any of the special symbols but rather letters.


答: The list of operators you can overload is here. Unfortunately (or fortunately), you cannot use any other character as an operator. The most basic reason for that is that operator overloading does not and must not change the logic of the syntax parsing of your code (such as what is an operator and what is not, what is the operator precedence, etc.).</p>


问:
Create Git Log using Gitlab CI
We need to generate commit history file automatically when user commits code into git repository.

It can be done using Jenkins, Gitlab Webhooks and Jenkins Git Changelog plugin. Also, it can be created using below git command.

```<code>$ git log --pretty=format:'At %ci, %cN committed %h : %s' --decorate --graph >log.log
</code>```

But, is there anyway we can generate commit history file using Gitlab CI/CD operations. The file can be saved in git repositry or local storage.

Sample Commit History File

```<code>* At 2018-11-16 18:02:21, kRiZ committed 1714a95 : Commit 4
* At 2018-11-15 16:06:06, kRiZ committed bab5c0c : Commit 3
* At 2018-11-14 18:05:09, kRiZ committed b3c9d86 : Commit 2
* At 2018-11-14 06:47:34, kRiZ committed 8e6ee30 : Add README.md
</code>```

答:
The library used by the Jenkins plugin also has a command line tool that can be used in anywhere:</p>

```<code>npx git-changelog-command-line -std -tec "
# Changelog

Changelog for {{ownerName}} {{repoName}}.

{{#tags}}
## {{name}}
 {{#issues}}
  {{#hasIssue}}
   {{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
   {{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
  {{/hasIssue}}
  {{^hasIssue}}
### {{name}}
  {{/hasIssue}}

  {{#commits}}
**{{{messageTitle}}}**

{{#messageBodyItems}}
 * {{.}}
{{/messageBodyItems}}

[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*

  {{/commits}}

 {{/issues}}
{{/tags}}
"
</code>```

Title: Create Git Log using Gitlab CI

Body:
We need to generate commit history file automatically when user commits code into git repository.

It can be done using Jenkins, Gitlab Webhooks and Jenkins Git Changelog plugin. Also, it can be created using below git command.

$ git log --pretty=format:'At %ci, %cN committed %h : %s' --decorate --graph >log.log

But, is there anyway we can generate commit history file using Gitlab CI/CD operations. The file can be saved in git repositry or local storage.

Sample Commit History File

* At 2018-11-16 18:02:21, kRiZ committed 1714a95 : Commit 4
* At 2018-11-15 16:06:06, kRiZ committed bab5c0c : Commit 3
* At 2018-11-14 18:05:09, kRiZ committed b3c9d86 : Commit 2
* At 2018-11-14 06:47:34, kRiZ committed 8e6ee30 : Add README.md

Body:
The library used by the Jenkins plugin also has a command line tool that can be used in anywhere:

npx git-changelog-command-line -std -tec "
# Changelog

Changelog for {{ownerName}} {{repoName}}.

{{#tags}}
## {{name}}
 {{#issues}}
  {{#hasIssue}}
   {{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
   {{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
  {{/hasIssue}}
  {{^hasIssue}}
### {{name}}
  {{/hasIssue}}

  {{#commits}}
**{{{messageTitle}}}**

{{#messageBodyItems}}
 * {{.}}
{{/messageBodyItems}}

[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*

  {{/commits}}

 {{/issues}}
{{/tags}}
"


问:
how to setup nodejs webapp as service?
I have nodejs installed, npm installed, modules installed, and my app codes. On my dev machine I simply type node app.js in my app folder to start the dev server, but now it's the time to deploy it to a real server I got problem.

Where is the regular folder to place my app codes.

Which user should be use to run my nodejs app. and how to make the user only have permission to execute app codes, and 80, 443, 843 ports.

How to write the service script, and stop server by kill pid?

答:
ports are determined by which port your app listens on. If you have physical access via ssh to a server and have root privileges etc then you can just treat it as a dev server.

I would recommend forever for keeping it running and maybe a writing a balancer to handle multiple node apps at once.

Permission handling has to be done based on connectivity. A user connects to your service and you authenticate it for its permission levels. This is done by hand.

The folder you place it is not very relevant.

If you have say a no.de server you can learn how to use their smart machines. THere are similar guides for say the Amazon EC2.

Title: how to setup nodejs webapp as service?


问:
How can I ensure tests with a marker are only run if explicitly asked in pytest?
I have some tests I marked with an appropriate marker. If I run pytest, by default they run, but I would like to skip them by default. The only option I know is to explicitly say "not marker" at pytest invocation, but I would like them not to run by default unless the marker is explicitly asked at command line.</p>

答:
A slight modification of the example in Control skipping of tests according to command line option:

```<code># conftest.py

import pytest

def pytest_collection_modifyitems(config, items):
    keywordexpr = config.option.keyword
    markexpr = config.option.markexpr
    if keywordexpr or markexpr:
        return  # let pytest handle this

    skip_mymarker = pytest.mark.skip(reason='mymarker not selected')
    for item in items:
        if 'mymarker' in item.keywords:
            item.add_marker(skip_mymarker)
</code>```

Example tests:

```<code>import pytest

def test_not_marked():
    pass

@pytest.mark.mymarker
def test_marked():
    pass
</code>```

Running the tests with the marker:

```<code>$ pytest -v -k mymarker
...
collected 2 items / 1 deselected / 1 selected
test_spam.py::test_marked PASSED
...
</code>```

Or:

```<code>$ pytest -v -m mymarker
...
collected 2 items / 1 deselected / 1 selected
test_spam.py::test_marked PASSED
...
</code>```

Without the marker:

```<code>$ pytest -v
...
collected 2 items

test_spam.py::test_not_marked PASSED
test_spam.py::test_marked SKIPPED
...
</code>```

Body:
A slight modification of the example in Control skipping of tests according to command line option:

# conftest.py

import pytest

def pytest_collection_modifyitems(config, items):
    keywordexpr = config.option.keyword
    markexpr = config.option.markexpr
    if keywordexpr or markexpr:
        return  # let pytest handle this

    skip_mymarker = pytest.mark.skip(reason='mymarker not selected')
    for item in items:
        if 'mymarker' in item.keywords:
            item.add_marker(skip_mymarker)

Example tests:

import pytest

def test_not_marked():
    pass

@pytest.mark.mymarker
def test_marked():
    pass

Running the tests with the marker:

$ pytest -v -k mymarker
...
collected 2 items / 1 deselected / 1 selected
test_spam.py::test_marked PASSED
...

Or:

$ pytest -v -m mymarker
...
collected 2 items / 1 deselected / 1 selected
test_spam.py::test_marked PASSED
...

Without the marker:

$ pytest -v
...
collected 2 items

test_spam.py::test_not_marked PASSED
test_spam.py::test_marked SKIPPED
...


问:
Two part post request to get CSRF Token then make another request
I'm attempting to access data by first logging in to the following site:
https://accessns.nscorp.com/accessNS/login/

It looks like it sends this requests to the backend:

Request URL: https://accessns.nscorp.com/accessNS/rest/auth/login

Request Method: POST

Status Code: 200 OK

Remote Address:167.121.11.85:443

Referrer    Policy:    no-referrer-when-downgrade

When I send that request in python, I'm able to get a response back with a CSRF Token.

Next, I would like to access:

Request URL:
https://accessns.nscorp.com/accessNS/rest/backend/ServicesIndustrial/services/industrial2/v2/onsite/details

Request Method: POST

Status Code: 200 OK Remote Address:
     167.121.11.85:443

Referrer Policy: no-referrer-when-downgrade

Which takes the following headers:

Accept: /

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.9

Connection: keep-alive

Content-Length: 58

Content-Type: application/json

Cookie: [some cookies]

CSRFTOKEN: [from auth request above]

Host: accessns.nscorp.com

Origin: https://accessns.nscorp.com

Referer: https://accessns.nscorp.com/accessNS/legacy/

User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36

Payload:
{userId: "username", classCode: "classcode", stationCode: "stationcode"}

My code fails when I attempt to use CSRF Token and cookies from the authorization request into the secondary request, but it doesn't fail when I manually login to the site, get the token/cookies, and hard code them into python.  In fact, all I need in terms of headers for the secodary request is CSRF Token and cookies to get a viable response.

```<code>with requests.Session() as s:

    login = {'Id': 'username', 'pwd': 'password'}
    auth = s.post('https://accessns.nscorp.com/accessNS/rest/auth/login',
                   json=login)

    headers = {}
    headers['CSRFTOKEN'] = auth.json()['response']['token']
    headers['Cookie'] = '; '.join('='.join((i.name, i.value)) for i in
                                  auth.cookies)

    payload = {'userId': 'username', 'classCode': 'classcode',
               'stationCode': 'stationcode'}

    url =
    'https://accessns.nscorp.com/accessNS/rest/backend/ServicesIndustrial/
     services/industrial2/v2/onsite/details'

    inv= s.post(url, json=payload, headers=headers)

    print(inv.json())
</code>```

I expect to get a json response with the data I've requests, however, using my code, I get:

{'time': 1559217902355, 'message': 'Object reference not set to an instance of an object.. Reference number: 1559217902355', 'cause': 'Invalid user input', 'isError': True}, which to me seems like it's an issue with my headers/payload, or I'm missing an intermediate step.

When I hardcode the csrf token/cookies and don't use a requests session, I get the response I want.

答: Figured it out, my code works fine.  Turns out the secondary request was being made to the wrong URL, which is strange because that's what's listed in every developer console I've checked.  </p>

Body:
I'm attempting to access data by first logging in to the following site:
https://accessns.nscorp.com/accessNS/login/

It looks like it sends this requests to the backend:

Request URL: https://accessns.nscorp.com/accessNS/rest/auth/login

Request Method: POST

Status Code: 200 OK

Remote Address:167.121.11.85:443

Referrer    Policy:    no-referrer-when-downgrade

When I send that request in python, I'm able to get a response back with a CSRF Token.

Next, I would like to access:

Request URL:
https://accessns.nscorp.com/accessNS/rest/backend/ServicesIndustrial/services/industrial2/v2/onsite/details

Request Method: POST

Status Code: 200 OK Remote Address:
     167.121.11.85:443

Referrer Policy: no-referrer-when-downgrade

Which takes the following headers:

Accept: /

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.9

Connection: keep-alive

Content-Length: 58

Content-Type: application/json

Cookie: [some cookies]

CSRFTOKEN: [from auth request above]

Host: accessns.nscorp.com

Origin: https://accessns.nscorp.com

Referer: https://accessns.nscorp.com/accessNS/legacy/

User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36

Payload:
{userId: "username", classCode: "classcode", stationCode: "stationcode"}

My code fails when I attempt to use CSRF Token and cookies from the authorization request into the secondary request, but it doesn't fail when I manually login to the site, get the token/cookies, and hard code them into python.  In fact, all I need in terms of headers for the secodary request is CSRF Token and cookies to get a viable response.

with requests.Session() as s:

    login = {'Id': 'username', 'pwd': 'password'}
    auth = s.post('https://accessns.nscorp.com/accessNS/rest/auth/login',
                   json=login)

    headers = {}
    headers['CSRFTOKEN'] = auth.json()['response']['token']
    headers['Cookie'] = '; '.join('='.join((i.name, i.value)) for i in
                                  auth.cookies)

    payload = {'userId': 'username', 'classCode': 'classcode',
               'stationCode': 'stationcode'}

    url =
    'https://accessns.nscorp.com/accessNS/rest/backend/ServicesIndustrial/
     services/industrial2/v2/onsite/details'

    inv= s.post(url, json=payload, headers=headers)

    print(inv.json())

I expect to get a json response with the data I've requests, however, using my code, I get:

{'time': 1559217902355, 'message': 'Object reference not set to an instance of an object.. Reference number: 1559217902355', 'cause': 'Invalid user input', 'isError': True}, which to me seems like it's an issue with my headers/payload, or I'm missing an intermediate step.

When I hardcode the csrf token/cookies and don't use a requests session, I get the response I want.


问:
Generic parameter 'Value' could not be inferred
I am trying to make a Data-Storage using NSCoder, for some weird reason, its showing this error to me where i try to use the <code>.encode</code> keyword, please help me understand what i'm doing wrong..     </p>

```<code>let encoder = PropertyListEncoder()

do {
    let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}
</code>```

答:
This fixed for me in Swift iOS.

Inherit Codable in the class which you are trying to encode.

In your case,

```<code>let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}
</code>```

Let's assume itemArray is the array of a class named 'Item'. Then your 'Item' needs to inherit Codable in swift.

Just as below.

```<code>import Foundation

class Item: Codable {
    var id: Int!
}
</code>```

All the best!

Body:
I am trying to make a Data-Storage using NSCoder, for some weird reason, its showing this error to me where i try to use the .encode keyword, please help me understand what i'm doing wrong..

let encoder = PropertyListEncoder()

do {
    let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}

Body:
This fixed for me in Swift iOS.

Inherit Codable in the class which you are trying to encode.

In your case,

let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}

Let's assume itemArray is the array of a class named 'Item'. Then your 'Item' needs to inherit Codable in swift.

Just as below.

import Foundation

class Item: Codable {
    var id: Int!
}

All the best!


答:
Give this a try:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  selectedFruit = null;
  fruits = [
    { name: 'Apple', code: 'Apple' },
    { name: 'Mango', code: 'Mango' },
    { name: 'Orange', code: 'Orange' },
    { name: 'Grapes', code: 'Grapes' },
    { name: 'Peach', code: 'Peach' },
  ];

  models = [
    { name: 'iPhone XS Max', code: 'iPhone XS Max' },
    { name: 'iPhone XS', code: 'iPhone XS' },
    { name: 'iPhone X', code: 'iPhone X' },
    { name: 'iPhone 8 Plus', code: 'iPhone 8 Plus' },
    { name: 'iPhone 8', code: 'iPhone 8' },
  ]
}
</code>```

And in your template:

```<code><h2>Fruits</h2>
<select class="custom-select" id="abc" [(ngModel)]="selectedFruit">
  <option value="null" hidden>Select</option>
  <option *ngFor="let fruit of fruits" [ngValue]="fruit.code"> {{fruit.name}}</option>
</select>

<h2>Phone Models</h2>
<select class="custom-select" id="abc" [disabled]="selectedFruit !== 'Apple'">
  <option value="" hidden>Select</option>
  <option *ngFor="let model of models" [ngValue]="model.code"> {{model.name}}</option>
</select>
</code>```

Here's a Working Sample StackBlitz for your ref.

Title: how to disable/enable dropdown angular 4

Body:
Give this a try:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  selectedFruit = null;
  fruits = [
    { name: 'Apple', code: 'Apple' },
    { name: 'Mango', code: 'Mango' },
    { name: 'Orange', code: 'Orange' },
    { name: 'Grapes', code: 'Grapes' },
    { name: 'Peach', code: 'Peach' },
  ];

  models = [
    { name: 'iPhone XS Max', code: 'iPhone XS Max' },
    { name: 'iPhone XS', code: 'iPhone XS' },
    { name: 'iPhone X', code: 'iPhone X' },
    { name: 'iPhone 8 Plus', code: 'iPhone 8 Plus' },
    { name: 'iPhone 8', code: 'iPhone 8' },
  ]
}

And in your template:

<h2>Fruits</h2>
<select class="custom-select" id="abc" [(ngModel)]="selectedFruit">
  <option value="null" hidden>Select</option>
  <option *ngFor="let fruit of fruits" [ngValue]="fruit.code"> {{fruit.name}}</option>
</select>

<h2>Phone Models</h2>
<select class="custom-select" id="abc" [disabled]="selectedFruit !== 'Apple'">
  <option value="" hidden>Select</option>
  <option *ngFor="let model of models" [ngValue]="model.code"> {{model.name}}</option>
</select>

Here's a Working Sample StackBlitz for your ref.


问:
Spring Cloud Config client doesn't get values from server
I have been following this tutorial from Baeldung in setting up a Spring Cloud Config server and client. I believe I have set up the server correctly since going to http://localhost:8888/service-config/development/master will seemingly correctly show the json with the user.role defined:

```<code>{"name":"service-config","profiles":["development"],"label":"master","version":"d30a6015a6b8cb1925f6e61cee22721f331e5783","state":null,"propertySources":[{"name":"file:///C:.../git/service-config-data/service-config-development.properties","source":{"user.role":"Developer"}},{"name":"file:///C:.../git/service-config-data/service-config.properties","source":{"user.role":"Developer"}}]}
</code>```

However, I cannot seem to correctly connect the Spring Cloud Config client to the server - the client fails to run with cannot resolve placeholder errors on the @Value("${user.role}") annotation. I've tried adding a default value to the annotation and then manually refreshing the values (using the @refreshscope annotation), but to no avail.

I've looked at the debug and trace logs by running the tools with --debug --trace flags but I cannot find when/if the client is making the call to the server and which config-data .properties file the server is actually looking for. I am a bit lost on how to proceed.

Here is my server application.properties:

```<code>spring.application.name=service-config
server.port=8888
spring.cloud.config.server.git.uri=file:///${user.home}/git/service-config-data
spring.cloud.config.server.git.clone-on-start=false
spring.security.user.name=root
spring.security.user.password=toor
</code>```

And inside the service-config-data folder, there are files with this inside:

```<code>user.role=Developer
</code>```

I have tried files called service-config.properties, service-config-client.properties, service-config-development.properties, and service-config-client-development.properties, and none of them seem to pull through the user.role.

Here is my client:

```<code>@SpringBootApplication
@RestController
@RefreshScope
public class ServiceConfigClient {

    @Value("${user.role:unknown}")
    private String role;

    @RequestMapping(
      value = "/whoami/{username}",
      method = RequestMethod.GET,
      produces = MediaType.TEXT_PLAIN_VALUE)
    public String whoami(@PathVariable("username") String username) {
        return String.format("Hello! You're %s and you'll become a(n) %s...\n", username, role);
    }
}
</code>```

And my client bootstrap.properties:

```<code>spring.application.name=service-config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.username=root
spring.cloud.config.password=toor

management.endpoints.web.exposure.include=*
</code>```

How do I correctly connect the client to the server so that it can successfully pull the config data? Thank you.

答: My problem was fixed by adding spring.cloud.config.name=service-config to the bootstrap.properties of the service-config-client as well as adding spring-cloud-config-client to and removing spring-cloud-config-server from my pom.xml

Body:
I have been following this tutorial from Baeldung in setting up a Spring Cloud Config server and client. I believe I have set up the server correctly since going to http://localhost:8888/service-config/development/master will seemingly correctly show the json with the user.role defined:

{"name":"service-config","profiles":["development"],"label":"master","version":"d30a6015a6b8cb1925f6e61cee22721f331e5783","state":null,"propertySources":[{"name":"file:///C:.../git/service-config-data/service-config-development.properties","source":{"user.role":"Developer"}},{"name":"file:///C:.../git/service-config-data/service-config.properties","source":{"user.role":"Developer"}}]}

However, I cannot seem to correctly connect the Spring Cloud Config client to the server - the client fails to run with cannot resolve placeholder errors on the @Value("${user.role}") annotation. I've tried adding a default value to the annotation and then manually refreshing the values (using the @refreshscope annotation), but to no avail.

I've looked at the debug and trace logs by running the tools with --debug --trace flags but I cannot find when/if the client is making the call to the server and which config-data .properties file the server is actually looking for. I am a bit lost on how to proceed.

Here is my server application.properties:

spring.application.name=service-config
server.port=8888
spring.cloud.config.server.git.uri=file:///${user.home}/git/service-config-data
spring.cloud.config.server.git.clone-on-start=false
spring.security.user.name=root
spring.security.user.password=toor

And inside the service-config-data folder, there are files with this inside:

user.role=Developer

I have tried files called service-config.properties, service-config-client.properties, service-config-development.properties, and service-config-client-development.properties, and none of them seem to pull through the user.role.

Here is my client:

@SpringBootApplication
@RestController
@RefreshScope
public class ServiceConfigClient {

    @Value("${user.role:unknown}")
    private String role;

    @RequestMapping(
      value = "/whoami/{username}",
      method = RequestMethod.GET,
      produces = MediaType.TEXT_PLAIN_VALUE)
    public String whoami(@PathVariable("username") String username) {
        return String.format("Hello! You're %s and you'll become a(n) %s...\n", username, role);
    }
}

And my client bootstrap.properties:

spring.application.name=service-config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.username=root
spring.cloud.config.password=toor

management.endpoints.web.exposure.include=*

How do I correctly connect the client to the server so that it can successfully pull the config data? Thank you.


问:
Trying to add Discord alerts/hooks to an existing python code
So i want to monitor a webpage, and if a change occurs, i would like to be notified of that via Discord.

Searching google, i landed on this page https://www.adventuresintechland.com/detect-when-a-webpage-changes-with-python/

and it seems to work when i test it on my website.
But i would like to add Discord alerts to this code but seem to be stuck

i have looked into Dhooks on github and have been stuck trying to implement it

```<code># Hunter Thornsberry
# http://www.adventuresintechland.com

# WebChange.py
# Alerts you when a webpage has changed it's content by comparing checksums of the html.

import hashlib
import urllib2
import random
import time

# url to be scraped
url = "http://raw.adventuresintechland.com/freedom.html"

# time between checks in seconds
sleeptime = 60

def getHash():
    # random integer to select user agent
    randomint = random.randint(0,7)

    # User_Agents
    # This helps skirt a bit around servers that detect repeaded requests from the same machine.
    # This will not prevent your IP from getting banned but will help a bit by pretending to be different browsers
    # and operating systems.
    user_agents = [
        'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
        'Opera/9.25 (Windows NT 5.1; U; en)',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
        'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
        'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:8.0.1) Gecko/20100101 Firefox/8.0.1',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19'
    ]

    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', user_agents[randomint])]
    response = opener.open(url)
    the_page = response.read()

    return hashlib.sha224(the_page).hexdigest()

current_hash = getHash() # Get the current hash, which is what the website is now

while 1: # Run forever
    if getHash() == current_hash: # If nothing has changed
        print "Not Changed"
    else: # If something has changed
        print "Changed"
        break
    time.sleep(sleeptime)
</code>```

答:
You will need to connect to the discord API to send a message on event. The information can be found here and here.

It is worth noting that the discord python library is currently only compatible with python 3.6, so you will have to run

```<code>pip install -U discord.py
</code>```

on python version 3.6 rather than python 3.7.

Body:
So i want to monitor a webpage, and if a change occurs, i would like to be notified of that via Discord.

Searching google, i landed on this page https://www.adventuresintechland.com/detect-when-a-webpage-changes-with-python/

and it seems to work when i test it on my website.
But i would like to add Discord alerts to this code but seem to be stuck

i have looked into Dhooks on github and have been stuck trying to implement it

# Hunter Thornsberry
# http://www.adventuresintechland.com

# WebChange.py
# Alerts you when a webpage has changed it's content by comparing checksums of the html.

import hashlib
import urllib2
import random
import time

# url to be scraped
url = "http://raw.adventuresintechland.com/freedom.html"

# time between checks in seconds
sleeptime = 60

def getHash():
    # random integer to select user agent
    randomint = random.randint(0,7)

    # User_Agents
    # This helps skirt a bit around servers that detect repeaded requests from the same machine.
    # This will not prevent your IP from getting banned but will help a bit by pretending to be different browsers
    # and operating systems.
    user_agents = [
        'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
        'Opera/9.25 (Windows NT 5.1; U; en)',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
        'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
        'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:8.0.1) Gecko/20100101 Firefox/8.0.1',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19'
    ]

    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', user_agents[randomint])]
    response = opener.open(url)
    the_page = response.read()

    return hashlib.sha224(the_page).hexdigest()

current_hash = getHash() # Get the current hash, which is what the website is now

while 1: # Run forever
    if getHash() == current_hash: # If nothing has changed
        print "Not Changed"
    else: # If something has changed
        print "Changed"
        break
    time.sleep(sleeptime)

Body:
You will need to connect to the discord API to send a message on event. The information can be found here and here.

It is worth noting that the discord python library is currently only compatible with python 3.6, so you will have to run

pip install -U discord.py

on python version 3.6 rather than python 3.7.


问:
Has many through many-to-many
I have the following table layout:

```<code>deals:
- id
- price

products:
- id
- name

deal_product:
- id
- deal_id
- product_id

metrics:
- id
- name

metric_product:
- id
- metric_id
- product_id
- value
</code>```

products and metrics have a many-to-many relationship with a pivot column of value.

deals and products also have a many-to-many relationship.

I can get metrics for a product with $product->metrics, but I want to be able to get all metrics for all products related to a deal, so I could do something like this: $deal->metrics.

I currently have the following in my Deal model:

```<code>public function metrics()
{
    $products = $this->products()->pluck('products.id')->all();

    return Metric::whereHas('products', function (Builder $query) use ($products) {
        $query->whereIn('products.id', $products);
    });
}
</code>```

But this doesn't return a relationship, so I cannot eager load it or get related models from it.

It needs to be in relationship format, because they need to be eager loaded for my use case.

Thanks for your help!

答:
In case anyone is still researching this, check out this package I recently developed. It provides you with a belongsToManyThrough() relationship and is super easy to install and use :)

https://github.com/shomisha/unusual-relationships

Title: Has many through many-to-many

Body:
I have the following table layout:

deals:
- id
- price

products:
- id
- name

deal_product:
- id
- deal_id
- product_id

metrics:
- id
- name

metric_product:
- id
- metric_id
- product_id
- value

products and metrics have a many-to-many relationship with a pivot column of value.

deals and products also have a many-to-many relationship.

I can get metrics for a product with $product->metrics, but I want to be able to get all metrics for all products related to a deal, so I could do something like this: $deal->metrics.

I currently have the following in my Deal model:

public function metrics()
{
    $products = $this->products()->pluck('products.id')->all();

    return Metric::whereHas('products', function (Builder $query) use ($products) {
        $query->whereIn('products.id', $products);
    });
}

But this doesn't return a relationship, so I cannot eager load it or get related models from it.

It needs to be in relationship format, because they need to be eager loaded for my use case.

Thanks for your help!


问:
Replace value with the value of nearest neighbor in Pandas dataframe
I have a problem with getting nearest values for some rows in pandas dataframe and fill another column with values from those rows.

data sample I have:

```<code>id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      100
A      A5      250      3
A      A6      250      100
B      B1      0        1
B      B2      30       2
</code>```

The thing is, wherever match_v is equal to 100, I need to replace that 100 with a value from the row where r_value is the closest to r_value from origin row(where match_v is equal to 100), but just withing group (grouped by id)

Expected output

```<code>id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      2
A      A5      250      3
A      A6      250      3
B      B1      0        1
B      B2      30       2
</code>```

I have tried with creating lead and leg with shift and then finding differences. But doesn't work well and it somehow messed up already good values.
I haven't tried anything else cause I really don't have any idea.

Any help or hint is welcomed and I if you need any additional info, I'm here.

Thanks in advance.

答:
Assuming there is always at least one valid value within the group when a 100 is first encountered.</p>

```<code>m = dict()
for i in range(len(df)):
    if df.loc[i, "match_v"] == 100:
        df.loc[i, "match_v"] = m[df.loc[i, "id"]]
    else:
        m[df.loc[i, "id"]] = df.loc[i, "match_v"]
</code>```

Body:
I have a problem with getting nearest values for some rows in pandas dataframe and fill another column with values from those rows.

data sample I have:

id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      100
A      A5      250      3
A      A6      250      100
B      B1      0        1
B      B2      30       2

The thing is, wherever match_v is equal to 100, I need to replace that 100 with a value from the row where r_value is the closest to r_value from origin row(where match_v is equal to 100), but just withing group (grouped by id)

Expected output

id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      2
A      A5      250      3
A      A6      250      3
B      B1      0        1
B      B2      30       2

I have tried with creating lead and leg with shift and then finding differences. But doesn't work well and it somehow messed up already good values.
I haven't tried anything else cause I really don't have any idea.

Any help or hint is welcomed and I if you need any additional info, I'm here.

Thanks in advance.

Body:
Assuming there is always at least one valid value within the group when a 100 is first encountered.

m = dict()
for i in range(len(df)):
    if df.loc[i, "match_v"] == 100:
        df.loc[i, "match_v"] = m[df.loc[i, "id"]]
    else:
        m[df.loc[i, "id"]] = df.loc[i, "match_v"]


问:
How to send and receive a generically typed object in a list
I'm trying to create a class in which I have two override functions via an interface. The interface will be generically typed and I want the functions to simple be conversions.

I've been able to make this work, however, when I create multiples of these objects and put them into a list and access them singularly then the function that should take the generic type as input gives the error: Type mismatch: inferred type is Any but Nothing was expected

In other words:

```<code>interface ConverterInterface<T>{
    fun sender(value: T): ByteArray
    fun receiver(bytes: ByteArray): T
}
</code>```

And this does work when first implemented:

```<code>class TestClass {
    val objA = object: ConverterInterface<String>{
        override fun sender(value: String): ByteArray {
            //...
        }

        override fun receiver(bytes: ByteArray): String {
            //...
        }
    }
}
</code>```

However, I want to store a list of these objects and access them later.

```<code>fun test(){
    val testList: List<ConverterInterface<*>> = listOf(objA)

    // This works
    testList[0].receiver(byteArrayOf())

    // This does not
    testList[0].sender("")
    /* Out-projected type 'ConverterInterface<*>' prohibits the use of
    'public abstract fun sender(value: T): ByteArray defined in ConverterInterface */
}
</code>```

I had to use the wildcard * for the list type because if I tried to use Any I would get a type inference failed error. To make it work I could set the type as out Any but this doesn't fix anything and causes only the receiver function to work.

I feel that what I'm trying to do may not be possible. Simply put I want to be able to access these functions without doing type casting.

答:
I'm not sure if this even a good solution but here is what I have come up with. I've created an abstract class that implements the interface but also contains a predefined function for the sender that casts to T internally:

```<code>interface ConverterInterface<T>{
    fun sender(value: T): ByteArray
    fun receiver(bytes: ByteArray): T
}

abstract class TestClass<T> : ConverterInterface<T>{
    fun realSender(value: Any): ByteArray{
        @Suppress("UNCHECKED_CAST")
        return sender(value as T)
    }
}

val testObj = object: TestClass<String>(){
    override fun sender(value: String): ByteArray {
        return byteArrayOf()
    }
    override fun receiver(bytes: ByteArray): String {
        return ""
    }

}

val testList: List<TestClass<*>> = listOf(testObj)

fun a(){
    testList[0].realSender("")
    testList[0].receiver(byteArrayOf())
}
</code>```

I understand that the function now accepts whatever is put into it and that this could cause exceptions, but as of the moment this is all I can come up with as a solution. Also, in my case at least, the class's functions should never receive anything other than their generic so a value of a different type being passed in would truly be an exception.

Body:
I'm trying to create a class in which I have two override functions via an interface. The interface will be generically typed and I want the functions to simple be conversions.

I've been able to make this work, however, when I create multiples of these objects and put them into a list and access them singularly then the function that should take the generic type as input gives the error: Type mismatch: inferred type is Any but Nothing was expected

In other words:

interface ConverterInterface<T>{
    fun sender(value: T): ByteArray
    fun receiver(bytes: ByteArray): T
}

And this does work when first implemented:

class TestClass {
    val objA = object: ConverterInterface<String>{
        override fun sender(value: String): ByteArray {
            //...
        }

        override fun receiver(bytes: ByteArray): String {
            //...
        }
    }
}

However, I want to store a list of these objects and access them later.

fun test(){
    val testList: List<ConverterInterface<*>> = listOf(objA)

    // This works
    testList[0].receiver(byteArrayOf())

    // This does not
    testList[0].sender("")
    /* Out-projected type 'ConverterInterface<*>' prohibits the use of
    'public abstract fun sender(value: T): ByteArray defined in ConverterInterface */
}

I had to use the wildcard * for the list type because if I tried to use Any I would get a type inference failed error. To make it work I could set the type as out Any but this doesn't fix anything and causes only the receiver function to work.

I feel that what I'm trying to do may not be possible. Simply put I want to be able to access these functions without doing type casting.

Body:
I'm not sure if this even a good solution but here is what I have come up with. I've created an abstract class that implements the interface but also contains a predefined function for the sender that casts to T internally:

interface ConverterInterface<T>{
    fun sender(value: T): ByteArray
    fun receiver(bytes: ByteArray): T
}

abstract class TestClass<T> : ConverterInterface<T>{
    fun realSender(value: Any): ByteArray{
        @Suppress("UNCHECKED_CAST")
        return sender(value as T)
    }
}

val testObj = object: TestClass<String>(){
    override fun sender(value: String): ByteArray {
        return byteArrayOf()
    }
    override fun receiver(bytes: ByteArray): String {
        return ""
    }

}

val testList: List<TestClass<*>> = listOf(testObj)

fun a(){
    testList[0].realSender("")
    testList[0].receiver(byteArrayOf())
}

I understand that the function now accepts whatever is put into it and that this could cause exceptions, but as of the moment this is all I can come up with as a solution. Also, in my case at least, the class's functions should never receive anything other than their generic so a value of a different type being passed in would truly be an exception.