问:
Rspec failing with Selenium::WebDriver::Error::InvalidSessionIdError
Edit: The Turnip piece is a red herring. Running rspec natively by itself remains an issue.

Example invocation:

bundle exec rspec spec/features/subscription_spec.rb:33

Errors:

```<code>Failures:

  1) Subscription should redirect to back for free subscription
     Got 0 failures and 2 other errors:

     1.1) Failure/Error: visit subscription_status_path

          Selenium::WebDriver::Error::NoSuchWindowError:
            Browsing context has been discarded
          # WebDriverError@chrome://marionette/content/error.js:175:5
          # NoSuchWindowError@chrome://marionette/content/error.js:409:5
          # assert.that/<@chrome://marionette/content/assert.js:428:13
          # assert.open@chrome://marionette/content/assert.js:183:72
          # GeckoDriver.prototype.get@chrome://marionette/content/driver.js:1109:10
          # despatch@chrome://marionette/content/server.js:305:40
          # execute@chrome://marionette/content/server.js:275:16
          # onPacket/<@chrome://marionette/content/server.js:248:20
          # onPacket@chrome://marionette/content/server.js:249:9
          # _onJSONObjectReady/<@chrome://marionette/content/transport.js:503:20
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:72:in `assert_ok'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `new'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `create_response'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/default.rb:114:in `request'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:64:in `call'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:567:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:59:in `get'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/navigation.rb:32:in `to'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver.rb:71:in `visit'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/session.rb:278:in `visit'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/dsl.rb:58:in `block (2 levels) in <module:DSL>'
          # ./spec/features/subscription_spec.rb:36:in `block (2 levels) in <top (required)>'
          # ./spec/rails_helper.rb:60:in `block (3 levels) in <top (required)>'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/generic/base.rb:16:in `cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:87:in `block (2 levels) in cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:88:in `cleaning'
          # ./spec/rails_helper.rb:59:in `block (2 levels) in <top (required)>'

     1.2) Failure/Error: example.run

          Selenium::WebDriver::Error::UnknownError:
            Failed to decode response from marionette
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:72:in `assert_ok'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `new'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `create_response'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/default.rb:114:in `request'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:64:in `call'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:567:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:92:in `alert_text'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/alert.rb:27:in `initialize'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/target_locator.rb:107:in `new'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/target_locator.rb:107:in `alert'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver_specializations/firefox_driver.rb:48:in `reset!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/session.rb:130:in `reset!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara.rb:322:in `block in reset_sessions!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara.rb:322:in `reverse_each'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara.rb:322:in `reset_sessions!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/rspec.rb:18:in `block (2 levels) in <top (required)>'
          # ./spec/rails_helper.rb:60:in `block (3 levels) in <top (required)>'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/generic/base.rb:16:in `cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:87:in `block (2 levels) in cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:88:in `cleaning'
          # ./spec/rails_helper.rb:59:in `block (2 levels) in <top (required)>'

Finished in 9.46 seconds (files took 4.92 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/features/subscription_spec.rb:33 # Subscription should redirect to back for free subscription

Traceback (most recent call last):
        12: from /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver.rb:458:in `block in setup_exit_handler'
        11: from /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver.rb:243:in `quit'
        10: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/firefox/marionette/driver.rb:56:in `quit'
         9: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/driver.rb:168:in `quit'
         8: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:155:in `quit'
         7: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:567:in `execute'
         6: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
         5: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:64:in `call'
         4: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/default.rb:114:in `request'
         3: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `create_response'
         2: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `new'
         1: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
/usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:72:in `assert_ok': Tried to run command without establishing a connection (Selenium::WebDriver::Error::InvalidSessionIdError)
</code>```

Gemfile:

...

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  # gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'pry', '~> 0.11.3'
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'pry-remote'
  gem 'faker'

  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '3.32.2'
  gem 'webdrivers', '4.4.1'

  gem 'rspec-rails'
  gem 'factory_bot_rails'
  gem 'rails-controller-testing'
  gem 'shoulda-matchers'

  # Cucumber, webmock, etc
  gem 'webmock', '3.8.3'
end

group :test do
  gem 'database_cleaner'
  gem 'elasticsearch-extensions'
  gem 'turnip'
end

...
```
<p>turnip_helper.rb:</p>
<pre class="lang-ruby prettyprint-override"><code>require 'rails_helper'
require 'turnip/capybara' # to use Capybara DSL methods in steps
require 'sidekiq/testing'
Dir.glob("spec/steps/**/*steps.rb") { |f| load f, true }
</code>```

rails_helper.rb:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'devise'
require 'webdrivers'
require 'factory_bot_rails'
require 'faker'
require 'capybara'
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
Capybara.register_driver :firefox_headless do |app|
  options = ::Selenium::WebDriver::Firefox::Options.new
  options.args << '--headless'
  options.args << '--width=1920'
  options.args << '--height=1080'
  Capybara::Selenium::Driver.new(app, browser: :firefox, options: options)
end
Capybara.javascript_driver = :firefox_headless
RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end
  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
end
RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.include Devise::Test::ControllerHelpers, type: :view
  config.include Devise::Test::IntegrationHelpers, type: :request
  config.include Devise::Test::IntegrationHelpers, type: :feature
  config.include FactoryBot::Syntax::Methods
end
Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :active_record
    with.library :active_model
    with.library :action_controller
    with.library :rails
  end
end
```
<p>spec_helper.rb:</p>
<pre class="lang-ruby prettyprint-override"><code>require 'rake'
require 'webmock/rspec'
require 'sidekiq/testing'
RSpec.configure do |config|
  config.before(:each) do
    Sidekiq::Worker.clear_all
    Sidekiq::Queue.all.each(&:clear)
    Sidekiq::RetrySet.new.clear
    Sidekiq::ScheduledSet.new.clear
    Sidekiq::DeadSet.new.clear
    WebMock.disable!
  end
  config.before :each, elasticsearch: true do
    ActiveRecord::Base.descendants.each do |model|
      if model.respond_to?(:__elasticsearch__)
        begin
          model.__elasticsearch__.create_index! index: model.index_name
          model.__elasticsearch__.refresh_index!
        rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
        rescue => e
          STDERR.puts "There was an error creating the elasticsearch index for #{model.name}: #{e.inspect}"
        end
      end
    end
  end
  config.after :each, elasticsearch: true do
    ActiveRecord::Base.descendants.each do |model|
      if model.respond_to?(:__elasticsearch__)
        begin
          model.__elasticsearch__.client.indices.delete index: model.index_name
        rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
        rescue => e
          STDERR.puts "There was an error removing the elasticsearch index for #{model.name}: #{e.inspect}"
        end
      end
    end
  end
end
RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.shared_context_metadata_behavior = :apply_to_host_groups
end
</code>```

subscription_spec.rb:33

  scenario 'should redirect to back for free subscription', js: true do
    blah blah
  end
```
<p>If I run an rspec test that doesn't declare <code>js: true</code>, it works.</p>
<p>I did some more exploration, and it turns out it's failing even without running after Turnip. So the Turnip piece may be a red herring.</p>
<p>At this point it's purely rspec/capybara that's failing (with the same errors from my stackoverflow post).</p>
<p>Interestingly, here's one particular task:</p>
<pre class="lang-ruby prettyprint-override"><code>  scenario 'should see an error message for existing subscription', js: true do
    premium_user.confirm
    sign_in_with premium_user.email, 'password'
    visit '/subscriptions'
    expect(page).to have_content 'You already have a subscription'
  end
</code>```

"sign_in_with" is a helper that uses Capybara syntax:

module Features
  module SessionHelpers
    def sign_up_with(email, password, confirmation)
      visit new_user_registration_path
      fill_in 'Email', with: email
      fill_in 'user[password]', with: password
      fill_in 'user[password_confirmation]', :with => confirmation
      click_button 'Sign up!'
    end

    def sign_in_with(email, password)
      visit new_user_session_path
      fill_in 'Email', with: email
      fill_in 'Password', with: password
      click_button 'Sign in'
    end
  end
end
```

This (the sign_in_with helper) works fine. If I use a binding.pry in this task, I see Firefox exists during "sign_in_with". But immediately after that step completes, Firefox goes away, and then the "visit" fails because Firefox is gone.

答:
I had a similar issue when running tests in a docker container.

The overhead of the browser was causing the container to run out of memory, and as a result the brower was getting killed.

If this applies to your situation you can get round this by increasing the shared memory space. This is how you'd do it with a docker-compose file:

```<code>version: '3.8'
services:
  ...
  web:
    shm_size: '256mb'
    ...
  ...
</code>```

I've written more about dealing with Selenium::WebDriver::Error::InvalidSessionIdError here: https://thecurve.io/dealing-with-cryptic-seleniumwebdrivererrorinvalidsessioniderror-errors/

Body:
Edit: The Turnip piece is a red herring. Running rspec natively by itself remains an issue.

Example invocation:

bundle exec rspec spec/features/subscription_spec.rb:33

Errors:

Failures:

  1) Subscription should redirect to back for free subscription
     Got 0 failures and 2 other errors:

     1.1) Failure/Error: visit subscription_status_path

          Selenium::WebDriver::Error::NoSuchWindowError:
            Browsing context has been discarded
          # WebDriverError@chrome://marionette/content/error.js:175:5
          # NoSuchWindowError@chrome://marionette/content/error.js:409:5
          # assert.that/<@chrome://marionette/content/assert.js:428:13
          # assert.open@chrome://marionette/content/assert.js:183:72
          # GeckoDriver.prototype.get@chrome://marionette/content/driver.js:1109:10
          # despatch@chrome://marionette/content/server.js:305:40
          # execute@chrome://marionette/content/server.js:275:16
          # onPacket/<@chrome://marionette/content/server.js:248:20
          # onPacket@chrome://marionette/content/server.js:249:9
          # _onJSONObjectReady/<@chrome://marionette/content/transport.js:503:20
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:72:in `assert_ok'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `new'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `create_response'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/default.rb:114:in `request'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:64:in `call'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:567:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:59:in `get'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/navigation.rb:32:in `to'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver.rb:71:in `visit'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/session.rb:278:in `visit'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/dsl.rb:58:in `block (2 levels) in <module:DSL>'
          # ./spec/features/subscription_spec.rb:36:in `block (2 levels) in <top (required)>'
          # ./spec/rails_helper.rb:60:in `block (3 levels) in <top (required)>'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/generic/base.rb:16:in `cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:87:in `block (2 levels) in cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:88:in `cleaning'
          # ./spec/rails_helper.rb:59:in `block (2 levels) in <top (required)>'

     1.2) Failure/Error: example.run

          Selenium::WebDriver::Error::UnknownError:
            Failed to decode response from marionette
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:72:in `assert_ok'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `new'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `create_response'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/default.rb:114:in `request'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:64:in `call'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:567:in `execute'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:92:in `alert_text'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/alert.rb:27:in `initialize'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/target_locator.rb:107:in `new'
          # /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/target_locator.rb:107:in `alert'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver_specializations/firefox_driver.rb:48:in `reset!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/session.rb:130:in `reset!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara.rb:322:in `block in reset_sessions!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara.rb:322:in `reverse_each'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara.rb:322:in `reset_sessions!'
          # /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/rspec.rb:18:in `block (2 levels) in <top (required)>'
          # ./spec/rails_helper.rb:60:in `block (3 levels) in <top (required)>'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/generic/base.rb:16:in `cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:87:in `block (2 levels) in cleaning'
          # /usr/local/bundle/gems/database_cleaner-1.8.4/lib/database_cleaner/configuration.rb:88:in `cleaning'
          # ./spec/rails_helper.rb:59:in `block (2 levels) in <top (required)>'

Finished in 9.46 seconds (files took 4.92 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/features/subscription_spec.rb:33 # Subscription should redirect to back for free subscription

Traceback (most recent call last):
        12: from /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver.rb:458:in `block in setup_exit_handler'
        11: from /usr/local/bundle/gems/capybara-3.32.2/lib/capybara/selenium/driver.rb:243:in `quit'
        10: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/firefox/marionette/driver.rb:56:in `quit'
         9: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/common/driver.rb:168:in `quit'
         8: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:155:in `quit'
         7: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/w3c/bridge.rb:567:in `execute'
         6: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/bridge.rb:167:in `execute'
         5: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:64:in `call'
         4: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/default.rb:114:in `request'
         3: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `create_response'
         2: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/http/common.rb:88:in `new'
         1: from /usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
/usr/local/bundle/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/remote/response.rb:72:in `assert_ok': Tried to run command without establishing a connection (Selenium::WebDriver::Error::InvalidSessionIdError)

Gemfile:

...

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  # gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'pry', '~> 0.11.3'
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'pry-remote'
  gem 'faker'

  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '3.32.2'
  gem 'webdrivers', '4.4.1'

  gem 'rspec-rails'
  gem 'factory_bot_rails'
  gem 'rails-controller-testing'
  gem 'shoulda-matchers'

  # Cucumber, webmock, etc
  gem 'webmock', '3.8.3'
end

group :test do
  gem 'database_cleaner'
  gem 'elasticsearch-extensions'
  gem 'turnip'
end

...

turnip_helper.rb:

require 'rails_helper'
require 'turnip/capybara' # to use Capybara DSL methods in steps
require 'sidekiq/testing'
Dir.glob("spec/steps/**/*steps.rb") { |f| load f, true }

rails_helper.rb:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'devise'
require 'webdrivers'
require 'factory_bot_rails'
require 'faker'
require 'capybara'
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
Capybara.register_driver :firefox_headless do |app|
  options = ::Selenium::WebDriver::Firefox::Options.new
  options.args << '--headless'
  options.args << '--width=1920'
  options.args << '--height=1080'
  Capybara::Selenium::Driver.new(app, browser: :firefox, options: options)
end
Capybara.javascript_driver = :firefox_headless
RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end
  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
end
RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.include Devise::Test::ControllerHelpers, type: :view
  config.include Devise::Test::IntegrationHelpers, type: :request
  config.include Devise::Test::IntegrationHelpers, type: :feature
  config.include FactoryBot::Syntax::Methods
end
Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :active_record
    with.library :active_model
    with.library :action_controller
    with.library :rails
  end
end

spec_helper.rb:

require 'rake'
require 'webmock/rspec'
require 'sidekiq/testing'
RSpec.configure do |config|
  config.before(:each) do
    Sidekiq::Worker.clear_all
    Sidekiq::Queue.all.each(&:clear)
    Sidekiq::RetrySet.new.clear
    Sidekiq::ScheduledSet.new.clear
    Sidekiq::DeadSet.new.clear
    WebMock.disable!
  end
  config.before :each, elasticsearch: true do
    ActiveRecord::Base.descendants.each do |model|
      if model.respond_to?(:__elasticsearch__)
        begin
          model.__elasticsearch__.create_index! index: model.index_name
          model.__elasticsearch__.refresh_index!
        rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
        rescue => e
          STDERR.puts "There was an error creating the elasticsearch index for #{model.name}: #{e.inspect}"
        end
      end
    end
  end
  config.after :each, elasticsearch: true do
    ActiveRecord::Base.descendants.each do |model|
      if model.respond_to?(:__elasticsearch__)
        begin
          model.__elasticsearch__.client.indices.delete index: model.index_name
        rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
        rescue => e
          STDERR.puts "There was an error removing the elasticsearch index for #{model.name}: #{e.inspect}"
        end
      end
    end
  end
end
RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.shared_context_metadata_behavior = :apply_to_host_groups
end

subscription_spec.rb:33

  scenario 'should redirect to back for free subscription', js: true do
    blah blah
  end

If I run an rspec test that doesn't declare js: true, it works.

I did some more exploration, and it turns out it's failing even without running after Turnip. So the Turnip piece may be a red herring.

At this point it's purely rspec/capybara that's failing (with the same errors from my stackoverflow post).

Interestingly, here's one particular task:

  scenario 'should see an error message for existing subscription', js: true do
    premium_user.confirm
    sign_in_with premium_user.email, 'password'
    visit '/subscriptions'
    expect(page).to have_content 'You already have a subscription'
  end

"sign_in_with" is a helper that uses Capybara syntax:

module Features
  module SessionHelpers
    def sign_up_with(email, password, confirmation)
      visit new_user_registration_path
      fill_in 'Email', with: email
      fill_in 'user[password]', with: password
      fill_in 'user[password_confirmation]', :with => confirmation
      click_button 'Sign up!'
    end

    def sign_in_with(email, password)
      visit new_user_session_path
      fill_in 'Email', with: email
      fill_in 'Password', with: password
      click_button 'Sign in'
    end
  end
end

This (the sign_in_with helper) works fine. If I use a binding.pry in this task, I see Firefox exists during "sign_in_with". But immediately after that step completes, Firefox goes away, and then the "visit" fails because Firefox is gone.

Body:
I had a similar issue when running tests in a docker container.

The overhead of the browser was causing the container to run out of memory, and as a result the brower was getting killed.

If this applies to your situation you can get round this by increasing the shared memory space. This is how you'd do it with a docker-compose file:

version: '3.8'
services:
  ...
  web:
    shm_size: '256mb'
    ...
  ...

I've written more about dealing with Selenium::WebDriver::Error::InvalidSessionIdError here: https://thecurve.io/dealing-with-cryptic-seleniumwebdrivererrorinvalidsessioniderror-errors/


来源: stackexchange

问:
How to specify and offset for select query on a table?
Is it possible to specify an offset for select query on a table ?</p>

答:
It's not currently supported. Some alternatives are below. But they depend on the use-case

Adding an index field to tables and querying on that range

Using something like timestamps to filter results

Indexing all the results in your own SQL table

ContentLicense: CC BY-SA 4.0


问:
How to change 1d array to 2d array under certain conditions
Is there a way through python numpy operations to produce the following result?

Input 1d array :

```<code>[3, 0, 0, 2, 2, 1]
</code>```

Output 2d array :

```<code>3 0 0 2 2 1
0 0 0 2 2 1
0 0 0 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1
</code>```

答:
in addition to jeromie’s brilliant answer, here is a support for unordered array:</p>
```<code>indexes = np.arange(len(arr))
idx = np.maximum(indexes[None,:], indexes[:, None])
arr[idx]
</code>```

Body:
Is there a way through python numpy operations to produce the following result?

Input 1d array :

[3, 0, 0, 2, 2, 1]

Output 2d array :

3 0 0 2 2 1
0 0 0 2 2 1
0 0 0 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1

Body:
in addition to jeromie’s brilliant answer, here is a support for unordered array:

indexes = np.arange(len(arr))
idx = np.maximum(indexes[None,:], indexes[:, None])
arr[idx]


问:
How can I use a custom json scheme with a yaml?
I try to map a custom json schema to a yaml file, based on this example:

```<code>"json.schemas": [
    {
        "fileMatch": [
            "/*.foo.json"
        ],
        "url": "./myschema.json"
    }
]

</code>```

this is my setting:

```<code>"json.schemas": [
    {
        "fileMatch": [
            "/home/ubuntu/test.yaml"
        ],
        "url": "/home/ubuntu/test-schema.json"
    }
]
</code>```

When I open the test.yaml file, I don't see that a JSON Schema is mapped  No JSON Schema.

I'm sure I miss something basic, but I can't figure out?

答: found a great guide here which explains the workaround

Body:
I try to map a custom json schema to a yaml file, based on this example:

"json.schemas": [
    {
        "fileMatch": [
            "/*.foo.json"
        ],
        "url": "./myschema.json"
    }
]

this is my setting:

"json.schemas": [
    {
        "fileMatch": [
            "/home/ubuntu/test.yaml"
        ],
        "url": "/home/ubuntu/test-schema.json"
    }
]

When I open the test.yaml file, I don't see that a JSON Schema is mapped  No JSON Schema.

I'm sure I miss something basic, but I can't figure out?


问:
"rusty_v8" build error on 32-bit platforms
I am new at Rust and Chromium V8 Engine.

I tried to build Deno from source on Raspberry Pi OS(32bit arm), but an error has occurred at rusty_v8 build. And same result on Intel 32bit.

```<code>  ../../../../.cargo/registry/src/github.com-1285ae84e5963aae/v8-0.39.0/src/binding.cc:40:1: error: static_assert failed due to requirement 'sizeof(v8::ScriptCompiler::Source) <= sizeof(unsigned int) * 8' "Source size mismatch"
  static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(size_t) * 8,
  ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3 warnings and 1 error generated.
</code>```

I thought the size of "size_t" depends the host machine's architecture, so I fixed "binding.cc" to

static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(uint64_t) * 8,
              "Source size mismatch");
```

Is this correct? And please explain what is this "static_assert"?

I'm not a native speaker so please forgive my weird English.

答: Unforunately, Deno doesn’t have any plans to support 32-bit arm.</p>

Body:
I am new at Rust and Chromium V8 Engine.

I tried to build Deno from source on Raspberry Pi OS(32bit arm), but an error has occurred at rusty_v8 build. And same result on Intel 32bit.

  ../../../../.cargo/registry/src/github.com-1285ae84e5963aae/v8-0.39.0/src/binding.cc:40:1: error: static_assert failed due to requirement 'sizeof(v8::ScriptCompiler::Source) <= sizeof(unsigned int) * 8' "Source size mismatch"
  static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(size_t) * 8,
  ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3 warnings and 1 error generated.

I thought the size of "size_t" depends the host machine's architecture, so I fixed "binding.cc" to

static_assert(sizeof(v8::ScriptCompiler::Source) <= sizeof(uint64_t) * 8,
              "Source size mismatch");

Is this correct? And please explain what is this "static_assert"?

I'm not a native speaker so please forgive my weird English.


问:
Return char array C
I have a function that makes a string with a certain number of #. String is stored as in char array (at list I think this is it... I'm new to C). This string is generated inside a function called blocks. I want to know how to return it so I can display it with printf("Someting Something %s", bricks) Do I have to change data type of ma string to char or how do I change the code to work?

```<code>int main(void)
{
    char hashes = blocks(3);
}

char blocks(int n)
{
    // string in which I will store data
    char line[] = "";
    int max = n + 1;
    for (int i = 0; i < max; i++)
    {
        // n times # is appended to char array line
        char brick[] = "#";
        strcat(line, brick);
    }
    return line;
}
</code>```

I want to know how to return string or array  ### and store it in variable hashes.

答:
Plenty problems.

line is not long enough to accommodate additional characters added by strcat. Actually, it can only accommodate null terminating character

You cant return the pointer to the local variable as this variable stops existing when the function returns.

Your function returns the char not char * pointer. So the pointer is being converted to int

hashes is assigned a nonsense value as per p3

I think you need to start from the C book.

Title: Return char array C

Body:
I have a function that makes a string with a certain number of #. String is stored as in char array (at list I think this is it... I'm new to C). This string is generated inside a function called blocks. I want to know how to return it so I can display it with printf("Someting Something %s", bricks) Do I have to change data type of ma string to char or how do I change the code to work?

int main(void)
{
    char hashes = blocks(3);
}

char blocks(int n)
{
    // string in which I will store data
    char line[] = "";
    int max = n + 1;
    for (int i = 0; i < max; i++)
    {
        // n times # is appended to char array line
        char brick[] = "#";
        strcat(line, brick);
    }
    return line;
}

I want to know how to return string or array  ### and store it in variable hashes.


问:
How to use scss variable in css
I need to change the font size using a variable as prescribed by the author. I am not sure on how to do it. The author claims tha t it ,can be done using css.

This is my css line

```<code>font-size:var(--sb-font-size:38px);
</code>```

https://github.com/MurhafSousli/ngx-sharebuttons/blob/master/CHANGELOG.MD

答:
You've confusing:

SCSS variables and CSS variables (the document you link to talks about the latter)

Setting and using CSS variables

Put the code to set a CSS variable in a ruleset, not in the middle of the code to read a CSS variable.

/* Set a variable */

:root {
  --sb-font-size: 38px;
}

/* Use a variable */

span {
  font-size: var(--sb-font-size);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Some <span>text</span></p></code>```

Title: How to use scss variable in css

Body:
I need to change the font size using a variable as prescribed by the author. I am not sure on how to do it. The author claims tha t it ,can be done using css.

This is my css line

font-size:var(--sb-font-size:38px);

https://github.com/MurhafSousli/ngx-sharebuttons/blob/master/CHANGELOG.MD

Body:
You've confusing:

SCSS variables and CSS variables (the document you link to talks about the latter)

Setting and using CSS variables

Put the code to set a CSS variable in a ruleset, not in the middle of the code to read a CSS variable.

/* Set a variable */

:root {
  --sb-font-size: 38px;
}

/* Use a variable */

span {
  font-size: var(--sb-font-size);
}

<p>Some <span>text</span></p>


问:
Cannot generate app bundle... something with mergeReleaseResources
I'm trying to generate the signed bundle to publish my first app, but I cannot make it compile and I have look for every error and can't find an answer.
This is the error message:

```<code>Task :app:mergeReleaseResources
 C:\Users\TNS SAS\AndroidStudioProjects\numBus\app\build\intermediates
   \incremental\mergeReleaseResources\stripped.dir\layout
   \activity_main.xml:17:53: Id 'id/ button' has an invalid entry name ' button'.
 C:\Users\TNS SAS\AndroidStudioProjects\numBus\app\build\intermediates
   \incremental\mergeReleaseResources\stripped.dir\layout
   \activity_main.xml: Failure to compile the resource file.

 Task :app:mergeReleaseResources FAILED
    Execution failed for task ':app:mergeReleaseResources'.
 A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable
 Resource compilation failed. Check logs for details.
</code>```

The original .xml that makes reference is this code:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="40dp"
    android:layout_marginTop="20dp"
    android:layout_marginEnd="40dp"
    android:layout_marginBottom="20dp"
    android:contentDescription="logo"
    app:layout_constraintBottom_toTopOf="@+id/tvCedula"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/logo" />

<EditText
    android:id="@+id/tvCedula"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:ems="10"
    android:hint="Cédula"
    android:inputType="number"
    android:minHeight="48dp"
    android:textColorHighlight="@color/purple_500"
    android:textColorLink="@color/purple_200"
    app:layout_constraintBottom_toTopOf="@+id/tvPlaca"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintStart_toStartOf="parent"/>

<EditText
    android:id="@+id/tvPlaca"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:ems="10"
    android:hint="Placa"
    android:inputType="textAutoComplete"
    android:minHeight="48dp"
    app:layout_constraintBottom_toTopOf="@+id/spinnerEmpresas"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:textAllCaps="true" />

<Spinner
    android:id="@+id/spinnerEmpresas"
    android:layout_width="220dp"
    android:layout_height="48dp"
    android:layout_marginBottom="16dp"
    android:animationCache="false"
    android:dropDownWidth="wrap_content"
    android:ems="10"
    android:minHeight="48dp"
    android:spinnerMode="dropdown"
    app:layout_constraintBottom_toTopOf="@+id/sign_in_button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    tools:ignore="SpeakableTextPresentCheck" />

<com.google.android.gms.common.SignInButton
    android:id="@+id/sign_in_button"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_marginBottom="150dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

When I look at the file that it's assembling, it is this:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.common.SignInButton
    android:id="@+id/ button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The solution is not deleting resources.... not to delete apcompability in gradle....

答:
I solved but i dont really know what it was.
Created new Project from scratch and copied and pasted every activity. Run it, generate signed bundle.... and that´s it.</p>

Body:
I'm trying to generate the signed bundle to publish my first app, but I cannot make it compile and I have look for every error and can't find an answer.
This is the error message:

Task :app:mergeReleaseResources
 C:\Users\TNS SAS\AndroidStudioProjects\numBus\app\build\intermediates
   \incremental\mergeReleaseResources\stripped.dir\layout
   \activity_main.xml:17:53: Id 'id/ button' has an invalid entry name ' button'.
 C:\Users\TNS SAS\AndroidStudioProjects\numBus\app\build\intermediates
   \incremental\mergeReleaseResources\stripped.dir\layout
   \activity_main.xml: Failure to compile the resource file.

 Task :app:mergeReleaseResources FAILED
    Execution failed for task ':app:mergeReleaseResources'.
 A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable
 Resource compilation failed. Check logs for details.

The original .xml that makes reference is this code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="40dp"
    android:layout_marginTop="20dp"
    android:layout_marginEnd="40dp"
    android:layout_marginBottom="20dp"
    android:contentDescription="logo"
    app:layout_constraintBottom_toTopOf="@+id/tvCedula"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/logo" />

<EditText
    android:id="@+id/tvCedula"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:ems="10"
    android:hint="Cédula"
    android:inputType="number"
    android:minHeight="48dp"
    android:textColorHighlight="@color/purple_500"
    android:textColorLink="@color/purple_200"
    app:layout_constraintBottom_toTopOf="@+id/tvPlaca"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintStart_toStartOf="parent"/>

<EditText
    android:id="@+id/tvPlaca"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:ems="10"
    android:hint="Placa"
    android:inputType="textAutoComplete"
    android:minHeight="48dp"
    app:layout_constraintBottom_toTopOf="@+id/spinnerEmpresas"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:textAllCaps="true" />

<Spinner
    android:id="@+id/spinnerEmpresas"
    android:layout_width="220dp"
    android:layout_height="48dp"
    android:layout_marginBottom="16dp"
    android:animationCache="false"
    android:dropDownWidth="wrap_content"
    android:ems="10"
    android:minHeight="48dp"
    android:spinnerMode="dropdown"
    app:layout_constraintBottom_toTopOf="@+id/sign_in_button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    tools:ignore="SpeakableTextPresentCheck" />

<com.google.android.gms.common.SignInButton
    android:id="@+id/sign_in_button"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_marginBottom="150dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

When I look at the file that it's assembling, it is this:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.common.SignInButton
    android:id="@+id/ button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

The solution is not deleting resources.... not to delete apcompability in gradle....


问:
How to serve ReactJS static files with expressJS?

The Problem

I have successfully served the index.html file of my React app, but the index.js that replaces <root> in the html file
with my first React component is not triggering on ReactDOM.render.
How do I get the index.js file to start? If my understanding of serving a React app is skewed in certain ways, I would greatly
appreciate clarification.

Folder Structure

/ - contains all server-side files, including server.js

/client/ - contains all React files

/client/build/ - contains all production-ready client files

/client/build/index.html

/client/build/static/js/main.[hash].js - seems to be a minified version of index.js that contains the ReactDOM.render for
my React app

Current Deployment

I am using Facebook's create-react-app for the /client/ directory, including npm run build to automatically populate /client/build/

File Snippets

```<code>// server.js
let app = express();
app.use(express.static(path.join(__dirname, '../client/public')));
</code>```

This successfully loads the default index.html provided by
create-react-app

```<code>// index.html
<body>
  <noscript>
    You need to enable JavaScript to run this app.
  </noscript>
  <div id="root"></div>
</body>
</code>```

The above section of code may/may not be useful, but it is the default
html file that comes with create-react-app. Do I need to replace the
noscript tag with a script tag that references the minified index.js
file? I have attempted that, and nothing changed, but perhaps it is
because of incorrect relative path-making.

答:
my project structure

project

-->client

back end(express)\

after using npn run build i found out that index.html in build was using wrong directory of css files or static instead of using

const path = require('path');
app.use(express.static(path.join(__dirname, '/client/build/')));```

i know i also tried ../client...... but not working

so what i did is cut and paste static folder of build in root directory this image can give you the idea, and its working structure

Body:
The Problem

I have successfully served the index.html file of my React app, but the index.js that replaces <root> in the html file
with my first React component is not triggering on ReactDOM.render.
How do I get the index.js file to start? If my understanding of serving a React app is skewed in certain ways, I would greatly
appreciate clarification.

Folder Structure

/ - contains all server-side files, including server.js

/client/ - contains all React files

/client/build/ - contains all production-ready client files

/client/build/index.html

/client/build/static/js/main.[hash].js - seems to be a minified version of index.js that contains the ReactDOM.render for
my React app

Current Deployment

I am using Facebook's create-react-app for the /client/ directory, including npm run build to automatically populate /client/build/

File Snippets

// server.js
let app = express();
app.use(express.static(path.join(__dirname, '../client/public')));

This successfully loads the default index.html provided by
create-react-app

// index.html

    You need to enable JavaScript to run this app.

The above section of code may/may not be useful, but it is the default
html file that comes with create-react-app. Do I need to replace the
noscript tag with a script tag that references the minified index.js
file? I have attempted that, and nothing changed, but perhaps it is
because of incorrect relative path-making.

Body:
my project structure

project

-->client

back end(express)\

after using npn run build i found out that index.html in build was using wrong directory of css files or static instead of using

const path = require('path');
app.use(express.static(path.join(__dirname, '/client/build/')));

i know i also tried ../client...... but not working

so what i did is cut and paste static folder of build in root directory this image can give you the idea, and its working structure


问:
What are the arguments against the use of the "<?="?

Possible Duplicate:

  Are PHP short tags acceptable to use?

The <?= is one of the very few elegant things about PHP, IMO. Yet, there are people that deliberately avoid it (in favor of the much longer <?php echo). Why would they do that?

答: Because the feature isn't enabled by default in PHP, so if someone else uses the code who doesn't, the code breaks.</p>

ContentLicense: CC BY-SA 3.0


答:
```<code>:root {
 --sb-font-size: 38px;
}
</code>```

then acces it

```<code>.test {
  font-size: var(--sb-font-size);
}
</code>```

Title: How to use scss variable in css

Body:
:root {
 --sb-font-size: 38px;
}

then acces it

.test {
  font-size: var(--sb-font-size);
}


问:
Is it possible to use FastAPI with Django?
I'm a Django developer and recently stumbled onto the FastAPI framework.

Then I decided to give it a shot. But usually when you talk about building RESTful APIs with Django you usually use the Django Rest Framework (DRF).

Is anybody aware if it is possible to substitute DRF by FastAPI using Django perks, like its ORM, and still have access to all of FastAPI's async features?

Up until now I only found one article on this. But in the process of integration the author lost most of the features of FastAPI.
You can find it here.

In the FastAPI docs, they do mention that it is possible to redirect certain request to a WSGI application here.

答:
there is good resource as follows:

Combine the power of FastAPI and Django


问:
Pandas: how to index dataframe for certain value or string without knowing the column name
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

```<code>fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons
</code>```

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

```<code>print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)
</code>```

Which results in:

```<code>Int64Index([1], dtype='int64')
</code>```

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

答:
You can use np.where as well.

Code:

import numpy as np
[(df.index[i], df.columns[c]) for i, c in zip(*np.where(df.isin(['Mangos'])))]
```
<h3>Output:</h3>
<pre class="lang-py prettyprint-override"><code>[(1, 'column3')]
</code>```

Body:
Although it seems very detrimental, I am having a hard time getting the index of a dataframe for a certain string or value at a random position in the dataframe.

I made an example dataframe:

fruits = {
    'column1':["Apples","Pears","Bananas","Oranges","Strawberries"],
    'column2':[1,2,3,4,5],
    'column3':["Kiwis","Mangos","Pineapples","Grapes","Melons"]
          }

df = pd.DataFrame(fruits)

        column1  column2     column3
0        Apples        1       Kiwis
1         Pears        2      Mangos
2       Bananas        3  Pineapples
3       Oranges        4      Grapes
4  Strawberries        5      Melons

Now I want to get the position index of Mangos, without having the knowledge in which column or row it exists. So far I succeeded in getting the row index:

print(df.loc[df.isin(["Mangos"]).any(axis=1)].index)

Which results in:

Int64Index([1], dtype='int64')

But now I would also like to retrieve the column index or column name.

This thread is a very simplified version of Get column name where value is something in pandas dataframe, but I could not figure out the code using the other thread.

Body:
You can use np.where as well.

Code:

import numpy as np
[(df.index[i], df.columns[c]) for i, c in zip(*np.where(df.isin(['Mangos'])))]

Output:

[(1, 'column3')]


问:
Recommended file structure by Google, for the new Android App Architecture
On 14 December 2021, Google launched a revamped guide to app architecture, where each Android app shall have at least UI and data layers. Based on the Google documentation regarding this new recommended architecture I can not find any reference to the file structure to adopt.

So I ask if there is any recommendation by Google for the file structure to adopt that best fits this architecture.

This question isn`t opinion-based, as I specifically ask for a recommendation from Google.

答:
Very recently, 31 Jan 2022, Manuel Vivo, Android Developer Relations Engineer @ Google, working on App Architecture, respond here to this same question, which I reproduce:

"That is actually a pretty good question, we do not have one (recommended architecture) at the moment, and that is something we want to work on, which is more about modularization, on how to structure your packages and folders and all that."


问:
Remove unwanted characters from Dataframe values in Pandas
I have the following Dataframe full of locus/gen names from a multiple genome alignment.

However, I am trying to get only a full list of the locus/name without the coordinates.

```<code>    Tuberculosis_locus  Smagmatis_locus             H37RA_locus             Bovis_locus
0   0:Rv0001:1-1524     1:MSMEG_RS33460:6986600-6988114 2:MRA_RS00005:1-1524    3:BQ2027_RS00005:1-1524
1   0:Rv0002:2052-3260  1:MSMEG_RS00005:499-1692    2:MRA_RS00010:2052-3260 3:BQ2027_RS00010:2052-3260
2   0:Rv0003:3280-4437  1:MSMEG_RS00015:2624-3778   2:MRA_RS00015:3280-4437 3:BQ2027_RS00015:3280-4437
</code>```

To avoid issues with empty cells, I am filling cells with 'N/A' and then striping the unwanted characters. But it's giving the same exact result, nothing seems to be happening.

```<code>for value in orthologs['Tuberculosis_locus']:
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].fillna("N/A")
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].map(lambda x: x.lstrip('\d:').rstrip(':\d+'))
</code>```

Any idea on what I am doing wrong? I'd like the following output:

```<code>Tuberculosis_locus  Smagmatis_locus  H37RA_locus  Bovis_locus
    0   Rv0001  MSMEG_RS33460   MRA_RS00005 BQ2027_RS00005
    1   Rv0002  MSMEG_RS00005   MRA_RS00010 BQ2027_RS00010
    2   Rv0003  MSMEG_RS00015   MRA_RS00015 BQ2027_RS00015
</code>```

答:
```<code>def clean(x):
    x = x.split(':')[1].strip()
    return x

orthologs = orthologs.applymap(clean)
</code>```

should work.

Explanation:

applymap is for the whole dataframe and apply is for a data column.

clean is a function you want to apply to every entry of the dataframe. Note that you don't need (x) anymore when you use it together with applymap or apply.

Body:
I have the following Dataframe full of locus/gen names from a multiple genome alignment.

However, I am trying to get only a full list of the locus/name without the coordinates.

    Tuberculosis_locus  Smagmatis_locus             H37RA_locus             Bovis_locus
0   0:Rv0001:1-1524     1:MSMEG_RS33460:6986600-6988114 2:MRA_RS00005:1-1524    3:BQ2027_RS00005:1-1524
1   0:Rv0002:2052-3260  1:MSMEG_RS00005:499-1692    2:MRA_RS00010:2052-3260 3:BQ2027_RS00010:2052-3260
2   0:Rv0003:3280-4437  1:MSMEG_RS00015:2624-3778   2:MRA_RS00015:3280-4437 3:BQ2027_RS00015:3280-4437

To avoid issues with empty cells, I am filling cells with 'N/A' and then striping the unwanted characters. But it's giving the same exact result, nothing seems to be happening.

for value in orthologs['Tuberculosis_locus']:
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].fillna("N/A")
    orthologs['Tuberculosis_locus'] = orthologs['Tuberculosis_locus'].map(lambda x: x.lstrip('\d:').rstrip(':\d+'))

Any idea on what I am doing wrong? I'd like the following output:

Tuberculosis_locus  Smagmatis_locus  H37RA_locus  Bovis_locus
    0   Rv0001  MSMEG_RS33460   MRA_RS00005 BQ2027_RS00005
    1   Rv0002  MSMEG_RS00005   MRA_RS00010 BQ2027_RS00010
    2   Rv0003  MSMEG_RS00015   MRA_RS00015 BQ2027_RS00015

Body:
def clean(x):
    x = x.split(':')[1].strip()
    return x

orthologs = orthologs.applymap(clean)

should work.

Explanation:

applymap is for the whole dataframe and apply is for a data column.

clean is a function you want to apply to every entry of the dataframe. Note that you don't need (x) anymore when you use it together with applymap or apply.


问:
failure to initialize SDL audio
When i Call SDL_Init passing in SDL_AUDIO_INIT, the function returns a failure.

I called SDL_GetError() but there does not seem to be any message.
I am not having problems getting VIDEO to initialize, only audio. I don't get any errors when compiling. I have linked the SDL mixer library in my makefile.

Here is a minimum reproducible example code:

```<code>#include <SDL2/SDL.h>
#include <stdio.h>
#include <string>

int main( int argc, char* args[] )
{

        //Initialize SDL
        if( SDL_Init( SDL_INIT_VIDEO  < 0))
        {
                printf( "SDL VIDEO could not initialize! SDL Error: %s\n", SDL_GetError() );
        }
        else if ( SDL_Init( SDL_INIT_AUDIO) < 0)
        {
                printf( "SDL AUDIO could not initialize! SDL Error: %s\n", SDL_GetError() );
        }
        else
        {
                printf("video and audio initialized");
        }

        return 0;
}
</code>```

output: SDL AUDIO could not initialize! SDL Error:

(there is no message for the error)

Here is the makefile

```<code>#OBJS specifies which files to compile as part of the project
OBJS = 21_sound_effects_and_music.cpp

#CC specifies which compiler we're using
CC = g++

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
COMPILER_FLAGS = -g -Wall

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lSDL2 -lSDL2_image -lSDL2_ttf -lSDL2_mixer

#OBJ_NAME specifies the name of our exectuable
OBJ_NAME = sdl_program

#This is the target that compiles our executable
all : $(OBJS)
        $(CC) $(OBJS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME)
</code>```

I am using Ubuntu 20.04

答:
install libasound2-dev libpulse-dev

and recompyling SDL2

Audio drivers   : disk dummy oss alsa(dynamic) pulse(dynamic) <--- IS OK

Title: failure to initialize SDL audio

Body:
When i Call SDL_Init passing in SDL_AUDIO_INIT, the function returns a failure.

I called SDL_GetError() but there does not seem to be any message.
I am not having problems getting VIDEO to initialize, only audio. I don't get any errors when compiling. I have linked the SDL mixer library in my makefile.

Here is a minimum reproducible example code:

#include <SDL2/SDL.h>
#include <stdio.h>
#include <string>

int main( int argc, char* args[] )
{

        //Initialize SDL
        if( SDL_Init( SDL_INIT_VIDEO  < 0))
        {
                printf( "SDL VIDEO could not initialize! SDL Error: %s\n", SDL_GetError() );
        }
        else if ( SDL_Init( SDL_INIT_AUDIO) < 0)
        {
                printf( "SDL AUDIO could not initialize! SDL Error: %s\n", SDL_GetError() );
        }
        else
        {
                printf("video and audio initialized");
        }

        return 0;
}

output: SDL AUDIO could not initialize! SDL Error:

(there is no message for the error)

Here is the makefile

#OBJS specifies which files to compile as part of the project
OBJS = 21_sound_effects_and_music.cpp

#CC specifies which compiler we're using
CC = g++

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
COMPILER_FLAGS = -g -Wall

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lSDL2 -lSDL2_image -lSDL2_ttf -lSDL2_mixer

#OBJ_NAME specifies the name of our exectuable
OBJ_NAME = sdl_program

#This is the target that compiles our executable
all : $(OBJS)
        $(CC) $(OBJS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME)

I am using Ubuntu 20.04


问:
After I installed nodemon by "npm i nodemon" , when I tried to run it by "nodemon server.js" , it gives me this error. What should I do?
Screenshot form VS code terminalnodemon : The term 'nodemon' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the
path is correct and try again.</p>

答:
I just meet that question.

First, you should make sure that you had installed nodemon in a global way (npm install -g nodemon), and make sure global package dir is in the environment variables.

Secondly, you should RESTART VScode if you are opening it now.
I spent lots of time to make sure the previous one, but it still fails, then when I restart VScode, everything is fine!


问:
Django Rest Framework File Upload
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:

```<code>class ProductList(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    def get(self,request):
        if request.user.is_authenticated():
            userCompanyId = request.user.get_profile().companyId
            products = Product.objects.filter(company = userCompanyId)
            serializer = ProductSerializer(products,many=True)
            return Response(serializer.data)

    def post(self,request):
        serializer = ProductSerializer(data=request.DATA, files=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(data=request.DATA)
</code>```

As the last line of post method should return all the data, I have several questions:

how to check if there is anything in request.FILES?

how to serialize file field?

how should I use parser?

答:
There are majorly 3 ways for upload files in drf

suppose you have Tag model with title and logo fields and TagSerializer

```<code>class Tag(models.Model):
    title = models.CharField(max_length=10, default='')
    file = models.FileField(upload_to='tag/', blank=True, null=True, )

class TagSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'
</code>```

you can choose one of them according to your situation.

1- using serializer:

```<code>class UploadFile(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request):

        serializer = TagSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

2- using write method :

```<code>def save_file(file: InMemoryUploadedFile, full_path):
    with open(full_path, 'wb+') as f:
        for chunk in file.chunks():
            f.write(chunk)

class UploadFile(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request):
        file: InMemoryUploadedFile = request.FILES['file']
        # define file_save_path variable
        full_path = file_save_path + file.name
        save_file(file, full_path)
        return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

3- using FileSystemStorage:

```<code>class UploadFile(APIView):
parser_classes = (MultiPartParser, FormParser)

def post(self, request):
    file: InMemoryUploadedFile = request.FILES['file']
    f = FileSystemStorage()
    # this will save file in MEDIA_ROOT path
    f.save(file.name, file)
    return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

Title: Django Rest Framework File Upload

Body:
I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:

class ProductList(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    def get(self,request):
        if request.user.is_authenticated():
            userCompanyId = request.user.get_profile().companyId
            products = Product.objects.filter(company = userCompanyId)
            serializer = ProductSerializer(products,many=True)
            return Response(serializer.data)

    def post(self,request):
        serializer = ProductSerializer(data=request.DATA, files=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(data=request.DATA)

As the last line of post method should return all the data, I have several questions:

how to check if there is anything in request.FILES?

how to serialize file field?

how should I use parser?

Body:
There are majorly 3 ways for upload files in drf

suppose you have Tag model with title and logo fields and TagSerializer

class Tag(models.Model):
    title = models.CharField(max_length=10, default='')
    file = models.FileField(upload_to='tag/', blank=True, null=True, )

class TagSerializer(rest_serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'

you can choose one of them according to your situation.

1- using serializer:

class UploadFile(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request):

        serializer = TagSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)

2- using write method :

def save_file(file: InMemoryUploadedFile, full_path):
    with open(full_path, 'wb+') as f:
        for chunk in file.chunks():
            f.write(chunk)

class UploadFile(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request):
        file: InMemoryUploadedFile = request.FILES['file']
        # define file_save_path variable
        full_path = file_save_path + file.name
        save_file(file, full_path)
        return Response(serializer.data, status=status.HTTP_200_OK)

3- using FileSystemStorage:

class UploadFile(APIView):
parser_classes = (MultiPartParser, FormParser)

def post(self, request):
    file: InMemoryUploadedFile = request.FILES['file']
    f = FileSystemStorage()
    # this will save file in MEDIA_ROOT path
    f.save(file.name, file)
    return Response(serializer.data, status=status.HTTP_200_OK)


问:
MySQL Replace Null with an Empty String
I have this table

user_id
title

1
ABCD

1
null

2
EFGH

I'am trying to get all the titles of every user id and convert null to an empty string.

I tried using this

SELECT IFNULL(title, '') FROM table WHERE user_id = 1

But it says that multiple rows returned, when I try 2 it returns a result.

Is there a way to convert all null relut to empty string if ther more than 1 result? Thanks.

答:
You can find a detailed answer on the following link.

Hope it resolves your issue.

Thanks

Title: MySQL Replace Null with an Empty String


问:
Open webp file with Pillow
On an Anaconda set up, I want to run following simple code:

from PIL import Image
img = Image.open('test.webp')
```
<p>This works on my Linux machine, but on Windows:</p>
```UserWarning: image file could not be identified because WEBP support not installed
  warnings.warn(message)
---------------------------------------------------------------------------
UnidentifiedImageError                    Traceback (most recent call last)
<ipython-input-3-79ee787a81b3> in <module>
----> 1 img = Image.open('test.webp')

~\miniconda3\lib\site-packages\PIL\Image.py in open(fp, mode, formats)
   3028     for message in accept_warnings:
   3029         warnings.warn(message)
-> 3030     raise UnidentifiedImageError(
   3031         "cannot identify image file %r" % (filename if filename else fp)
   3032     )

UnidentifiedImageError: cannot identify image file 'test.webp'
```

I do have the libwebp package installed, and libwebp.dll is present in the Library\bin directory of my Anaconda set up.

Any idea?

答:
Looks like no solution is in sight. Assuming dwebp from the libwepb library is available in the system, this works for me to generate a Pillow Image object from a WEBP file:

import os
import subprocess
from PIL import Image, UnidentifiedImageError
from io import BytesIO

class dwebpException(Exception):
    pass

def dwebp(file: str):
    webp = subprocess.run(
        f"dwebp {file} -quiet -o -", shell=True, capture_output=True
    )
    if webp.returncode != 0:
        raise dwebpException(webp.stderr.decode())
    else:
        return Image.open(BytesIO(webp.stdout))

filename = 'test.webp'

try:
    img = Image.open(filename)
except UnidentifiedImageError:
    if os.path.splitext(filename)[1].lower() == ".webp":
        img = dwebp(filename)
    else:
        raise
```

Title: Open webp file with Pillow

Body:
On an Anaconda set up, I want to run following simple code:

from PIL import Image
img = Image.open('test.webp')

This works on my Linux machine, but on Windows:

UserWarning: image file could not be identified because WEBP support not installed
  warnings.warn(message)
---------------------------------------------------------------------------
UnidentifiedImageError                    Traceback (most recent call last)
<ipython-input-3-79ee787a81b3> in <module>
----> 1 img = Image.open('test.webp')

~\miniconda3\lib\site-packages\PIL\Image.py in open(fp, mode, formats)
   3028     for message in accept_warnings:
   3029         warnings.warn(message)
-> 3030     raise UnidentifiedImageError(
   3031         "cannot identify image file %r" % (filename if filename else fp)
   3032     )

UnidentifiedImageError: cannot identify image file 'test.webp'

I do have the libwebp package installed, and libwebp.dll is present in the Library\bin directory of my Anaconda set up.

Any idea?


问:
Merge two JSON into one JSON using Java and validate in karate feature file
Json1 {"key1" :"one","key2":"two"}
Json2 {"FN": "AB","LN":"XY"}
I wish to have Json3 {"key1" :"one","key2":"two","FN": "AB","LN":"XY"}

I have used below code but it does not work:

```<code>        JSONObject mergedJSON = new JSONObject();
        try {
            mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
            for (String Key : JSONObject.getNames(json2)) {
                mergedJSON.put(Key, json2.get(Key));
            }

        } catch (JSONException e) {

            throw new RuntimeException("JSON Exception" + e);
        }
        return mergedJSON;
    }

      * call defaultCOM {ID: "COM-123"}
        * def defaultResponse = response.data.default
        * def jMap = mergeJSON.toMap(defaultResponse)
Here error comes (language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'org.json.JSONObject': Unsupported target type
</code>```

答:
All I'll say is that the recommended way to merge 2 JSONs is given in the documentation: https://github.com/karatelabs/karate#json-transforms

```<code>* def foo = { a: 1 }
* def bar = karate.merge(foo, { b: 2 })
* match bar == { a: 1, b: 2 }
</code>```

I'll also say that when you use custom Java code, you should stick to using Map or List: https://github.com/karatelabs/karate#calling-java

And if you use things like JSONObject whatever that is, you are on your own - and please consider that not supported by Karate.

When you have to mix Java and the Karate-style JS code (and this something you should try to avoid as far as possible) you need to be aware of some caveats: https://github.com/karatelabs/karate/wiki/1.0-upgrade-guide#js-to-java

Body:
Json1 {"key1" :"one","key2":"two"}
Json2 {"FN": "AB","LN":"XY"}
I wish to have Json3 {"key1" :"one","key2":"two","FN": "AB","LN":"XY"}

I have used below code but it does not work:

        JSONObject mergedJSON = new JSONObject();
        try {
            mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
            for (String Key : JSONObject.getNames(json2)) {
                mergedJSON.put(Key, json2.get(Key));
            }

        } catch (JSONException e) {

            throw new RuntimeException("JSON Exception" + e);
        }
        return mergedJSON;
    }

      * call defaultCOM {ID: "COM-123"}
        * def defaultResponse = response.data.default
        * def jMap = mergeJSON.toMap(defaultResponse)
Here error comes (language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'org.json.JSONObject': Unsupported target type

Body:
All I'll say is that the recommended way to merge 2 JSONs is given in the documentation: https://github.com/karatelabs/karate#json-transforms

* def foo = { a: 1 }
* def bar = karate.merge(foo, { b: 2 })
* match bar == { a: 1, b: 2 }

I'll also say that when you use custom Java code, you should stick to using Map or List: https://github.com/karatelabs/karate#calling-java

And if you use things like JSONObject whatever that is, you are on your own - and please consider that not supported by Karate.

When you have to mix Java and the Karate-style JS code (and this something you should try to avoid as far as possible) you need to be aware of some caveats: https://github.com/karatelabs/karate/wiki/1.0-upgrade-guide#js-to-java


问:
Refactoring and simplifying for loops to be more "Swifty"
I have a fairly simple for-loop that I would like to refactor to be more "Swifty".  I'm sure this is do-able with some kind of map or other cool mechanism.  If it's not too much to ask, it would be beneficial of me to hear a thought-process behind refactoring/creating these, as it's one area of Swift that I just can't seem to wrap my head around very well (I'm stuck on an old-school for-loop mindset!).

The loop goes through an array of dictionaries to find the one we need (based on a refKey==refVal), then it simply pulls a different value needed from that particular dictionary based on "keyForWhatWeWant":

```<code>for currentDictionary in dictionaries where currentDictionary["refKey"] == "refVal" {
    if let valueWeWant = currentDictionary["keyForWhatWeWant"] {
        return valueWeWant
    }
}
</code>```

I do want it to pass through this code and move on if it does not find the value, though, FYI.

答:
You can use Swift collection method first where predicate to find the dictionaries that fit your criteria and then get its key "keyForWhatWeWant". IMO the for loop approach seems cleaner:</p>
```<code>if let valueWeWant = dictionaries.first(where: {
    $0["refKey"] == "refVal" && $0["keyForWhatWeWant"] != nil
})?["keyForWhatWeWant"] {
    print("valueWeWant:", valueWeWant)
}
</code>```

Body:
I have a fairly simple for-loop that I would like to refactor to be more "Swifty".  I'm sure this is do-able with some kind of map or other cool mechanism.  If it's not too much to ask, it would be beneficial of me to hear a thought-process behind refactoring/creating these, as it's one area of Swift that I just can't seem to wrap my head around very well (I'm stuck on an old-school for-loop mindset!).

The loop goes through an array of dictionaries to find the one we need (based on a refKey==refVal), then it simply pulls a different value needed from that particular dictionary based on "keyForWhatWeWant":

for currentDictionary in dictionaries where currentDictionary["refKey"] == "refVal" {
    if let valueWeWant = currentDictionary["keyForWhatWeWant"] {
        return valueWeWant
    }
}

I do want it to pass through this code and move on if it does not find the value, though, FYI.

Body:
You can use Swift collection method first where predicate to find the dictionaries that fit your criteria and then get its key "keyForWhatWeWant". IMO the for loop approach seems cleaner:

if let valueWeWant = dictionaries.first(where: {
    $0["refKey"] == "refVal" && $0["keyForWhatWeWant"] != nil
})?["keyForWhatWeWant"] {
    print("valueWeWant:", valueWeWant)
}


问:
Gnome-terminal --tab variables don't work
I am trying to open a new terminal tab and have a for loop print the iterator.

gnome-terminal --tab -- /bin/bash -c "for (( num=1;num!=-1;num++ ));do echo $num; sleep 2;done"

After executing the above command for some reason it only prints out the number 3

However, if i run it the command without using gnome-terminal it works as expected.
for (( num=1;num!=-1;num++ ));do echo $num; sleep 2;done

Anyone know why?

答:
$num will interpolate the value of num in the original shell into the string passed as argument to the new /bin/bash.

Use ' instead of " to suppress interpolation.


问:
How to find unicode character class in PHP
I am having hard times finding a way to get the unicode class of a char.

list of unicode classes: https://www.php.net/manual/en/regexp.reference.unicode.php

The desired function in python: https://docs.python.org/3/library/unicodedata.html#unicodedata.category

I just want the PHP equivalent to this python function.

For example, if I called the x function like this: x('-') it would return Pd because Pd is the class hyphen belongs to.

Thanks.

答:
So Apparently there is no built-in function that does that, so I wrote this function:

<?php
$UNICODE_CATEGORIES = [
        "Cc",
        "Cf",
        "Cs",
        "Co",
        "Cn",
        "Lm",
        "Mn",
        "Mc",
        "Me",
        "No",
        "Zs",
        "Zl" ,
        "Zp",
        "Pc",
        "Pd",
        "Ps" ,
        "Pe" ,
        "Pi" ,
        "Pf" ,
        "Po" ,
        "Sm",
        "Sc",
        "Sk",
        "So",
        "Zs",
        "Zl",
        "Zp"
    ];

function uni_category($char, $UNICODE_CATEGORIES) {
    foreach ($UNICODE_CATEGORIES as $category) {
        if (preg_match('/\p{'.$category.'}/', $char))
            return $category;
    }
    return null;
}
// call the function
print uni_category('-', $UNICODE_CATEGORIES); // it returns Pd
```

This code works for me, I hope it helps someby in the future :).

Body:
So Apparently there is no built-in function that does that, so I wrote this function:

<?php
$UNICODE_CATEGORIES = [
        "Cc",
        "Cf",
        "Cs",
        "Co",
        "Cn",
        "Lm",
        "Mn",
        "Mc",
        "Me",
        "No",
        "Zs",
        "Zl" ,
        "Zp",
        "Pc",
        "Pd",
        "Ps" ,
        "Pe" ,
        "Pi" ,
        "Pf" ,
        "Po" ,
        "Sm",
        "Sc",
        "Sk",
        "So",
        "Zs",
        "Zl",
        "Zp"
    ];

function uni_category($char, $UNICODE_CATEGORIES) {
    foreach ($UNICODE_CATEGORIES as $category) {
        if (preg_match('/\p{'.$category.'}/', $char))
            return $category;
    }
    return null;
}
// call the function
print uni_category('-', $UNICODE_CATEGORIES); // it returns Pd

This code works for me, I hope it helps someby in the future :).


问:
Why are anonymous types in .NET implemented as reference type?
Because an anonymous type is readonly anyway, is would be more efficient if they implemented them as structs so that linq queries doesn't need to create tons of temporary objects:

```<code>// This doesn't make any sense, it is just for demonstration
var result = thingies
.Select(x=> new {A = 1, B = 2, C = 3});
</code>```

Btw. I got this idea, when reading this

EDIT:

The greatest thing would be if the compiler would, depending on the size and usage of the variable (must if be passed to lots of methods), decide whether to make if a value type or reference type.

But could the following sentence which I found in the msdn cause problems then:

If two or more anonymous types in the same assembly have the same
  number and type of properties, in the same order, the compiler treats
  them as the same type.

Since an anonymous object (with its associated type) cannot leave the method which it is defined in we have no problems here, do we?

答:
The full .NET garbage collector is particularly well-optimized for two cases: large, long-lived objects that last significant amounts of time, and small, short-lived objects that die off quickly. Gen0 collections are practically free given how fast they are (so fast and frequent, in fact, that many profilers don't even bother showing them or their contents), so there's little reason to avoid temporaries that will be gone within the scope of the function that created them.

Anonymous types fit the second case almost perfectly; they're not meant to outlive the function that creates them (although you can do it with some trickery). Given this model, and given the fact that most value types are relatively expensive to copy around, and given that many LINQ queries involve a long chain of functions that would all require yet another copy, it makes sense to me that the designers chose to make them reference types.

Body:
Because an anonymous type is readonly anyway, is would be more efficient if they implemented them as structs so that linq queries doesn't need to create tons of temporary objects:

// This doesn't make any sense, it is just for demonstration
var result = thingies
.Select(x=> new {A = 1, B = 2, C = 3});

Btw. I got this idea, when reading this

EDIT:

The greatest thing would be if the compiler would, depending on the size and usage of the variable (must if be passed to lots of methods), decide whether to make if a value type or reference type.

But could the following sentence which I found in the msdn cause problems then:

If two or more anonymous types in the same assembly have the same
  number and type of properties, in the same order, the compiler treats
  them as the same type.

Since an anonymous object (with its associated type) cannot leave the method which it is defined in we have no problems here, do we?


问:
PHP Time() to Google Calendar Dates time format
I have PHP times for the start and end times of an event.  This is a simple <?php time(); ?> for some future date's start and end time.  I was wondering if anyone knew of a way to take either the numerical format (PHP time()) or taking some string value representing that time (I could do a strtotime($sometimevalue);) and turn it into the required Google Calendar time format.

Enough talking - here is an example of the time format:

```<code>20150107T003000Z/20150107T023000Z
</code>```

This equates to January 6th, 2015 at 5:30 PM to January 6th, 2015 at 7:30PM.

So can someone explain to me how to translate a time() to this format?

答:
The easiest way I use:</p>
```<code>$postBody = new Google_Service_Calendar_Event(array(
.......
    'start' => array(
            'dateTime' => date_format($event_Start_datetime,'c');
........

//'c' - formats DateTime object as needed for Google Calendar
</code>```

Body:
I have PHP times for the start and end times of an event.  This is a simple <?php time(); ?> for some future date's start and end time.  I was wondering if anyone knew of a way to take either the numerical format (PHP time()) or taking some string value representing that time (I could do a strtotime($sometimevalue);) and turn it into the required Google Calendar time format.

Enough talking - here is an example of the time format:

20150107T003000Z/20150107T023000Z

This equates to January 6th, 2015 at 5:30 PM to January 6th, 2015 at 7:30PM.

So can someone explain to me how to translate a time() to this format?

Body:
The easiest way I use:

$postBody = new Google_Service_Calendar_Event(array(
.......
    'start' => array(
            'dateTime' => date_format($event_Start_datetime,'c');
........

//'c' - formats DateTime object as needed for Google Calendar


问:
How to truncate text in TailwindCSS?
I am using truncate in TailwindCSS to make text ellipsis if text-overflow more than one line but it does not work.

My code not works below:

```<code><div className="ml-1 inline-block">
   <span>Label: </span>
   <span className="font-semibold truncate">
     long texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
   </span>
</div>
</code>```

How can I fix It?

答:
First thing first your parent or the element must have a specific width otherwise how the element suppose to know when to stop and truncate? also in order to truncate to work your element's display must not be display inline since span is display inline by default you should change it to block

```<code>  <div className="ml-1 inline-block w-[200px]">
     <span>Label: </span>
     <span className="font-semibold truncate block">
       long texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
     </span>
  </div>
</code>```

Title: How to truncate text in TailwindCSS?

Body:
I am using truncate in TailwindCSS to make text ellipsis if text-overflow more than one line but it does not work.

My code not works below:

   Label:

     long texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt

How can I fix It?

Body:
First thing first your parent or the element must have a specific width otherwise how the element suppose to know when to stop and truncate? also in order to truncate to work your element's display must not be display inline since span is display inline by default you should change it to block

  <div className="ml-1 inline-block w-[200px]">
     <span>Label: </span>
     <span className="font-semibold truncate block">
       long texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
     </span>
  </div>


问:
How do you send complex objects using WCF? Does it work? Is it good?
Can I have a data contract of this shape??

```<code>[DataContract]

public class YearlyStatistic{

[DataMember]
public string Year{get;set;}

[DataMember]
public string StatisticName {get;set;}

[DataMember]
public List<MonthlyStatistic> MonthlyStats {get;set}
};
</code>```

I am assuming here that class MonthlyStatistic will also need to be a DataContract. Can you do this in a web service?

答:
To use the same model for web services, mark your class as Serializable use the XmlRoot and XmlElement in the System.Xml.Serialization namespace.  Here is a sample using your example:

```<code>[Serializable]
[XmlRoot("YearlyStatistic")]
public class YearlyStatistic
{
    [XmlElement("Year")]
    public string Year { get; set; }

    [XmlElement("StatisticName")]
    public string StatisticName { get; set; }

    [XmlElement("MonthlyStats")]
    public List<MonthlyStatistic> MonthlyStats { get; set; }
}
</code>```

You will have to do the same thing for your complex object properties of the parent object.

OwnerDisplayName: Perpetualcoder

ContentLicense: CC BY-SA 2.5

Body:
Can I have a data contract of this shape??

[DataContract]

public class YearlyStatistic{

[DataMember]
public string Year{get;set;}

[DataMember]
public string StatisticName {get;set;}

[DataMember]
public List<MonthlyStatistic> MonthlyStats {get;set}
};

I am assuming here that class MonthlyStatistic will also need to be a DataContract. Can you do this in a web service?

LastEditorDisplayName: Perpetualcoder

Body:
To use the same model for web services, mark your class as Serializable use the XmlRoot and XmlElement in the System.Xml.Serialization namespace.  Here is a sample using your example:

[Serializable]
[XmlRoot("YearlyStatistic")]
public class YearlyStatistic
{
    [XmlElement("Year")]
    public string Year { get; set; }

    [XmlElement("StatisticName")]
    public string StatisticName { get; set; }

    [XmlElement("MonthlyStats")]
    public List<MonthlyStatistic> MonthlyStats { get; set; }
}

You will have to do the same thing for your complex object properties of the parent object.

OwnerDisplayName: Michael Kniskern

LastEditorDisplayName: Michael Kniskern


问:
setInterval() still triggering after clearInterval() in NodeJS
I have the following code setting and clearing an interval inside a NodeJS script.

Starting interval works fine, but when trying to clear it, the stopping interval console will trigger, but the interval will continue firing every minute.

```<code>app.get("/api", async (req, res) => {

    active = req.query.active;

    let interval = null;

    if (active == "true") {

        console.log("starting interval");

        interval = setInterval(async function() {
            try {
                const Posts = await getPosts();
                const Comments = await getComments();
                sendPosts().then(() => sendComments());

            } catch (e) {
                throw e;
            };
        }, 60000);

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: true});

    } else {

        console.log("stopping interval");

        clearInterval(interval);
        interval = null;

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: false});
    }

});
</code>```

What am I missing?

答:
Your interval variable is declared inside the route handler. Every time the route is called, a new interval variable is created. Reassigning that variable inside one invocation of the route does not change its value during other invocations of the route. You need:

```<code>let interval = null;
app.get("/api", async (req, res) => {
    // ...
</code>```

You should also catch errors properly - your current approach will result in unhandled rejections here:

```<code>    interval = setInterval(async function() {
        try {
            const Posts = await getPosts();
            const Comments = await getComments();
            sendPosts().then(() => sendComments());

        } catch (e) {
            throw e;
        };
    }, 60000);
</code>```

Only throw if there's something that can handle it up the call stack - if not, you should do whatever you reasonably can with the error at that point and stop without throwing.

Body:
I have the following code setting and clearing an interval inside a NodeJS script.

Starting interval works fine, but when trying to clear it, the stopping interval console will trigger, but the interval will continue firing every minute.

app.get("/api", async (req, res) => {

    active = req.query.active;

    let interval = null;

    if (active == "true") {

        console.log("starting interval");

        interval = setInterval(async function() {
            try {
                const Posts = await getPosts();
                const Comments = await getComments();
                sendPosts().then(() => sendComments());

            } catch (e) {
                throw e;
            };
        }, 60000);

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: true});

    } else {

        console.log("stopping interval");

        clearInterval(interval);
        interval = null;

        res.json({ reddit: subreddit, discordChannel: discordChannel, activated: false});
    }

});

What am I missing?

Body:
Your interval variable is declared inside the route handler. Every time the route is called, a new interval variable is created. Reassigning that variable inside one invocation of the route does not change its value during other invocations of the route. You need:

let interval = null;
app.get("/api", async (req, res) => {
    // ...

You should also catch errors properly - your current approach will result in unhandled rejections here:

    interval = setInterval(async function() {
        try {
            const Posts = await getPosts();
            const Comments = await getComments();
            sendPosts().then(() => sendComments());

        } catch (e) {
            throw e;
        };
    }, 60000);

Only throw if there's something that can handle it up the call stack - if not, you should do whatever you reasonably can with the error at that point and stop without throwing.


问:
HTML div goes on next line even though width is 33%
Please help me understand this. Here is my HTML (body)

```<code><body>
    <main class="container">
        <div class="row">
            <div class="col">Sparky</div>
            <div class="col">Vegeta</div>
            <div class="col">Flufferpants</div>
        </div>
    </main>
</body>
</code>```

Here is my CSS

```<code>* {
    font-size: 25px;
    /* box-sizing: border-box; */
}
body {
    background-color: gray;
}
.container {
    max-width: 600px;
    margin: 0 auto;
    background-color: lightgoldenrodyellow;
}
.row {
    background-color: rgb(119, 103, 134);
    width: 100%;
}
.col {
    display: inline-block;
    width: 33%;
    height: 200px;
}
</code>```

I am trying to have the 3 cols be on a single row, evenly spaced apart. I know this is easily done through flexbox, but I wanted to try using the width property manually.

Even when I set each of the col to be width 33%, it still rolls onto the next line. What's going on here?

https://jsfiddle.net/zd29ewb6/

Thanks

答:
using inline-block elements there always be a whitespace between the elements and you set your width 33% and adding the width of all the 3 divs its width
gets more then the parents width so it shift the third element to next line. so you can reduce the width of col like this.

```<code>.col {
    display: inline-block;
    width: 30%;
    height: 200px;
}
</code>```

Body:
Please help me understand this. Here is my HTML (body)

Sparky

Vegeta

Flufferpants

Here is my CSS

* {
    font-size: 25px;
    /* box-sizing: border-box; */
}
body {
    background-color: gray;
}
.container {
    max-width: 600px;
    margin: 0 auto;
    background-color: lightgoldenrodyellow;
}
.row {
    background-color: rgb(119, 103, 134);
    width: 100%;
}
.col {
    display: inline-block;
    width: 33%;
    height: 200px;
}

I am trying to have the 3 cols be on a single row, evenly spaced apart. I know this is easily done through flexbox, but I wanted to try using the width property manually.

Even when I set each of the col to be width 33%, it still rolls onto the next line. What's going on here?

https://jsfiddle.net/zd29ewb6/

Thanks

Body:
using inline-block elements there always be a whitespace between the elements and you set your width 33% and adding the width of all the 3 divs its width
gets more then the parents width so it shift the third element to next line. so you can reduce the width of col like this.

.col {
    display: inline-block;
    width: 30%;
    height: 200px;
}


答:
You need to move "let interval" outside of the call to app.get().

Right now the variable is declared inside the closure of the function which means it gets initialized every time a request comes in.

If it's outside the function, the variable becomes part of the global scope and its value will be remembered between requests.

Title: setInterval() still triggering after clearInterval() in NodeJS