问:
How to make a horizontal StackView to have the first element's width and fill the rest of it
I'm new with swift and trying to create an input field at the moment. My problem is, that I would like to have a Label as shown in the picture:

So far, I'm working with StackViews: One vertical one for the input fields, and three horizontal ones to have the Title and the user input. My code so far is as follows:

```<code>// Initialize outter stackview
    let feedbackOutterSV = UIStackView()
    view.addSubview(feedbackOutterSV)
    feedbackOutterSV.translatesAutoresizingMaskIntoConstraints = false
    feedbackOutterSV.axis = NSLayoutConstraint.Axis.vertical
    NSLayoutConstraint.activate([
        feedbackOutterSV.topAnchor.constraint(equalTo: tutorialText.bottomAnchor, constant: 10),
        feedbackOutterSV.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        feedbackOutterSV.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        feedbackOutterSV.heightAnchor.constraint(equalToConstant: 300)
    ])

    // Initalize inner stackview for title
    let feedbackInnerSVTitle = UIStackView()
    feedbackOutterSV.addArrangedSubview(feedbackInnerSVTitle)
    feedbackInnerSVTitle.translatesAutoresizingMaskIntoConstraints = false
    feedbackInnerSVTitle.axis = .horizontal
    feedbackInnerSVTitle.alignment = .fill
    feedbackInnerSVTitle.distribution = .fillProportionally

    let titleLabel = UILabel()
    feedbackInnerSVTitle.addArrangedSubview(titleLabel)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = "feedback.input.title".localize()
    titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
    titleLabel.textColor = .gray

    let titleTextView = UITextView()
    feedbackInnerSVTitle.addArrangedSubview(titleTextView)
    titleTextView.translatesAutoresizingMaskIntoConstraints = false
    titleTextView.font = UIFont.preferredFont(forTextStyle: .body)
    titleTextView.isScrollEnabled = false

    NSLayoutConstraint.activate([
        titleLabel.widthAnchor.constraint(equalToConstant: 39)
    ])
</code>```

This code gives the expected output for English, however I have to implement it in different languages, so I can't use a constant width.

Can anyone tell me how to change my code, so I don't need the constant constraint but the width of the Label is adjusted to the length of the word?

Thanks in advance

答:
I think you could use NSLayoutConstraint.activate([
  titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 0)] to let it grow depending on the content

Body:
I'm new with swift and trying to create an input field at the moment. My problem is, that I would like to have a Label as shown in the picture:

So far, I'm working with StackViews: One vertical one for the input fields, and three horizontal ones to have the Title and the user input. My code so far is as follows:

// Initialize outter stackview
    let feedbackOutterSV = UIStackView()
    view.addSubview(feedbackOutterSV)
    feedbackOutterSV.translatesAutoresizingMaskIntoConstraints = false
    feedbackOutterSV.axis = NSLayoutConstraint.Axis.vertical
    NSLayoutConstraint.activate([
        feedbackOutterSV.topAnchor.constraint(equalTo: tutorialText.bottomAnchor, constant: 10),
        feedbackOutterSV.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        feedbackOutterSV.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        feedbackOutterSV.heightAnchor.constraint(equalToConstant: 300)
    ])

    // Initalize inner stackview for title
    let feedbackInnerSVTitle = UIStackView()
    feedbackOutterSV.addArrangedSubview(feedbackInnerSVTitle)
    feedbackInnerSVTitle.translatesAutoresizingMaskIntoConstraints = false
    feedbackInnerSVTitle.axis = .horizontal
    feedbackInnerSVTitle.alignment = .fill
    feedbackInnerSVTitle.distribution = .fillProportionally

    let titleLabel = UILabel()
    feedbackInnerSVTitle.addArrangedSubview(titleLabel)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = "feedback.input.title".localize()
    titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
    titleLabel.textColor = .gray

    let titleTextView = UITextView()
    feedbackInnerSVTitle.addArrangedSubview(titleTextView)
    titleTextView.translatesAutoresizingMaskIntoConstraints = false
    titleTextView.font = UIFont.preferredFont(forTextStyle: .body)
    titleTextView.isScrollEnabled = false

    NSLayoutConstraint.activate([
        titleLabel.widthAnchor.constraint(equalToConstant: 39)
    ])

This code gives the expected output for English, however I have to implement it in different languages, so I can't use a constant width.

Can anyone tell me how to change my code, so I don't need the constant constraint but the width of the Label is adjusted to the length of the word?

Thanks in advance


来源: stackexchange

问:
how to create help system in java
We are developing new web application and we must integrate help in it. Does anyone know any good opensource help application that we can integrate it in our system or is better to develop help center from scratch? We are using java 1.6. Help must be related to articles, forms,...

Thx

答:
Some years ago, I worked with the Eclipse Help System. Eclipse is not necessarily needed to integrate it in your project. Its helpfiles are also based on .html pages. Unfortunatly I dont know if they continue developing it, but at this time it already provided all the aspects you would expect from a help system.

There are a lot examples out there on how to integrate it in your project, but its possible, that maybe there are already better frameworks today.

ContentLicense: CC BY-SA 3.0

Title: how to create help system in java


问:
Adding strings in lists together
I want to transform the list ["A","B","A","A","B"] to the list ["AB","BA","AA","AB"].

I have tried to define a new list in which the first element is deleted and then add the strings of the lists together. After which I plan to delete the last element of the new list to get the result.

```<code>lista = sequences
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]
</code>```

But all I get is

TypeError: 'list' object cannot be interpreted as an integer

Any help is welcome.

Edit : Thank you guys, all your solutions worked perfectly :)

答:
Best solution, using zip with a list comprehension, cleverest:

```<code>>>> l = ["A","B","A","A","B"]
>>> [x + y for x, y in zip(l, l[1:])]
['AB', 'BA', 'AA', 'AB']
>>>
</code>```

Or use an enumerate with a list comprehension:

```<code>>>> l = ["A","B","A","A","B"]
>>> [v + l[i + 1] for i, v in enumerate(l[:-1])]
['AB', 'BA', 'AA', 'AB']
>>>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Adding strings in lists together

Body:
I want to transform the list ["A","B","A","A","B"] to the list ["AB","BA","AA","AB"].

I have tried to define a new list in which the first element is deleted and then add the strings of the lists together. After which I plan to delete the last element of the new list to get the result.

lista = sequences
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]

But all I get is

TypeError: 'list' object cannot be interpreted as an integer

Any help is welcome.

Edit : Thank you guys, all your solutions worked perfectly :)

Body:
Best solution, using zip with a list comprehension, cleverest:

>>> l = ["A","B","A","A","B"]
>>> [x + y for x, y in zip(l, l[1:])]
['AB', 'BA', 'AA', 'AB']
>>>

Or use an enumerate with a list comprehension:

>>> l = ["A","B","A","A","B"]
>>> [v + l[i + 1] for i, v in enumerate(l[:-1])]
['AB', 'BA', 'AA', 'AB']
>>>


问:
How to check if user is logged in using ajax in Symfony?
I wonder what is the best way how to check if user is logged in Symfony (4.x) using ajax xhr request? Currently I'm using combination of controller action (to handle success response) and event subscriber (to prevent redirection to login form if user is trying to access controller action while not logged in). Is there any better way to handle this?</p>

答:
Currently I'm using combination of controller action (to handle success response)

I assume it is something like this

```<code>/**
 * @Route("/me/")
 */
public function meAction(): JsonResponse
{
    return new JsonResponse([
        'authenticated' => $this->getUser() !== null,
    ]);
}
</code>```

event subscriber (to prevent redirection to login form if user is
  trying to access controller action while not logged in)

You can just add the following line in your security.yml

```<code>access_control
    - { path: ^/me/$, role: IS_AUTHENTICATED_ANONYMOUSLY }
</code>```

Make sure to add it before any other access checks, this will tell the firewall to allow anonymous access for this path.

Also make sure that anonymous access is enabled for your firewall

```<code>firewalls:
    secured_area:
        anonymous: true
</code>```

In case you don't want to allow anonymous access

there is nothing wrong with having anonymous: true, but if for some reason you don't want to allow it and still avoid a redirect - you can implement a custom Entry Point

```<code>class XhrAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
    /**
     * {@inheritdoc}
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        return new JsonResponse(
            ['authenticated' => false],
            200 // can be 200 or 401 up to you.
        );
    }
}
</code>```

and then add it to your configs

```<code>// services.yml
Security\XhrAuthenticationEntryPoint: ~

// security.yml
firewalls:
    secured_area:
        entry_point: Security\XhrAuthenticationEntryPoint
</code>```

Body:
Currently I'm using combination of controller action (to handle success response)

I assume it is something like this

/**
 * @Route("/me/")
 */
public function meAction(): JsonResponse
{
    return new JsonResponse([
        'authenticated' => $this->getUser() !== null,
    ]);
}

event subscriber (to prevent redirection to login form if user is
  trying to access controller action while not logged in)

You can just add the following line in your security.yml

access_control
    - { path: ^/me/$, role: IS_AUTHENTICATED_ANONYMOUSLY }

Make sure to add it before any other access checks, this will tell the firewall to allow anonymous access for this path.

Also make sure that anonymous access is enabled for your firewall

firewalls:
    secured_area:
        anonymous: true

In case you don't want to allow anonymous access

there is nothing wrong with having anonymous: true, but if for some reason you don't want to allow it and still avoid a redirect - you can implement a custom Entry Point

class XhrAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
    /**
     * {@inheritdoc}
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        return new JsonResponse(
            ['authenticated' => false],
            200 // can be 200 or 401 up to you.
        );
    }
}

and then add it to your configs

// services.yml
Security\XhrAuthenticationEntryPoint: ~

// security.yml
firewalls:
    secured_area:
        entry_point: Security\XhrAuthenticationEntryPoint


问:
How to get Runner class inside cucumber event handler
I need to define a custom annotations in cucumber runner class. I have a event handler class where i get a callback when a test case is finished/started etc.

The issue i am facing is i am not able to get the runner class inside the event handler class, and hence i am unable to read the custom annotations applied in the runner class.

Is there a way for that in cucumber.

Eg. in junit , i can get the custom annotation applied in the test class as :
public void testFinished(Description description) { description.getTestClass();} from where i could read my annotation.

in testng, itestContext.getTestClass().getRealClass();.

Any help would be highly appreciated.

Many thanks in advance.

Eg. i need to read the annotations here,

```<code>private EventHandler<TestCaseFinished> caseFinishedEventHandler = new EventHandler<TestCaseFinished>() {
    @Override
    public void receive(TestCaseFinished event) {
     //Read annotations here...
    }
}; /*Or here*/ private EventHandler<TestRunFinished> runFinishedEventHandler = new EventHandler<TestRunFinished>() {
    @Override
    public void receive(TestRunFinished event) {

    }
};
</code>```

答:
Solved this issue by :

For Junit : Extending Cucumber runner class. class argument of the constructor returns the runner class where custom annotations are present.

For TestNG : Extending AbstractTestNGCucumberTests in case of TestNG. this.getClass() returns the runner class where custom annotations are present.

Body:
I need to define a custom annotations in cucumber runner class. I have a event handler class where i get a callback when a test case is finished/started etc.

The issue i am facing is i am not able to get the runner class inside the event handler class, and hence i am unable to read the custom annotations applied in the runner class.

Is there a way for that in cucumber.

Eg. in junit , i can get the custom annotation applied in the test class as :
public void testFinished(Description description) { description.getTestClass();} from where i could read my annotation.

in testng, itestContext.getTestClass().getRealClass();.

Any help would be highly appreciated.

Many thanks in advance.

Eg. i need to read the annotations here,

private EventHandler<TestCaseFinished> caseFinishedEventHandler = new EventHandler<TestCaseFinished>() {
    @Override
    public void receive(TestCaseFinished event) {
     //Read annotations here...
    }
}; /*Or here*/ private EventHandler<TestRunFinished> runFinishedEventHandler = new EventHandler<TestRunFinished>() {
    @Override
    public void receive(TestRunFinished event) {

    }
};


问:
Why only the first value is written to the variable
I want to get the properties of an object and call a function depending on the property. I'm trying to do it like this:

```<code>let page = {};
Object.keys(product.details).forEach((k) => {
  console.log(k)
  switch (k) {
    case 'description':
      page.add(getDescription());
      break;
    case 'comment':
      page.add(getComment());
      break;
    case 'subDescription':
      page.add(getSubDescription());
      break;
  }
});
console.log(page);
</code>```

My object:

```<code>{
  about: 'text',
  description: 'text',
  comment: 'text',
  subDescription: 'text'
}
</code>```

What do I get in the console:

```<code>about
description
...\src\views\partials\product\description.hbs
</code>```

Why is only the first function called, and the rest not? What's my mistake?

答:
This is just a guess - maybe page.add() simply doesn't exist.

products.about is the first key in your object - so inside the forEach loop you get

console.log(k) -> about -> nothing else

the next key is description
console.log(k) -> description -> now it tries to execute page.add(getDescription());
because it's defined in the switch-block. In case that function doesn't exist it will crash here.

Body:
I want to get the properties of an object and call a function depending on the property. I'm trying to do it like this:

let page = {};
Object.keys(product.details).forEach((k) => {
  console.log(k)
  switch (k) {
    case 'description':
      page.add(getDescription());
      break;
    case 'comment':
      page.add(getComment());
      break;
    case 'subDescription':
      page.add(getSubDescription());
      break;
  }
});
console.log(page);

My object:

{
  about: 'text',
  description: 'text',
  comment: 'text',
  subDescription: 'text'
}

What do I get in the console:

about
description
...\src\views\partials\product\description.hbs

Why is only the first function called, and the rest not? What's my mistake?


问:
Docker image not found during local deployment ("no such image")
I want to test my service and to do so I deploy it locally and until now everything worked fine. However, for some unrelated reason I was forced to delete all my docker images and since then I'm unable to deploy the service locally. Upon deployment I receive the following error:

404 Client Error: Not Found for url:
  http+docker://localnpipe/v1.39/images/471b7320d98e95ad137228efff17267535936b632a749f817dbee3e9d03cd814/json

And also:

ImageNotFound: 404 Client Error: Not Found ("no such image:
  471b7320d98e95ad137228efff17267535936b632a749f817dbee3e9d03cd814: No
  such image:
  sha256:471b7320d98e95ad137228efff17267535936b632a749f817dbee3e9d03cd814")

What I did to deploy the model:

```<code>from azureml.core.model import Model
from azureml.core import Workspace
from azureml.core.webservice import LocalWebservice
from azureml.core.model import InferenceConfig

ws = Workspace.from_config("config.json")

deployment_config = LocalWebservice.deploy_configuration(port=8890)

inference_config = InferenceConfig(runtime= "python",
                               entry_script="score.py",
                               conda_file="env.yml")

model_box = Model(ws, "box")
model_view = Model(ws, "view_crop")
model_damage = Model(ws, "damage_crop")

service = Model.deploy(ws, "test-service", [model_box, model_view, model_damage], inference_config, deployment_config)

service.wait_for_deployment(True)
</code>```

I understand why there is no image present, but I would expect that it is downloaded in that case.

Is there a way to force the build process to re-download the docker base image?

Thanks in advance.

答:
I just found the problem and corresponding solution:

I deleted all images but there where still some containers based on deleted images present. Deleting the corresponding container had the desired effect that the docker image is reloaded from the server.

You can delete all containers with docker kill $(docker ps -q).

Body:
I want to test my service and to do so I deploy it locally and until now everything worked fine. However, for some unrelated reason I was forced to delete all my docker images and since then I'm unable to deploy the service locally. Upon deployment I receive the following error:

404 Client Error: Not Found for url:
  http+docker://localnpipe/v1.39/images/471b7320d98e95ad137228efff17267535936b632a749f817dbee3e9d03cd814/json

And also:

ImageNotFound: 404 Client Error: Not Found ("no such image:
  471b7320d98e95ad137228efff17267535936b632a749f817dbee3e9d03cd814: No
  such image:
  sha256:471b7320d98e95ad137228efff17267535936b632a749f817dbee3e9d03cd814")

What I did to deploy the model:

from azureml.core.model import Model
from azureml.core import Workspace
from azureml.core.webservice import LocalWebservice
from azureml.core.model import InferenceConfig

ws = Workspace.from_config("config.json")

deployment_config = LocalWebservice.deploy_configuration(port=8890)

inference_config = InferenceConfig(runtime= "python",
                               entry_script="score.py",
                               conda_file="env.yml")

model_box = Model(ws, "box")
model_view = Model(ws, "view_crop")
model_damage = Model(ws, "damage_crop")

service = Model.deploy(ws, "test-service", [model_box, model_view, model_damage], inference_config, deployment_config)

service.wait_for_deployment(True)

I understand why there is no image present, but I would expect that it is downloaded in that case.

Is there a way to force the build process to re-download the docker base image?

Thanks in advance.


问:
Rails active_storage:install will not install
I am trying to store images in my post section of my app using active_storage. However, when I am trying to run rails active_storage:install via the terminal, I am getting a message that rails aborts every time.

I have already tried to include require 'active_storage/engine' within my application.rb file but the problem keeps persisting.

Gemfile

```<code>source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.5.1'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.3'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
    # See https://github.com/rails/execjs#readme for more supported runtimes
    # gem 'mini_racer', platforms: :ruby

    # Use CoffeeScript for .coffee assets and views
    gem 'coffee-rails', '~> 4.2'
    # Turbolinks makes navigating your web application faster. Read
    more:
    https://github.com/turbolinks/turbolinks
    gem 'turbolinks', '~> 5'
    # Build JSON APIs with ease. Read more:
    https://github.com/rails/jbuilder
    gem 'jbuilder', '~> 2.5'
    # Use Redis adapter to run Action Cable in production
    # gem 'redis', '~> 4.0'
    # Use ActiveModel has_secure_password
    # gem 'bcrypt', '~> 3.1.7'

    # Use ActiveStorage variant
    # gem 'mini_magick', '~> 4.8'

    # Use Capistrano for deployment
    # gem 'capistrano-rails', group: :development

    # Reduces boot times through caching; required in config/boot.rb
    gem 'bootsnap', '>= 1.1.0', require: false

    gem 'devise'
    gem 'pg'
    gem 'bootstrap', '~> 4.3.1'
    gem 'jquery-rails'
    gem 'font-awesome-rails'

    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]
     end

    group :development do
     # Access an interactive console on exception pages or by calling '
    console' anywhere in the code.
    gem 'web-console', '>= 3.3.0'
    gem 'listen', '>= 3.0.5', '< 3.2'
     # Spring speeds up development by keeping your application running
       in
    the background. Read more: https://github.com/rails/spring
      gem 'spring'
      gem 'spring-watcher-listen', '~> 2.0.0'
    end

    group :test do
      # Adds support for Capybara system testing and selenium driver
      gem 'capybara', '>= 2.15'
      gem 'selenium-webdriver'
      # Easy installation and use of chromedriver to run system tests
        with Chrome
      gem 'chromedriver-helper'
    end

    # Windows does not include zoneinfo files, so bundle the tzinfo-data
    gem
    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

application.rb

```<code>require_relative 'boot'

require 'rails/all'
require 'active_storage/engine'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Instagram
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated
Rails version.
config.load_defaults 5.2

# Settings in config/environments/* take precedence over those
specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after
loading
    # the framework and any gems in your application.
  end
end
</code>```

User.rb

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and
    :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :posts, dependable: :destroy

end
</code>```

Post.rb

```<code>class Post < ApplicationRecord
  belongs_to :user
end
</code>```

and finally, my terminal output.

```<code> rails active_storage:install --trace
    ** Invoke active_storage:install (first_time)
    ** Invoke environment (first_time)
    ** Execute environment
    rails aborted!
    ArgumentError: Unknown key: :dependable. Valid keys are:
    :class_name, :anonymous_class, :foreign_key, :validate, :autosave,
    :table_name, :before_add, :after_add, :before_remove, :after_remove,
    :extend, :primary_key, :dependent, :as, :through, :source,
    :source_type, :inverse_of, :counter_cache, :join_table,
    :foreign_type, :index_errors
</code>```

I am expecting the output to create a db migration table as follows.

db/migrate/20180924134051_create_active_storage_tables.active_storage.rb

答:
change

```<code>has_many :posts, dependable: :destroy
</code>```

to

```<code>has_many :posts, dependent: :destroy
</code>```

Body:
I am trying to store images in my post section of my app using active_storage. However, when I am trying to run rails active_storage:install via the terminal, I am getting a message that rails aborts every time.

I have already tried to include require 'active_storage/engine' within my application.rb file but the problem keeps persisting.

Gemfile

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.5.1'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.3'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
    # See https://github.com/rails/execjs#readme for more supported runtimes
    # gem 'mini_racer', platforms: :ruby

    # Use CoffeeScript for .coffee assets and views
    gem 'coffee-rails', '~> 4.2'
    # Turbolinks makes navigating your web application faster. Read
    more:
    https://github.com/turbolinks/turbolinks
    gem 'turbolinks', '~> 5'
    # Build JSON APIs with ease. Read more:
    https://github.com/rails/jbuilder
    gem 'jbuilder', '~> 2.5'
    # Use Redis adapter to run Action Cable in production
    # gem 'redis', '~> 4.0'
    # Use ActiveModel has_secure_password
    # gem 'bcrypt', '~> 3.1.7'

    # Use ActiveStorage variant
    # gem 'mini_magick', '~> 4.8'

    # Use Capistrano for deployment
    # gem 'capistrano-rails', group: :development

    # Reduces boot times through caching; required in config/boot.rb
    gem 'bootsnap', '>= 1.1.0', require: false

    gem 'devise'
    gem 'pg'
    gem 'bootstrap', '~> 4.3.1'
    gem 'jquery-rails'
    gem 'font-awesome-rails'

    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]
     end

    group :development do
     # Access an interactive console on exception pages or by calling '
    console' anywhere in the code.
    gem 'web-console', '>= 3.3.0'
    gem 'listen', '>= 3.0.5', '< 3.2'
     # Spring speeds up development by keeping your application running
       in
    the background. Read more: https://github.com/rails/spring
      gem 'spring'
      gem 'spring-watcher-listen', '~> 2.0.0'
    end

    group :test do
      # Adds support for Capybara system testing and selenium driver
      gem 'capybara', '>= 2.15'
      gem 'selenium-webdriver'
      # Easy installation and use of chromedriver to run system tests
        with Chrome
      gem 'chromedriver-helper'
    end

    # Windows does not include zoneinfo files, so bundle the tzinfo-data
    gem
    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

application.rb

require_relative 'boot'

require 'rails/all'
require 'active_storage/engine'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Instagram
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated
Rails version.
config.load_defaults 5.2

# Settings in config/environments/* take precedence over those
specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after
loading
    # the framework and any gems in your application.
  end
end

User.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and
    :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :posts, dependable: :destroy

end

Post.rb

class Post < ApplicationRecord
  belongs_to :user
end

and finally, my terminal output.

 rails active_storage:install --trace
    ** Invoke active_storage:install (first_time)
    ** Invoke environment (first_time)
    ** Execute environment
    rails aborted!
    ArgumentError: Unknown key: :dependable. Valid keys are:
    :class_name, :anonymous_class, :foreign_key, :validate, :autosave,
    :table_name, :before_add, :after_add, :before_remove, :after_remove,
    :extend, :primary_key, :dependent, :as, :through, :source,
    :source_type, :inverse_of, :counter_cache, :join_table,
    :foreign_type, :index_errors

I am expecting the output to create a db migration table as follows.

db/migrate/20180924134051_create_active_storage_tables.active_storage.rb

Body:
change

has_many :posts, dependable: :destroy

to

has_many :posts, dependent: :destroy


问:
What is the best place to store your JAR's and other libs in Mac OS X
My question is simple: what is the best place to store all my jar's, gwt and other frameworks on mac os x ?

I thought that it is /Library/Java/Extensions.
But I'm not sure that it is correct.

答:
There are two ways to install java stuff:

Use a package manager like Homebrew or MacPorts,

Or do things your own way.

As a sample, here is how MacPorts installs Tomcat:

```<code>/Library/LaunchDaemons/blah.blah.start.Tomcat.daemon
/opt/local/etc/LaunchDaemons/blah.blah.plist
/opt/local/bin/start-tomcat-script
/opt/local/share/docs/...tomcat docs
/opt/local/share/java/...tomcat classes
</code>```

You don't want to mimic that manually because it's an insane amount of work and there is no benefit. You either sudo port install tomcat6 or uncompress the whole Tomcat in /Users/YOURUSER/java/apache/tomcat/6/ and add bin to the path. Same thing for SDKs.

If you want to install just jars (not SDKs), use Maven as much as you can. You said something about trouble adding to your local repository. That's not correct, you can have several repositories and enable/disable them per project. I have one for the stuff maven downloads, and another one where I manually add things. If you are the only user of your machine put the repo somewhere inside your home, otherwise use /opt/local/var/ or anywhere you like.

Don't overthink it, it's about you getting work done.

Body:
There are two ways to install java stuff:

Use a package manager like Homebrew or MacPorts,

Or do things your own way.

As a sample, here is how MacPorts installs Tomcat:

/Library/LaunchDaemons/blah.blah.start.Tomcat.daemon
/opt/local/etc/LaunchDaemons/blah.blah.plist
/opt/local/bin/start-tomcat-script
/opt/local/share/docs/...tomcat docs
/opt/local/share/java/...tomcat classes

You don't want to mimic that manually because it's an insane amount of work and there is no benefit. You either sudo port install tomcat6 or uncompress the whole Tomcat in /Users/YOURUSER/java/apache/tomcat/6/ and add bin to the path. Same thing for SDKs.

If you want to install just jars (not SDKs), use Maven as much as you can. You said something about trouble adding to your local repository. That's not correct, you can have several repositories and enable/disable them per project. I have one for the stuff maven downloads, and another one where I manually add things. If you are the only user of your machine put the repo somewhere inside your home, otherwise use /opt/local/var/ or anywhere you like.

Don't overthink it, it's about you getting work done.


问:
Python HTTP request with json data isn't getting php response with json data
I am trying to send a python http request with some json data (I will use this json data in a later case) to server. Server should give a response with some json data (using PHP). Unfortunately there is no any response even though request status code is 200. Any help please!</p>

```<code>#request.py

import requests
import urllib3
import json
import os
import time
import sys

#http Request
url = 'http://localhost/response.php'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

while True:

    postMessage = '{"Info": {"ID": 1, "IP": "192.168.1.1"}}'
    response = requests.post(url, json=postMessage, headers=headers)
    #trying to decode the response
    try:
        decodedresponse = json.loads(response.text)
        print(decodedresponse)

    except(ValueError, KeyError, TypeError):
        print("some Error")

#always getting the above print statement!

    break
</code>```

```<code>#response.php

<?php

if(!empty($_POST['json'])){
  $data = [ 'a', 'b', 'c' ];
  header('Content-type:application/json;charset=utf-8');
  echo json_encode($data);

}
 ?>

</code>```

答:
Check your $_POST structure.</p>

```<code><?php
if(!empty($_POST['Info'])){
   $data = [ 'a', 'b', 'c' ];
   echo json_encode($data);
 }
 else{
     echo json_encode(ison_decode($_POST, TRUE));
 }
</code>```

Body:
I am trying to send a python http request with some json data (I will use this json data in a later case) to server. Server should give a response with some json data (using PHP). Unfortunately there is no any response even though request status code is 200. Any help please!

#request.py

import requests
import urllib3
import json
import os
import time
import sys

#http Request
url = 'http://localhost/response.php'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

while True:

    postMessage = '{"Info": {"ID": 1, "IP": "192.168.1.1"}}'
    response = requests.post(url, json=postMessage, headers=headers)
    #trying to decode the response
    try:
        decodedresponse = json.loads(response.text)
        print(decodedresponse)

    except(ValueError, KeyError, TypeError):
        print("some Error")

#always getting the above print statement!

    break

#response.php

<?php

if(!empty($_POST['json'])){
  $data = [ 'a', 'b', 'c' ];
  header('Content-type:application/json;charset=utf-8');
  echo json_encode($data);

}
 ?>

Body:
Check your $_POST structure.

<?php
if(!empty($_POST['Info'])){
   $data = [ 'a', 'b', 'c' ];
   echo json_encode($data);
 }
 else{
     echo json_encode(ison_decode($_POST, TRUE));
 }


问:
Add anti-aliasing/bandlimit for looped wav sample (NOT Fourier transform)
How to build antialiasing interpolation using c++ code? I have a simple 4096 or 1024 buffer. Of course when I play this at high frequencies I get aliasing issues. to avoid this, the signal must be limited by the bandwidth at high frequencies. Roughly speaking, the 'sawtooth' wave at high frequencies should looks like a regular sine. And that is what I want to get so that my sound didn't sound dirty like you moving knobs in your old FM/AM radio in your car.

I know how to build bandlimited square,triangle,sawtoth with Fourier transform. So my question is only about wavetable

答:
Found solution in the AudioKit sources. One buffer will be split into 10 buffers/octaves. So when you play a sound, you don't play your original wave, but play a sample that was prepared for a specific octave.

Import to your project WaveStack.hpp

```<code>namespace AudioKitCore
{

    // WaveStack represents a series of progressively lower-resolution sampled versions of a
    // waveform. Client code supplies the initial waveform, at a resolution of 1024 samples,
    // equivalent to 43.6 Hz at 44.1K samples/sec (about 23.44 cents below F1, midi note 29),
    // and then calls initStack() to create the filtered higher-octave versions.
    // This provides a basis for anti-aliased oscillators; see class WaveStackOscillator.

    struct WaveStack
    {
        // Highest-resolution rep uses 2^maxBits samples
        static constexpr int maxBits = 10;  // 1024

        // maxBits also defines the number of octave levels; highest level has just 2 samples
        float *pData[maxBits];

        WaveStack();
        ~WaveStack();

        // Fill pWaveData with 1024 samples, then call this
        void initStack(float *pWaveData, int maxHarmonic=512);

        void init();
        void deinit();

        float interp(int octave, float phase);
    };

}
</code>```

WaveStack.cpp

```<code>#include "WaveStack.hpp"
#include "kiss_fftr.h"

namespace AudioKitCore
{

    WaveStack::WaveStack()
    {
        int length = 1 << maxBits;                  // length of level-0 data
        pData[0] = new float[2 * length];           // 2x is enough for all levels
        for (int i=1; i<maxBits; i++)
        {
            pData[i] = pData[i - 1] + length;
            length >>= 1;
        }
    }

    WaveStack::~WaveStack()
    {
        delete[] pData[0];
    }

    void WaveStack::initStack(float *pWaveData, int maxHarmonic)
    {
        // setup
        int fftLength = 1 << maxBits;
        float *buf = new float[fftLength];
        kiss_fftr_cfg fwd = kiss_fftr_alloc(fftLength, 0, 0, 0);
        kiss_fftr_cfg inv = kiss_fftr_alloc(fftLength, 1, 0, 0);

        // copy supplied wave data for octave 0
        for (int i=0; i < fftLength; i++) pData[0][i] = pWaveData[i];

        // perform initial forward FFT to get spectrum
        kiss_fft_cpx spectrum[fftLength / 2 + 1];
        kiss_fftr(fwd, pData[0], spectrum);

        float scaleFactor = 1.0f / (fftLength / 2);

        for (int octave = (maxHarmonic==512) ? 1 : 0; octave < maxBits; octave++)
        {
            // zero all harmonic coefficients above new Nyquist limit
            int maxHarm = 1 << (maxBits - octave - 1);
            if (maxHarm > maxHarmonic) maxHarm = maxHarmonic;
            for (int h=maxHarm; h <= fftLength/2; h++)
            {
                spectrum[h].r = 0.0f;
                spectrum[h].i = 0.0f;
            }

            // perform inverse FFT to get filtered waveform
            kiss_fftri(inv, spectrum, buf);

            // resample filtered waveform
            int skip = 1 << octave;
            float *pOut = pData[octave];
            for (int i=0; i < fftLength; i += skip) *pOut++ = scaleFactor * buf[i];
        }

        // teardown
        kiss_fftr_free(inv);
        kiss_fftr_free(fwd);
        delete[] buf;
    }

    void WaveStack::init()
    {
    }

    void WaveStack::deinit()
    {
    }

    float WaveStack::interp(int octave, float phase)
    {
        while (phase < 0) phase += 1.0;
        while (phase >= 1.0) phase -= 1.0f;

        int nTableSize = 1 << (maxBits - octave);
        float readIndex = phase * nTableSize;
        int ri = int(readIndex);
        float f = readIndex - ri;
        int rj = ri + 1; if (rj >= nTableSize) rj -= nTableSize;

        float *pWaveTable = pData[octave];
        float si = pWaveTable[ri];
        float sj = pWaveTable[rj];
        return (float)((1.0 - f) * si + f * sj);
    }

}
</code>```

Then use it in this way:

```<code>//wave and outputWave should be float[1024];
void getSample(int octave, float* wave, float* outputWave){

    uint_fast32_t impulseCount = 1024;

    if (octave == 0){
        impulseCount = 737;
    }else if (octave == 1){
        impulseCount = 369;
    }
    else if (octave == 2){
        impulseCount = 185;
    }
    else if (octave == 3){
        impulseCount = 93;
    }
    else if (octave == 4){
        impulseCount = 47;
    }
    else if (octave == 5){
        impulseCount = 24;
    }
    else if (octave == 6){
        impulseCount = 12;
    }
    else if (octave == 7){
        impulseCount = 6;
    }
    else if (octave == 8){
        impulseCount = 3;
    }
    else if (octave == 9){
        impulseCount = 2;
    }

    //Get sample for octave
    stack->initStack(wave, impulseCount);

    for (int i = 0; i < 1024;i++){
        float phase = (1.0/float(1024))*i;

        //get interpolated wave and apply volume compensation
        outputWave[i] = stack->interp(0, phase) / 2.0;
    }

}
</code>```

Then... when 10 buffers is ready. You can use them when playing a sound. Using this code you can get index of buffer/octave depending to your frequency

```<code>uint_fast8_t getBufferIndex(const float& frequency){

    if (frequency >= 0 && frequency < 40){
        return 0;
    }
    else if (frequency >= 40 && frequency < 80){
        return 1;
    }else if (frequency >= 80 && frequency < 160){
        return 2;
    }else if (frequency >= 160 && frequency < 320){
        return 3;
    }else if (frequency >= 320 && frequency < 640){
        return 4;
    }else if (frequency >= 640 && frequency < 1280){
        return 5;
    }else if (frequency >= 1280 && frequency < 2560){
        return 6;
    }else if (frequency >= 2560 && frequency < 5120){
        return 7;
    }else if (frequency >= 5120 && frequency < 10240){
        return 8;
    }else if (frequency >= 10240){
        return 9;
    }
    return 0;
}
</code>```

So if I know that my note frequency 440hz. Then for this note I'm getting wave in this way:

```<code>float notInterpolatedSound[1024];
float interpolatedSound[1024];

uint_fast8_t octaveIndex = getBufferIndex(440.0);
getSample(octaveIndex, notInterpolatedSound, interpolatedSound);

//tada!
</code>```

ps. the code above is a low pass filter. I also tried to do sinc interpolation. But sinc worked for me very expensive and not exactly. Although maybe I did it wrong.

Body:
Found solution in the AudioKit sources. One buffer will be split into 10 buffers/octaves. So when you play a sound, you don't play your original wave, but play a sample that was prepared for a specific octave.

Import to your project WaveStack.hpp

namespace AudioKitCore
{

    // WaveStack represents a series of progressively lower-resolution sampled versions of a
    // waveform. Client code supplies the initial waveform, at a resolution of 1024 samples,
    // equivalent to 43.6 Hz at 44.1K samples/sec (about 23.44 cents below F1, midi note 29),
    // and then calls initStack() to create the filtered higher-octave versions.
    // This provides a basis for anti-aliased oscillators; see class WaveStackOscillator.

    struct WaveStack
    {
        // Highest-resolution rep uses 2^maxBits samples
        static constexpr int maxBits = 10;  // 1024

        // maxBits also defines the number of octave levels; highest level has just 2 samples
        float *pData[maxBits];

        WaveStack();
        ~WaveStack();

        // Fill pWaveData with 1024 samples, then call this
        void initStack(float *pWaveData, int maxHarmonic=512);

        void init();
        void deinit();

        float interp(int octave, float phase);
    };

}

WaveStack.cpp

#include "WaveStack.hpp"
#include "kiss_fftr.h"

namespace AudioKitCore
{

    WaveStack::WaveStack()
    {
        int length = 1 << maxBits;                  // length of level-0 data
        pData[0] = new float[2 * length];           // 2x is enough for all levels
        for (int i=1; i<maxBits; i++)
        {
            pData[i] = pData[i - 1] + length;
            length >>= 1;
        }
    }

    WaveStack::~WaveStack()
    {
        delete[] pData[0];
    }

    void WaveStack::initStack(float *pWaveData, int maxHarmonic)
    {
        // setup
        int fftLength = 1 << maxBits;
        float *buf = new float[fftLength];
        kiss_fftr_cfg fwd = kiss_fftr_alloc(fftLength, 0, 0, 0);
        kiss_fftr_cfg inv = kiss_fftr_alloc(fftLength, 1, 0, 0);

        // copy supplied wave data for octave 0
        for (int i=0; i < fftLength; i++) pData[0][i] = pWaveData[i];

        // perform initial forward FFT to get spectrum
        kiss_fft_cpx spectrum[fftLength / 2 + 1];
        kiss_fftr(fwd, pData[0], spectrum);

        float scaleFactor = 1.0f / (fftLength / 2);

        for (int octave = (maxHarmonic==512) ? 1 : 0; octave < maxBits; octave++)
        {
            // zero all harmonic coefficients above new Nyquist limit
            int maxHarm = 1 << (maxBits - octave - 1);
            if (maxHarm > maxHarmonic) maxHarm = maxHarmonic;
            for (int h=maxHarm; h <= fftLength/2; h++)
            {
                spectrum[h].r = 0.0f;
                spectrum[h].i = 0.0f;
            }

            // perform inverse FFT to get filtered waveform
            kiss_fftri(inv, spectrum, buf);

            // resample filtered waveform
            int skip = 1 << octave;
            float *pOut = pData[octave];
            for (int i=0; i < fftLength; i += skip) *pOut++ = scaleFactor * buf[i];
        }

        // teardown
        kiss_fftr_free(inv);
        kiss_fftr_free(fwd);
        delete[] buf;
    }

    void WaveStack::init()
    {
    }

    void WaveStack::deinit()
    {
    }

    float WaveStack::interp(int octave, float phase)
    {
        while (phase < 0) phase += 1.0;
        while (phase >= 1.0) phase -= 1.0f;

        int nTableSize = 1 << (maxBits - octave);
        float readIndex = phase * nTableSize;
        int ri = int(readIndex);
        float f = readIndex - ri;
        int rj = ri + 1; if (rj >= nTableSize) rj -= nTableSize;

        float *pWaveTable = pData[octave];
        float si = pWaveTable[ri];
        float sj = pWaveTable[rj];
        return (float)((1.0 - f) * si + f * sj);
    }

}

Then use it in this way:

//wave and outputWave should be float[1024];
void getSample(int octave, float* wave, float* outputWave){

    uint_fast32_t impulseCount = 1024;

    if (octave == 0){
        impulseCount = 737;
    }else if (octave == 1){
        impulseCount = 369;
    }
    else if (octave == 2){
        impulseCount = 185;
    }
    else if (octave == 3){
        impulseCount = 93;
    }
    else if (octave == 4){
        impulseCount = 47;
    }
    else if (octave == 5){
        impulseCount = 24;
    }
    else if (octave == 6){
        impulseCount = 12;
    }
    else if (octave == 7){
        impulseCount = 6;
    }
    else if (octave == 8){
        impulseCount = 3;
    }
    else if (octave == 9){
        impulseCount = 2;
    }

    //Get sample for octave
    stack->initStack(wave, impulseCount);

    for (int i = 0; i < 1024;i++){
        float phase = (1.0/float(1024))*i;

        //get interpolated wave and apply volume compensation
        outputWave[i] = stack->interp(0, phase) / 2.0;
    }

}

Then... when 10 buffers is ready. You can use them when playing a sound. Using this code you can get index of buffer/octave depending to your frequency

uint_fast8_t getBufferIndex(const float& frequency){

    if (frequency >= 0 && frequency < 40){
        return 0;
    }
    else if (frequency >= 40 && frequency < 80){
        return 1;
    }else if (frequency >= 80 && frequency < 160){
        return 2;
    }else if (frequency >= 160 && frequency < 320){
        return 3;
    }else if (frequency >= 320 && frequency < 640){
        return 4;
    }else if (frequency >= 640 && frequency < 1280){
        return 5;
    }else if (frequency >= 1280 && frequency < 2560){
        return 6;
    }else if (frequency >= 2560 && frequency < 5120){
        return 7;
    }else if (frequency >= 5120 && frequency < 10240){
        return 8;
    }else if (frequency >= 10240){
        return 9;
    }
    return 0;
}

So if I know that my note frequency 440hz. Then for this note I'm getting wave in this way:

float notInterpolatedSound[1024];
float interpolatedSound[1024];

uint_fast8_t octaveIndex = getBufferIndex(440.0);
getSample(octaveIndex, notInterpolatedSound, interpolatedSound);

//tada!

ps. the code above is a low pass filter. I also tried to do sinc interpolation. But sinc worked for me very expensive and not exactly. Although maybe I did it wrong.


问:
Loop Through Column Names with Similar Structure
I have a very large dataset. Of those, a small subset have the same column name with an indexing value that is numeric (unlike the post "How to extract columns with same name but different identifiers in R" where the indexing value is a string). For example

```<code>Q_1_1, Q_1_2, Q_1_3, ...
</code>```

I am looking for a way to either loop through just those columns using the indices or to subset them all at once.

I have tried to use paste() to write their column names but have had no luck. See sample code below

Define Dataframe

```<code>df = data.frame("Q_1_1" = rep(1,5),"Q_1_2" = rep(2,5),"Q_1_3" = rep(3,5))
</code>```

Define the Column Name Using Paste

```<code>cn <- as.symbol(paste("Q_1_",1, sep=""))
cn
df$cn
df$Q_1_1
</code>```

I want df$cn to return the same thing as df$Q_1_1, but df$cn returns NULL.

答:
If you are just trying to subset your data frame by column name, you could use dplyr for subseting all your indexed columns at once and a regex to match all column names with a certain pattern:

```<code>library(dplyr)

df = data.frame("Q_1_1" = rep(1,5),"Q_1_2" = rep(2,5),"Q_1_3" = rep(3,5), "A_1" = rep(4,5))

newdf <- df %>%
  dplyr::select(matches("Q_[0-9]_[0-9]"))
</code>```

the [0-9] in the regex matches any digit between the _. Depending on what variable you're trying to match you might have to change the regular expression.

The problem with your solution was that you only saved the name of your columns but did not actually assign it back to the data frame / to a column.

I hope this helps!

Body:
I have a very large dataset. Of those, a small subset have the same column name with an indexing value that is numeric (unlike the post "How to extract columns with same name but different identifiers in R" where the indexing value is a string). For example

Q_1_1, Q_1_2, Q_1_3, ...

I am looking for a way to either loop through just those columns using the indices or to subset them all at once.

I have tried to use paste() to write their column names but have had no luck. See sample code below

Define Dataframe

df = data.frame("Q_1_1" = rep(1,5),"Q_1_2" = rep(2,5),"Q_1_3" = rep(3,5))

Define the Column Name Using Paste

cn <- as.symbol(paste("Q_1_",1, sep=""))
cn
df$cn
df$Q_1_1

I want df$cn to return the same thing as df$Q_1_1, but df$cn returns NULL.

Body:
If you are just trying to subset your data frame by column name, you could use dplyr for subseting all your indexed columns at once and a regex to match all column names with a certain pattern:

library(dplyr)

df = data.frame("Q_1_1" = rep(1,5),"Q_1_2" = rep(2,5),"Q_1_3" = rep(3,5), "A_1" = rep(4,5))

newdf <- df %>%
  dplyr::select(matches("Q_[0-9]_[0-9]"))

the [0-9] in the regex matches any digit between the _. Depending on what variable you're trying to match you might have to change the regular expression.

The problem with your solution was that you only saved the name of your columns but did not actually assign it back to the data frame / to a column.

I hope this helps!


Title: Adding strings in lists together

Body:
Use zip():

>>> lst = ["A","B","A","A","B"]
>>> [x + y for x, y in zip(lst, lst[1:])]
['AB', 'BA', 'AA', 'AB']


问:
How do I turn off echo in a terminal?
I'm writing a Bourne shell script and have a password input like this:

```<code>echo -n 'Password: '
read password
</code>```

Obviously, I don't want the password being echoed to the terminal, so I want to turn off echo for the duration of the read. I know there's way to do this with stty, but I'll ask the question for the benefit of the community whilst I go read the manpage. ;)

答: read -s password works on my linux box.

Title: How do I turn off echo in a terminal?

Body:
I'm writing a Bourne shell script and have a password input like this:

echo -n 'Password: '
read password

Obviously, I don't want the password being echoed to the terminal, so I want to turn off echo for the duration of the read. I know there's way to do this with stty, but I'll ask the question for the benefit of the community whilst I go read the manpage. ;)

Body: read -s password works on my linux box.


问:
Juint 5 cannot resolve parameter to method
I have a simple test for a web endpoint and I am testing a json schema using restAssured. I keep getting:

```<code>org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String arg0] in method [void People.init(java.lang.String,java.lang.String)].
</code>```

I've read the JUnit 5 manual and I really don't understand this error.
As far as I can see there is nothing wrong with the input strings to the init method. I really don't get this error. Could someone please explain to me what's causing this error and how to get around it in this context?

```<code>import Utils;
import org.junit.jupiter.api.*;
import org.springframework.test.context.TestPropertySource;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;

@DisplayName(value = "Tests endpoint")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestPropertySource(locations = "classpath:resources")

class People {

private String PEOPLE_QUERY = "PeopleQStar.json";
private String host = "http://dev-dev/";
private String endPoint = "people";

Utils utils = new Utils();

@BeforeAll
void init(String host, String endPoint)
{
    utils.setHostAndPath(host, endPoint);
    utils.setCommonSettings();
}

@AfterAll
void cleanUp()
{
    utils.tearDown();
}

@Order(1)
@DisplayName("Check if endpoint is up")
@Test
void initialComCheck()
{
    get().then().statusCode(200);
}

@Order(2)
@Test
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {

    get("?q=*").then().assertThat()
            .body(matchesJsonSchemaInClasspath(PEOPLE_QUERY));
}
}
</code>```

答:
Consider following changes to your code:

```<code>import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
//... other imports and annotations
@ExtendWith(CustomParameterResolver.class) // your custom parameter resolver, see below
class People {

//...

  @BeforeAll
  void init(Server server) // custom stub for storage of your params
  {
    utils.setHostAndPath(server.getHost(), server.getEndpoint());
    utils.setCommonSettings();
  }

  // other methods as it is
}

  static class Server {
    private String host = "http://dev-dev/";
    private String endpoint = "people";

    public String getHost() {
      return host;
    }

    public String getEndpoint() {
      return endpoint;
    }
  }

  static class CustomParameterResolver implements ParameterResolver {

    @Override
    public boolean supportsParameter(ParameterContext parameterContext,
        ExtensionContext extensionContext) throws ParameterResolutionException {
      return (parameterContext.getParameter().getType() == Server.class);
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext,
        ExtensionContext extensionContext) throws ParameterResolutionException {
      return new Server();
    }
  }
</code>```

That should help to solve your issue. Main problem in your case is @BeforeAll method default signature(which is without parameters). That is why you getting an exception( because it's not aware of any custom parameters you trying to pass). To solve this JUnit 5 API allows you to define custom ParameterResolver and subsequently apply it with @ExtendsWith

I've introduced stub object for simplification, but I'm sure that there is an option to solve this with 2 String parameters

Body:
I have a simple test for a web endpoint and I am testing a json schema using restAssured. I keep getting:

org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [java.lang.String arg0] in method [void People.init(java.lang.String,java.lang.String)].

I've read the JUnit 5 manual and I really don't understand this error.
As far as I can see there is nothing wrong with the input strings to the init method. I really don't get this error. Could someone please explain to me what's causing this error and how to get around it in this context?

import Utils;
import org.junit.jupiter.api.*;
import org.springframework.test.context.TestPropertySource;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;

@DisplayName(value = "Tests endpoint")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestPropertySource(locations = "classpath:resources")

class People {

private String PEOPLE_QUERY = "PeopleQStar.json";
private String host = "http://dev-dev/";
private String endPoint = "people";

Utils utils = new Utils();

@BeforeAll
void init(String host, String endPoint)
{
    utils.setHostAndPath(host, endPoint);
    utils.setCommonSettings();
}

@AfterAll
void cleanUp()
{
    utils.tearDown();
}

@Order(1)
@DisplayName("Check if endpoint is up")
@Test
void initialComCheck()
{
    get().then().statusCode(200);
}

@Order(2)
@Test
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {

    get("?q=*").then().assertThat()
            .body(matchesJsonSchemaInClasspath(PEOPLE_QUERY));
}
}

Body:
Consider following changes to your code:

import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
//... other imports and annotations
@ExtendWith(CustomParameterResolver.class) // your custom parameter resolver, see below
class People {

//...

  @BeforeAll
  void init(Server server) // custom stub for storage of your params
  {
    utils.setHostAndPath(server.getHost(), server.getEndpoint());
    utils.setCommonSettings();
  }

  // other methods as it is
}

  static class Server {
    private String host = "http://dev-dev/";
    private String endpoint = "people";

    public String getHost() {
      return host;
    }

    public String getEndpoint() {
      return endpoint;
    }
  }

  static class CustomParameterResolver implements ParameterResolver {

    @Override
    public boolean supportsParameter(ParameterContext parameterContext,
        ExtensionContext extensionContext) throws ParameterResolutionException {
      return (parameterContext.getParameter().getType() == Server.class);
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext,
        ExtensionContext extensionContext) throws ParameterResolutionException {
      return new Server();
    }
  }

That should help to solve your issue. Main problem in your case is @BeforeAll method default signature(which is without parameters). That is why you getting an exception( because it's not aware of any custom parameters you trying to pass). To solve this JUnit 5 API allows you to define custom ParameterResolver and subsequently apply it with @ExtendsWith

I've introduced stub object for simplification, but I'm sure that there is an option to solve this with 2 String parameters


问:
CSS: UL bullets are hidden
I have a basic CSS question.

I have a list, but I can't get the bullets to show ..

Here is a screenshot

The only way i can get them to show is by making the position set to inside, but I want it set to outside as it is.. no matter how much padding or nmargin i add to the left, I can't seem to get the bullets to show.

Here is the CSS applied.. I have applied it to everything.. the UL, the LI, etc

```<code>list-style-image: none;
list-style-position: outside;
list-style-type: square;
</code>```

Here is the HTML

```<code><ul class="static" style="display: block; ">
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/group-medical-plans.aspx"><span class="additional-background"><span class="menu-item-text">Group Medical Plans</span></span></a>
    </li>
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/self-funding-administration.aspx"><span class="additional-background"><span class="menu-item-text">Self-Funding Administration</span></span></a>
    </li>
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/workers-comp.aspx"><span class="additional-background"><span class="menu-item-text">Workers Comp</span></span></a>
    </li>
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/cobra-administrative-services.aspx"><span class="additional-background"><span class="menu-item-text">COBRA Administrative Services</span></span></a>
    </li>
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/medicare-plans.aspx"><span class="additional-background"><span class="menu-item-text">Medicare Plans</span></span></a>
    </li>
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/individual-family-plans.aspx"><span class="additional-background"><span class="menu-item-text">Individual-Family Plans</span></span></a>
    </li>
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/selling-area-maps.aspx"><span class="additional-background"><span class="menu-item-text">Selling Area Maps</span></span></a>
    </li>
    <li class="static">
        <a class="static menu-item" href="/producers/products-services/Pages/provider-networks.aspx"><span class="additional-background"><span class="menu-item-text">Provider Networks</span></span></a>
    </li>
</ul>
</code>```

EDIT

Okay, it still isnt working, here is my LESS

```<code>ul {
    background-color: @color-grey-border;
    width: 100%;
    padding-left: 30px !important;
    list-style-type: square !important;
    list-style-image: none !important;
    list-style-position: outside !important;
    overflow-x: visible !important;
    margin-left: 30px !important;

    li {
        padding-left: 30px !important;
        list-style-type: square !important;
        list-style-image: none !important;
        list-style-position: outside !important;
        overflow-x: visible !important;
        margin-left: 30px !important;

        .menu-item {
            border-bottom-color: #fff !important;
            padding: @base * .5 0 !important;
            width: 100% !important;
        }
    }
}
</code>```

EDIT -

Here are 4 more screenshots

http://see.weareinto.com/BtJh - http://see.weareinto.com/BtRh

http://see.weareinto.com/BsvD - http://see.weareinto.com/Bsjs

答:
ul.a {
      list-style-type: circle;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="a">
   <li>Coffee</li>
   <li>Tea</li>
   <li>Coca Cola</li>
 </ul>

    </code>```

Title: CSS: UL bullets are hidden

Body:
I have a basic CSS question.

I have a list, but I can't get the bullets to show ..

Here is a screenshot

The only way i can get them to show is by making the position set to inside, but I want it set to outside as it is.. no matter how much padding or nmargin i add to the left, I can't seem to get the bullets to show.

Here is the CSS applied.. I have applied it to everything.. the UL, the LI, etc

list-style-image: none;
list-style-position: outside;
list-style-type: square;

Here is the HTML

        Group Medical Plans

        Self-Funding Administration

        Workers Comp

        COBRA Administrative Services

        Medicare Plans

        Individual-Family Plans

        Selling Area Maps

        Provider Networks

EDIT

Okay, it still isnt working, here is my LESS

ul {
    background-color: @color-grey-border;
    width: 100%;
    padding-left: 30px !important;
    list-style-type: square !important;
    list-style-image: none !important;
    list-style-position: outside !important;
    overflow-x: visible !important;
    margin-left: 30px !important;

    li {
        padding-left: 30px !important;
        list-style-type: square !important;
        list-style-image: none !important;
        list-style-position: outside !important;
        overflow-x: visible !important;
        margin-left: 30px !important;

        .menu-item {
            border-bottom-color: #fff !important;
            padding: @base * .5 0 !important;
            width: 100% !important;
        }
    }
}

EDIT -

Here are 4 more screenshots

http://see.weareinto.com/BtJh - http://see.weareinto.com/BtRh

http://see.weareinto.com/BsvD - http://see.weareinto.com/Bsjs

Body:
ul.a {
      list-style-type: circle;
    }

<ul class="a">
   <li>Coffee</li>
   <li>Tea</li>
   <li>Coca Cola</li>
 </ul>


问:
Place text box in appbar in Flutter
I want to implement an Appbar like below where there are a textbox and multiple icons:

The icons can be added in action easily, but how to add the text box and add search action to it. There are many search bar plugins available, but all of them occupy the whole app bar and no way to mention the hints. Can anyone give some idea, it will be a great help for me.

答:
In the title propiery, inside the AppBar, you can pass a widget, which means you can add any component you want, like a TextField. see the example below:

```<code>appBar: AppBar(
        title: TextField(
          decoration: InputDecoration(
            hintText: 'Search',
            prefixIcon: Icon(Icons.search)
          ),
        ),
      ),
</code>```

I suggest to you, to wrap this TextField in a GestureDetector, disable the TextField with the proprierty called enable (set to false), and in the onTap method inside the GestureDetector, you can call a showSearch() method.

To call this showSearch(), you'll need to pass a context and a searchDelegate which is a component that extends a class, check this example:

```<code>class CustomSearchDelegate extends SearchDelegate {
  @override
  List<Widget> buildActions(BuildContext context) {
    // TODO: implement buildActions
    return null;
  }

  @override
  Widget buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    return null;
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return null;
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    return null;
  }
}
</code>```

Source: Implementing search in Flutter

Now, you can do this:

```<code>GestureDetector:
  onTap: () => showSearch(context: context, delegate: CustomSearchScreen()),
  child: ....
</code>```

Title: Place text box in appbar in Flutter

Body:
In the title propiery, inside the AppBar, you can pass a widget, which means you can add any component you want, like a TextField. see the example below:

appBar: AppBar(
        title: TextField(
          decoration: InputDecoration(
            hintText: 'Search',
            prefixIcon: Icon(Icons.search)
          ),
        ),
      ),

I suggest to you, to wrap this TextField in a GestureDetector, disable the TextField with the proprierty called enable (set to false), and in the onTap method inside the GestureDetector, you can call a showSearch() method.

To call this showSearch(), you'll need to pass a context and a searchDelegate which is a component that extends a class, check this example:

class CustomSearchDelegate extends SearchDelegate {
  @override
  List<Widget> buildActions(BuildContext context) {
    // TODO: implement buildActions
    return null;
  }

  @override
  Widget buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    return null;
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return null;
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    return null;
  }
}

Source: Implementing search in Flutter

Now, you can do this:

GestureDetector:
  onTap: () => showSearch(context: context, delegate: CustomSearchScreen()),
  child: ....


问:
How to import xml package to databricks
Any one follow the following links before about xml
https://github.com/databricks/spark-xml

I just keep having problem on importing import com.databricks.spark.xml._

Error

My databricks version

Actually I also want to know how to install the package

```<code>$SPARK_HOME/bin/spark-shell --packages com.databricks:spark-xml_2.12:0.5.0
</code>```

答:
You can install package/library by using import library option available in databricks homepage.

Here choose maven option and give maven coordinates or you have the privilege to search package as well

After this you need to attach the library to your cluster by navigating Clusters>Libraries.
Now you can directly use this library as below without importing it.

```<code>df = spark.read.format('com.databricks.spark.xml').options(rowTag='book').load(' /FileStore/tables/sample.xml')
</code>```

Title: How to import xml package to databricks

Body:
Any one follow the following links before about xml
https://github.com/databricks/spark-xml

I just keep having problem on importing import com.databricks.spark.xml._

Error

My databricks version

Actually I also want to know how to install the package

$SPARK_HOME/bin/spark-shell --packages com.databricks:spark-xml_2.12:0.5.0

Body:
You can install package/library by using import library option available in databricks homepage.

Here choose maven option and give maven coordinates or you have the privilege to search package as well

After this you need to attach the library to your cluster by navigating Clusters>Libraries.
Now you can directly use this library as below without importing it.

df = spark.read.format('com.databricks.spark.xml').options(rowTag='book').load(' /FileStore/tables/sample.xml')


问:
Which Lisp should I learn?

Which Lisp (dialect) should I learn, and why?

The fragmentation between CL and Scheme slows uptake (at least for me!).

So, give me the "true answer", please!

I have tried to read feature comparisons, and they seem to get bogged down in esoterica (that I don't fully understand) like whether the dialect is fully tail-recursive, and the like.  I'm hoping you all (collectively) can make the opaque differences clear.

Things I like

Good library support, good environments, and Unicode support.

Things I dislike

Flamewars. Features that are useful at the beginning, but interfere with long-term learning.

Updates

I've been mostly using MzScheme, which I'm enjoying just fine, once I got readline support going.  I don't run a GUI on Unix, so it seemed to be a fine environment option for me.

I'm also very happy that Clojure has an easy to install .deb package on debian, so it's much easier to play with.  This is a big win.  Despite the hostility of some rather easy-to-anger below, low barrier to entry is a win.  I like being spoonfed.

After reading a lot more of SICP, I do understand the issues around tail recursion much better.

答:
Clojure is an actively developed, modern dialect of Lisp. It's based on the JVM, so all the Java libraries are immediately available, and therefore also has Unicode support.

This is one alternative, not the One True Answer.

OwnerDisplayName: Gregg Lind

Title: Which Lisp should I learn?

LastEditorDisplayName: Gregg Lind

OwnerDisplayName: Greg Hewgill

ContentLicense: CC BY-SA 2.5


问:
Convert HTML string to an image in Python
I want to convert following HTML to PNG image in Python.

    Bold text

```

This HTML is, of course, an example.

I have tried 'pisa' but it converts html to PDF, not to image.
I can convert HTML to PDF and then convert PDF to PNG, but I was wondering if there is any direct solution (i.e HTML to PNG). Any built-in or external module will work nicely.

If this can be done in Graphicsmagick or Imagemagick, then it will be perfect.

答:
webkit2png. The original version is OSX-only, but luckily there is a cross-platform fork:
https://github.com/AdamN/python-webkit2png

Body:
I want to convert following HTML to PNG image in Python.

    Bold text

This HTML is, of course, an example.

I have tried 'pisa' but it converts html to PDF, not to image.
I can convert HTML to PDF and then convert PDF to PNG, but I was wondering if there is any direct solution (i.e HTML to PNG). Any built-in or external module will work nicely.

If this can be done in Graphicsmagick or Imagemagick, then it will be perfect.


问:
ODBC Connection to SYBASE ASE using Python
Could you please help me with a recommended package to connect to Sybase ASE using python 3.6
I heard about sybpydb but I couldn't  find it online.
Could you please recommend the optimum way to build this connection</p>

答:
You can use below code to connect Sybase ASE. I have tried and  connected successfully for Sybase ASE16 from Python 3.7.</p>
```<code>import pyodbc
user = "user_name"
passwd = "Password"
host = "server_name"
db = "database_name"
port = "port"
driver="Adaptive Server Enterprise"
#driver="FreeTDS"
query="select count (*) from emp"

print(datetime.datetime.now())
conn = pyodbc.connect(driver=driver, server=host, database=db,port = prt,uid=user, pwd=passwd)
print(conn)
cursor = conn.cursor()
cursor.execute(query)
row = cursor.fetchall()
print(row)
conn.close()
</code>```

Body:
You can use below code to connect Sybase ASE. I have tried and  connected successfully for Sybase ASE16 from Python 3.7.

import pyodbc
user = "user_name"
passwd = "Password"
host = "server_name"
db = "database_name"
port = "port"
driver="Adaptive Server Enterprise"
#driver="FreeTDS"
query="select count (*) from emp"

print(datetime.datetime.now())
conn = pyodbc.connect(driver=driver, server=host, database=db,port = prt,uid=user, pwd=passwd)
print(conn)
cursor = conn.cursor()
cursor.execute(query)
row = cursor.fetchall()
print(row)
conn.close()


问:
how I can count the total number of nodes List Structures in java
I'm trying to write a function to return the number of nodes in the list in java.

I have a class name waypoint, it define the point and other class named TourElement. TourElement is used to create nodes which are contain a point.

//Waypoint

```<code>public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
</code>```

//Tour Element

```<code>public class TourElement {
 private Waypoint points;
 private TourElement next;
  public void setWaypoint( Waypoint points)
 {
   this.points = points;
 }
  public void setTourElement(TourElement next)
  {
      this.next = next;
  }
 Waypoint getWaypoint()
 {
     return this.points;
 }

 TourElement getNext()
 {
     return this.next;
 }
</code>```

// I have some trouble with getNoOfWaypoints() method, what is wrong with my code?. my method does not pass the test case :

```<code>int getNoOfWaypoints()
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        System.out.println(count);
    }
    return count;
}
</code>```

//test cases are provided by my teacher

```<code>  private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }

    private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }

public void testGetNoOfWaypoints_NotChangingList() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        int unused = elem.getNoOfWaypoints();

        assertArrayEquals(new int[] {0, 0}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {1, 1}, elem.getNext().getWaypoint().toArray());
        assertArrayEquals(new int[] {2, 2}, elem.getNext().getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext().getNext());
    }
</code>```

I dont know what is problem with my out put. and I really want to know how to pass the testcase. Please help me figure it out. thank u so much in advance!!

答:
The condition (current.next != null) will be either always false or always true, since you never modify current inside the loop.

It should be:

```<code>int getNoOfWaypoints()
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        System.out.println(count);
        current = current.next;
    }
    return count;
}
</code>```

Body:
I'm trying to write a function to return the number of nodes in the list in java.

I have a class name waypoint, it define the point and other class named TourElement. TourElement is used to create nodes which are contain a point.

//Waypoint

public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

//Tour Element

public class TourElement {
 private Waypoint points;
 private TourElement next;
  public void setWaypoint( Waypoint points)
 {
   this.points = points;
 }
  public void setTourElement(TourElement next)
  {
      this.next = next;
  }
 Waypoint getWaypoint()
 {
     return this.points;
 }

 TourElement getNext()
 {
     return this.next;
 }

// I have some trouble with getNoOfWaypoints() method, what is wrong with my code?. my method does not pass the test case :

int getNoOfWaypoints()
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        System.out.println(count);
    }
    return count;
}

//test cases are provided by my teacher

  private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }

    private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }

public void testGetNoOfWaypoints_NotChangingList() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        int unused = elem.getNoOfWaypoints();

        assertArrayEquals(new int[] {0, 0}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {1, 1}, elem.getNext().getWaypoint().toArray());
        assertArrayEquals(new int[] {2, 2}, elem.getNext().getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext().getNext());
    }

I dont know what is problem with my out put. and I really want to know how to pass the testcase. Please help me figure it out. thank u so much in advance!!

Body:
The condition (current.next != null) will be either always false or always true, since you never modify current inside the loop.

It should be:

int getNoOfWaypoints()
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        System.out.println(count);
        current = current.next;
    }
    return count;
}


问:
Query must begin with SELECT or WITH error?
I tried to execute the plsql IF statement based on the condition. But it does not work.

```<code>declare
  admin varchar2(4000);
  user1 varchar2(4000);

begin
  Admin := q'~
             SELECT *  INTO ADMIN FROM CI_PREFERENCE ;
             ~';
  User1 :='~
             SELECT * FROM CI_PREFERENCE  WHERE EMAIL_ID = lower(:APP_USER);
           ~';
  if :G_ADMIN = 'A' then
    return admin;
  else
    return user1;
  end if;
end;
</code>```

It Shows:

ORA-20001: Query must begin with SELECT or WITH error

答:
It looks like your code is missing the Q for the alternative quoting syntax.  Replace

```<code>User1 :='~
             SELECT * FROM CI_PREFERENCE  WHERE EMAIL_ID = lower(:APP_USER);
           ~';
</code>```

with

```<code>User1 := q'~
             SELECT * FROM CI_PREFERENCE  WHERE EMAIL_ID = lower(:APP_USER);
           ~';
</code>```

Body:
I tried to execute the plsql IF statement based on the condition. But it does not work.

declare
  admin varchar2(4000);
  user1 varchar2(4000);

begin
  Admin := q'~
             SELECT *  INTO ADMIN FROM CI_PREFERENCE ;
             ~';
  User1 :='~
             SELECT * FROM CI_PREFERENCE  WHERE EMAIL_ID = lower(:APP_USER);
           ~';
  if :G_ADMIN = 'A' then
    return admin;
  else
    return user1;
  end if;
end;

It Shows:

ORA-20001: Query must begin with SELECT or WITH error

Body:
It looks like your code is missing the Q for the alternative quoting syntax.  Replace

User1 :='~
             SELECT * FROM CI_PREFERENCE  WHERE EMAIL_ID = lower(:APP_USER);
           ~';

with

User1 := q'~
             SELECT * FROM CI_PREFERENCE  WHERE EMAIL_ID = lower(:APP_USER);
           ~';


问:
Excel - Split cell with a delimiter and if delimiter not found get complete cell value to another cell
I have an excel file with data where I want a Split cell with a delimiter and if the delimiter is not found then copy that cell value to another cell

e.g.

ABC Ltd.

ABC Ltd. - Ind

PQR Ltd. - USA

LMN Corp.

Output - delimiter "-"

ColumnA       ColumnB

ABC Ltd.   ABC Ltd.

ABC Ltd.    Ind

PQR Ltd.     USA

LMN Corp.    LMN Corp.

However, I'm using below formula but not getting what I want.

=TRIM(LEFT(B2,FIND("-",B2)-1))

=TRIM(REPLACE(B2,1,FIND("-",B2),""))

答:
Another solution:

Formula:

=IF(LEN(A1)-LEN(SUBSTITUTE(A1,"-",""))>0,RIGHT(A1,LEN(A1)-FIND("-",A1,1)-1),A1)


问:
On the click of the image it is not removing in jQuery
Selecting the multiple image from the input tag after that I am previewing the selected image but when I click on that image it should delete from the input tag it does not select that picture any more. But in my case that picture is removing only in preview not in input. And save it into database

Here is the code

    <?php
       include_once 'Functions.php';
       $connect=new Connection();
       $link=$connect->Connect();

       print_r($_FILES['fil']['name']);
    ?>

        <form name="update"  enctype='multipart/form-data' method="POST">
          <input type="file" name="fil[]" multiple id="gallery-photo-add" class="a1">

          <input type="submit" name="btnupdate" value="Update" />
        </form>

```

答:
Here is HTML Code :

```<code><div class="container">
     <form id="fileupload" action="#" method="POST" enctype="multipart/form-data">
         <div class="row files" id="files1">
             <h2>Files 1</h2>
             <span class="btn btn-default btn-file">
                 Browse  <input type="file" name="files1" multiple />
             </span><br/>
             <ul class="fileList"></ul>
         </div>
         <div class="row">
             <button type="x" id="uploadBtn" class="btn primary start">Start upload</button>
         </div>
         <div class="row">
            <div class="span16">
                <table class="zebra-striped"><tbody class="files"></tbody></table>
            </div>
        </div>
    </form>
</div>
</code>```

Here is CSS Code :

```<code>.btn-file {
    position: relative;
    overflow: hidden;
}

.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}
</code>```

Here is jQuery Code :

```<code>$.fn.fileUploader = function (filesToUpload, sectionIdentifier) {
    var fileIdCounter = 0;

    this.closest(".files").change(function (evt) {
        var output = [];

        for (var i = 0; i < evt.target.files.length; i++) {
            fileIdCounter++;
            var file = evt.target.files[i];
            var fileId = sectionIdentifier + fileIdCounter;

            filesToUpload.push({
                id: fileId,
                file: file
            });

            var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + fileId + "\">Remove</a>";

            output.push("<li><strong>", escape(file.name), "</strong> - ", file.size, " bytes.     ", removeLink, "</li> ");
        };

        $(this).children(".fileList")
            .append(output.join(""));

        //reset the input to null - nice little chrome bug!
        evt.target.value = null;
    });

    $(this).on("click", ".removeFile", function (e) {
        e.preventDefault();

        var fileId = $(this).parent().children("a").data("fileid");

        // loop through the files array and check if the name of that file matches FileName
        // and get the index of the match
        for (var i = 0; i < filesToUpload.length; ++i) {
            if (filesToUpload[i].id === fileId)
                filesToUpload.splice(i, 1);
        }

        $(this).parent().remove();
    });

    this.clear = function () {
        for (var i = 0; i < filesToUpload.length; ++i) {
            if (filesToUpload[i].id.indexOf(sectionIdentifier) >= 0)
                filesToUpload.splice(i, 1);
        }

        $(this).children(".fileList").empty();
    }

    return this;
};

(function () {
    var filesToUpload = [];

    var files1Uploader = $("#files1").fileUploader(filesToUpload, "files1");

    $("#uploadBtn").click(function (e) {
        e.preventDefault();

        var formData = new FormData();

        for (var i = 0, len = filesToUpload.length; i < len; i++) {
            formData.append("files", filesToUpload[i].file);
        }

        $.ajax({
            url: "",
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (data) {
                alert("DONE");

                files1Uploader.clear();

            },
            error: function (data) {
                alert("ERROR - " + data.responseText);
            }
        });
    });
});

Try above code. Hope this will help
</code>```

Body:
Here is HTML Code :

<div class="container">
     <form id="fileupload" action="#" method="POST" enctype="multipart/form-data">
         <div class="row files" id="files1">
             <h2>Files 1</h2>
             <span class="btn btn-default btn-file">
                 Browse  <input type="file" name="files1" multiple />
             </span><br/>
             <ul class="fileList"></ul>
         </div>
         <div class="row">
             <button type="x" id="uploadBtn" class="btn primary start">Start upload</button>
         </div>
         <div class="row">
            <div class="span16">
                <table class="zebra-striped"><tbody class="files"></tbody></table>
            </div>
        </div>
    </form>
</div>

Here is CSS Code :

.btn-file {
    position: relative;
    overflow: hidden;
}

.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}

Here is jQuery Code :

$.fn.fileUploader = function (filesToUpload, sectionIdentifier) {
    var fileIdCounter = 0;

    this.closest(".files").change(function (evt) {
        var output = [];

        for (var i = 0; i < evt.target.files.length; i++) {
            fileIdCounter++;
            var file = evt.target.files[i];
            var fileId = sectionIdentifier + fileIdCounter;

            filesToUpload.push({
                id: fileId,
                file: file
            });

            var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + fileId + "\">Remove</a>";

            output.push("<li><strong>", escape(file.name), "</strong> - ", file.size, " bytes. &nbsp; &nbsp; ", removeLink, "</li> ");
        };

        $(this).children(".fileList")
            .append(output.join(""));

        //reset the input to null - nice little chrome bug!
        evt.target.value = null;
    });

    $(this).on("click", ".removeFile", function (e) {
        e.preventDefault();

        var fileId = $(this).parent().children("a").data("fileid");

        // loop through the files array and check if the name of that file matches FileName
        // and get the index of the match
        for (var i = 0; i < filesToUpload.length; ++i) {
            if (filesToUpload[i].id === fileId)
                filesToUpload.splice(i, 1);
        }

        $(this).parent().remove();
    });

    this.clear = function () {
        for (var i = 0; i < filesToUpload.length; ++i) {
            if (filesToUpload[i].id.indexOf(sectionIdentifier) >= 0)
                filesToUpload.splice(i, 1);
        }

        $(this).children(".fileList").empty();
    }

    return this;
};

(function () {
    var filesToUpload = [];

    var files1Uploader = $("#files1").fileUploader(filesToUpload, "files1");

    $("#uploadBtn").click(function (e) {
        e.preventDefault();

        var formData = new FormData();

        for (var i = 0, len = filesToUpload.length; i < len; i++) {
            formData.append("files", filesToUpload[i].file);
        }

        $.ajax({
            url: "",
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (data) {
                alert("DONE");

                files1Uploader.clear();

            },
            error: function (data) {
                alert("ERROR - " + data.responseText);
            }
        });
    });
});

Try above code. Hope this will help


问:
How to load datagrid binding information with a button?
I want a DataGrid to be filled or loaded when the user click the button "load"

This is my Grid:

```<code>  <Grid>
     <DataGrid Name="test" ItemsSource="{Binding Items}"  AutoGenerateColumns="True" Margin="0,0,286.4,190.6" />
     <Button Content="Load" Command="{Binding cmdReset_Click}" Margin="450,0,165.4,702.6"/>
  </Grid>
</code>```

and this is my ViewModel

```<code> namespace test.ViewModel
 {

    class ViewModel : INotifyPropertyChanged
    {

        public DelegateCommand cmdReset_Click { get; }

        public ViewModel()
        {
            cmdReset_Click = new DelegateCommand(Reset_Click);
            Items = GetData();
        }

        public class Log
        {
            public int ID { get; set; }
            public string PDO { get; set; }
            public string LOCATION { get; set; }
            public string HOSTAME { get; set; }
            public int SEVERITY { get; set; }
            public DateTime TIMESTAMP { get; set; }
            public string MESSAGE { get; set; }

        }

        public List<Log> Items { get; set; } = new List<Log>();

        private List<Log> GetData()
        {
                List<Log> logs = new List<Log>();
                    logs.Add(new Log()
                    {
                        PDO = "TEST",
                        ID = "TEST",
                        //LOCATION = "TEST",
                        HOSTAME = "TEST",
                        SEVERITY = "TEST",
                        TIMESTAMP = "TEST",
                        MESSAGE = "TEST",
                    });
                }
            return logs;
        }
        private void Reset_Click()
        {
            Items = GetData();
        }
    }
}
</code>```

Right now I am getting the list info after running the program. What I need to get this info AFTER the Button is clicked

答:
```<code>public DelegateCommand cmdReset_Click { get; }

public ViewModel()
{
    cmdReset_Click = new DelegateCommand(Reset_Click);
    Items = GetData();
}

public class Log
{
    public int ID { get; set; }
    public string PDO { get; set; }
    public string LOCATION { get; set; }
    public string HOSTAME { get; set; }
    public int SEVERITY { get; set; }
    public DateTime TIMESTAMP { get; set; }
    public string MESSAGE { get; set; }

}

public List<Log> Items {get; set;} = new List<Logs>();

private GetData()
{
   List<Log> logs = new List<Log>();
        logs.Add(new Log()
            {
                PDO = "test",
                ID = "number",
                HOSTAME = "test",
                SEVERITY = "number",
                TIMESTAMP = "nate",
                MESSAGE ="number",
            });
        }
        return logs;

}

private void Reset_Click()
{
    Items = GetData();
}
</code>```

Body:
I want a DataGrid to be filled or loaded when the user click the button "load"

This is my Grid:

  <Grid>
     <DataGrid Name="test" ItemsSource="{Binding Items}"  AutoGenerateColumns="True" Margin="0,0,286.4,190.6" />
     <Button Content="Load" Command="{Binding cmdReset_Click}" Margin="450,0,165.4,702.6"/>
  </Grid>

and this is my ViewModel

 namespace test.ViewModel
 {

    class ViewModel : INotifyPropertyChanged
    {

        public DelegateCommand cmdReset_Click { get; }

        public ViewModel()
        {
            cmdReset_Click = new DelegateCommand(Reset_Click);
            Items = GetData();
        }

        public class Log
        {
            public int ID { get; set; }
            public string PDO { get; set; }
            public string LOCATION { get; set; }
            public string HOSTAME { get; set; }
            public int SEVERITY { get; set; }
            public DateTime TIMESTAMP { get; set; }
            public string MESSAGE { get; set; }

        }

        public List<Log> Items { get; set; } = new List<Log>();

        private List<Log> GetData()
        {
                List<Log> logs = new List<Log>();
                    logs.Add(new Log()
                    {
                        PDO = "TEST",
                        ID = "TEST",
                        //LOCATION = "TEST",
                        HOSTAME = "TEST",
                        SEVERITY = "TEST",
                        TIMESTAMP = "TEST",
                        MESSAGE = "TEST",
                    });
                }
            return logs;
        }
        private void Reset_Click()
        {
            Items = GetData();
        }
    }
}

Right now I am getting the list info after running the program. What I need to get this info AFTER the Button is clicked


问:
In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?
I'm using Eclipse for Java development. All my sources compile fine and the resulting application compiles fine. However, I keep getting an "red-x" error notification in the Package Explorer.

All my sources in this source directory (too long for the snapshot) compile fine, none of the show the "red-x" error icon.

Any suggestions on how to fix the problem would be highly appreciated.

答:
I encountered this problem today and found this link. I followed as mentioned by Patrick Schaefer above and opened the Update Maven project Dialog. Click on my working project and selected the checkbox "Force Update of Snapshots/Releases" and 'Ok'. All the red cross vanished.
I hope this helps anybody in a similar situation.</p>

OwnerDisplayName: Alfred B. Thordarson


问:
eliminate rows from bed file
I produced a bed file like this

```<code>Simple_repeat   KQ420259.1  45090   45150   (TTAT)n .   +
Simple_repeat   KQ420259.1  46815   46864   (TG)n   .   +
Simple_repeat   KQ420259.1  47062   47104   (GT)n   .   +
SINE/tRNA-Deu   KQ420259.1  49227   49290   AmnSINE2    .   +
Simple_repeat   KQ416943.1  112522  112609  (ATAC)n .   +
Simple_repeat   KQ416943.1  113250  113283  (ACA)n  .   +
Simple_repeat   KQ416943.1  113283  113358  (ACT)n  .   +
Simple_repeat   KQ416943.1  117308  117357  (AC)n   .   +
Simple_repeat   KQ416943.1  117357  117435  (ACAC)n .   +
Simple_repeat   KQ416944.1  117964  118025  (TATG)n .   +
DNA/TcMar       KQ416944.1  121083  121651  HSMAR1  .   +
Low_complexity  KQ416944.1  124929  124970  A-rich  .   +
</code>```

and I would to eliminate all the rows containing KQ416943.1 . I don't know if exists a way to do it preserving the order. I'll appreciate your help. Thank you

答:
try this:</p>

```<code>grep -v "KQ416943.1" yourfile.txt > output.txt
</code>```

Title: eliminate rows from bed file

Body:
I produced a bed file like this

Simple_repeat   KQ420259.1  45090   45150   (TTAT)n .   +
Simple_repeat   KQ420259.1  46815   46864   (TG)n   .   +
Simple_repeat   KQ420259.1  47062   47104   (GT)n   .   +
SINE/tRNA-Deu   KQ420259.1  49227   49290   AmnSINE2    .   +
Simple_repeat   KQ416943.1  112522  112609  (ATAC)n .   +
Simple_repeat   KQ416943.1  113250  113283  (ACA)n  .   +
Simple_repeat   KQ416943.1  113283  113358  (ACT)n  .   +
Simple_repeat   KQ416943.1  117308  117357  (AC)n   .   +
Simple_repeat   KQ416943.1  117357  117435  (ACAC)n .   +
Simple_repeat   KQ416944.1  117964  118025  (TATG)n .   +
DNA/TcMar       KQ416944.1  121083  121651  HSMAR1  .   +
Low_complexity  KQ416944.1  124929  124970  A-rich  .   +

and I would to eliminate all the rows containing KQ416943.1 . I don't know if exists a way to do it preserving the order. I'll appreciate your help. Thank you

Body:
try this:

grep -v "KQ416943.1" yourfile.txt > output.txt