问:
Embed javascript form 500 Internal Server Error
Context
I would like to offer a bike rental companies (shops) the option to redirect guests to an online reservation process on my platform, so they can let customers make a reservation for a bike of the shop. (e.g. online reservation process is just for their shop)

Current step
My first step is to create an embedded javascript form (form_availability), where shop website visitors can select an arrival, departure date and subsequently see the available bike_categories. To clarify, I would like to show the initial form with arrival and departure options for tthat shop.

Approach

I created an api/v1/shops (routes, controllers and views)

I created an embed.js using webpacker:vue

I implemented <%= javascript_pack_tag "embed" %> in my own app to test (url: http://localhost:3000/en/shops/58/website_integration)

The website of the respective shop is http://localhost:3000

Question

It's the first time I'm doing this, and I get an error messages I don't know how to deal with/solve.

console

```<code>embed.js:23 GET http://localhost:3000/api/v1/shops/http%3A%2F%2Flocalhost%3A3000%2Fen%2Fshops%2F3%2Fwebsite_integration/form_availability 500 (Internal Server Error)

./app/javascript/packs/embed.js @ embed.js:23
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83
</code>```

```<code>{type: "NoMethodError", message: "undefined method `url' for ["http://localhost:3000/en/shops/3/website_integration"]:Array", backtrace: Array(76)}

type: "NoMethodError"
message: "undefined method `url' for ["http://localhost:3000/en/shops/3/website_integration"]:Array"
backtrace: (76) ["/Users/robtuinte/code/Tumble25/camping_pms/app/models/shop.rb:41:in `block in <class:Shop>'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/active_record/relation.rb:288:in `instance_exec'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ib/active_record/relation.rb:288:in `_exec_scope'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…e_record/scoping/named.rb:186:in `block in scope'", "/Users/robtuinte/code/Tumble25/camping_pms/app/con…/v1/shops_controller.rb:16:in `form_availability'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…metal/basic_implicit_render.rb:6:in `send_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…stract_controller/base.rb:194:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…troller/metal/rendering.rb:30:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ller/callbacks.rb:42:in `block in process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ctive_support/callbacks.rb:132:in `run_callbacks'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ct_controller/callbacks.rb:41:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…controller/metal/rescue.rb:22:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…nstrumentation.rb:34:in `block in process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ort/notifications.rb:168:in `block in instrument'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/notifications/instrumenter.rb:23:in `instrument'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tive_support/notifications.rb:168:in `instrument'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…r/metal/instrumentation.rb:32:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…r/metal/params_wrapper.rb:256:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ties/controller_runtime.rb:24:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/abstract_controller/base.rb:134:in `process'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….2.3/lib/action_view/rendering.rb:32:in `process'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/action_controller/metal.rb:191:in `dispatch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/action_controller/metal.rb:252:in `dispatch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…on_dispatch/routing/route_set.rb:52:in `dispatch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ction_dispatch/routing/route_set.rb:34:in `serve'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…dispatch/journey/router.rb:52:in `block in serve'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ib/action_dispatch/journey/router.rb:35:in `each'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/action_dispatch/journey/router.rb:35:in `serve'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ction_dispatch/routing/route_set.rb:840:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…n-js-3.5.1/lib/i18n/js/middleware.rb:14:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…1.2.8/lib/warden/manager.rb:36:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/warden-1.2.8/lib/warden/manager.rb:34:in `catch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…s/warden-1.2.8/lib/warden/manager.rb:34:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ck-2.0.7/lib/rack/tempfile_reaper.rb:15:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…5.0/gems/rack-2.0.7/lib/rack/etag.rb:25:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ck-2.0.7/lib/rack/conditional_get.rb:25:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…5.0/gems/rack-2.0.7/lib/rack/head.rb:12:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…atch/http/content_security_policy.rb:18:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/rack/session/abstract/id.rb:232:in `context'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…0.7/lib/rack/session/abstract/id.rb:226:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tion_dispatch/middleware/cookies.rb:670:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….2.3/lib/active_record/migration.rb:559:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tch/middleware/callbacks.rb:28:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…active_support/callbacks.rb:98:in `run_callbacks'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ion_dispatch/middleware/callbacks.rb:26:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tion_dispatch/middleware/executor.rb:14:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…patch/middleware/debug_exceptions.rb:61:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…0/lib/web_console/middleware.rb:135:in `call_app'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/web_console/middleware.rb:30:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…3.7.0/lib/web_console/middleware.rb:20:in `catch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…-3.7.0/lib/web_console/middleware.rb:20:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…spatch/middleware/show_exceptions.rb:33:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…s-5.2.3/lib/rails/rack/logger.rb:38:in `call_app'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….3/lib/rails/rack/logger.rb:26:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…support/tagged_logging.rb:71:in `block in tagged'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/active_support/tagged_logging.rb:28:in `tagged'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/active_support/tagged_logging.rb:71:in `tagged'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…lties-5.2.3/lib/rails/rack/logger.rb:26:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/sprockets/rails/quiet_assets.rb:13:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ion_dispatch/middleware/remote_ip.rb:81:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….5.0/lib/request_store/middleware.rb:19:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…on_dispatch/middleware/request_id.rb:27:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ck-2.0.7/lib/rack/method_override.rb:22:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/gems/rack-2.0.7/lib/rack/runtime.rb:22:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…e/strategy/local_cache_middleware.rb:29:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tion_dispatch/middleware/executor.rb:14:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ction_dispatch/middleware/static.rb:127:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ems/rack-2.0.7/lib/rack/sendfile.rb:111:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…acker/dev_server_proxy.rb:29:in `perform_request'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…s/rack-proxy-0.6.5/lib/rack/proxy.rb:57:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/railties-5.2.3/lib/rails/engine.rb:524:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…uma-4.1.0/lib/puma/configuration.rb:228:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…-4.1.0/lib/puma/server.rb:664:in `handle_request'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…-4.1.0/lib/puma/server.rb:467:in `process_client'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ma-4.1.0/lib/puma/server.rb:328:in `block in run'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…uma/thread_pool.rb:135:in `block in spawn_thread'"]
__proto__:
</code>```

logs

```<code>Started GET "/api/v1/shops/http%3A%2F%2Flocalhost%3A3000%2Fen%2Fshops%2F3%2Fwebsite_integration/form_availability" for ::1 at 2020-02-18 10:24:21 +0100
Processing by Api::V1::ShopsController#form_availability as JSON
  Parameters: {"id"=>"http://localhost:3000/en/shops/3/website_integration"}
Completed 500 Internal Server Error in 2ms (Views: 0.7ms | ActiveRecord: 0.0ms)
</code>```

Code

routes

```<code>namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :shops, only: [:show] do
        get :form_availability , on: :member
      end
    end
  end
</code>```

controller/api/v1/shops_controller.rb

```<code>class Api::V1::ShopsController < Api::V1::BaseController
  def form_availability
    binding.pry
    @shop = Shop.by_url(params[:id])
    render "shops/form_availability"
  end
end
</code>```

models

```<code>class Shop < ApplicationRecord
  has_many :bike_categories, dependent: :destroy
  has_many :bikes, through: :bike_categories
  has_many :reservations, dependent: :destroy

  def self.by_url(url)
    binding.pry
    uri = url.split("?").first
    uri.sub!(/\/$/, '')

    where(website: uri)
  end
end

class Reservation < ApplicationRecord
  belongs_to :shop
  belongs_to :bike
end

class Bike < ApplicationRecord
  belongs_to :bike_category
  has_many :reservations, dependent: :destroy
end

class BikeCategory < ApplicationRecord
  belongs_to :shop
  has_many :bikes, dependent: :destroy
end
</code>```

javascript/packs/embed.js

```<code>let url = window.location.href

fetch(`http://localhost:3000/api/v1/shops/${encodeURIComponent(url)}/form_availability`,{
  headers: {accept: 'application/json'}
})
.then(response => response.json())
.then(data => console.log(data))```

views/api/vi/shop/form_availability.json.jbuilder
```

<p>json.extract! @shop, :id, :name, :slug, :description, :street, :street_number, :zipcode, :city, :country, :email, :phone, :website, :vat_number, :currency, :photo, :test_modus, :default_vat, :price_notation, :paytime, :billing_id, :default_shop_language, :default_age_table, :inv_pay_deadline</p>

```

```

答:
The reason why you are seeing this error, is because the server is responding with a 404 and this is being delivered in HTML rather than JSON format.

You will find some guidance to get error messages in JSON for api requests here (might be helpful for better error handling and debugging):

Need to return JSON-formatted 404 error in Rails

The problem why you are getting back a 404 in this particular case though, is that the URL in the fetch call is composed incorrectly. There are two issues here:

There is a typo - http://localhost:3000/api/vi/... - it should be v1 as defined in your routes, not vi.

The URI schema in the javascript is composed incorrectly - you can see all available routes per your route definitions by executing rails routes. You should be able to find the correct URI pattern in the output - /api/v1/dummies/:id/form_availability(.:format) in your case.

So, your embed.js should look something like this:

```<code>let url = window.location.href

fetch(`http://localhost:3000/api/v1/shops/${encodeURIComponent(url)}/form_availability`,{
  headers: {accept: 'application/json'}
})
.then(response => response.json())
.then(data => console.log(data))
</code>```

One comment to the class method self.by_url(url) that you defined in the Shop model. The standard way of doing this, is using scopes (https://guides.rubyonrails.org/active_record_querying.html#scopes).

So in your model it should be something like this instead of the class method:

```<code>scope :by_url, ->(url) { where(website: url.split('?').first.sub(/\/$/, '')) }
</code>```

Body:
Context
I would like to offer a bike rental companies (shops) the option to redirect guests to an online reservation process on my platform, so they can let customers make a reservation for a bike of the shop. (e.g. online reservation process is just for their shop)

Current step
My first step is to create an embedded javascript form (form_availability), where shop website visitors can select an arrival, departure date and subsequently see the available bike_categories. To clarify, I would like to show the initial form with arrival and departure options for tthat shop.

Approach

I created an api/v1/shops (routes, controllers and views)

I created an embed.js using webpacker:vue

I implemented <%= javascript_pack_tag "embed" %> in my own app to test (url: http://localhost:3000/en/shops/58/website_integration)

The website of the respective shop is http://localhost:3000

Question

It's the first time I'm doing this, and I get an error messages I don't know how to deal with/solve.

console

embed.js:23 GET http://localhost:3000/api/v1/shops/http%3A%2F%2Flocalhost%3A3000%2Fen%2Fshops%2F3%2Fwebsite_integration/form_availability 500 (Internal Server Error)

./app/javascript/packs/embed.js @ embed.js:23
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83

{type: "NoMethodError", message: "undefined method `url' for ["http://localhost:3000/en/shops/3/website_integration"]:Array", backtrace: Array(76)}

type: "NoMethodError"
message: "undefined method `url' for ["http://localhost:3000/en/shops/3/website_integration"]:Array"
backtrace: (76) ["/Users/robtuinte/code/Tumble25/camping_pms/app/models/shop.rb:41:in `block in <class:Shop>'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/active_record/relation.rb:288:in `instance_exec'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ib/active_record/relation.rb:288:in `_exec_scope'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…e_record/scoping/named.rb:186:in `block in scope'", "/Users/robtuinte/code/Tumble25/camping_pms/app/con…/v1/shops_controller.rb:16:in `form_availability'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…metal/basic_implicit_render.rb:6:in `send_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…stract_controller/base.rb:194:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…troller/metal/rendering.rb:30:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ller/callbacks.rb:42:in `block in process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ctive_support/callbacks.rb:132:in `run_callbacks'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ct_controller/callbacks.rb:41:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…controller/metal/rescue.rb:22:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…nstrumentation.rb:34:in `block in process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ort/notifications.rb:168:in `block in instrument'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/notifications/instrumenter.rb:23:in `instrument'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tive_support/notifications.rb:168:in `instrument'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…r/metal/instrumentation.rb:32:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…r/metal/params_wrapper.rb:256:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ties/controller_runtime.rb:24:in `process_action'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/abstract_controller/base.rb:134:in `process'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….2.3/lib/action_view/rendering.rb:32:in `process'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/action_controller/metal.rb:191:in `dispatch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/action_controller/metal.rb:252:in `dispatch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…on_dispatch/routing/route_set.rb:52:in `dispatch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ction_dispatch/routing/route_set.rb:34:in `serve'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…dispatch/journey/router.rb:52:in `block in serve'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ib/action_dispatch/journey/router.rb:35:in `each'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/action_dispatch/journey/router.rb:35:in `serve'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ction_dispatch/routing/route_set.rb:840:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…n-js-3.5.1/lib/i18n/js/middleware.rb:14:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…1.2.8/lib/warden/manager.rb:36:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/warden-1.2.8/lib/warden/manager.rb:34:in `catch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…s/warden-1.2.8/lib/warden/manager.rb:34:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ck-2.0.7/lib/rack/tempfile_reaper.rb:15:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…5.0/gems/rack-2.0.7/lib/rack/etag.rb:25:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ck-2.0.7/lib/rack/conditional_get.rb:25:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…5.0/gems/rack-2.0.7/lib/rack/head.rb:12:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…atch/http/content_security_policy.rb:18:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/rack/session/abstract/id.rb:232:in `context'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…0.7/lib/rack/session/abstract/id.rb:226:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tion_dispatch/middleware/cookies.rb:670:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….2.3/lib/active_record/migration.rb:559:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tch/middleware/callbacks.rb:28:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…active_support/callbacks.rb:98:in `run_callbacks'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ion_dispatch/middleware/callbacks.rb:26:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tion_dispatch/middleware/executor.rb:14:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…patch/middleware/debug_exceptions.rb:61:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…0/lib/web_console/middleware.rb:135:in `call_app'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/web_console/middleware.rb:30:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…3.7.0/lib/web_console/middleware.rb:20:in `catch'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…-3.7.0/lib/web_console/middleware.rb:20:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…spatch/middleware/show_exceptions.rb:33:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…s-5.2.3/lib/rails/rack/logger.rb:38:in `call_app'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….3/lib/rails/rack/logger.rb:26:in `block in call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…support/tagged_logging.rb:71:in `block in tagged'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/active_support/tagged_logging.rb:28:in `tagged'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…b/active_support/tagged_logging.rb:71:in `tagged'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…lties-5.2.3/lib/rails/rack/logger.rb:26:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/lib/sprockets/rails/quiet_assets.rb:13:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ion_dispatch/middleware/remote_ip.rb:81:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge….5.0/lib/request_store/middleware.rb:19:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…on_dispatch/middleware/request_id.rb:27:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ck-2.0.7/lib/rack/method_override.rb:22:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/gems/rack-2.0.7/lib/rack/runtime.rb:22:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…e/strategy/local_cache_middleware.rb:29:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…tion_dispatch/middleware/executor.rb:14:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ction_dispatch/middleware/static.rb:127:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ems/rack-2.0.7/lib/rack/sendfile.rb:111:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…acker/dev_server_proxy.rb:29:in `perform_request'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…s/rack-proxy-0.6.5/lib/rack/proxy.rb:57:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…/railties-5.2.3/lib/rails/engine.rb:524:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…uma-4.1.0/lib/puma/configuration.rb:228:in `call'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…-4.1.0/lib/puma/server.rb:664:in `handle_request'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…-4.1.0/lib/puma/server.rb:467:in `process_client'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…ma-4.1.0/lib/puma/server.rb:328:in `block in run'", "/Users/robtuinte/.rbenv/versions/2.5.3/lib/ruby/ge…uma/thread_pool.rb:135:in `block in spawn_thread'"]
__proto__:

logs

Started GET "/api/v1/shops/http%3A%2F%2Flocalhost%3A3000%2Fen%2Fshops%2F3%2Fwebsite_integration/form_availability" for ::1 at 2020-02-18 10:24:21 +0100
Processing by Api::V1::ShopsController#form_availability as JSON
  Parameters: {"id"=>"http://localhost:3000/en/shops/3/website_integration"}
Completed 500 Internal Server Error in 2ms (Views: 0.7ms | ActiveRecord: 0.0ms)

Code

routes

namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :shops, only: [:show] do
        get :form_availability , on: :member
      end
    end
  end

controller/api/v1/shops_controller.rb

class Api::V1::ShopsController < Api::V1::BaseController
  def form_availability
    binding.pry
    @shop = Shop.by_url(params[:id])
    render "shops/form_availability"
  end
end

models

class Shop < ApplicationRecord
  has_many :bike_categories, dependent: :destroy
  has_many :bikes, through: :bike_categories
  has_many :reservations, dependent: :destroy

  def self.by_url(url)
    binding.pry
    uri = url.split("?").first
    uri.sub!(/\/$/, '')

    where(website: uri)
  end
end

class Reservation < ApplicationRecord
  belongs_to :shop
  belongs_to :bike
end

class Bike < ApplicationRecord
  belongs_to :bike_category
  has_many :reservations, dependent: :destroy
end

class BikeCategory < ApplicationRecord
  belongs_to :shop
  has_many :bikes, dependent: :destroy
end

javascript/packs/embed.js

let url = window.location.href

fetch(`http://localhost:3000/api/v1/shops/${encodeURIComponent(url)}/form_availability`,{
  headers: {accept: 'application/json'}
})
.then(response => response.json())
.then(data => console.log(data))```

views/api/vi/shop/form_availability.json.jbuilder

json.extract! @shop, :id, :name, :slug, :description, :street, :street_number, :zipcode, :city, :country, :email, :phone, :website, :vat_number, :currency, :photo, :test_modus, :default_vat, :price_notation, :paytime, :billing_id, :default_shop_language, :default_age_table, :inv_pay_deadline

Body:
The reason why you are seeing this error, is because the server is responding with a 404 and this is being delivered in HTML rather than JSON format.

You will find some guidance to get error messages in JSON for api requests here (might be helpful for better error handling and debugging):

Need to return JSON-formatted 404 error in Rails

The problem why you are getting back a 404 in this particular case though, is that the URL in the fetch call is composed incorrectly. There are two issues here:

There is a typo - http://localhost:3000/api/vi/... - it should be v1 as defined in your routes, not vi.

The URI schema in the javascript is composed incorrectly - you can see all available routes per your route definitions by executing rails routes. You should be able to find the correct URI pattern in the output - /api/v1/dummies/:id/form_availability(.:format) in your case.

So, your embed.js should look something like this:

let url = window.location.href

fetch(`http://localhost:3000/api/v1/shops/${encodeURIComponent(url)}/form_availability`,{
  headers: {accept: 'application/json'}
})
.then(response => response.json())
.then(data => console.log(data))

One comment to the class method self.by_url(url) that you defined in the Shop model. The standard way of doing this, is using scopes (https://guides.rubyonrails.org/active_record_querying.html#scopes).

So in your model it should be something like this instead of the class method:

scope :by_url, ->(url) { where(website: url.split('?').first.sub(/\/$/, '')) }


来源: stackexchange

问:
Python: Removing list element while iterating over list
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

```<code>for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list
</code>```

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

答:
To meet these criteria: modify original list in situ, no list copies, only one pass, works, a traditional solution is to iterate backwards:

```<code>for i in xrange(len(somelist) - 1, -1, -1):
    element = somelist[i]
    do_action(element)
    if check(element):
        del somelist[i]
</code>```

Bonus: Doesn't do len(somelist) on each iteration. Works on any version of Python (at least as far back as 1.5.2) ... s/xrange/range/ for 3.X.

Update: If you want to iterate forwards, it's possible, just trickier and uglier:

```<code>i = 0
n = len(somelist)
while i < n:
    element = somelist[i]
    do_action(element)
    if check(element):
        del somelist[i]
        n = n - 1
    else:
        i = i + 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list

What should I use in place of remove_element?
I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

Body:
To meet these criteria: modify original list in situ, no list copies, only one pass, works, a traditional solution is to iterate backwards:

for i in xrange(len(somelist) - 1, -1, -1):
    element = somelist[i]
    do_action(element)
    if check(element):
        del somelist[i]

Bonus: Doesn't do len(somelist) on each iteration. Works on any version of Python (at least as far back as 1.5.2) ... s/xrange/range/ for 3.X.

Update: If you want to iterate forwards, it's possible, just trickier and uglier:

i = 0
n = len(somelist)
while i < n:
    element = somelist[i]
    do_action(element)
    if check(element):
        del somelist[i]
        n = n - 1
    else:
        i = i + 1


问:
Is it possible to select more statements in SQLite?
I have the following code :

```<code>SELECT Description FROM KeysDB WHERE Count='0 (Blocked)' OR ErrorCode='0xC004C060' AND Description LIKE '%Win%'
</code>```

It works normally until I change it.

```<code>SELECT Description FROM KeysDB WHERE Count='0 (Blocked)' OR ErrorCode='0xC004C003' OR ErrorCode='0xC004C060' AND Description LIKE '%Win%'
</code>```

I want to select all Windows product key with Count = 0 (Blocked) or ErrorCode = 0xC004C060 or ErrorCode = 0xC004C003

答:
and / or have different operator precedence. That means their binding strength is differently.

You can use parentheses to make it how you like. Not sure if this is how you intended it but you get the picture:

```<code>SELECT Description
FROM KeysDB
WHERE
(
   Count='0 (Blocked)' OR ErrorCode='0xC004C003' OR ErrorCode='0xC004C060'
)
AND Description LIKE '%Win%'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following code :

SELECT Description FROM KeysDB WHERE Count='0 (Blocked)' OR ErrorCode='0xC004C060' AND Description LIKE '%Win%'

It works normally until I change it.

SELECT Description FROM KeysDB WHERE Count='0 (Blocked)' OR ErrorCode='0xC004C003' OR ErrorCode='0xC004C060' AND Description LIKE '%Win%'

I want to select all Windows product key with Count = 0 (Blocked) or ErrorCode = 0xC004C060 or ErrorCode = 0xC004C003

Body:
and / or have different operator precedence. That means their binding strength is differently.

You can use parentheses to make it how you like. Not sure if this is how you intended it but you get the picture:

SELECT Description
FROM KeysDB
WHERE
(
   Count='0 (Blocked)' OR ErrorCode='0xC004C003' OR ErrorCode='0xC004C060'
)
AND Description LIKE '%Win%'


问:
Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes
```<code>Exception in thread "main" java.lang.SecurityException: Invalid signature file d                    igest for Manifest main attributes
        at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVeri                    fier.java:240)
        at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier                    .java:193)
        at java.util.jar.JarVerifier.processEntry(JarVerifier.java:262)
        at java.util.jar.JarVerifier.update(JarVerifier.java:216)
        at java.util.jar.JarFile.initializeVerifier(JarFile.java:341)
        at java.util.jar.JarFile.getInputStream(JarFile.java:406)
        at sun.misc.URLClassPath$JarLoader$2.getInputStream(URLClassPath.java:75                    2)
        at sun.misc.Resource.cachedInputStream(Resource.java:77)
        at sun.misc.Resource.getByteBuffer(Resource.java:160)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:436)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480)
</code>```

Hi i am getting this error and i was wondering if anybody could tell me what was causing this.This is the snapshot of pox file of my project. Any help would be appreciated.

```<code><dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.50</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.29</version>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1101-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>org.objectweb.joram</groupId>
        <artifactId>jftp</artifactId>
        <version>1.52</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.2</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <artifactSet>
                            <excludes>
                                <exclude>junit:junit</exclude>
                                <exclude>org.apache.maven:lib:tests</exclude>
                            </excludes>
                        </artifactSet>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

答:
This error means that maven shade plugin has modified one of your dependencies hence the signature for those libraries are invalid.

remove the signature files is a work around and a solution depending on your use case. For me it is a bad practice so I ended up replacing the maven shade plugin for Apache Maven Assembly Plugin to create the jar with the dependencies and seems to work https://maven.apache.org/plugins/maven-assembly-plugin/

example:

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>
                                    your.class.with.main.method
                                </mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

build your jar with dependencies included:

```<code>mvn package
</code>```

Body:
Exception in thread "main" java.lang.SecurityException: Invalid signature file d                    igest for Manifest main attributes
        at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVeri                    fier.java:240)
        at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier                    .java:193)
        at java.util.jar.JarVerifier.processEntry(JarVerifier.java:262)
        at java.util.jar.JarVerifier.update(JarVerifier.java:216)
        at java.util.jar.JarFile.initializeVerifier(JarFile.java:341)
        at java.util.jar.JarFile.getInputStream(JarFile.java:406)
        at sun.misc.URLClassPath$JarLoader$2.getInputStream(URLClassPath.java:75                    2)
        at sun.misc.Resource.cachedInputStream(Resource.java:77)
        at sun.misc.Resource.getByteBuffer(Resource.java:160)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:436)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480)

Hi i am getting this error and i was wondering if anybody could tell me what was causing this.This is the snapshot of pox file of my project. Any help would be appreciated.

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.50</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.29</version>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1101-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>org.objectweb.joram</groupId>
        <artifactId>jftp</artifactId>
        <version>1.52</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.2</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <artifactSet>
                            <excludes>
                                <exclude>junit:junit</exclude>
                                <exclude>org.apache.maven:lib:tests</exclude>
                            </excludes>
                        </artifactSet>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Body:
This error means that maven shade plugin has modified one of your dependencies hence the signature for those libraries are invalid.

remove the signature files is a work around and a solution depending on your use case. For me it is a bad practice so I ended up replacing the maven shade plugin for Apache Maven Assembly Plugin to create the jar with the dependencies and seems to work https://maven.apache.org/plugins/maven-assembly-plugin/

example:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>
                                    your.class.with.main.method
                                </mainClass>
                            </manifest>
                        </archive>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </execution>
            </executions>
        </plugin>

build your jar with dependencies included:

mvn package


问:
SSDT crashes when SSIS package tries to access MS-Access database
We want to migrate SSIS packages from 2008 to 2014.

We have Windows10 + Visual Studio Proff 2015 + SSDT 2015: When we try access a MS-Access database (particularly *.accdb) file from DataFlow tax. As soon as we add the *.accdb file into connectionManager and clicks ok. It starts validating the OLEDB connection, and then Visual Studio gets crashed.

Same is happening with Windows10 + Visual Studio 2010 (shell) + SQL Server 2012 Business Intelligence with Service Pack 4.

After this it will crash as soon as we open the project again. This is because as soon as you open project will open SSIS package into design mode, connection manager will again try to validate it. You can avoid design time validation, but then ultimately it will crash again while running.

ConnStr: "Data Source=C:\Users\abc.accdb;Provider=Microsoft.ACE.OLEDB.12.0;"

When we tried to find out the reasons, we could find two specific things.

A) In the event log we saw two consistent errors every times VS crashes.

i) This error is same every time:

Faulting application name: devenv.exe, version: 14.0.25420.1, time stamp: 0x57685d85
Faulting module name: mso40uiwin32client.dll, version: 16.0.4666.1000, time stamp: 0x5a8363ef
Exception code: 0xc0000005
Fault offset: 0x0014a102
Faulting process id: 0x3730
Faulting application start time: 0x01d3e8600acedd50
Faulting application path: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe
Faulting module path: C:\Program Files (x86)\Common Files\Microsoft Shared\Office16\mso40uiwin32client.dll
Report Id: c54747c6-db07-4897-82aa-02ae596645b1
Faulting package full name:
Faulting package-relative application ID:

ii) AccessViolation exception is common, however stack would shown some or the other assemblies each time.

Application: devenv.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at Microsoft.SqlServer.Dts.Pipeline.Wrapper.CManagedComponentWrapperClass.AcquireConnections(System.Object)
   at Microsoft.DataTransformationServices.Design.PipelineUtils.AcquireConnections(Microsoft.SqlServer.Dts.Pipeline.Wrapper.IDTSComponentMetaData100, Microsoft.SqlServer.Dts.Runtime.Connections, Boolean)
   at Microsoft.DataTransformationServices.Design.DtsComponentDesigner+<>c__DisplayClass3.<ValidateComponentInternal>b__0()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr, System.Object[], System.Object, System.Object[] ByRef)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Messaging.IMessageSink)
   at System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(System.Object)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Notes:
Following workarounds have been tried till now but no luck.

Tried running SSDT under administrator.

Edit 'shownfirstrunoptin' property in registry.

Reinstall Visual Studio 2015.

Reinstall SSDT 2015

Reinstall SQL Server 2012 Business Intelligence with Service Pack 4.

Using 'Target Server Version' as 2012/14/16.

Run64BitRunTime to true/false.

In connection mgr: Using both 12.0 and 16.0 OLEDB providers.

Other package which is using *.mdb is running fine.

答:
I've had a similar problem when using (SSIS) OLEDB Source connecting to the MS Access 2016 database. SSDT Visual Studio 2017 would just freeze forever. I had to kill VS with a Task Manager.
I solved it by using ADO NET Source (instead of OLEDB Source) and .Net Provider for OleDB/Microsoft Office 16.0 Access.

If you close a solution with Access data source, then you have to close the visual studio as well before opening your solution with Access data source.

Sounds very flaky to me guys. Need to test after deployed again - low confidence though :(


问:
Find next or previous ID when query contains multiple cases
I am looking for the most efficient way to find the next or previous ID of the following query:

```<code>SELECT *
  FROM transactions
 ORDER
    BY CASE order_status
       WHEN 'order_accepted' THEN 1
       WHEN 'processing_order' THEN 2
       WHEN 'order_send_mailer' THEN 3
       WHEN 'order_send' THEN 4
       WHEN 'order_received' THEN 5
       WHEN 'order_refunded' THEN 6
       ELSE 7 END
      , id DESC limit 1;
</code>```

I tried adding a where id > '$id' or where id < '$id' claus to the query but it didn't give me te next or previous ID I was looking for.

For those that need some explanation of what I am trying to do: It's to go to the next or previous order by case with a forward of backward button.

What it currently looks like:

```<code>-id- -order_status-
9399 order_accepted
9398 processing_order
9363 processing_order
9403 order_send_mailer
9318 order_send
9346 order_received
9345 order_received
9050 order_refunded
</code>```

The next ID for example of 9403 would be 9363 and previous ID would be 9318

答:
Change your order_status into an enum column. This will save disk space and make sorting by order_status simpler and faster.

```<code>-- Add a new version of the column using an enum.
-- These strings are aliases for ordered numbers.
-- 'order_accepted' is 1, 'processing_order' is 2, etc.
alter table transactions add column enum_order_status enum(
    'order_accepted',
    'processing_order',
    'order_send_mailer',
    'order_send',
    'order_received',
    'order_refunded'
  ) not null;

-- Copy the status into the new enum column.
-- MySQL will translate the string into the number for you.
update transactions
set enum_order_status = order_status;

-- Drop the old column.
alter table transactions drop column order_status;

-- Rename the new enum column.
alter table transactions rename column enum_order_status to order_status;

-- Index it.
create index transactions_order_status on transactions(order_status);

-- Enjoy your vastly simplified and much faster query.
select *
from transactions
order by order_status, id desc
</code>```

That's not actually necessary, but it makes everything much simpler.

With that out of the way, use the window functions lead and lag to refer to the previous and next rows in a query.

```<code>select
  id, order_status,
  lead(id) over w, lead(order_status) over w,
  lag(id) over w, lag(order_status) over w
from transactions
window w as (order by order_status, id desc);
</code>```

Note, window functions were added in MySQL 8. If you're using an older version I recommend upgrading ASAP; MySQL 8 has many big improvements. Otherwise you can simulate it with correlated subqueries and self-joins.

If you want the previous and next rows of a specific row, use the technique from this answer. We add row_numbers to the table in the desired order, and then fetch 9403 and its previous and next row by row number.

```<code>-- Add a row number to your table in the desired order.
with ordered_transactions as (
  select
    *, row_number() over w as rn
  from transactions
  window w as (order by order_status, id desc)
)
select *
from ordered_transactions
-- Find the row number for ID 9403, then add -1, 0, and 1.
-- If 9403 is row number 5 you'll fetch row numbers 4, 5, and 6.
where ot.rn in (
  select rn+i
  from ordered_transactions ot
  -- All this is doing is making us three "rows" where i = -1, 0, and 1.
  cross join (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) cj
  where ot.id = 9403
);
</code>```

Try it.

Body:
I am looking for the most efficient way to find the next or previous ID of the following query:

SELECT *
  FROM transactions
 ORDER
    BY CASE order_status
       WHEN 'order_accepted' THEN 1
       WHEN 'processing_order' THEN 2
       WHEN 'order_send_mailer' THEN 3
       WHEN 'order_send' THEN 4
       WHEN 'order_received' THEN 5
       WHEN 'order_refunded' THEN 6
       ELSE 7 END
      , id DESC limit 1;

I tried adding a where id > '$id' or where id < '$id' claus to the query but it didn't give me te next or previous ID I was looking for.

For those that need some explanation of what I am trying to do: It's to go to the next or previous order by case with a forward of backward button.

What it currently looks like:

-id- -order_status-
9399 order_accepted
9398 processing_order
9363 processing_order
9403 order_send_mailer
9318 order_send
9346 order_received
9345 order_received
9050 order_refunded

The next ID for example of 9403 would be 9363 and previous ID would be 9318

Body:
Change your order_status into an enum column. This will save disk space and make sorting by order_status simpler and faster.

-- Add a new version of the column using an enum.
-- These strings are aliases for ordered numbers.
-- 'order_accepted' is 1, 'processing_order' is 2, etc.
alter table transactions add column enum_order_status enum(
    'order_accepted',
    'processing_order',
    'order_send_mailer',
    'order_send',
    'order_received',
    'order_refunded'
  ) not null;

-- Copy the status into the new enum column.
-- MySQL will translate the string into the number for you.
update transactions
set enum_order_status = order_status;

-- Drop the old column.
alter table transactions drop column order_status;

-- Rename the new enum column.
alter table transactions rename column enum_order_status to order_status;

-- Index it.
create index transactions_order_status on transactions(order_status);

-- Enjoy your vastly simplified and much faster query.
select *
from transactions
order by order_status, id desc

That's not actually necessary, but it makes everything much simpler.

With that out of the way, use the window functions lead and lag to refer to the previous and next rows in a query.

select
  id, order_status,
  lead(id) over w, lead(order_status) over w,
  lag(id) over w, lag(order_status) over w
from transactions
window w as (order by order_status, id desc);

Note, window functions were added in MySQL 8. If you're using an older version I recommend upgrading ASAP; MySQL 8 has many big improvements. Otherwise you can simulate it with correlated subqueries and self-joins.

If you want the previous and next rows of a specific row, use the technique from this answer. We add row_numbers to the table in the desired order, and then fetch 9403 and its previous and next row by row number.

-- Add a row number to your table in the desired order.
with ordered_transactions as (
  select
    *, row_number() over w as rn
  from transactions
  window w as (order by order_status, id desc)
)
select *
from ordered_transactions
-- Find the row number for ID 9403, then add -1, 0, and 1.
-- If 9403 is row number 5 you'll fetch row numbers 4, 5, and 6.
where ot.rn in (
  select rn+i
  from ordered_transactions ot
  -- All this is doing is making us three "rows" where i = -1, 0, and 1.
  cross join (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) cj
  where ot.id = 9403
);

Try it.


问:
in node.js im unable to pass a variable to a member function of a class
I fixed this the right code is below

Im using mongodb and im trying to create a authentication function isAuthenticated that returns true or false if the user is in the database through a callback function. However I can't bring callback inside of client.connect . Im wondering why this is and what I could do to do this.

```<code>function isAuthenticated(username, password, callback1)
{

  //callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err, callback1) {      //client.connect is the mongodb client object

    //callback1(true); <<<<<<< THIS DOESNT WORK HERE SAYS callback is not a function

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});
</code>```

right code:

```<code>function isAuthenticated(username, password, callback1)
{

  return callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err) {      //client.connect is the mongodb client object

    return callback1(true); <<<<<<< WORKS NOW

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});
</code>```

答:
You have a very big misunderstanding of how functions work in javascript. First, let's fix your bug. Simply remove the second callback1 in your code:

```<code>function isAuthenticated(username, password, callback1)
{

  client.connect(url, function(err, db) {
    callback1(true); <<<<<<< THIS WORKS PERFECTLY FINE
  });

}
</code>```

Explaining the basics of how all this works in javascript is beyond the scope of a single answer. It involves first-class functions, anonymous functions and closures - that's at least two question's worth of answers. I suggest you google "javascript first class functions" and watch/read through the articles and tutorials.

Body:
I fixed this the right code is below

Im using mongodb and im trying to create a authentication function isAuthenticated that returns true or false if the user is in the database through a callback function. However I can't bring callback inside of client.connect . Im wondering why this is and what I could do to do this.

function isAuthenticated(username, password, callback1)
{

  //callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err, callback1) {      //client.connect is the mongodb client object

    //callback1(true); <<<<<<< THIS DOESNT WORK HERE SAYS callback is not a function

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});

right code:

function isAuthenticated(username, password, callback1)
{

  return callback1(true); <<<<<<<<<THIS WORKS HERE

  client.connect(function(err) {      //client.connect is the mongodb client object

    return callback1(true); <<<<<<< WORKS NOW

  });
}

////
////

//this is how im calling the isAthenticated function in my route
isAuthenticated("user1", "pass1", function(result)
{
    console.log("callback ran");
    console.log("result: " + result);
});

Body:
You have a very big misunderstanding of how functions work in javascript. First, let's fix your bug. Simply remove the second callback1 in your code:

function isAuthenticated(username, password, callback1)
{

  client.connect(url, function(err, db) {
    callback1(true); <<<<<<< THIS WORKS PERFECTLY FINE
  });

}

Explaining the basics of how all this works in javascript is beyond the scope of a single answer. It involves first-class functions, anonymous functions and closures - that's at least two question's worth of answers. I suggest you google "javascript first class functions" and watch/read through the articles and tutorials.


问:
How do I rotate a html canvas shape by only using a transform?
I am wondering how you can rotate an image by only using the transform function. From my understanding this is not possible, since the only things you can do with transform are the following:

Horizontal scaling

Horizontal skewing

Vertical skewing

Vertical scaling

Horizontal moving

Vertical moving

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations

And I don't see how any of these would be able to rotate the shape, is this even possible. I assume it must be possible, since rotate is in-fact a type transformation.

答:
use transform "rotate".and use it as below

p{
  color:red;
  font-size:12px;
  text-align:center;
}

.rotate1{
  transform:rotate(45deg);
    margin-top:40px;
}

.rotate2{
  transform:rotate(90deg);
  margin-top:40px;
}

.rotate3{
  transform:rotate(180deg);
  margin-top:40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="rotate1">ROTATE1</p>
<p class="rotate2">ROTATE2</p>
<p class="rotate3">ROTATE3</p></code>```

Body:
use transform "rotate".and use it as below

p{
  color:red;
  font-size:12px;
  text-align:center;
}

.rotate1{
  transform:rotate(45deg);
    margin-top:40px;
}

.rotate2{
  transform:rotate(90deg);
  margin-top:40px;
}

.rotate3{
  transform:rotate(180deg);
  margin-top:40px;
}

<p class="rotate1">ROTATE1</p>
<p class="rotate2">ROTATE2</p>
<p class="rotate3">ROTATE3</p>


问:
How to skip the first row of data in SQL Query?
I have this code:

select DOLFUT from [DATABASE $]

How do I get it to get data from the 2nd line? (skip only the first line of data and collect all the rest)

答:
You can use LIMIT to skip any number of row you want. Something like

```<code>SELECT * FROM table
LIMIT 1 OFFSET 10
</code>```

```<code>SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15
</code>```

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

```<code>SELECT * FROM tbl LIMIT 95,18446744073709551615;
</code>```

With one argument, the value specifies the number of rows to return from the beginning of the result set:

```<code>SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows
</code>```

MySql docs

Body:
You can use LIMIT to skip any number of row you want. Something like

SELECT * FROM table
LIMIT 1 OFFSET 10

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows

MySql docs


问:
Dynamic data from v-for displayed in imported modal using slots
Problem:
I have a v-for of cards with interpolated data. When someone clicks a card, it triggers a modal component (separate component, using slots).

I want to display the data (title, img, previewUrl, downloadUrl) for whatever card was clicked in the modal, but currently I'm getting an error:
 is not defined on the instance but referenced during render

Obviously data is not getting passed into the modal, even though I'm referencing the (card). I want to pass it the index of the card that was clicked, but am unsure of the best way to do this.

I assume that slots can be used to pass dynamic v-for data in the way I'm doing it. I hope I won't have to switch to props as that would muddy things.

Tried so far:

{{ card.title }}

{{ card.subtitle }}

        <Modal v-show="isModalVisible" @close="closeModal">
            <template v-slot:header>{{ img }} </template>
            <template v-slot:body>
              {{ title }}

                <button class="modal-btn btn btn-large">Preview</button>
                <button class="modal-btn btn btn-large">Download</button>

            </template>
          </Modal>

DATA

```<code>`cards: [
        {
          title: "Card Title",
          subtitle: "Card subtitle",
          img: require("@/assets/images/test.jpg"),
          previewUrl: "https://test.com",
          downloadUrl: "https://test.com"
        },`
</code>```

METHODS:

```<code>  `methods: {
    showModal(card) {
      this.isModalVisible = true;
      this.title = card.title;
      this.img = card.img;
      this.previewUrl = card.previewUrl;
      this.downloadUrl = card.downloadUrl;
      this.isModalVisible = true;
    },
    closeModal() {
      this.isModalVisible = false;
    }
  }`
</code>```

The imported modal component

```<code>`<template>
  <div>
    <div class="modal-backdrop" @click.self="close">
      <div class="card relative">
        <button type="button" class="btn-close" @click="close">
          <i class="material-icons">clear</i>
        </button>
        <header class="modal-header mb-1">
          <slot name="header" />
        </header>
        <div class="mt-1 text-center">
          <slot name="header-sub" />
        </div>
        <slot name="body" />
        <footer class="text-center p-2">
          <slot name="footer" />
        </footer>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "modal",

  methods: {
    close() {
      this.$emit("close");
    }
  }
};
</script>`
</code>```

答:
you should set the data of modal before and in the click set the correct info

for example in you data set

```<code>{
modalInfo:{title:'',img:''}
}
</code>```

then in click set it like this

```<code> showModal(card) {
      this.modalInfo.title = card.title;
      this.modalInfo.img = card.img;
      this.isModalVisible = true;
    }
</code>```

and in the modal part set it like this

```<code>        <!-- Cards -->
        <div class="card-wrapper">
          <div v-for="(card, index) in cards" :key="index" class="card">
            <div @click="showModal(card)" class="card-body">
              <img :src="card.img" alt="resource img" />
              <h4 class="card-title">{{ card.title }}</h4>
              <h6 class="card-subtitle">{{ card.subtitle }}</h6>
            </div>
          </div>
        </div>
<!-- MODAL -->
        <Modal v-show="isModalVisible" @close="closeModal">
            <template v-slot:header>{{ modalInfo.img }} </template>
            <template v-slot:body>
              {{ modalInfo.title }}
              <div class="text-center mb-1 mt-2">
                <a :href="previewUrl"><button class="modal-btn btn btn-large">Preview</button></a>
</code>```

Body:
Problem:
I have a v-for of cards with interpolated data. When someone clicks a card, it triggers a modal component (separate component, using slots).

I want to display the data (title, img, previewUrl, downloadUrl) for whatever card was clicked in the modal, but currently I'm getting an error:
 is not defined on the instance but referenced during render

Obviously data is not getting passed into the modal, even though I'm referencing the (card). I want to pass it the index of the card that was clicked, but am unsure of the best way to do this.

I assume that slots can be used to pass dynamic v-for data in the way I'm doing it. I hope I won't have to switch to props as that would muddy things.

Tried so far:

{{ card.title }}

{{ card.subtitle }}

        <Modal v-show="isModalVisible" @close="closeModal">
            <template v-slot:header>{{ img }} </template>
            <template v-slot:body>
              {{ title }}

                <button class="modal-btn btn btn-large">Preview</button>
                <button class="modal-btn btn btn-large">Download</button>

            </template>
          </Modal>

DATA

`cards: [
        {
          title: "Card Title",
          subtitle: "Card subtitle",
          img: require("@/assets/images/test.jpg"),
          previewUrl: "https://test.com",
          downloadUrl: "https://test.com"
        },`

METHODS:

  `methods: {
    showModal(card) {
      this.isModalVisible = true;
      this.title = card.title;
      this.img = card.img;
      this.previewUrl = card.previewUrl;
      this.downloadUrl = card.downloadUrl;
      this.isModalVisible = true;
    },
    closeModal() {
      this.isModalVisible = false;
    }
  }`

The imported modal component

`<template>

        <button type="button" class="btn-close" @click="close">
          clear
        </button>

          <slot name="header" />

          <slot name="header-sub" />

        <slot name="body" />

          <slot name="footer" />

</template>

`

Body:
you should set the data of modal before and in the click set the correct info

for example in you data set

{
modalInfo:{title:'',img:''}
}

then in click set it like this

 showModal(card) {
      this.modalInfo.title = card.title;
      this.modalInfo.img = card.img;
      this.isModalVisible = true;
    }

and in the modal part set it like this

        <!-- Cards -->
        <div class="card-wrapper">
          <div v-for="(card, index) in cards" :key="index" class="card">
            <div @click="showModal(card)" class="card-body">
              <img :src="card.img" alt="resource img" />
              <h4 class="card-title">{{ card.title }}</h4>
              <h6 class="card-subtitle">{{ card.subtitle }}</h6>
            </div>
          </div>
        </div>
<!-- MODAL -->
        <Modal v-show="isModalVisible" @close="closeModal">
            <template v-slot:header>{{ modalInfo.img }} </template>
            <template v-slot:body>
              {{ modalInfo.title }}
              <div class="text-center mb-1 mt-2">
                <a :href="previewUrl"><button class="modal-btn btn btn-large">Preview</button></a>


问:
implement remote oauth server and exchange token with client without save token on server
I'm developing a small Java application to access the chat of my yt live streams. Other than twitch yt doesn't have an irc server to access the chat so I'm forced to use the yt API. Basically I plan to only use it by myself, but I maybe will offer it for some friends or maybe even make it public.

I already successfully gained access to the the API, but only if I have the client secret and token stored on my system. When I want to open it public I have to setup an auth server and then transfer the token the client. The main issue is the method com.google.api.client.auth.oauth2.AuthorizationCodeFlow.createAndStoreCredential(TokenResponse, String) which is needed to actually create the token. This will store the token where ever the code runs - so in the planed environment on the server, not on the client.

I also found this: OAuth-server, storing user tokens - so if I understand this correctly whenever a service use google oauth it stores the access token on it's own storage and then someone interact with the client.
So, I have these two questions:

How do I implement such an auth service if I want to open a project to the public so it can be used by others?

How do I send the token to the client? Or has all communication has to be done over my server?
2a) If the answer to the previous question is yes, how do I secure the access so each client can only access it's own token when it's only identified by a simple string?

Currently, this is the code to get a token:

```<code>public class Main
{
    public final static void main(final String... args)
    {
        (new Main()).start();
    }
    private Main() {}
    private void start()
    {
        try
        {
            File DATA_STORE_DIR=new File(System.getProperty("user.home"), "yta");
            JsonFactory JSON_FACTORY=JacksonFactory.getDefaultInstance();
            List<String> SCOPES=Arrays.asList(YouTubeScopes.YOUTUBE_READONLY, YouTubeScopes.YOUTUBE, YouTubeScopes.YOUTUBE_FORCE_SSL, YouTubeScopes.YOUTUBE_UPLOAD);
            DataStoreFactory DATA_STORE_FACTORY=new FileDataStoreFactory(DATA_STORE_DIR);
            NetHttpTransport transport=GoogleNetHttpTransport.newTrustedTransport();
            GoogleClientSecrets clientSecrets=GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(new FileInputStream(new File(DATA_STORE_DIR, "client_secret.json"))));
            GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow=new GoogleAuthorizationCodeFlow.Builder(transport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).build();
            String authURL=googleAuthorizationCodeFlow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build();
            Desktop.getDesktop().browse(new URI(authURL));
            String authToken=System.console().readLine();
            GoogleTokenResponse googleTokenResponse=googleAuthorizationCodeFlow.newTokenRequest(authToken).setRedirectUri("urn:ietf:wg:oauth:2.0:oob").execute();
            Credential credential=googleAuthorizationCodeFlow.createAndStoreCredential(googleTokenResponse, "userId");
        }
        catch(IOException|GeneralSecurityException|URISyntaxException ex)
        {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
</code>```

Which ends up in a file "StoredCredential" is created in the DATA_STORE_DIR directory which contains the auth token identified by "userId". To transfer the token to the client I can just call getRefreshToken and getAccessToken, send them to the client, store them on the client, build a new Credential instance from those two strings and "activated" it by refreshing it. To get rid of the token on the server side I then could just call delete on the datastore - and to increase security I could use a UUID for this one flow so it would be hard for some attacker to intercept the token - but a risk is still there. So I'm searching for a way to create the token without it stored on the server (not even for a short time) to prevent possible attack vector.
Any of you know how to do this?

// update
So, I tinkered with it to see how I would create a token on the client - which still require my client-id and client-secret used in the auth code flow (otherwise you get an exception telling you to set these). This ended up in these lines:

```<code>credential=(new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()))
    .setTransport(transport)
    .setJsonFactory(JSON_FACTORY)
    .setTokenServerEncodedUrl("https://oauth2.googleapis.com/token")
    .setClientAuthentication(new ClientParametersAuthentication("client-id", "client-secret"))
    .build()
.setAccessToken("access-token")
.setRefreshToken("refresh-token");
</code>```

Well, as far as I can tell it isn't even possible to transfer a Credential object to a remote client without also exposing the API secret which has to be kept secret. This would mean that any call has to be gone through the server, which has to somehow uniquely identify the client over several sessions/connections, and that each reply has to be forwarded back to the client.

So - this brings me to the question: Is what I want to do * even possible?
*= Write a program in java which access the chat of my live stream - which stores its token local but request an external server to get it

I also tried to use an API key - but it seems for what I want to do this doesn't have sufficient permissions - even a simple channel id lookup for my given username fails ... so I have to use OAuth

// update 2
Well - it seems no to matter - I hit the max limit of a normal free user account of 10k per day within 5 minutes - guess I have to switch to twitch then ...

答:
So, I found a solution: https://github.com/cryptearth/YouTubeLiveChat/commit/b1ce15400688b6907600b006463ce538132bd807
It boils down to two things I didn't understand until now:

The Credential.Builder works fine with just give "null" as the client-secret.

The AuthorizationCodeFlow doesn't need a DataStoreFactory.

So, when not setting a DataStoreFactory for the AuthorizationCodeFlow the Credential gets created, but just not stored anywhere (in the source there's a simple if(null) to check for if a DataStoreFactory was set). This also the client id doesn't really matter as there's no risk that another thread could access the newly created Credential.
As AccessTokens only have a limited validity (about an hour) I didn't test what happens when the client runs for longer than this, but as the doc hints there're internal checks so I guess it would try to refresh itself - which would fail. Or, if the refresh didn't happen the next call will fail just with an 401 - Unauthorized reply from Google. So by disable the auto-refresh mechanism I guess I have to somehow check it myself and let a refresh happen on the server at the right timing. To refresh I just sent the refresh token to the server wich then respond with a new access token and the new lifetime of it.
So, the server doesn't have to store anything and the client only the refresh token - DONE! Re-Implement the auto-refresh stuff could be done dirty by abusing the Exception caused by the 401 reply after the validity ran out - would work but is considered bad code style - have to figure out how to write it somewhat not-bad.

About hitting the 10k limit in 5min: I set the timeout to 10sec - gave me about 2h30m on a test - still not enough for my own daily streams - and if I would share it I had to lengthen the timeout even further. So, if 10sec get me 2h30m I would need a poll timeout of 100sec to get about 24h - for one uses(!) - that's 1m40s - multiplied by the number of users. Guess I would have to make a proper project page and somehow had to increase my max quota ... but that's a story for another day.

Question solved - project dev paused.

Body:
I'm developing a small Java application to access the chat of my yt live streams. Other than twitch yt doesn't have an irc server to access the chat so I'm forced to use the yt API. Basically I plan to only use it by myself, but I maybe will offer it for some friends or maybe even make it public.

I already successfully gained access to the the API, but only if I have the client secret and token stored on my system. When I want to open it public I have to setup an auth server and then transfer the token the client. The main issue is the method com.google.api.client.auth.oauth2.AuthorizationCodeFlow.createAndStoreCredential(TokenResponse, String) which is needed to actually create the token. This will store the token where ever the code runs - so in the planed environment on the server, not on the client.

I also found this: OAuth-server, storing user tokens - so if I understand this correctly whenever a service use google oauth it stores the access token on it's own storage and then someone interact with the client.
So, I have these two questions:

How do I implement such an auth service if I want to open a project to the public so it can be used by others?

How do I send the token to the client? Or has all communication has to be done over my server?
2a) If the answer to the previous question is yes, how do I secure the access so each client can only access it's own token when it's only identified by a simple string?

Currently, this is the code to get a token:

public class Main
{
    public final static void main(final String... args)
    {
        (new Main()).start();
    }
    private Main() {}
    private void start()
    {
        try
        {
            File DATA_STORE_DIR=new File(System.getProperty("user.home"), "yta");
            JsonFactory JSON_FACTORY=JacksonFactory.getDefaultInstance();
            List<String> SCOPES=Arrays.asList(YouTubeScopes.YOUTUBE_READONLY, YouTubeScopes.YOUTUBE, YouTubeScopes.YOUTUBE_FORCE_SSL, YouTubeScopes.YOUTUBE_UPLOAD);
            DataStoreFactory DATA_STORE_FACTORY=new FileDataStoreFactory(DATA_STORE_DIR);
            NetHttpTransport transport=GoogleNetHttpTransport.newTrustedTransport();
            GoogleClientSecrets clientSecrets=GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(new FileInputStream(new File(DATA_STORE_DIR, "client_secret.json"))));
            GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow=new GoogleAuthorizationCodeFlow.Builder(transport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).build();
            String authURL=googleAuthorizationCodeFlow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build();
            Desktop.getDesktop().browse(new URI(authURL));
            String authToken=System.console().readLine();
            GoogleTokenResponse googleTokenResponse=googleAuthorizationCodeFlow.newTokenRequest(authToken).setRedirectUri("urn:ietf:wg:oauth:2.0:oob").execute();
            Credential credential=googleAuthorizationCodeFlow.createAndStoreCredential(googleTokenResponse, "userId");
        }
        catch(IOException|GeneralSecurityException|URISyntaxException ex)
        {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

Which ends up in a file "StoredCredential" is created in the DATA_STORE_DIR directory which contains the auth token identified by "userId". To transfer the token to the client I can just call getRefreshToken and getAccessToken, send them to the client, store them on the client, build a new Credential instance from those two strings and "activated" it by refreshing it. To get rid of the token on the server side I then could just call delete on the datastore - and to increase security I could use a UUID for this one flow so it would be hard for some attacker to intercept the token - but a risk is still there. So I'm searching for a way to create the token without it stored on the server (not even for a short time) to prevent possible attack vector.
Any of you know how to do this?

// update
So, I tinkered with it to see how I would create a token on the client - which still require my client-id and client-secret used in the auth code flow (otherwise you get an exception telling you to set these). This ended up in these lines:

credential=(new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()))
    .setTransport(transport)
    .setJsonFactory(JSON_FACTORY)
    .setTokenServerEncodedUrl("https://oauth2.googleapis.com/token")
    .setClientAuthentication(new ClientParametersAuthentication("client-id", "client-secret"))
    .build()
.setAccessToken("access-token")
.setRefreshToken("refresh-token");

Well, as far as I can tell it isn't even possible to transfer a Credential object to a remote client without also exposing the API secret which has to be kept secret. This would mean that any call has to be gone through the server, which has to somehow uniquely identify the client over several sessions/connections, and that each reply has to be forwarded back to the client.

So - this brings me to the question: Is what I want to do * even possible?
*= Write a program in java which access the chat of my live stream - which stores its token local but request an external server to get it

I also tried to use an API key - but it seems for what I want to do this doesn't have sufficient permissions - even a simple channel id lookup for my given username fails ... so I have to use OAuth

// update 2
Well - it seems no to matter - I hit the max limit of a normal free user account of 10k per day within 5 minutes - guess I have to switch to twitch then ...


问:
When upload file: Curl return "Empty reply from server" only on Linux but Windows
when I upload a file to Mediafire Hosting by use CURL, i get "Empty reply from server" on Ubuntu, CentOs
but with same code ,I can upload that file on Windows.
What Linux difference from Windows ? How can i solve this matter ?</p>

答:
Use ReturnTransfer before CURL_FILE

```<code>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
</code>```

http://www.php.net/manual/en/function.curl-setopt.php#99082

I don't know why i use RETURNTRANSFER after CURLOPT_FILE and it work in Windows O_O.
even in Linux , i use same as Windows, i can upload to many hosting but Mediafire.
very strange ><

Body:
Use ReturnTransfer before CURL_FILE

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);

http://www.php.net/manual/en/function.curl-setopt.php#99082

I don't know why i use RETURNTRANSFER after CURLOPT_FILE and it work in Windows O_O.
even in Linux , i use same as Windows, i can upload to many hosting but Mediafire.
very strange ><


问:
How to Implement Video Ads like YouTube and Netflix that shows before playing the actual video
**I am trying to make a video streaming site programmed in

PHP or ASP.NET

I am trying to recreate the senerio that YouTube show.
ie. When someone clicks the video it shows a video ad in my video player.
**

Problem: I want to show then the video promotion ad without actually adding the video to all 20k+ videos and let there be 4 video promo named 1/2/3/4.mp4 respectively so it should be random that the video is played.

答:
Using WebM is a option but you can make it like a refresh timer that selects the a random no.

Example ( for starter)

$a = (url of the video)
$b = generate random no. (1-4)  //i didn't add. Any code

Now when the page let www.example.com

Create a timer of about the time of the video then play the video after which die() the connection and play the video link with the end of timer with header()

I am not good at explaning but it should work


问:
how to add files to SVN
im trying to add a word document to my svn repository, however im confused on how to, im doing it through terminal

```<code> A    wc4/code
 A    wc4/code/branches
  A    wc4/code/prototype_demo
 A    wc4/code/tags
 A    wc4/code/trunk
 A    wc4/docs
 A    wc4/docs/0_diaries
 A    wc4/docs/1_plan
A    wc4/docs/2_interim_report
</code>```

these are the files and i've done
"cd wc4/docs/2_interim_report"
then "svn mkdir interim"
which made another sub file interim

how do i add my word document inside it because when i do

"svn add /desktop/interim report" which is where the file is saved it is giving me error

```<code>  W150002: '/Users/char/wc4/docs/2_interim_report/interim'
  is already under version control
  svn: warning: W155010:
 '/Users/char/wc4/docs/2_interim_report/report.doc' not found
 svn: E200009: Could not add all targets because some targets don't exist
svn: E200009: Could not add all targets because some targets are already versioned
svn: E200009: Illegal target for the requested operation
</code>```

答:
You should be able to:

```<code>svn add wc4/docs/2_interm_report/interm/report.doc
svn commit wc4/docs
</code>```

Adding files is fairly simple. If I want to add dir1/file1 to my repository and upload to the server I would:

```<code>svn add dir1/file1
svn commit dir1/file1
</code>```

But what is dir1 doesn't exist already? In that case I'd make the directory (doesn't need to be done in SVN) and then make the file like normal. Then simply:

```<code>svn add dir1
svn commit dir1
</code>```

This will add dir1 and all child directories/files to the svn repository, ready to be committed.

When the output of svn status shows an A before your filename, it means you have "added" that file/directory to your working copy and it is ready to be sent to the server.  You need to follow that up with an svn commit to send it to the server.

svn mkdir is mostly useful if you want to create a directory on a repository directly without checking out a working copy first. For example, I'd use svn mkdir http://example.com/svn/repo/trunk to make a directory named trunk in a remote repository before checking it out to add fresh content.

Title: how to add files to SVN

Body:
im trying to add a word document to my svn repository, however im confused on how to, im doing it through terminal

 A    wc4/code
 A    wc4/code/branches
  A    wc4/code/prototype_demo
 A    wc4/code/tags
 A    wc4/code/trunk
 A    wc4/docs
 A    wc4/docs/0_diaries
 A    wc4/docs/1_plan
A    wc4/docs/2_interim_report

these are the files and i've done
"cd wc4/docs/2_interim_report"
then "svn mkdir interim"
which made another sub file interim

how do i add my word document inside it because when i do

"svn add /desktop/interim report" which is where the file is saved it is giving me error

  W150002: '/Users/char/wc4/docs/2_interim_report/interim'
  is already under version control
  svn: warning: W155010:
 '/Users/char/wc4/docs/2_interim_report/report.doc' not found
 svn: E200009: Could not add all targets because some targets don't exist
svn: E200009: Could not add all targets because some targets are already versioned
svn: E200009: Illegal target for the requested operation

Body:
You should be able to:

svn add wc4/docs/2_interm_report/interm/report.doc
svn commit wc4/docs

Adding files is fairly simple. If I want to add dir1/file1 to my repository and upload to the server I would:

svn add dir1/file1
svn commit dir1/file1

But what is dir1 doesn't exist already? In that case I'd make the directory (doesn't need to be done in SVN) and then make the file like normal. Then simply:

svn add dir1
svn commit dir1

This will add dir1 and all child directories/files to the svn repository, ready to be committed.

When the output of svn status shows an A before your filename, it means you have "added" that file/directory to your working copy and it is ready to be sent to the server.  You need to follow that up with an svn commit to send it to the server.

svn mkdir is mostly useful if you want to create a directory on a repository directly without checking out a working copy first. For example, I'd use svn mkdir http://example.com/svn/repo/trunk to make a directory named trunk in a remote repository before checking it out to add fresh content.


问:
bootstrap navbar hamburger dropdown working fine on desktop (all resolutions) but not on mobile device
My bootstrap and css is functioning fine on desktop browser, but when I go to the site via mobile there are two issues: the navbar isn't as wide as the hamburger toggle and image (regardless of image resize), and the hamburger drop down does not push page contents down--it overlays on contents--this could be fine, but I'd at least need to correct for width of navbar.

Any help is much appreciated

HTML

```<code><!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link rel="stylesheet" href="<css file>" >

</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark sticky-top" >
  <a class="navbar-brand" href="/"> <img src="{% static "br_email/logo.png" %}" id = "logo"></a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="/"><b>Home</b><span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/events/"><b>Events</b></a>
      </li>

        <li class="nav-item">
        <a class="nav-link" href="/contact/"><b>Contact</b></a>
      </li>
    </ul>
      <ul class="navbar-nav ml-auto">
              <a class="nav-item nav-link" href="/profile/"> <b>Profile</b></a>
              <a class="nav-item nav-link" href="/logout/"> <b>Logout</b></a>

      </span>
      </ul>
  </div>
</nav>

  <main role="main" >
         {% block content %}{% endblock %}
    </main>

  <div class="content"></div>

  <footer class="footer">

        <div class="row d-flex align-items-center">
            <!--<!– Grid column –>-->
            <div class="col-12 pt-4">
                <!--<!–Copyright–>-->
                <p class="text-center">
                    © 2020
                     •
                    <a href="/contact/" >
                        <strong> Contact </strong>
                    </a>
                </p>

            </div>
        </div>

  </footer>

   <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <!--<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>-->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    <script type="text/javascript">// <![CDATA[
            function loading(){
                $("#loading").show();
                $("#content").hide();
          }
    // ]]>
    </script>

<script>
    $(document).ready(function(){
        if ($(document).height() > $(window).height()) {
            $('#footer').css('position', 'relative');
        }
});
</script>

<script>
    $(function(){
        $('a').each(function(){
            if ($(this).prop('href') == window.location.href) {
                $(this).addClass('active'); $(this).parents('li').addClass('active');
            }
        });
    });
</script>

</body>
</html>

</code>```

Navbar related CSS

```<code>.navbar-fixed-top {height: 40x;}
.navbar-brand img {height: 40px;}

.navbar-dark{
    background-color: #1a2125;
}

.site-header .navbar-nav .nav-link {
  color: #cbd5db;
}

.site-header .navbar-nav .nav-link:hover {
  color: #ffffff;
}

.site-header .navbar-nav .nav-link.active {
  font-weight: 500;
}
</code>```

答: Your navbar might resize if it doesn't have a defined width property. I looked through all of your code, and it doesn't look like your navbar has a set width in your css, or in your javascript/jquery/etc. The  tag is also a block-level element, meaning that it will take up the entire space of a new row. If you wanted to change the width more easily, you could change it to an inline-block element in css, or use the margin and padding settings. One other mistake I caught is that in your css, at the top of the snippet, you typed 40x instead of 40px (Not sure if you caught that). If you read through your code carefully you may or may not find other mistakes.

Body:
My bootstrap and css is functioning fine on desktop browser, but when I go to the site via mobile there are two issues: the navbar isn't as wide as the hamburger toggle and image (regardless of image resize), and the hamburger drop down does not push page contents down--it overlays on contents--this could be fine, but I'd at least need to correct for width of navbar.

Any help is much appreciated

HTML

<!DOCTYPE html>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link rel="stylesheet" href="<css file>" >

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home(current)

        Events

        Contact

               Profile
               Logout

         {% block content %}{% endblock %}

                    © 2020
                     •

                         Contact

Navbar related CSS

.navbar-fixed-top {height: 40x;}
.navbar-brand img {height: 40px;}

.navbar-dark{
    background-color: #1a2125;
}

.site-header .navbar-nav .nav-link {
  color: #cbd5db;
}

.site-header .navbar-nav .nav-link:hover {
  color: #ffffff;
}

.site-header .navbar-nav .nav-link.active {
  font-weight: 500;
}

Body: Your navbar might resize if it doesn't have a defined width property. I looked through all of your code, and it doesn't look like your navbar has a set width in your css, or in your javascript/jquery/etc. The <nav> tag is also a block-level element, meaning that it will take up the entire space of a new row. If you wanted to change the width more easily, you could change it to an inline-block element in css, or use the margin and padding settings. One other mistake I caught is that in your css, at the top of the snippet, you typed 40x instead of 40px (Not sure if you caught that). If you read through your code carefully you may or may not find other mistakes.


问:
Why is an ExecutorService created via newCachedThreadPool evil?
Paul Tyma presentation has this line:

Executors.newCacheThreadPool evil, die die die

Why is it evil ?

I will hazard a guess: is it because the number of threads will grow in an unbounded fashion. Thus a server that has been slashdotted, would probably die if the JVM's max thread count was reached ?

答:
There are a couple of issues with it. Unbounded growth in terms of threads an obvious issue – if you have cpu bound tasks then allowing many more than the available CPUs to run them is simply going to create scheduler overhead with your threads context switching all over the place and none actually progressing much. If your tasks are IO bound though things get more subtle. Knowing how to size pools of threads that are waiting on network or file IO is much more difficult, and depends a lot on the latencies of those IO events. Higher latencies mean you need (and can support) more threads.

The cached thread pool continues adding new threads as the rate of task production outstrips the rate of execution. There are a couple of small barriers to this (such as locks that serialise new thread id creation) but this can unbound growth can lead to out-of-memory errors.

The other big problem with the cached thread pool is that it can be slow for task producer thread. The pool is configured with a SynchronousQueue for tasks to be offered to. This queue implementation basically has zero size and only works when there is a matching consumer for a producer (there is a thread polling when another is offering). The actual implementation was significantly improved in Java6, but it is still comparatively slow for the producer, particularly when it fails (as the producer is then responsible for creating a new thread to add to the pool). Often it is more ideal for the producer thread to simply drop the task on an actual queue and continue.

The problem is, no-one has a pool that has a small core set of threads which when they are all busy creates new threads up to some max and then enqueues subsequent tasks. Fixed thread pools seem to promise this, but they only start adding more threads when the underlying queue rejects more tasks (it is full). A LinkedBlockingQueue never gets full so these pools never grow beyond the core size. An ArrayBlockingQueue has a capacity, but as it only grows the pool when capacity is reached this doesn't mitigate the production rate until it is already a big problem. Currently the solution requires using a good rejected execution policy such as caller-runs, but it needs some care.

Developers see the cached thread pool and blindly use it without really thinking through the consequences.


问:
C# ToList or list add make wrong result
```<code>var su = SysallocunitsRow<sysallocunit>(myreader);

List<sysallocunit> sul= new List<sysallocunit>();

foreach( var s in su)
{
    logger.Info("su auid is  " + s.auid);
    sul.Add(s);
}

foreach (var a in sul)
{
    logger.Info("sul unit is  " + a.auid);
}
</code>```

The result :

```<code>```
.........................
su auid is  72057594048675840
su auid is  72057594049265664
su auid is  72057594049331200
su auid is  72057594049462272
su auid is  72057594049527808
su auid is  72057594049658880

sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
```
</code>```

I want to convert an IEnumerable<T> to a list, but .ToList() or List.Add() cause the list duplicate the last one, and have wrong result.

Does anyone have any idea why?

答:
Instead of adding s into sul, create a new object of sysallocunit and add it.
Changing your first foreach as below should resolve the issue of duplicate values.</p>

```<code>foreach( var s in su)
{
    logger.Info("su auid is  " + s.auid);
    sul.Add(new sysallocunit(){ auid = s.auid });
}
</code>```

Title: C# ToList or list add make wrong result

Body:
var su = SysallocunitsRow<sysallocunit>(myreader);

List<sysallocunit> sul= new List<sysallocunit>();

foreach( var s in su)
{
    logger.Info("su auid is  " + s.auid);
    sul.Add(s);
}

foreach (var a in sul)
{
    logger.Info("sul unit is  " + a.auid);
}

The result :

```
.........................
su auid is  72057594048675840
su auid is  72057594049265664
su auid is  72057594049331200
su auid is  72057594049462272
su auid is  72057594049527808
su auid is  72057594049658880

sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
sul unit is  72057594049658880
```

I want to convert an IEnumerable<T> to a list, but .ToList() or List.Add() cause the list duplicate the last one, and have wrong result.

Does anyone have any idea why?

Body:
Instead of adding s into sul, create a new object of sysallocunit and add it.
Changing your first foreach as below should resolve the issue of duplicate values.

foreach( var s in su)
{
    logger.Info("su auid is  " + s.auid);
    sul.Add(new sysallocunit(){ auid = s.auid });
}