问:
Android recyclerview and fragment : put my data fetch into my recycler view
I'm stuck with this since 1 week and I can't get why my data fetch are not displayed into my cardAdaptater. I can see they are fetched well but I can't acces to them after it in the fragment

Here is my HomePageFragment where data should be displayed

```<code>class HomePage {
    class HomeFragment : Fragment(), HeaderScrollBarAdapter.ItemClickListener {

        private var cardAdapter: HomeCardItemAdapter? = null
        private val url = "https://kolibrii-prod.herokuapp.com/tutorial"
        private var listTuto = ArrayList<Model.Tuto>()

        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
            inflater.inflate(R.layout.fragment_home, container, false)

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

            super.onViewCreated(view, savedInstanceState)
            getData()

            // Set up card recycler view
            val cardRecyclerView = view.findViewById<RecyclerView>(R.id.menuheaderscrollbar2)
            val verticalLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
            cardRecyclerView.layoutManager = verticalLayoutManager
            cardRecyclerView.adapter = cardAdapter
            Log.d("tutorender",listTuto.toString())
        }

        // Function to fetch Tutorial data
        private fun getData() {

            val jsonArrayRequest = JsonArrayRequest(url,
                Response.Listener<JSONArray> { response ->
                    for (i in 0 until response.length()) {
                        try {
                            val jsonObject = response.getJSONObject(i)
                            val jsonTitle = jsonObject.getString("title")
                            val jsonDuration = jsonObject.getString("duration")
                            val jsonPrice = jsonObject.getString("price")
                            val jsonLevel = "Facile"
                            val jsonImg = (R.drawable.testons)
                            val jsonId = jsonObject.getInt("id")
                            val tutoEntrie = Model.Tuto(jsonTitle,jsonDuration,jsonPrice,jsonLevel, jsonImg, jsonId)
                            listTuto.add(tutoEntrie)
                        }
                        catch (e: JSONException) {
                            e.printStackTrace()
                        }

                    }

                    cardAdapter?.notifyDataSetChanged()
                    Log.d("tuto", listTuto.toString())
                }, Response.ErrorListener { Log.e("Volley", "Volley error on tutorial") })
            val requestQueue = Volley.newRequestQueue(activity)
            requestQueue.add(jsonArrayRequest)
        }
    }
}
</code>```

Here is my cardAdapter.kit :

```<code>class HomeCardItemAdapter // data is passed into the constructor
internal constructor(
    context: FragmentActivity?,
    private val tutos: ArrayList<Model.Tuto>
   //private val mCatePicture: List<Int>
)
    : RecyclerView.Adapter<HomeCardItemAdapter.ViewHolder>() {
    private val mInflater: LayoutInflater = LayoutInflater.from(context)
    private var mClickListener: ItemClickListener? = null

    // inflates the row layout from xml when needed
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = mInflater.inflate(R.layout.feed_card_items, parent, false)
        return ViewHolder(view)
    }

    // binds the data to the view and textview in each row
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentTuto = tutos.get(position)
     //   val catePicture= mCatePicture[position]
        holder.titleTextView.text = currentTuto.title
        holder.timeTextView.text = currentTuto.duration
        holder.priceTextView.text = currentTuto.price
       holder.levelTextView.text = currentTuto.level
        //holder.categoryImageView.setImageResource(catePicture)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            holder.cardImageView.clipToOutline = true
        }
    }

    // total number of rows
    override fun getItemCount(): Int {
                return tutos.size
        }

    // stores and recycles views as they are scrolled off screen
    inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {
        internal var cardImageView: ImageView = itemView.findViewById(R.id.card_img_bg)
        internal var titleTextView: TextView = itemView.findViewById(R.id.card_title)
        internal var priceTextView: TextView = itemView.findViewById(R.id.card_price)
        internal var timeTextView: TextView = itemView.findViewById(R.id.card_time)
        internal var levelTextView: TextView = itemView.findViewById(R.id.card_level)
        internal var categoryImageView: ImageView = itemView.findViewById(R.id.card_theme_icon)

}
</code>```

Thank you in advance to the people who could help me

答:
You never initialize the adapter, it's always null and due to the the safe operator (?) those calls are never actually invoked.

```<code>// Function to fetch Tutorial data
private fun getData() {
   val jsonArrayRequest = JsonArrayRequest(url,
   Response.Listener<JSONArray> { response ->
   for (i in 0 until response.length()) {
      try {
         val jsonObject = response.getJSONObject(i)
         val jsonTitle = jsonObject.getString("title")
         val jsonDuration = jsonObject.getString("duration")
         val jsonPrice = jsonObject.getString("price")
         val jsonLevel = "Facile"
         val jsonImg = (R.drawable.testons)
         val jsonId = jsonObject.getInt("id")
         val tutoEntrie = Model.Tuto(jsonTitle,jsonDuration,jsonPrice,jsonLevel, jsonImg, jsonId)
         listTuto.add(tutoEntrie)
      } catch (e: JSONException) {
         e.printStackTrace()
      }

    }

    // THIS HERE IS NEVER ACTUALLY CALLED AS THE ADAPTER IS ALWAYS NULL
    cardAdapter?.notifyDataSetChanged()

    Log.d("tuto", listTuto.toString())
    }, Response.ErrorListener { Log.e("Volley", "Volley error on tutorial") })
        val requestQueue = Volley.newRequestQueue(activity)
        requestQueue.add(jsonArrayRequest)
    }
}
</code>```

add this before notifyDataSetChanged

```<code>cardAdapter = HomeCardItemAdapter(this, listTuto)
// attach adapter
findViewById<RecyclerView>(R.id.menuheaderscrollbar2).adapter = cardAdapter
cardAdapter?.notifyDataSetChanged() // this might not be necessary
</code>```

EDIT: added further explanation:

Your call to getData() is prior to configuring your recyclerview and attaching the adapter. Therefore you should modify the onViewCreated() as followed.

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
     super.onViewCreated(view, savedInstanceState)

     // Set up card recycler view
     val cardRecyclerView = view.findViewById<RecyclerView>(R.id.menuheaderscrollbar2)
     val verticalLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
     cardRecyclerView.layoutManager = verticalLayoutManager

     // now that recyclerview is ready
     getData()
}

</code>```

Body:
I'm stuck with this since 1 week and I can't get why my data fetch are not displayed into my cardAdaptater. I can see they are fetched well but I can't acces to them after it in the fragment

Here is my HomePageFragment where data should be displayed

class HomePage {
    class HomeFragment : Fragment(), HeaderScrollBarAdapter.ItemClickListener {

        private var cardAdapter: HomeCardItemAdapter? = null
        private val url = "https://kolibrii-prod.herokuapp.com/tutorial"
        private var listTuto = ArrayList<Model.Tuto>()

        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
            inflater.inflate(R.layout.fragment_home, container, false)

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

            super.onViewCreated(view, savedInstanceState)
            getData()

            // Set up card recycler view
            val cardRecyclerView = view.findViewById<RecyclerView>(R.id.menuheaderscrollbar2)
            val verticalLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
            cardRecyclerView.layoutManager = verticalLayoutManager
            cardRecyclerView.adapter = cardAdapter
            Log.d("tutorender",listTuto.toString())
        }

        // Function to fetch Tutorial data
        private fun getData() {

            val jsonArrayRequest = JsonArrayRequest(url,
                Response.Listener<JSONArray> { response ->
                    for (i in 0 until response.length()) {
                        try {
                            val jsonObject = response.getJSONObject(i)
                            val jsonTitle = jsonObject.getString("title")
                            val jsonDuration = jsonObject.getString("duration")
                            val jsonPrice = jsonObject.getString("price")
                            val jsonLevel = "Facile"
                            val jsonImg = (R.drawable.testons)
                            val jsonId = jsonObject.getInt("id")
                            val tutoEntrie = Model.Tuto(jsonTitle,jsonDuration,jsonPrice,jsonLevel, jsonImg, jsonId)
                            listTuto.add(tutoEntrie)
                        }
                        catch (e: JSONException) {
                            e.printStackTrace()
                        }

                    }

                    cardAdapter?.notifyDataSetChanged()
                    Log.d("tuto", listTuto.toString())
                }, Response.ErrorListener { Log.e("Volley", "Volley error on tutorial") })
            val requestQueue = Volley.newRequestQueue(activity)
            requestQueue.add(jsonArrayRequest)
        }
    }
}

Here is my cardAdapter.kit :

class HomeCardItemAdapter // data is passed into the constructor
internal constructor(
    context: FragmentActivity?,
    private val tutos: ArrayList<Model.Tuto>
   //private val mCatePicture: List<Int>
)
    : RecyclerView.Adapter<HomeCardItemAdapter.ViewHolder>() {
    private val mInflater: LayoutInflater = LayoutInflater.from(context)
    private var mClickListener: ItemClickListener? = null

    // inflates the row layout from xml when needed
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = mInflater.inflate(R.layout.feed_card_items, parent, false)
        return ViewHolder(view)
    }

    // binds the data to the view and textview in each row
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentTuto = tutos.get(position)
     //   val catePicture= mCatePicture[position]
        holder.titleTextView.text = currentTuto.title
        holder.timeTextView.text = currentTuto.duration
        holder.priceTextView.text = currentTuto.price
       holder.levelTextView.text = currentTuto.level
        //holder.categoryImageView.setImageResource(catePicture)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            holder.cardImageView.clipToOutline = true
        }
    }

    // total number of rows
    override fun getItemCount(): Int {
                return tutos.size
        }

    // stores and recycles views as they are scrolled off screen
    inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {
        internal var cardImageView: ImageView = itemView.findViewById(R.id.card_img_bg)
        internal var titleTextView: TextView = itemView.findViewById(R.id.card_title)
        internal var priceTextView: TextView = itemView.findViewById(R.id.card_price)
        internal var timeTextView: TextView = itemView.findViewById(R.id.card_time)
        internal var levelTextView: TextView = itemView.findViewById(R.id.card_level)
        internal var categoryImageView: ImageView = itemView.findViewById(R.id.card_theme_icon)

}

Thank you in advance to the people who could help me

Body:
You never initialize the adapter, it's always null and due to the the safe operator (?) those calls are never actually invoked.

// Function to fetch Tutorial data
private fun getData() {
   val jsonArrayRequest = JsonArrayRequest(url,
   Response.Listener<JSONArray> { response ->
   for (i in 0 until response.length()) {
      try {
         val jsonObject = response.getJSONObject(i)
         val jsonTitle = jsonObject.getString("title")
         val jsonDuration = jsonObject.getString("duration")
         val jsonPrice = jsonObject.getString("price")
         val jsonLevel = "Facile"
         val jsonImg = (R.drawable.testons)
         val jsonId = jsonObject.getInt("id")
         val tutoEntrie = Model.Tuto(jsonTitle,jsonDuration,jsonPrice,jsonLevel, jsonImg, jsonId)
         listTuto.add(tutoEntrie)
      } catch (e: JSONException) {
         e.printStackTrace()
      }

    }

    // THIS HERE IS NEVER ACTUALLY CALLED AS THE ADAPTER IS ALWAYS NULL
    cardAdapter?.notifyDataSetChanged()

    Log.d("tuto", listTuto.toString())
    }, Response.ErrorListener { Log.e("Volley", "Volley error on tutorial") })
        val requestQueue = Volley.newRequestQueue(activity)
        requestQueue.add(jsonArrayRequest)
    }
}

add this before notifyDataSetChanged

cardAdapter = HomeCardItemAdapter(this, listTuto)
// attach adapter
findViewById<RecyclerView>(R.id.menuheaderscrollbar2).adapter = cardAdapter
cardAdapter?.notifyDataSetChanged() // this might not be necessary

EDIT: added further explanation:

Your call to getData() is prior to configuring your recyclerview and attaching the adapter. Therefore you should modify the onViewCreated() as followed.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
     super.onViewCreated(view, savedInstanceState)

     // Set up card recycler view
     val cardRecyclerView = view.findViewById<RecyclerView>(R.id.menuheaderscrollbar2)
     val verticalLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
     cardRecyclerView.layoutManager = verticalLayoutManager

     // now that recyclerview is ready
     getData()
}


来源: stackexchange

问:
"The calling thread must be STA, because many UI components require this" exception during unit test
I have a class called OptionsWindow which inherits from Window which is for picking from options in a window. And a Dialog Class which deals with these dialogs. In my test, im trying to mock the choice picked from the dialog.

```<code>[TestMethod]
public async Task Test()
{
    dialog.Setup(e => e.ShowDialog(It.IsAny<Window>(), It.IsAny<IntPtr>()))
                .Returns(true)
                .Callback<Window, IntPtr>((w, ip) => {
                    if (w.DataContext != null && w.DataContext is OptionsViewModel ovm)
                        ovm.Result = -1;
                    });
    await tester.ShowWindow();
    //assert....
}
</code>```

Then in the class being tested, i have these methods.

```<code>public async Task ShowWindow()
{
    var res = ShowDialog();
    //do other stuff...
}

private int ShowDialog()
{
    OptionsViewModel vm = //.....
    dialog.ShowDialog(new OptionsWindow(vm));
    return vm.Result;
}
</code>```

however, i get the error "The calling thread must be STA, because many UI components require this" when it tries to set the Result of the OptionsViewModel.

During manual testing, everything worked fine and there were no threading issues so im not sure why im getting these here... any help is great. thanks

(im using Microsoft.VisualStudio.TestTools.UnitTesting btw)

答:
In my test, im trying to mock the choice picked from the dialog.

Usually, if writing tests is difficult, that indicates the code should be better designed.

In this case, direct dependence on UI components is not ideal. There's a pattern called ports and adapters (a.k.a. Hexagonal Architecture, a.k.a. Clean Architecture) that would help here. In summary, you define interfaces from the application's perspective, and then have small adapter objects implement those interfaces.

So you could have the application define an interface that provides what it needs:

```<code>public interface IUserInteraction
{
  int ModalOptionsWindow();
}
</code>```

with an implementation:

```<code>public sealed class WpfUserInteraction : IUserInteraction
{
  int ModalOptionsWindow()
  {
    OptionsViewModel vm = //.....
    dialog.ShowDialog(new OptionsWindow(vm));
    return vm.Result;
  }
}
</code>```

What exactly the interface covers is up to you. Generally, I like to keep my ViewModels on the application side of the port, and only have views on the UI side of the port.

Once you have an interface, inject the IUserInteraction and have your code call that. After that, the unit testing is simplified.

However, if you are in a legacy code scenario, where you need to write tests before refactoring, then you can unit test UI code. It's just not easy. See WpfContext or WindowsFormsContext in this old archive for a way to create an STA thread and pump messages from within a unit test.

ContentLicense: CC BY-SA 4.0

Body:
I have a class called OptionsWindow which inherits from Window which is for picking from options in a window. And a Dialog Class which deals with these dialogs. In my test, im trying to mock the choice picked from the dialog.

[TestMethod]
public async Task Test()
{
    dialog.Setup(e => e.ShowDialog(It.IsAny<Window>(), It.IsAny<IntPtr>()))
                .Returns(true)
                .Callback<Window, IntPtr>((w, ip) => {
                    if (w.DataContext != null && w.DataContext is OptionsViewModel ovm)
                        ovm.Result = -1;
                    });
    await tester.ShowWindow();
    //assert....
}

Then in the class being tested, i have these methods.

public async Task ShowWindow()
{
    var res = ShowDialog();
    //do other stuff...
}

private int ShowDialog()
{
    OptionsViewModel vm = //.....
    dialog.ShowDialog(new OptionsWindow(vm));
    return vm.Result;
}

however, i get the error "The calling thread must be STA, because many UI components require this" when it tries to set the Result of the OptionsViewModel.

During manual testing, everything worked fine and there were no threading issues so im not sure why im getting these here... any help is great. thanks

(im using Microsoft.VisualStudio.TestTools.UnitTesting btw)

Body:
In my test, im trying to mock the choice picked from the dialog.

Usually, if writing tests is difficult, that indicates the code should be better designed.

In this case, direct dependence on UI components is not ideal. There's a pattern called ports and adapters (a.k.a. Hexagonal Architecture, a.k.a. Clean Architecture) that would help here. In summary, you define interfaces from the application's perspective, and then have small adapter objects implement those interfaces.

So you could have the application define an interface that provides what it needs:

public interface IUserInteraction
{
  int ModalOptionsWindow();
}

with an implementation:

public sealed class WpfUserInteraction : IUserInteraction
{
  int ModalOptionsWindow()
  {
    OptionsViewModel vm = //.....
    dialog.ShowDialog(new OptionsWindow(vm));
    return vm.Result;
  }
}

What exactly the interface covers is up to you. Generally, I like to keep my ViewModels on the application side of the port, and only have views on the UI side of the port.

Once you have an interface, inject the IUserInteraction and have your code call that. After that, the unit testing is simplified.

However, if you are in a legacy code scenario, where you need to write tests before refactoring, then you can unit test UI code. It's just not easy. See WpfContext or WindowsFormsContext in this old archive for a way to create an STA thread and pump messages from within a unit test.


问:
process url's into application's output and strip them to create files with name of urls
Created a script which makes use of an existing tool which process url's to get additional information.

now, this tool has an output format with the switch "-o" but due to the impossibility to create a filename with "output-$url-tool.txt", where the $url is a list which gets read line by line, thus: "http://www.something.com, (new line) https://www.something.com" etc.

Is it possible to strip the url while processing it to create a file with the stripped name "output-something.com-tool.txt" per url?

this might be a bit fuzzy to read but i kinda got lost and don't know any other way to ask this. im sorry.

see the example below for what i tried but obviously doesnt work due to the markup of the file.

for url in $(cat /urls.txt); do tool -u $url -o output-$url-tool.html; done

答:
The construct you're using isn't particularly safe. Since cat urls.txt is split by whitespace, any whitespace accidentally in the file will break your processing. If you're sure you want to handle things line-by-line, use read.

You'll also want to quote your variables, and remove or modify characters which are not permitted within filenames.

```<code>while read -r url; do
  tool -u "$url" -o "output-${url//\//_}-tool.html"
done < urls.txt
</code>```

And if you want to strip the method, you can do that with additional parameter expansion:

```<code>shopt -s extglob
while read -r url; do
  url="${url#http?(s)://}"
  url="${url%%/*}"
  tool -u "$url" -o "output-${url}-tool.html"
done < urls.txt
</code>```

This uses extglob to make the s in https optional, and includes only the domain name in the filename buy stripping everything earlier in the URL, along with the entire path.

Note that extglob requires bash version 4 or above.

Body:
The construct you're using isn't particularly safe. Since cat urls.txt is split by whitespace, any whitespace accidentally in the file will break your processing. If you're sure you want to handle things line-by-line, use read.

You'll also want to quote your variables, and remove or modify characters which are not permitted within filenames.

while read -r url; do
  tool -u "$url" -o "output-${url//\//_}-tool.html"
done < urls.txt

And if you want to strip the method, you can do that with additional parameter expansion:

shopt -s extglob
while read -r url; do
  url="${url#http?(s)://}"
  url="${url%%/*}"
  tool -u "$url" -o "output-${url}-tool.html"
done < urls.txt

This uses extglob to make the s in https optional, and includes only the domain name in the filename buy stripping everything earlier in the URL, along with the entire path.

Note that extglob requires bash version 4 or above.


问:
jQuery dilemma in loading different pages on one page
Hello i need some help to figure out what to do .

I am trying to create a page that has a list of events and each time I click one of the list's elements a different photo gallery should load. I did this by loading each gallery in a different iframe.

The problem is that right now the only thing it dose is loading the first galery and the other ones don't seem to manage loading any pictures (if I refresh each frame than they work fine)

What should i do?

This is the script I used in the webpage

You can find the page source here http://www.avantsolutions.ro/exp.txt

答:
You can try with jQuery UI Plugin instead of iFrame.
On clicking of list item(West pane), you can load center pane div with corresponding images.
Check the examples here.</p>

ContentLicense: CC BY-SA 3.0


问:
Dataflow unable to GET a reference to BigQuery tables when too many cores or more than one machine
My streaming Dataflow pipeline is supposed to read analytics hits from Pub/Sub and write them to BigQuery. If I use too many machines, or they're too big, it throws rate limit errors when getting a reference to the tables, more precisely when executing _get_or_create_table.

The rate limit that is reached seems to be one of these: 100 API requests per second per user, 300 concurrent API requests per user.

It is not blocking the pipeline (rows get written after some point), but I have the feeling it blocks some of the threads and prevents me from fully taking advantage of the parallelization. Switching from one machine with 4 CPUs to 5 with each 8 CPUs brought no improvement to the latency (in fact it got worse).

How can I avoid this error, and have a high number of machines write to BQ ?

Here's the log from the Dataflow monitoring interface. It is appearing regularly when I launch the pipeline:

```<code>...
File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/bigquery.py", line 1087, in get_or_create_table
    found_table = self._get_table(project_id, dataset_id, table_id)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/utils/retry.py", line 184, in wrapper
    return fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/bigquery.py", line 925, in _get_table
    response = self.client.tables.Get(request)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/internal/clients/bigquery/bigquery_v2_client.py", line 611, in Get
    config, request, global_params=global_params)
  File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 722, in _RunMethod
    return self.ProcessHttpResponse(method_config, http_response, request)
  File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 728, in ProcessHttpResponse
    self.__ProcessHttpResponse(method_config, http_response, request))
  File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 599, in __ProcessHttpResponse
    http_response, method_config=method_config, request=request)

HttpForbiddenError: HttpError accessing <https://www.googleapis.com/bigquery/v2/projects/<project_id>/datasets/<dataset_id>/tables/<table_id>?alt=json>: response: <{'status': '403', 'content-length': '577', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'expires': 'Sun, 25 Nov 2018 14:36:24 GMT', 'vary': 'Origin, X-Origin', 'server': 'GSE', '-content-encoding': 'gzip', 'cache-control': 'private, max-age=0', 'date': 'Sun, 25 Nov 2018 14:36:24 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json; charset=UTF-8'}>, content <{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "rateLimitExceeded",
    "message": "Exceeded rate limits: Your user_method exceeded quota for api requests per user per method. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors",
    "locationType": "other",
    "location": "helix_api.method_request"
   }
  ],
  "code": 403,
  "message": "Exceeded rate limits: Your user_method exceeded quota for api requests per user per method. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors"
</code>```

Here's the code of the pipeline. I cut pretty much everything in it to see if this still happens:

```<code>p = beam.Pipeline(options=options)

msgs = p | 'Read' >> beam.io.gcp.pubsub.ReadFromPubSub(
    topic='projects/{project}/topics/{topic}'.format(
        project=args.project, topic=args.hits_topic),
    id_label='hit_id',
    timestamp_attribute='time')

lines = msgs | beam.Map(lambda x: {'content': x})

(lines
    | 'WriteToBQ' >> beam.io.gcp.bigquery.WriteToBigQuery(args.table,
                                                          dataset=args.dataset,
                                                          project=args.project))
</code>```

答: Try upgrading to the latest apache_beam library (2.12.0 as of writing). https://github.com/apache/beam/commit/932e802279a2daa0ff7797a8fc81e952a4e4f252 introduced caching of tables that would otherwise trigger the rate limits you likely encountered in an older version of this library.

Body:
My streaming Dataflow pipeline is supposed to read analytics hits from Pub/Sub and write them to BigQuery. If I use too many machines, or they're too big, it throws rate limit errors when getting a reference to the tables, more precisely when executing _get_or_create_table.

The rate limit that is reached seems to be one of these: 100 API requests per second per user, 300 concurrent API requests per user.

It is not blocking the pipeline (rows get written after some point), but I have the feeling it blocks some of the threads and prevents me from fully taking advantage of the parallelization. Switching from one machine with 4 CPUs to 5 with each 8 CPUs brought no improvement to the latency (in fact it got worse).

How can I avoid this error, and have a high number of machines write to BQ ?

Here's the log from the Dataflow monitoring interface. It is appearing regularly when I launch the pipeline:

...
File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/bigquery.py", line 1087, in get_or_create_table
    found_table = self._get_table(project_id, dataset_id, table_id)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/utils/retry.py", line 184, in wrapper
    return fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/bigquery.py", line 925, in _get_table
    response = self.client.tables.Get(request)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/internal/clients/bigquery/bigquery_v2_client.py", line 611, in Get
    config, request, global_params=global_params)
  File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 722, in _RunMethod
    return self.ProcessHttpResponse(method_config, http_response, request)
  File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 728, in ProcessHttpResponse
    self.__ProcessHttpResponse(method_config, http_response, request))
  File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 599, in __ProcessHttpResponse
    http_response, method_config=method_config, request=request)

HttpForbiddenError: HttpError accessing <https://www.googleapis.com/bigquery/v2/projects/<project_id>/datasets/<dataset_id>/tables/<table_id>?alt=json>: response: <{'status': '403', 'content-length': '577', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'expires': 'Sun, 25 Nov 2018 14:36:24 GMT', 'vary': 'Origin, X-Origin', 'server': 'GSE', '-content-encoding': 'gzip', 'cache-control': 'private, max-age=0', 'date': 'Sun, 25 Nov 2018 14:36:24 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json; charset=UTF-8'}>, content <{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "rateLimitExceeded",
    "message": "Exceeded rate limits: Your user_method exceeded quota for api requests per user per method. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors",
    "locationType": "other",
    "location": "helix_api.method_request"
   }
  ],
  "code": 403,
  "message": "Exceeded rate limits: Your user_method exceeded quota for api requests per user per method. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors"

Here's the code of the pipeline. I cut pretty much everything in it to see if this still happens:

p = beam.Pipeline(options=options)

msgs = p | 'Read' >> beam.io.gcp.pubsub.ReadFromPubSub(
    topic='projects/{project}/topics/{topic}'.format(
        project=args.project, topic=args.hits_topic),
    id_label='hit_id',
    timestamp_attribute='time')

lines = msgs | beam.Map(lambda x: {'content': x})

(lines
    | 'WriteToBQ' >> beam.io.gcp.bigquery.WriteToBigQuery(args.table,
                                                          dataset=args.dataset,
                                                          project=args.project))


问:
Why fopen with x mode gives me "failed to open stream: No such file or directory in"
I want to use mode x because as I can see from php.net that if the file exists it gives and error and also return false, and if not it creates it (also the directory's).

This is the script. It is located in www.ex.com/s/index.php

```<code>$urlParts = "/img/logo.png";
$fp = fopen( __DIR__ . $urlParts, "x" );
</code>```

This should create logo.png (and also create the directory /img/) if it does not exist...but it is not working like this.

Anyone can help? Thanks!

答:
```<code>fopen("/img/logo.png","x");
</code>```

It will not create the img directory in any case. If the directory does not exist, then it will always throw this warning.

Warning: fopen(/img/logo.png): failed to open stream: No such file or directory

```<code>fopen("logo.png","x");
</code>```

If logo.png does not already exist, then it will create it without any warning.
If logo.png already exists, then it will always throw this warning.

Warning: fopen(logo.png): failed to open stream: No such file or directory

fopen("","x") is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. Now let me help you understand why it happens.

In POSIX, The O_CREAT flag causes a file to be created if it doesn't
already exist. If you include the O_CREAT flag, you must also pass a third argument to open to designate the permissions. If you want to avoid writing over an existing file, use the combination O_CREAT | O_EXCL. This combination returns an error if the file already exists.

C program using POSIX

```<code>#include <fcntl.h>
#include <sys/stat.h>
int open(const char *path, int oflag, ...);
</code>```

Conclusion:
So we will use the "x" mode only when we want to avoid writing over an existing file.

Body:
I want to use mode x because as I can see from php.net that if the file exists it gives and error and also return false, and if not it creates it (also the directory's).

This is the script. It is located in www.ex.com/s/index.php

$urlParts = "/img/logo.png";
$fp = fopen( __DIR__ . $urlParts, "x" );

This should create logo.png (and also create the directory /img/) if it does not exist...but it is not working like this.

Anyone can help? Thanks!

Body:
fopen("/img/logo.png","x");

It will not create the img directory in any case. If the directory does not exist, then it will always throw this warning.

Warning: fopen(/img/logo.png): failed to open stream: No such file or directory

fopen("logo.png","x");

If logo.png does not already exist, then it will create it without any warning.
If logo.png already exists, then it will always throw this warning.

Warning: fopen(logo.png): failed to open stream: No such file or directory

fopen("","x") is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. Now let me help you understand why it happens.

In POSIX, The O_CREAT flag causes a file to be created if it doesn't
already exist. If you include the O_CREAT flag, you must also pass a third argument to open to designate the permissions. If you want to avoid writing over an existing file, use the combination O_CREAT | O_EXCL. This combination returns an error if the file already exists.

C program using POSIX

#include <fcntl.h>
#include <sys/stat.h>
int open(const char *path, int oflag, ...);

Conclusion:
So we will use the "x" mode only when we want to avoid writing over an existing file.


问:
Pass a lambda expression in place of iComparator in VB.Net
I have the following C# expression

```<code>var orderedMatches = matches.OrderBy((t1, t2) => t1.Item1 - t2.Item1).ToList();
</code>```

And am trying to translate to VB with Option Strict On, most translators produce something like below

```<code>Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1 As Tuple(Of Integer, String), t2 As Object) t1.Item1 - t2.Item1).ToList()
</code>```

Or just below and neither one compiles.

```<code>Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1, t2) t1.Item1 - t2.Item1).ToList()
</code>```

I have tried multiple converters and also setting Option Strict Off and setting T1 and T2 to Object.
The usual error is

```<code>BC36532 Nested function does not have the same signature as delegate 'Func(Of Tuple(Of Integer, String), Object)'
</code>```

OrderBy is defined as

```<code>Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey)) As IOrderedEnumerable(Of TSource)
</code>```

or

```<code>Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey), comparer As IComparer(Of TKey)) As IOrderedEnumerable(Of TSource)
</code>```

I need to code to compile with errors preferably with Option Strict On

答:
```<code>'Hint: Would be usually done in the project settings...
Option Explicit On
Option Strict On
Option Infer On

Module StartUp

    Public Sub Main(args As String())
        Dim matches = GenerateData()
        Dim orderedMatches = (From e In matches Order By e.Item1).ToList()
        orderedMatches.ForEach(Sub(x) Console.Out.WriteLine(x))
        Console.Read()
    End Sub

    Private Iterator Function GenerateData() As IEnumerable(Of Tuple(Of Int32, String))
        Yield Tuple.Create(100, "Hundred")
        Yield Tuple.Create(1, "One")
        Yield Tuple.Create(Int32.MinValue, "MinValue")
        Yield Tuple.Create(Int32.MaxValue, "MaxValue")
        Yield Tuple.Create(0, "Zero")
    End Function

End Module
</code>```

Body:
I have the following C# expression

var orderedMatches = matches.OrderBy((t1, t2) => t1.Item1 - t2.Item1).ToList();

And am trying to translate to VB with Option Strict On, most translators produce something like below

Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1 As Tuple(Of Integer, String), t2 As Object) t1.Item1 - t2.Item1).ToList()

Or just below and neither one compiles.

Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1, t2) t1.Item1 - t2.Item1).ToList()

I have tried multiple converters and also setting Option Strict Off and setting T1 and T2 to Object.
The usual error is

BC36532 Nested function does not have the same signature as delegate 'Func(Of Tuple(Of Integer, String), Object)'

OrderBy is defined as

Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey)) As IOrderedEnumerable(Of TSource)

or

Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey), comparer As IComparer(Of TKey)) As IOrderedEnumerable(Of TSource)

I need to code to compile with errors preferably with Option Strict On


问:
why the main method is printing nothing in the sub class?
"mysecondclass" which is a sub class of the super class "myfirstclass"
should inherit all the properties of the super class "myfirstclass"
and it's expected to output the value of x but instead it prints nothing

```<code>package myfirstproject;

public class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }
    public static void main(String[] args) {
/* it asked me to define this main method here although it's useless in this situation
   */
    }
}
class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //prints nothing
    }
}
</code>```

i am really newbie in java and i am actually still learning it's basics
also i do not know why it always asks me to add the main method in the super class although i have already declared one in the sub class (i heard one main method is enough for one java file)
any help is really appreciated , thanks in advance

答:
Just change the public keyword to the second class. If you are using an online compiler, they usually look for the main method inside the public class. </p>

```<code>package myfirstproject;

 class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }

}
public class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //printx X
    }
}
</code>```

Body:
"mysecondclass" which is a sub class of the super class "myfirstclass"
should inherit all the properties of the super class "myfirstclass"
and it's expected to output the value of x but instead it prints nothing

package myfirstproject;

public class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }
    public static void main(String[] args) {
/* it asked me to define this main method here although it's useless in this situation
   */
    }
}
class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //prints nothing
    }
}

i am really newbie in java and i am actually still learning it's basics
also i do not know why it always asks me to add the main method in the super class although i have already declared one in the sub class (i heard one main method is enough for one java file)
any help is really appreciated , thanks in advance

Body:
Just change the public keyword to the second class. If you are using an online compiler, they usually look for the main method inside the public class.

package myfirstproject;

 class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }

}
public class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //printx X
    }
}


问:
Tooltips at right of the columns of an amcharts4 horizontal barchart
I have an amcharts 4 horizontal bar chart as in this fiddle. I want to have the tooltips at the right of the columns, with the tooltip pointer touching the extremity of the column.

I have tried

```<code>tooltip.adapter.add("dx", (x, target) => {
  return valueAxis.valueToPoint(target.dataItem.valueX).x;
})
</code>```

but that does not provide the wanted result. I have also tried to play with horizontalCenter, rotation, but unsuccessfully.

答:
I have found the solution.

```<code>    tooltip.dx = 0;
    tooltip.rotation = 180;
    tooltip.label.verticalCenter = "bottom";
    tooltip.label.rotation = 180;

    columnTemplate.adapter.add("tooltipX", (x, target) => {
      if (target.dataItem.valueX > 0) {
        return valueAxis.valueToPoint(target.dataItem.valueX + minValue).x;
      } else {
        return 0;
      }
    });
</code>```

If the value is negative, then the tooltip is at the left of the column. This is also what I wanted.

Fiddle: jsfiddle.

Body:
I have an amcharts 4 horizontal bar chart as in this fiddle. I want to have the tooltips at the right of the columns, with the tooltip pointer touching the extremity of the column.

I have tried

tooltip.adapter.add("dx", (x, target) => {
  return valueAxis.valueToPoint(target.dataItem.valueX).x;
})

but that does not provide the wanted result. I have also tried to play with horizontalCenter, rotation, but unsuccessfully.

Body:
I have found the solution.

    tooltip.dx = 0;
    tooltip.rotation = 180;
    tooltip.label.verticalCenter = "bottom";
    tooltip.label.rotation = 180;

    columnTemplate.adapter.add("tooltipX", (x, target) => {
      if (target.dataItem.valueX > 0) {
        return valueAxis.valueToPoint(target.dataItem.valueX + minValue).x;
      } else {
        return 0;
      }
    });

If the value is negative, then the tooltip is at the left of the column. This is also what I wanted.

Fiddle: jsfiddle.


问:
Macro button for +1 water consumed to match =Today()
I am in process of completing a food journal and I track it in Excel. I like to update live (vs. end of day) and every time I have a glass of water, I would like to press the macro button and it finds today's date and adds +1 to it on a running tally.

Is there a way to do a Match Function to find today's date in cell A4 with a formula in A4 as:
=Today()  and match it with my food journal dates (dates are in Column B)?

Trying to Match today's date with A4 and the number will increase the number of water glass consumed by 1 each time. I am familiar with MATCH and INDEX as formulas but can't figure it out in VBA.

All I have now is the add 1 to cell

```<code>Cells(1,1).Value = Cells(1,1).Value + 1
</code>```

I would like to get a cumulative number by pressing a macro button x number of times to give me total water glass consumption for today.

答:
It sounds like the best way to do this with VBA is to use the Range.Find method. Here is the documentation for using it correctly, as well as how you can handle not finding the value you are looking for. https://learn.microsoft.com/en-us/office/vba/api/excel.range.find

The Range.Find method returns a range object, which is basically a cell address. You could offset that address by one column to update the value in Column B. Your Cells(1,1).Value = Cells(1,1).Value + 1 should work just fine for that. Let me know if you have any questions! Good Luck!

Body:
I am in process of completing a food journal and I track it in Excel. I like to update live (vs. end of day) and every time I have a glass of water, I would like to press the macro button and it finds today's date and adds +1 to it on a running tally.

Is there a way to do a Match Function to find today's date in cell A4 with a formula in A4 as:
=Today()  and match it with my food journal dates (dates are in Column B)?

Trying to Match today's date with A4 and the number will increase the number of water glass consumed by 1 each time. I am familiar with MATCH and INDEX as formulas but can't figure it out in VBA.

All I have now is the add 1 to cell

Cells(1,1).Value = Cells(1,1).Value + 1

I would like to get a cumulative number by pressing a macro button x number of times to give me total water glass consumption for today.


问:
Is NULL necessary?
Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)

I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.

I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?

I am guessing it does not matter from what I've tested and read.

```<code>ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2
</code>```

答:
You don't have to write it, when you skip it column will be created as 'NULL'.

Following statements are equal:

```<code>ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150) NULL;
</code>```

If you want to add a column and DB engine should guarantee you that this new column will be always populated you can add a NOT NULL column with a default value.

Other option will be to change the column to NOT NULL after the update.

Title: Is NULL necessary?

Body:
Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)

I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.

I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?

I am guessing it does not matter from what I've tested and read.

ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2

Body:
You don't have to write it, when you skip it column will be created as 'NULL'.

Following statements are equal:

ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150) NULL;

If you want to add a column and DB engine should guarantee you that this new column will be always populated you can add a NOT NULL column with a default value.

Other option will be to change the column to NOT NULL after the update.


问:
Angular 7 : How to fix value overwriting during dynamic field addition?
I am working on an Angular application, wherein I have to do some configuration setup using 4 fields:

Department Name (drop down)

Service Name (drop down)

Status (text field)

Level (text field).

I want to add multiple set of these fields and create a JSON structure.

'Department Name' and 'Service Name' values are fetched using API calls.

'Service Name' options is populated based on 'Department Name' selected.

Though I am able to add the fields dynamically, but when I select nth Department Name, corresponding Service Name overwrites all (n-1) 'Service Name' fields.

Here is my component.html file:

//mapFormGroup returns FormArray for given set of fields

        Department Name
        // getServices fetches all services for selected department
        <select class="form-control" formControlName="deptId" type="text" (change)="getServices($event.target.value)">
            // deptList contains list of all departments
            <option *ngFor="let dept of deptList" [value]="dept.id">{{dept.name}}</option>
        </select>
        Service Name
        <select class="form-control" formControlName="serviceName" type="text">
            // serviceList contains list of all services for given department
            <option *ngFor="let service of serviceList" [value]="service.wfName">{{service.description}}</option>
        </select>

```

I expect correct mapping of Department & Service Name fields. But the latest one is overwriting previous entries.

答:
```<code>dataSource: ServiceName[]; // create class for service or can have just [];
ngOnInit(){
 this.dataSource = [];
  this.ServiceNameService.getServiceDetails().subscribe( resp => {
    resp.forEach(element => {
      console.log(element);
      const config = new  ServiceName(
      element.ServiceId, element.Name); // this is constructor or if general array
       //change accordingly
      this.dataSource.push(config);
  });
}
getServices(val){
this.ServiceNameList = this.dataSource.filter(obj =>
             String(obj.DepartmentName).toUpperCase() === String(val));
}
</code>```

Body:
I am working on an Angular application, wherein I have to do some configuration setup using 4 fields:

Department Name (drop down)

Service Name (drop down)

Status (text field)

Level (text field).

I want to add multiple set of these fields and create a JSON structure.

'Department Name' and 'Service Name' values are fetched using API calls.

'Service Name' options is populated based on 'Department Name' selected.

Though I am able to add the fields dynamically, but when I select nth Department Name, corresponding Service Name overwrites all (n-1) 'Service Name' fields.

Here is my component.html file:

//mapFormGroup returns FormArray for given set of fields

        Department Name
        // getServices fetches all services for selected department
        <select class="form-control" formControlName="deptId" type="text" (change)="getServices($event.target.value)">
            // deptList contains list of all departments
            <option *ngFor="let dept of deptList" [value]="dept.id">{{dept.name}}</option>
        </select>
        Service Name
        <select class="form-control" formControlName="serviceName" type="text">
            // serviceList contains list of all services for given department
            <option *ngFor="let service of serviceList" [value]="service.wfName">{{service.description}}</option>
        </select>

I expect correct mapping of Department & Service Name fields. But the latest one is overwriting previous entries.


问:
When I open soft keyboard in child activity of activity group.Tabs shifted upward in Android
When I open soft keyboard in child activity of activity group.Tabs shifted upward

here is the images for the problem.
Bugs TabActivity in Child ActivityGroup

答:
In your AndroidManifest.xml, add the following to your specific activity:</p>

```<code>android:windowSoftInputMode="adjustPan"
</code>```

Body:
In your AndroidManifest.xml, add the following to your specific activity:

android:windowSoftInputMode="adjustPan"


问:
Catch all exceptions in django rest framework
I guess this is more of a code quality question but it does involve handling unhandled exceptions is Django rest framework.

Deleting a protected record just return
500 internal server error

So I added the example custom exception handler. The first line returns a response that is none.

response = exception_handler(exc, context)

```<code>from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is None:
        #DRF could not process the exception so we will treat it as a 500 and try to get the user as much info as possible.
        response = Response({'error': str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

return response
</code>```

So in this case I am treating it as a 500 because the DRF couldn't handle the exc.

I guess my question is is this an appropriate way to handle it and does anyone have experience with this have a better solution?

Update:

```<code>Traceback:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54.         return view_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
116.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
495.             response = self.handle_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
455.             self.raise_uncaught_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
492.             response = handler(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create
21.         self.perform_create(serializer)

File "/device_mgmt/selection/views.py" in perform_create
84.             serializer.save(realm=utils.get_realm_from_request(self.request))

File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in save
214.             self.instance = self.create(validated_data)

File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in create
943.             instance = ModelClass._default_manager.create(**validated_data)

File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in create
422.         obj.save(force_insert=True, using=self.db)

File "/device_mgmt/selection/models.py" in save
123.         self.full_clean()

File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in full_clean
1203.             raise ValidationError(errors)

Exception Type: ValidationError at /company/api/company/
Exception Value: {'id': ['Company with this Id already exists.']}
</code>```

Django models are throwing validation error but rest framework view it calling it uncaught.

答:
This seems to be the thing I was looking for...

https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f

Basically convert the django exception into a drf exception with the same details.

```<code>"""
Sometimes in your Django model you want to raise a ``ValidationError``
in the ``save`` method, for
some reason.
This exception is not managed by Django Rest Framework because it
occurs after its validation
process. So at the end, you'll have a 500.
Correcting this is as simple as overriding the exception handler, by
converting the Django
``ValidationError`` to a DRF one.
"""

from django.core.exceptions import ValidationError as
DjangoValidationError

from rest_framework.exceptions import ValidationError as
DRFValidationError
from rest_framework.views import exception_handler as
drf_exception_handler

def exception_handler(exc, context):
    """Handle Django ValidationError as an accepted exception
    Must be set in settings:
    >>> REST_FRAMEWORK = {
    ...     # ...
    ...     'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
    ...     # ...
    ... }
    For the parameters, see ``exception_handler``
    """

    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail={'error': exc.message_dict})
        elif hasattr(exc, 'message'):
            exc = DRFValidationError(detail={'error': exc.message})
        elif hasattr(exc, 'messages'):
            exc = DRFValidationError(detail={'error': exc.messages})

    return drf_exception_handler(exc, context)
</code>```

This worked for me and now instead of a generic 500 response I get a 500 response with the relevant details.

Body:
I guess this is more of a code quality question but it does involve handling unhandled exceptions is Django rest framework.

Deleting a protected record just return
500 internal server error

So I added the example custom exception handler. The first line returns a response that is none.

response = exception_handler(exc, context)

from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is None:
        #DRF could not process the exception so we will treat it as a 500 and try to get the user as much info as possible.
        response = Response({'error': str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

return response

So in this case I am treating it as a 500 because the DRF couldn't handle the exc.

I guess my question is is this an appropriate way to handle it and does anyone have experience with this have a better solution?

Update:

Traceback:

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34.             response = get_response(request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54.         return view_func(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view
116.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
495.             response = self.handle_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
455.             self.raise_uncaught_exception(exc)

File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
492.             response = handler(request, *args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create
21.         self.perform_create(serializer)

File "/device_mgmt/selection/views.py" in perform_create
84.             serializer.save(realm=utils.get_realm_from_request(self.request))

File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in save
214.             self.instance = self.create(validated_data)

File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in create
943.             instance = ModelClass._default_manager.create(**validated_data)

File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in create
422.         obj.save(force_insert=True, using=self.db)

File "/device_mgmt/selection/models.py" in save
123.         self.full_clean()

File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in full_clean
1203.             raise ValidationError(errors)

Exception Type: ValidationError at /company/api/company/
Exception Value: {'id': ['Company with this Id already exists.']}

Django models are throwing validation error but rest framework view it calling it uncaught.

Body:
This seems to be the thing I was looking for...

https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f

Basically convert the django exception into a drf exception with the same details.

"""
Sometimes in your Django model you want to raise a ``ValidationError``
in the ``save`` method, for
some reason.
This exception is not managed by Django Rest Framework because it
occurs after its validation
process. So at the end, you'll have a 500.
Correcting this is as simple as overriding the exception handler, by
converting the Django
``ValidationError`` to a DRF one.
"""

from django.core.exceptions import ValidationError as
DjangoValidationError

from rest_framework.exceptions import ValidationError as
DRFValidationError
from rest_framework.views import exception_handler as
drf_exception_handler

def exception_handler(exc, context):
    """Handle Django ValidationError as an accepted exception
    Must be set in settings:
    >>> REST_FRAMEWORK = {
    ...     # ...
    ...     'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
    ...     # ...
    ... }
    For the parameters, see ``exception_handler``
    """

    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail={'error': exc.message_dict})
        elif hasattr(exc, 'message'):
            exc = DRFValidationError(detail={'error': exc.message})
        elif hasattr(exc, 'messages'):
            exc = DRFValidationError(detail={'error': exc.messages})

    return drf_exception_handler(exc, context)

This worked for me and now instead of a generic 500 response I get a 500 response with the relevant details.


问:
Besides ? and *, what other wildcards are allowed in conditional formatting?
The google help on conditional formatting of cells in google sheets has a small section on wildcards but only talks about ? and * (and how to escape them).  Are other wildcards allowed?  I have cells that look like:

```<code>some text
1.2.3 more text
4.5.6 even more
another section
7.8.9 stuff
</code>```

I want to have the cells without numbers be bold.  In the conditional formatting, I can choose "text does not contain" and I want to specify "digit" as a wildcard.  Standard regexp doesn't seem to work.  I've tried [0-9], :d, #, \d.

Google help doesn't list anything else so I'm guessing no other wildcards are supported other than ? and *?

答:
Like yourself, I was unable to find any additional wildcards beyond what is specified here, the "?" and "*" wildcards.

However, a great feature of Google Sheets is the ability to use custom formulas in combination with custom formatting, at which point the only limit is requiring your custom formula evaluates to a "truthy" (true or false like value).

Here is how you could implement what you are looking for - "Custom formula is":

```<code>=REGEXMATCH(FIRST_COLUMN:FIRST_COLUMN,"^[^\d]+$")
</code>```

Body:
The google help on conditional formatting of cells in google sheets has a small section on wildcards but only talks about ? and * (and how to escape them).  Are other wildcards allowed?  I have cells that look like:

some text
1.2.3 more text
4.5.6 even more
another section
7.8.9 stuff

I want to have the cells without numbers be bold.  In the conditional formatting, I can choose "text does not contain" and I want to specify "digit" as a wildcard.  Standard regexp doesn't seem to work.  I've tried [0-9], :d, #, \d.

Google help doesn't list anything else so I'm guessing no other wildcards are supported other than ? and *?

Body:
Like yourself, I was unable to find any additional wildcards beyond what is specified here, the "?" and "*" wildcards.

However, a great feature of Google Sheets is the ability to use custom formulas in combination with custom formatting, at which point the only limit is requiring your custom formula evaluates to a "truthy" (true or false like value).

Here is how you could implement what you are looking for - "Custom formula is":

=REGEXMATCH(FIRST_COLUMN:FIRST_COLUMN,"^[^\d]+$")


问:
DOCKER environment in production
I am new to docker and just started playing around it. I have a following setup of my app in production as of now:

Server machine 1 : running spring-boot microservices

Server machine 2 : running redis

Server machine 3 : running postgres

If I use docker in server machine 1 and run all of the microservices as container and run the redis and postgres as a container as well in server machine 1, is this is correct thing to do ?  Or I have to run the docker on all the server machines and run containers separately.

Which is the best practice to do ?

答:
When first starting out I suggest doing it all on 1 machine. Your database containers can use volumes to save data to the machine itself. So when you need to switch to a different machine, because 1 machine is too slow, you can easily transfer your database data. When starting to use more than 1 machine to run Docker you probably want to use a deployment option like Kubernetes or Docker swarm. This will simplify the process of setting up your environments on different machines, because it will be done by Kubernetes.

Also when your application is getting a lot of traffic you might want to switch to Managed Databases, which are provided by services like GCP, AWS, Digitalocean, etc. A managed database will scale automatically, get updates frequently and back-up automatically. This will take a lot of burden of your shoulders. I personally use Managed Databases myself.

My suggestion for now: Use 1 machine, learn Kubernetes when your application gets more traffic. Look into managed databases (available for Redis and Postgres).

Title: DOCKER environment in production


问:
Why isn't this for loop returning any non-false members?
This for loop isn't returning any true members.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    clientList[indexPath.row].s += 1

    if clientList[indexPath.row].s % 2 == 0 {
        clientList[indexPath.row].isSelected = true
    } else if clientList[indexPath.row].s % 2 != 0{
        clientList[indexPath.row].isSelected = false
    }
}
```

<p>Here is the for-loop:</p>

<pre class="lang-swift prettyprint-override"><code>@IBAction func toClientsButton(_ sender: Any) {
    for y in 0...clientList.count - 1 {
        if clientList[y].isSelected == true {
            clientsSelected.append(clientList[y])
        }
    }
}
</code>```

When the next screen loads, no values are in the clientsSelected array.

Am I doing something wrong?

答: I think I figured it out. I was trying to append everything the array with the @IBAction and segue to the next view controller at the same time, which loaded data from the array. Thanks for the answers, I changed up my code a bit as well.

Body:
This for loop isn't returning any true members.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    clientList[indexPath.row].s += 1

    if clientList[indexPath.row].s % 2 == 0 {
        clientList[indexPath.row].isSelected = true
    } else if clientList[indexPath.row].s % 2 != 0{
        clientList[indexPath.row].isSelected = false
    }
}

Here is the for-loop:

@IBAction func toClientsButton(_ sender: Any) {
    for y in 0...clientList.count - 1 {
        if clientList[y].isSelected == true {
            clientsSelected.append(clientList[y])
        }
    }
}

When the next screen loads, no values are in the clientsSelected array.

Am I doing something wrong?


问:
How to bind configuration to array of JSON Objects .Net Core
I'm trying to bind a JSON file to a model for configuration settings in a dotnet core project.

The json looks like:

```<code>"Settings": {
  "Values": [
  { "Value1": "1" },
  { "Value2": "2" }
]}
</code>```

My model looks like:

```<code>public class Settings
{
    public List<Value> Values{ get; set; }
}

public class Value
{
    public string Value1 { get; set; }

    public string Value2 { get; set; }
}
</code>```

I bind with the following:

```<code>var settings = _configuration.GetSection("Settings").Get<Settings>();
</code>```

But this results in settings containing two Value objects in the list - the first Value object has Value1 = 1 & Value2 = null, and the second Value object has Value1 = null & Value2 = 2. How can I bind such that it settings only has one Value object in Values with both properties populated?

This is not the same as suggested here:
 https://stackoverflow.com/questions/51488845/how-to-read-a-string-array-in-appsettings-json

This is because each object in the array in this case have different properties whereas in the proposed duplicate all objects are consistent.

答:
The easiest way to get your values is probably to make your Class look like this:

```<code>public class Settings
{
    public Dictionary<string, string>[] Values{ get; set; }
}
</code>```

This will be parsed as an Array of Dictionary items, where each item will contain only 1 key-value of your Values.

UPDATE:

You can add a function inside your Settings class to get all the settings as 1 dictionary:

```<code>public Dictionary<string, string> GetSettings()
{
    var settingsValues = new Dictionary<string, string>();
    foreach (var valueDict in Values)
    {
        foreach (var setting in valueDict)
        {
            settingsValues.Add(setting.Key, setting.Value);
        }
    }
    return settingsValues;
}
</code>```

Body:
I'm trying to bind a JSON file to a model for configuration settings in a dotnet core project.

The json looks like:

"Settings": {
  "Values": [
  { "Value1": "1" },
  { "Value2": "2" }
]}

My model looks like:

public class Settings
{
    public List<Value> Values{ get; set; }
}

public class Value
{
    public string Value1 { get; set; }

    public string Value2 { get; set; }
}

I bind with the following:

var settings = _configuration.GetSection("Settings").Get<Settings>();

But this results in settings containing two Value objects in the list - the first Value object has Value1 = 1 & Value2 = null, and the second Value object has Value1 = null & Value2 = 2. How can I bind such that it settings only has one Value object in Values with both properties populated?

This is not the same as suggested here:
 https://stackoverflow.com/questions/51488845/how-to-read-a-string-array-in-appsettings-json

This is because each object in the array in this case have different properties whereas in the proposed duplicate all objects are consistent.

Body:
The easiest way to get your values is probably to make your Class look like this:

public class Settings
{
    public Dictionary<string, string>[] Values{ get; set; }
}

This will be parsed as an Array of Dictionary items, where each item will contain only 1 key-value of your Values.

UPDATE:

You can add a function inside your Settings class to get all the settings as 1 dictionary:

public Dictionary<string, string> GetSettings()
{
    var settingsValues = new Dictionary<string, string>();
    foreach (var valueDict in Values)
    {
        foreach (var setting in valueDict)
        {
            settingsValues.Add(setting.Key, setting.Value);
        }
    }
    return settingsValues;
}


问:
App upload failed because the key was used in other apps
I am trying to upload an app to Google Play in app bundle format but it is failing with the below error -

You uploaded an APK or Android App Bundle that is signed with a key that is also used to sign APKs that are delivered to users. Because you are enrolled in App Signing by Google Play, you should sign your APK or Android App Bundle with a new key before you upload.

I already have some apps released in the market which are signed with the same keystore (but in apk format).

I want to use the same keystore to sign this app as well. Is this possible without creating a new keystore?

答:
This message indicates that you are signing your App Bundle with a key that is used as an app signing key by another of your apps. However the App Bundle should be signed with an app upload key. The two shouldn't be mixed.

The definitions of those terms can be found on this documentation (see "Description of keys, artifacts and tools").

When you enroll in App Signing by Play, the default is for Play to generate the app signing key. If you want Play to sign the APKs it generates with the same key as another of your app, you have to select "(Advanced options) Provide the app signing key that Google Play uses for this app" at the time of enrollment:

Hope that helps,


问:
Push JHipster 6.0.1 to Gitlab repository
After having everything ready to deploy, I realized JHipster doesn't have a Dockerfile anymore and the packaging is done with jib. The generated gitlab-ci.yml has a docker-push stage with a command like this:

```<code>./mvnw jib:build -Djib.to.image=$IMAGE_TAG -Djib.to.auth.username=gitlab-ci-token  -Djib.to.auth.password=$CI_BUILD_TOKEN
</code>```

but it fails with

```<code>[ERROR] Failed to execute goal com.google.cloud.tools:jib-maven-plugin:0.9.11:build (default-cli) on project test-project: Obtaining project build output files failed; make sure you have compiled your project before trying to build the image. (Did you accidentally run "mvn clean jib:build" instead of "mvn clean compile jib:build"?): /builds/amatos/test-project/target/classes -> [Help 1]
</code>```

As that failed, I tried to run the command locally like this:

```<code>./mvnw jib:build -Djib.to.image=registry.gitlab.com/amatos/test-project:v6.0.1 -Djib.to.auth.username=amatos -Djib.to.auth.password=password
</code>```

but instead of trying to connect to Gitlab's registry, it tries to connect to registry.hub.docker.com:

```<code>[INFO] Retrieving registry credentials for registry.hub.docker.com...
</code>```

What I would like to know is: how do I set it to connect to Gitlab instead of Docker Hub?

答: In order to connect to a custom repository, I changed -Djib.to.image to -Dimage and it worked

Body:
After having everything ready to deploy, I realized JHipster doesn't have a Dockerfile anymore and the packaging is done with jib. The generated gitlab-ci.yml has a docker-push stage with a command like this:

./mvnw jib:build -Djib.to.image=$IMAGE_TAG -Djib.to.auth.username=gitlab-ci-token  -Djib.to.auth.password=$CI_BUILD_TOKEN

but it fails with

[ERROR] Failed to execute goal com.google.cloud.tools:jib-maven-plugin:0.9.11:build (default-cli) on project test-project: Obtaining project build output files failed; make sure you have compiled your project before trying to build the image. (Did you accidentally run "mvn clean jib:build" instead of "mvn clean compile jib:build"?): /builds/amatos/test-project/target/classes -> [Help 1]

As that failed, I tried to run the command locally like this:

./mvnw jib:build -Djib.to.image=registry.gitlab.com/amatos/test-project:v6.0.1 -Djib.to.auth.username=amatos -Djib.to.auth.password=password

but instead of trying to connect to Gitlab's registry, it tries to connect to registry.hub.docker.com:

[INFO] Retrieving registry credentials for registry.hub.docker.com...

What I would like to know is: how do I set it to connect to Gitlab instead of Docker Hub?