问:
Can't connect to postgres in docker
I am trying to connect Postgres DB to a Rails app using docker-compose as following

docker-compose.yml

```<code>version: '3.8'
services:
  db:
    image: postgres:12.1
    volumes:
      - pg-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: "password"
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/rails6
    ports:
      - "3000:3000"
    depends_on:
      - db
volumes:
  pg-data:

</code>```

Dockerfile

```<code>FROM ruby:2.5

RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client yarn

RUN mkdir /rails6
WORKDIR /rails6

RUN gem install bundler:2

COPY package.json yarn.lock ./
RUN yarn install --check-files

COPY Gemfile* ./
RUN bundle install

COPY . /rails6

EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]
</code>```

But when I run docker-compose run web rake db:create I get following error.

```<code>ActiveRecord::NoDatabaseError: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:50:in `rescue in postgresql_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:33:in `postgresql_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:887:in `new_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:931:in `checkout_new_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:910:in `try_to_checkout_new_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:871:in `acquire_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:593:in `checkout'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:437:in `connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:1119:in `retrieve_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_handling.rb:221:in `retrieve_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_handling.rb:189:in `connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/postgresql_database_tasks.rb:12:in `connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/postgresql_database_tasks.rb:21:in `create'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:126:in `create'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:185:in `block in create_current'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:479:in `block (2 levels) in each_current_configuration'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:476:in `each'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:476:in `block in each_current_configuration'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:475:in `each'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:475:in `each_current_configuration'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:184:in `create_current'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/railties/databases.rake:39:in `block (2 levels) in <top (required)>'
</code>```

Am I missing something?

答:
dI had a very similar issue and then realized that I had not added my db host to the config/database.yml

```<code>default: &default
    adapter: postgresql
    encoding: unicode
    host: db
    # For details on connection pooling, see Rails configuration guide
    # https://guides.rubyonrails.org/configuring.html#database-pooling
    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
    username: <%= ENV['MYAPP_DATABASE_USERNAME'] %>
    password: <%= ENV['MYAPP_DATABASE_PASSWORD'] %>
</code>```

The value for "host" is db because it is the service name in the docker-compose.yml

```<code>...
services:
  db: # <--- right here
    image: postgres:12.1
    volumes:
      - pg-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: "password"
...
</code>```

Title: Can't connect to postgres in docker

Body:
I am trying to connect Postgres DB to a Rails app using docker-compose as following

docker-compose.yml

version: '3.8'
services:
  db:
    image: postgres:12.1
    volumes:
      - pg-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: "password"
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/rails6
    ports:
      - "3000:3000"
    depends_on:
      - db
volumes:
  pg-data:

Dockerfile

FROM ruby:2.5

RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client yarn

RUN mkdir /rails6
WORKDIR /rails6

RUN gem install bundler:2

COPY package.json yarn.lock ./
RUN yarn install --check-files

COPY Gemfile* ./
RUN bundle install

COPY . /rails6

EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

But when I run docker-compose run web rake db:create I get following error.

ActiveRecord::NoDatabaseError: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:50:in `rescue in postgresql_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:33:in `postgresql_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:887:in `new_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:931:in `checkout_new_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:910:in `try_to_checkout_new_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:871:in `acquire_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:593:in `checkout'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:437:in `connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:1119:in `retrieve_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_handling.rb:221:in `retrieve_connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/connection_handling.rb:189:in `connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/postgresql_database_tasks.rb:12:in `connection'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/postgresql_database_tasks.rb:21:in `create'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:126:in `create'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:185:in `block in create_current'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:479:in `block (2 levels) in each_current_configuration'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:476:in `each'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:476:in `block in each_current_configuration'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:475:in `each'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:475:in `each_current_configuration'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/tasks/database_tasks.rb:184:in `create_current'
/usr/local/bundle/gems/activerecord-6.0.3/lib/active_record/railties/databases.rake:39:in `block (2 levels) in <top (required)>'

Am I missing something?

Body:
dI had a very similar issue and then realized that I had not added my db host to the config/database.yml

default: &default
    adapter: postgresql
    encoding: unicode
    host: db
    # For details on connection pooling, see Rails configuration guide
    # https://guides.rubyonrails.org/configuring.html#database-pooling
    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
    username: <%= ENV['MYAPP_DATABASE_USERNAME'] %>
    password: <%= ENV['MYAPP_DATABASE_PASSWORD'] %>

The value for "host" is db because it is the service name in the docker-compose.yml

...
services:
  db: # <--- right here
    image: postgres:12.1
    volumes:
      - pg-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: "password"
...


来源: stackexchange

问:
How to implement Authentication and Authorization in WCF Restful Service
I am trying to implement security for the WCF rest service which will be exposed over the net for consuming. Here are the requirements

Authorization for Service and Specific API's

The service should authorize the partner and check if the partner has the access to the API which is called and i have multiple partners calling these restful APIs.

How do I authorize each of these partners for APIs in a centralized way?

Authentication for the User

I need to perform Authentication for users in order to perform the Add,Delete operations.

How do I authenticate the users for specific APIs in centralized way.

答:
Look at Azure Storage REST api security documentation here to get a fair idea about how MS has designed security around their API.

Most of the REST API i have seen use a API token based approach where these tokens are passed along each request to identify the caller.
Also look at this thread

ContentLicense: CC BY-SA 3.0


问:
How to compare values of corresponding cells in multiple named column ranges and change interior color in another corresponding cell
I want to write a code in Excel VBA that compares the values in corresponding cells in 3 named ranges (say, "Peter", "Paul" & "John"), and if all three values are >= 3, then the interior color of the corresponding cell in a fourth named range say, "James", is changed to Green. I wrote the code using offset but the code doesn't work properly if I insert new columns in-between "Peter", "Paul" and "John". Please can you help me write a code that uses named ranges, to avoid an error when new columns are added?
Thank you.</p>

```<code>If Cell.Value >= 3 Then
            If Cell.Offset(0, 1).Value >= 3 Then
                If Cell.Offset(0, 2).Value >= 3 Then
                    If Cell.Offset(0, 3).Value >= 3 Then
                        Cell.Offset(0, 4).Interior.ColorIndex = 4
                    End If
                End If
            End If
        End If
    Next Cell
</code>```

答:
This works

```<code>Dim xCel As Range, rPtr As Long
Dim xSht As Worksheet

Set xSht = ActiveSheet
rPtr = 0
For Each xCel In xSht.Range("Peter").Cells
   rPtr = rPtr + 1
   If xCel.Value >= 3 Then
      If xSht.Range("Paul").Cells(rPtr, 1).Value >= 3 Then
         If xSht.Range("John").Cells(rPtr, 1).Value >= 3 Then
            xSht.Range("James").Cells(rPtr, 1).Interior.ColorIndex = 34
         End If
      End If
   End If
Next xCel
</code>```

This solves the problem you mentioned, but it still presumes all ranges are the same length and single column

ContentLicense: CC BY-SA 4.0

Body:
I want to write a code in Excel VBA that compares the values in corresponding cells in 3 named ranges (say, "Peter", "Paul" & "John"), and if all three values are >= 3, then the interior color of the corresponding cell in a fourth named range say, "James", is changed to Green. I wrote the code using offset but the code doesn't work properly if I insert new columns in-between "Peter", "Paul" and "John". Please can you help me write a code that uses named ranges, to avoid an error when new columns are added?
Thank you.

If Cell.Value >= 3 Then
            If Cell.Offset(0, 1).Value >= 3 Then
                If Cell.Offset(0, 2).Value >= 3 Then
                    If Cell.Offset(0, 3).Value >= 3 Then
                        Cell.Offset(0, 4).Interior.ColorIndex = 4
                    End If
                End If
            End If
        End If
    Next Cell

Body:
This works

Dim xCel As Range, rPtr As Long
Dim xSht As Worksheet

Set xSht = ActiveSheet
rPtr = 0
For Each xCel In xSht.Range("Peter").Cells
   rPtr = rPtr + 1
   If xCel.Value >= 3 Then
      If xSht.Range("Paul").Cells(rPtr, 1).Value >= 3 Then
         If xSht.Range("John").Cells(rPtr, 1).Value >= 3 Then
            xSht.Range("James").Cells(rPtr, 1).Interior.ColorIndex = 34
         End If
      End If
   End If
Next xCel

This solves the problem you mentioned, but it still presumes all ranges are the same length and single column


问:
Combining Collections in Directus
I've setup a Directus CMS project with 3 collections as follows:

Actors

Movies

TV Shows

I'd like to associate Movies and TV Shows with Actors in a multi-select ordered list. I've tried looking at the one-to-many relationship and some others and can't seem to figure out how to build this. Ideally I would like it to look roughly like:

Editing Actor record John Smith

Multi-select array (or possibly some other interface) that includes all TV Shows and Movies

All TV Shows and Movies are shown by in multi-select by field "Title" of which both collections have

User can check boxes for individual TV Shows or Movies and order them in the multi-select as they'd like.

Do I need an intermediary junction collection? Am I missing something obvious here?

From initial impressions Directus looks to be an awesome CMS!

答:
you were on the right track, but the relationship type you are looking for is a "many-to-many" (or M2M). This is because a movie can have many actors, and actors can be in many movies.

You can see the Directus documentation for this relationship setup here:

https://docs.directus.io/guides/relationships.html#many-to-many

You will add two junction tables, something like actor_movies and actor_tv_shows, each with a schema like this:

id — The primary key of the relationship

actor_id — The foreign key that holds the actor id

movie_id — The foreign key that holds the movie id

Therefore, each record in these tables link an actor to a Movie or TV Show.

Title: Combining Collections in Directus


问:
Angular Material: Prevent Slider from Overlapping with Menu
I am just getting started with Angular Material and experiencing the problem that the slider component overlaps with my menu.

How can I make sure the slider is displayed below the menu - is there some non-overlapping flag I can set to accomplish this?

May html code looks like this:

```<code><button mat-button [matMenuTriggerFor]="aboveMenu">Above</button>
<mat-menu #aboveMenu="matMenu" yPosition="above">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<button mat-button [matMenuTriggerFor]="belowMenu">Below</button>
<mat-menu #belowMenu="matMenu" [overlapTrigger]="false" yPosition="below">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<button mat-button [matMenuTriggerFor]="beforeMenu">Before</button>
<mat-menu #beforeMenu="matMenu" xPosition="before">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<button mat-button [matMenuTriggerFor]="afterMenu">After</button>
<mat-menu #afterMenu="matMenu" xPosition="after">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<mat-slider min="1" max="100" step="1" value="1"></mat-slider>
</code>```

Thank you very much for your help!

Best regards, Sam

答:
You could try to use flex-wrap in your styles this way:

```<code>display: flex; flex-wrap: wrap;
</code>```

Here is a simple snippet adding it as an inline style but I do suggest that you add them in a separate file and reference the divs with classes.

I hope It helps you!

    <button mat-button [matMenuTriggerFor]="aboveMenu">Above</button>
    <button mat-button [matMenuTriggerFor]="belowMenu">Below</button>
    <button mat-button [matMenuTriggerFor]="beforeMenu">Before</button>
    <button mat-button [matMenuTriggerFor]="afterMenu">After</button>

    <input type="range" min="1" max="100" value="50">

```

More information about flex and flex-wrap:

https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap

Body:
I am just getting started with Angular Material and experiencing the problem that the slider component overlaps with my menu.

How can I make sure the slider is displayed below the menu - is there some non-overlapping flag I can set to accomplish this?

May html code looks like this:

<button mat-button [matMenuTriggerFor]="aboveMenu">Above</button>
<mat-menu #aboveMenu="matMenu" yPosition="above">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<button mat-button [matMenuTriggerFor]="belowMenu">Below</button>
<mat-menu #belowMenu="matMenu" [overlapTrigger]="false" yPosition="below">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<button mat-button [matMenuTriggerFor]="beforeMenu">Before</button>
<mat-menu #beforeMenu="matMenu" xPosition="before">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<button mat-button [matMenuTriggerFor]="afterMenu">After</button>
<mat-menu #afterMenu="matMenu" xPosition="after">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

<mat-slider min="1" max="100" step="1" value="1"></mat-slider>

Thank you very much for your help!

Best regards, Sam

Body:
You could try to use flex-wrap in your styles this way:

display: flex; flex-wrap: wrap;

Here is a simple snippet adding it as an inline style but I do suggest that you add them in a separate file and reference the divs with classes.

I hope It helps you!

<div style="display: flex; flex-wrap: wrap;">
  <div style="width: 100%;">
    <button mat-button [matMenuTriggerFor]="aboveMenu">Above</button>
    <button mat-button [matMenuTriggerFor]="belowMenu">Below</button>
    <button mat-button [matMenuTriggerFor]="beforeMenu">Before</button>
    <button mat-button [matMenuTriggerFor]="afterMenu">After</button>
  </div>
  <div style="width: 100%;">
    <input type="range" min="1" max="100" value="50">
  </div>
</div>

More information about flex and flex-wrap:

https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap


问:
What's the better-practice way to rotate a string by one character in Python?
I'm doing a codecademy task and was wondering which of the following set of code is considered best practice:

The task is to create a function, given a string username , that shifts all letters one to the right.
For example the username : AbeSimp would become pAbeSim, this becomes the password and is stored in the string password.

Here is my code:

```<code>def password_generator(username):
    password = ""
    password = username[-1] + username[:-1]
    return password
</code>```

The Solution code is :

```<code>def password_generator(username):
    password = ""
    for i in range(0, len(user_name)):
       password += user_name[i-1]
    return password
</code>```

Any explanation is appreciated - thanks!

答:
I get what you are asking i think I just have the code that you need.

```<code>from random import shuffle

def password_generator(username):
    username = list(username)
    shuffle(username)
    return ''.join(username)
print(password_generator('THIS-IS-USERNAME'))
</code>```

the output I got is:

```<code>SNE--SSHIATIRMEU

Process finished with exit code 0
</code>```

It changed THIS-IS-USERNAME to SNE--SSHIATIRMEU

hope this helps you

Body:
I'm doing a codecademy task and was wondering which of the following set of code is considered best practice:

The task is to create a function, given a string username , that shifts all letters one to the right.
For example the username : AbeSimp would become pAbeSim, this becomes the password and is stored in the string password.

Here is my code:

def password_generator(username):
    password = ""
    password = username[-1] + username[:-1]
    return password

The Solution code is :

def password_generator(username):
    password = ""
    for i in range(0, len(user_name)):
       password += user_name[i-1]
    return password

Any explanation is appreciated - thanks!

Body:
I get what you are asking i think I just have the code that you need.

from random import shuffle

def password_generator(username):
    username = list(username)
    shuffle(username)
    return ''.join(username)
print(password_generator('THIS-IS-USERNAME'))

the output I got is:

SNE--SSHIATIRMEU

Process finished with exit code 0

It changed THIS-IS-USERNAME to SNE--SSHIATIRMEU

hope this helps you


问:
Why are annotations in higher-order functions unsupported?
This is the error I get when using custom annotation in a higher-order function:

Is there any way to use annotations in higher-order functions? If not, what would be an alternative solution (apart from using enums)?

This is how my custom annotation looks like:

```<code>companion object {
   private const val PERMISSION_DENIED = 1
   private const val PROVIDER_DISABLED = 2
   private const val SUCCESS = 3

   @IntDef(PERMISSION_DENIED, PROVIDER_DISABLED, SUCCESS)
   @Retention(AnnotationRetention.SOURCE)
   annotation class PreconditionResult
}
</code>```

答:
Workaround

There's a workaround which involves functional interfaces (notice the fun interface below).

Note: Unfortunately, functional interfaces that are defined in kotlin code are only available since the upcoming 1.4 release. You can test it now with 1.4-M1.

fun interface FulFilled {
    fun execute(@PreconditionResult fulFilled: Int): Unit
}

private fun checkPrecondition(context: Context, fulFilled: Fulfilled) {
}
```

<pre class="lang-kotlin prettyprint-override"><code>checkPrecondition(context) { fulFilled -> println("Got $fulFilled")}
</code>```

Possible solution

I'm not sure if it would achieve what you need to, but it's also possible to drop the argument name from your type definition:

private fun checkPrecondition(context: String, callback: (@PreconditionResult Int) -> Unit) {
```

<p>You'll need to change the target of your annotation to a type:</p>

<pre class="lang-kotlin prettyprint-override"><code>    @Retention(AnnotationRetention.SOURCE)
    @Target(AnnotationTarget.TYPE)
    annotation class PreconditionResult
</code>```

Body:
This is the error I get when using custom annotation in a higher-order function:

Is there any way to use annotations in higher-order functions? If not, what would be an alternative solution (apart from using enums)?

This is how my custom annotation looks like:

companion object {
   private const val PERMISSION_DENIED = 1
   private const val PROVIDER_DISABLED = 2
   private const val SUCCESS = 3

   @IntDef(PERMISSION_DENIED, PROVIDER_DISABLED, SUCCESS)
   @Retention(AnnotationRetention.SOURCE)
   annotation class PreconditionResult
}

Body:
Workaround

There's a workaround which involves functional interfaces (notice the fun interface below).

Note: Unfortunately, functional interfaces that are defined in kotlin code are only available since the upcoming 1.4 release. You can test it now with 1.4-M1.

fun interface FulFilled {
    fun execute(@PreconditionResult fulFilled: Int): Unit
}

private fun checkPrecondition(context: Context, fulFilled: Fulfilled) {
}

checkPrecondition(context) { fulFilled -> println("Got $fulFilled")}

Possible solution

I'm not sure if it would achieve what you need to, but it's also possible to drop the argument name from your type definition:

private fun checkPrecondition(context: String, callback: (@PreconditionResult Int) -> Unit) {

You'll need to change the target of your annotation to a type:

    @Retention(AnnotationRetention.SOURCE)
    @Target(AnnotationTarget.TYPE)
    annotation class PreconditionResult


问:
C++ invalid function type casting
I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:

```<code>void SomeFunction() { }

class A {
  public:
    typedef std::function<void(void)> AFunction;
    static void AMethod(AFunction f) { f(); }
};

class B {
  public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); }
};
</code>```

Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!

答:
The easiest way is to make it static and so there is no this object, but if you need it (the this object), you can use lambdas:

```<code>class B {
public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() {
        std::function<void(void)> el = [&](){this->B1Method();};
        A::AMethod(el);
    }
};
</code>```

Title: C++ invalid function type casting

Body:
I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:

void SomeFunction() { }

class A {
  public:
    typedef std::function<void(void)> AFunction;
    static void AMethod(AFunction f) { f(); }
};

class B {
  public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); }
};

Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!

Body:
The easiest way is to make it static and so there is no this object, but if you need it (the this object), you can use lambdas:

class B {
public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() {
        std::function<void(void)> el = [&](){this->B1Method();};
        A::AMethod(el);
    }
};


问:
Document enum class values using Doxygen without enabling EXTRACT_ALL
I wasn't able to show documentation for values of enum classes without setting EXTRACT_ALL. The comments for preserve, truncate and append aren't there. The enum itself is documented. If I enable EXTRACT_ALL I get a list.

My code is:

```<code>namespace grimoire
{

...

/// @brief Behaviour of function open_for_write for already existing files.
/// @see open_for_write()
enum class OpenMode
{
    preserve = std::ofstream::out,   /// Already existing file aren't opened.
    truncate = std::ofstream::trunc, /// Discard existing contents.
    append   = std::ofstream::app    /// Append to existing contents.
};

...

}
</code>```

I'm using CMake to run Doxygen with:

```<code>#set(DOXYGEN_EXTRACT_ALL YES)
doxygen_add_docs(
    docs
    "${CMAKE_CURRENT_SOURCE_DIR}/include/grimoire"
    "${CMAKE_CURRENT_SOURCE_DIR}/src")
</code>```

Edit:

It doesn't even work with a classical enum and without explicit values. It looks like it has to do with my settings.

Solved:

I had to add a comment to the enclosing namespace. Doxygen extracted the enum itself and other stuff like functions and classes inside that namespace but not the enum entries.

答:
Doxygen does not always pickup an enum, this can be overcome by means of using the \file command.
Furthermore you document the enum values after its definition, this means you should not use /// but ///<

So the limited example would looks like:

```<code>/// \file

/// @brief Behavior of function open_for_write for already existing files.
/// @see open_for_write()
enum class OpenMode
{
    preserve = std::ofstream::out,   ///< Already existing file aren't opened.
    truncate = std::ofstream::trunc, ///< Discard existing contents.
    append   = std::ofstream::app    ///< Append to existing contents.
};
</code>```

Edit:
Based on the answer from OP, the given solution was not complete as the original problem was embedded in an namespace. To be able to show the enum in that case it is not sufficient to add the \file but it is also necessary the document the namespace. So a more complete example:

```<code>/// \file

/// The namespace documentation
namespace NS
{
  /// @brief Behavior of function open_for_write for already existing files.
  /// @see open_for_write()
  enum class OpenMode
  {
      preserve = std::ofstream::out,   ///< Already existing file aren't opened.
      truncate = std::ofstream::trunc, ///< Discard existing contents.
      append   = std::ofstream::app    ///< Append to existing contents.
  };
};
</code>```

Body:
I wasn't able to show documentation for values of enum classes without setting EXTRACT_ALL. The comments for preserve, truncate and append aren't there. The enum itself is documented. If I enable EXTRACT_ALL I get a list.

My code is:

namespace grimoire
{

...

/// @brief Behaviour of function open_for_write for already existing files.
/// @see open_for_write()
enum class OpenMode
{
    preserve = std::ofstream::out,   /// Already existing file aren't opened.
    truncate = std::ofstream::trunc, /// Discard existing contents.
    append   = std::ofstream::app    /// Append to existing contents.
};

...

}

I'm using CMake to run Doxygen with:

#set(DOXYGEN_EXTRACT_ALL YES)
doxygen_add_docs(
    docs
    "${CMAKE_CURRENT_SOURCE_DIR}/include/grimoire"
    "${CMAKE_CURRENT_SOURCE_DIR}/src")

Edit:

It doesn't even work with a classical enum and without explicit values. It looks like it has to do with my settings.

Solved:

I had to add a comment to the enclosing namespace. Doxygen extracted the enum itself and other stuff like functions and classes inside that namespace but not the enum entries.

Body:
Doxygen does not always pickup an enum, this can be overcome by means of using the \file command.
Furthermore you document the enum values after its definition, this means you should not use /// but ///<

So the limited example would looks like:

/// \file

/// @brief Behavior of function open_for_write for already existing files.
/// @see open_for_write()
enum class OpenMode
{
    preserve = std::ofstream::out,   ///< Already existing file aren't opened.
    truncate = std::ofstream::trunc, ///< Discard existing contents.
    append   = std::ofstream::app    ///< Append to existing contents.
};

Edit:
Based on the answer from OP, the given solution was not complete as the original problem was embedded in an namespace. To be able to show the enum in that case it is not sufficient to add the \file but it is also necessary the document the namespace. So a more complete example:

/// \file

/// The namespace documentation
namespace NS
{
  /// @brief Behavior of function open_for_write for already existing files.
  /// @see open_for_write()
  enum class OpenMode
  {
      preserve = std::ofstream::out,   ///< Already existing file aren't opened.
      truncate = std::ofstream::trunc, ///< Discard existing contents.
      append   = std::ofstream::app    ///< Append to existing contents.
  };
};


问:
Problem: horizontal scrollbar appears when I add an image to a column using bootstrap 4 grid system
I am super new to coding and web development and I am not sure how to solve my issue:

I am trying to add an image to the column that I created using bootstrap 4 grid system. However, as soon as I add the image, a horizontal scrollbar appears on the screen and I'm not sure why.

Here is a screenshot of what happens: https://gyazo.com/c383ecb9180181349363e0636047867c

```<code><div class="container">
<div class="row">
    <div class="col-6">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit.
    </div>
    <div class="col-6">
        <img src="https://images.unsplash.com/photo-1585600270404-543d0eac85e1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3042&q=80">
    </div>
</div>
</code>```

My second issue is that although the horizontal scrollbar gets removed when I use the "img-fluid" class for my image, however when I change the container to container-fluid so that it covers the entire width of the screen and then use the class "px-0" for my container to remove the extra padding, I once again get horizontal scrollbars appearing on my screen.

```<code><div class="container-fluid px-0">
<div class="row">
    <div class="col-6">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit.
    </div>
    <div class="col-6">
        <img class="img-fluid" src="https://images.unsplash.com/photo-1585600270404-543d0eac85e1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3042&q=80">
    </div>
</div>
</code>```

答:
Either you can set overflow : hidden to the second column container if you want your page to not scroll, or you can set height and width of the image to avoid scrolling and to make the whole image visible.

```<code> <div class="col-6">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit.
 </div>
 <div class="col-6" style="overflow: hidden">
   <img height="100px" width="100px" src="https://images.unsplash.com/photo-1585600270404-543d0eac85e1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3042&q=80" />
 </div>
</code>```

Learn more about overflow property at https://www.w3schools.com/css/css_overflow.asp and image attributes at https://www.w3schools.com/html/html_images.asp

To solve your second problem, just add the margin:0 to the

Body:
I am super new to coding and web development and I am not sure how to solve my issue:

I am trying to add an image to the column that I created using bootstrap 4 grid system. However, as soon as I add the image, a horizontal scrollbar appears on the screen and I'm not sure why.

Here is a screenshot of what happens: https://gyazo.com/c383ecb9180181349363e0636047867c

        Lorem ipsum dolor sit amet, consectetur adipisicing elit.

My second issue is that although the horizontal scrollbar gets removed when I use the "img-fluid" class for my image, however when I change the container to container-fluid so that it covers the entire width of the screen and then use the class "px-0" for my container to remove the extra padding, I once again get horizontal scrollbars appearing on my screen.

        Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Body:
Either you can set overflow : hidden to the second column container if you want your page to not scroll, or you can set height and width of the image to avoid scrolling and to make the whole image visible.

 <div class="col-6">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit.
 </div>
 <div class="col-6" style="overflow: hidden">
   <img height="100px" width="100px" src="https://images.unsplash.com/photo-1585600270404-543d0eac85e1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3042&q=80" />
 </div>

Learn more about overflow property at https://www.w3schools.com/css/css_overflow.asp and image attributes at https://www.w3schools.com/html/html_images.asp

To solve your second problem, just add the margin:0 to the <div class="row">


问:
Updating and retrieving data with async/await issue
I have an async method that calls an api to write the data and retrieve it. However the get method always returns the previous result. I get the updated data if I introduce a delay between the method calls.

```<code>public async Task<ServerResult<IEnumerable<int>>> UpdateData(int data)
{
    var updatedResult = await apiClient.UpdateAsync(data);
    //If the updatedResult.StatusCode != 200 return appropriate message, otherwise get the updated data and return it.
    var getResult = await apiClient.GetAllAsync();
    return getResult
}
</code>```

My understanding of the async/await is that each awaited method is asynchronously sequentially executed which means the GetAllAsync runs only after UpdateAsync completes (i.e. Task.Run(() => UpdateAsync(data)).ContinueWith(t => return GetAllAsync())). How can I make sure GetAllAsync runs only after UpdateAsync without resorting to delays or have the client make a separate get call?

答:
What happens inside the api client? It seems to me that the code inside it, does not await on the call. You need to await all the included asynchronous operations.

The line:

```<code>var updatedResult = await apiClient.UpdateAsync(data);
</code>```

Will return the execution to the original code execution path only when it's completely done.

If inside the UpdateAsync code there is a line without the await keyword, then it would be fire and forget.

Maybe this happens on the server side. Maybe the server side queues the request and does not save on the spot. Check all these and update the question if there is still an issue.

Body:
I have an async method that calls an api to write the data and retrieve it. However the get method always returns the previous result. I get the updated data if I introduce a delay between the method calls.

public async Task<ServerResult<IEnumerable<int>>> UpdateData(int data)
{
    var updatedResult = await apiClient.UpdateAsync(data);
    //If the updatedResult.StatusCode != 200 return appropriate message, otherwise get the updated data and return it.
    var getResult = await apiClient.GetAllAsync();
    return getResult
}

My understanding of the async/await is that each awaited method is asynchronously sequentially executed which means the GetAllAsync runs only after UpdateAsync completes (i.e. Task.Run(() => UpdateAsync(data)).ContinueWith(t => return GetAllAsync())). How can I make sure GetAllAsync runs only after UpdateAsync without resorting to delays or have the client make a separate get call?

Body:
What happens inside the api client? It seems to me that the code inside it, does not await on the call. You need to await all the included asynchronous operations.

The line:

var updatedResult = await apiClient.UpdateAsync(data);

Will return the execution to the original code execution path only when it's completely done.

If inside the UpdateAsync code there is a line without the await keyword, then it would be fire and forget.

Maybe this happens on the server side. Maybe the server side queues the request and does not save on the spot. Check all these and update the question if there is still an issue.


问:
rails db:migrate fails due to duplicate table
I got some problems about my database.

I've generated a model Comment once, but this Comment migration not what I wanted, so I drop it, and succeeded to drop. Now I try to re-generate it, and keep running rails db:migrate, but something went wrong.

It shows :

"PG::DuplicateTable: ERROR:  relation "comments" already exists",

I've checked my schema.rb, did not have this comment table.

My database using "psql", and Rails version is "Rails 6.0.2.2". I've been searched related problem, but seems like not what I faced.

答:
according your description, I have also encountered this, this is what I tried and solved:

```<code>psql

rails db

\d:

drop table tablename;
</code>```

hope to solve your problem

Body:
according your description, I have also encountered this, this is what I tried and solved:

psql

rails db

\d:

drop table tablename;

hope to solve your problem


问:
Handle a clock in multiplayer game
I'm working on a quick game where players have a block (a clock like).

So I store in a database when the game starts and when every move is made so I can easily compute the time it took for each player to make moves.

I know I can't trust client to say when the opponent timer is over so, currently, I check every second the time remaining for each ongoing game.

I know it's not sustainable and I want to know how I can check server-side that ongoing games are not over because one player no longer have time.

So, this is how I do currently :

I store in database when the game start (server time)

I store each move in database and when it was make (server time)

Clients are updated via sockets after a move with the time remaining

Clients update the clock (only for display).

Every second, I calculate server-side :

The time between the first move and the start of the game, the time between the 2nd move and the 3rd move, etc. to know how many times it took for the first player to play every moves

I do the same for the 2nd player with the time between 1st move and 2nd move, 3rd and 4th, etc...

When the time elapsed for one player is more than the time allowed, the server send (via sockets) the end of the game.

I want to know how I can do not compute every second because I want the server to update the result when no one is connected to the game.

Thank you.

答:
Not only you must not trust client-side clock, but you also don't need to.

As said by @Roko-c-buljan, build your timer/clock logic server side. On every move, both players are "synced" and will locally start their timer. If you have a streamed connection to the server, then the server can notify both clients that the timer is over and give the other player its move.

This way, if there is a cracked client, the server will simply ignore the move while it's already the other client's turn.

Title: Handle a clock in multiplayer game


问:
Is it possible to get all arguments of a SCSS mixin, akin to JavaScript?
In JavasSript, we can get arguments like this:

function ab(a,b){
    console.log(arguments[0],arguments[1]);
}
ab(1,2);
// 1 2
```

<p>I want to know if there is any way to get SCSS <code>@mixin</code> variables as a list just like how we can do it in JavaScript?</p>

```@mixin ab($a:1,$b:2){

@debug arguments; // stuff like this

}
```

答:
You are looking for something like this?</p>

```<code>@mixin grid($flex) {
    @if $flex {
        @include flex;
    } @else {
        display: block;
    }
}

@include grid(true);
</code>```

Body:
In JavasSript, we can get arguments like this:

function ab(a,b){
    console.log(arguments[0],arguments[1]);
}
ab(1,2);
// 1 2

I want to know if there is any way to get SCSS @mixin variables as a list just like how we can do it in JavaScript?

@mixin ab($a:1,$b:2){

@debug arguments; // stuff like this

}

Body:
You are looking for something like this?

@mixin grid($flex) {
    @if $flex {
        @include flex;
    } @else {
        display: block;
    }
}

@include grid(true);


问:
ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file
When I use the command:

```<code>C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android
</code>```

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?

答:
Give:

```<code>keytool -list -keystore ~/.android/debug.keystore
</code>```

Also in your line there is a space in keystore. Please check it.

Body:
When I use the command:

C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?

Body:
Give:

keytool -list -keystore ~/.android/debug.keystore

Also in your line there is a space in keystore. Please check it.


问:
AttributeError: type object 'FooEnv' has no attribute 'reset'
I am new in Python and I faced with a problem in my code. I try to build my custom environment for a Deep Q-Network program. The name of my environment is "FooEnv".But when I run the main code, I faced with this error in line FooEnv.reset()

type object 'FooEnv' has no attribute 'reset'

This is my main code, That I call "FooEnv" here:

```<code>import json
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import sgd
from FooEnv import FooEnv
class ExperienceReplay(object):
  def __init__(self, max_memory=100, discount=.9):
    self.max_memory = max_memory
    self.memory = list()
    self.discount = discount

  def remember(self, states, game_over):
    # memory[i] = [[state_t, action_t, reward_t, state_t+1], game_over?]
    self.memory.append([states, game_over])
    if len(self.memory) > self.max_memory:
        del self.memory[0]

  def get_batch(self, model, batch_size=10):
    len_memory = len(self.memory)
    num_actions = model.output_shape[-1]
    # env_dim = self.memory[0][0][0].shape[1]
    env_dim = self.memory[0][0][0].shape[1]
    inputs = np.zeros((min(len_memory, batch_size), env_dim))
    targets = np.zeros((inputs.shape[0], num_actions))
    for i, idx in enumerate(np.random.randint(0, len_memory,
                                              size=inputs.shape[0])):
        state_t, action_t, reward_t, state_tp1 = self.memory[idx][0]
        game_over = self.memory[idx][1]

        inputs[i:i+1] = state_t
        # There should be no target values for actions not taken.
        # Thou shalt not correct actions not taken #deep
        targets[i] = model.predict(state_t)[0]
        Q_sa = np.max(model.predict(state_tp1)[0])
        if game_over:  # if game_over is True
            targets[i, action_t] = reward_t
        else:
            # reward_t + gamma * max_a' Q(s', a')
            targets[i, action_t] = reward_t + self.discount * Q_sa
    return inputs, targets
if __name__ == "__main__":
    # parameters
    epsilon = .1
    num_actions = 2
    epoch = 1000
    max_memory = 500
    hidden_size = 100
    batch_size = 50
    input_size = 2
    f_c=[2.4*10**9]
    eta_Los=[1]
    eta_NLos=[2]
    x_threshold = [5]
    model = Sequential()
    model.add(Dense(hidden_size, input_shape=(2, ), activation='relu'))
    model.add(Dense(hidden_size, activation='relu'))
    model.add(Dense(num_actions))
    model.compile(sgd(lr=.2), "mse")
    # Define environment/game
    env = FooEnv(f_c, eta_Los, eta_NLos)
    # Initialize experience replay object
    exp_replay = ExperienceReplay(max_memory=max_memory)
    FooEnv.reset()
</code>```

And this is my FooEnv code:

```<code>import numpy as  np
import math
class FooEnv(object):
  def __init__(self, f_c, eta_Los, eta_NLos):
    self.f_c = f_c
    self.eta_Los = eta_Los
    self.eta_NLos = eta_NLos
    self.num_actions = 2
  def reset(self):
    state=self.state
    E_Consumtion, Average_Delay_UAV, Average_DeLay_FAP = state
    E_Consumtion=0
    Average_Delay_UAV=0
    Average_DeLay_FAP=0
    self.state = np.append(E_Consumtion,Average_Delay_UAV,Average_DeLay_FAP)
    self.steps_beyond_done = None
    return np.array(self.state)
</code>```

I would greatly appreciated it if you could help me with this.

答: FooEnv is a class and env is an object of that class.  You want to reset the object, not the class.</p>

Body:
I am new in Python and I faced with a problem in my code. I try to build my custom environment for a Deep Q-Network program. The name of my environment is "FooEnv".But when I run the main code, I faced with this error in line FooEnv.reset()

type object 'FooEnv' has no attribute 'reset'

This is my main code, That I call "FooEnv" here:

import json
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import sgd
from FooEnv import FooEnv
class ExperienceReplay(object):
  def __init__(self, max_memory=100, discount=.9):
    self.max_memory = max_memory
    self.memory = list()
    self.discount = discount

  def remember(self, states, game_over):
    # memory[i] = [[state_t, action_t, reward_t, state_t+1], game_over?]
    self.memory.append([states, game_over])
    if len(self.memory) > self.max_memory:
        del self.memory[0]

  def get_batch(self, model, batch_size=10):
    len_memory = len(self.memory)
    num_actions = model.output_shape[-1]
    # env_dim = self.memory[0][0][0].shape[1]
    env_dim = self.memory[0][0][0].shape[1]
    inputs = np.zeros((min(len_memory, batch_size), env_dim))
    targets = np.zeros((inputs.shape[0], num_actions))
    for i, idx in enumerate(np.random.randint(0, len_memory,
                                              size=inputs.shape[0])):
        state_t, action_t, reward_t, state_tp1 = self.memory[idx][0]
        game_over = self.memory[idx][1]

        inputs[i:i+1] = state_t
        # There should be no target values for actions not taken.
        # Thou shalt not correct actions not taken #deep
        targets[i] = model.predict(state_t)[0]
        Q_sa = np.max(model.predict(state_tp1)[0])
        if game_over:  # if game_over is True
            targets[i, action_t] = reward_t
        else:
            # reward_t + gamma * max_a' Q(s', a')
            targets[i, action_t] = reward_t + self.discount * Q_sa
    return inputs, targets
if __name__ == "__main__":
    # parameters
    epsilon = .1
    num_actions = 2
    epoch = 1000
    max_memory = 500
    hidden_size = 100
    batch_size = 50
    input_size = 2
    f_c=[2.4*10**9]
    eta_Los=[1]
    eta_NLos=[2]
    x_threshold = [5]
    model = Sequential()
    model.add(Dense(hidden_size, input_shape=(2, ), activation='relu'))
    model.add(Dense(hidden_size, activation='relu'))
    model.add(Dense(num_actions))
    model.compile(sgd(lr=.2), "mse")
    # Define environment/game
    env = FooEnv(f_c, eta_Los, eta_NLos)
    # Initialize experience replay object
    exp_replay = ExperienceReplay(max_memory=max_memory)
    FooEnv.reset()

And this is my FooEnv code:

import numpy as  np
import math
class FooEnv(object):
  def __init__(self, f_c, eta_Los, eta_NLos):
    self.f_c = f_c
    self.eta_Los = eta_Los
    self.eta_NLos = eta_NLos
    self.num_actions = 2
  def reset(self):
    state=self.state
    E_Consumtion, Average_Delay_UAV, Average_DeLay_FAP = state
    E_Consumtion=0
    Average_Delay_UAV=0
    Average_DeLay_FAP=0
    self.state = np.append(E_Consumtion,Average_Delay_UAV,Average_DeLay_FAP)
    self.steps_beyond_done = None
    return np.array(self.state)

I would greatly appreciated it if you could help me with this.


问:
SQL PHP query multiple tables data
Noob alert here!
I'm trying to display some data on my php page from two tables but I don't know how to do it

```<code>db_bandas TABLE
banda_id | banda_name
    1    |  Rolling Beatles
    2    |  Linkin Bizkit

db_albuns TABLE
album_id | album_name | banda_id | album_ano
    1    |    Music   |    1     |  2000
    2    |   another  |    2     |  2014
    3    |  good one  |    1     |  2004
</code>```

What I want to show on the page is like :

```<code> 1  | Music    | Rolling Beatles | 2000
 2  | another  | Linkin Bizkit   | 2014
 3  | good one | Rolling Beatles | 2004
</code>```

I've tried the query like this

```<code>$sql = "SELECT db_albuns.album_nome AS album_nome, db_albuns.album_id AS album_id, db_albuns.album_ano AS album.ano, db_banda.banda_nome AS banda_nome FROM db_albuns,db_banda";

</code>```

答:
You can use Join to do it</p>

```<code>$sql = "SELECT db_albuns.album_nome,
db_albuns.album_id, db_albuns.album_ano,
db_banda.banda_nome
FROM db_albuns join db_banda
on  db_albuns.banda_id = db_banda.banda_id";
</code>```

Title: SQL PHP query multiple tables data

Body:
Noob alert here!
I'm trying to display some data on my php page from two tables but I don't know how to do it

db_bandas TABLE
banda_id | banda_name
    1    |  Rolling Beatles
    2    |  Linkin Bizkit

db_albuns TABLE
album_id | album_name | banda_id | album_ano
    1    |    Music   |    1     |  2000
    2    |   another  |    2     |  2014
    3    |  good one  |    1     |  2004

What I want to show on the page is like :

 1  | Music    | Rolling Beatles | 2000
 2  | another  | Linkin Bizkit   | 2014
 3  | good one | Rolling Beatles | 2004

I've tried the query like this

$sql = "SELECT db_albuns.album_nome AS album_nome, db_albuns.album_id AS album_id, db_albuns.album_ano AS album.ano, db_banda.banda_nome AS banda_nome FROM db_albuns,db_banda";

Body:
You can use Join to do it

$sql = "SELECT db_albuns.album_nome,
db_albuns.album_id, db_albuns.album_ano,
db_banda.banda_nome
FROM db_albuns join db_banda
on  db_albuns.banda_id = db_banda.banda_id";


问:
Dash Python by plot.ly callbacks, and Attributes and Properties in web applications
In Dash, by Plotly helping section in Callbacks https://dash.plotly.com/interactive-graphing it is stated that:

Dash components are described declaratively by a set of attributes. All of these attributes can be updated by callback functions

Using the definition of What is the difference between properties and attributes in HTML?:

Attributes: Attributes are defined by HTML. They initialize DOM properties and then they are done.

Properties: Properties are defined by the DOM (Document Object Model). After DOM has been fully initialized these properties can change.

It is logic and reasonable to say that Dash Callbacks retrieve a specific DOM object by its id, and 'read' its property (not the HTML attribute that initialized it). Example: it is possible to have an Input Callback listening to a graph figure 'hoverData' change property.

If this assumption is true:

So basically dash Callbacks operate after the DOM has been initialized, also again they operate on DOM properties not HTML attributes.

So again if true case this could be clearly stated in documentation which would improve to avoid developers confusing this sometimes not very obvious terms.

答: Have found an answer, dash callbacks work with DOM Properties which is more accurate than saying HTML attributes.</p>


问:
2D dynamic array of structures does not work as intended
So, I have a 2D array of structures. I enter the structure element by element, yet the program prints some random data, instead of the entered information. For example, ptr[0][0].Flat_ID should be 101, yet it prints  8 and as for the other elements, it's total gibberish. Any ideas why it does that?
Structure:

```<code>typedef struct
{
   int Flat_ID;
   int count_Rooms;
   int count_Adults;
   int count_Children;
   char Family_Surname[20];
   char Date[15];
   float rent;
}S_Apartament;
</code>```

And the program inside main():

```<code>int floors=1, flats_per_floor=2;
S_Apartament Flats;
S_Apartament **ptr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floors);//Declaring an array of pointers. It has to be dynamic, as per the assignment
        if(ptr == NULL)
        {
            printf("Memory fail");
            free(ptr);
            exit(8);

        }
        for (int i = 0; i <  floors; i++)
        {
            ptr[i] = (S_Apartament *)malloc(sizeof(S_Apartament)*flats_per_floor);//Each pointer from the first array now is an array of its own, with elements being structures
            if(ptr[i] == NULL)
            {
                printf("Memory fail");
                free(ptr);
                exit(8);

            }
        }
        for(int i = 0; i <  floors; i++)
        {
            for(int j = 0; j < flats_per_floor; j++)
            {
                printf("ID:\n");
                scanf("%d", &ptr[i][j].Flat_ID);
                printf("\n");
                printf("Rooms:\n");
                scanf("%d", &ptr[i][j].count_Rooms);
                printf("\n");
                printf("Adults:\n");
                scanf("%d", &ptr[i][j].count_Adults);
                printf("\n");
                printf("Children:\n");
                scanf("%d", &ptr[i][j].count_Children);
                printf("\n");
                printf("Name:\n");
                scanf("%s", ptr[i][j].Family_Surname);
                printf("\n");
                printf("Date of entry: \n");
                scanf("%s", ptr[i][j].Date);
                printf("\n");
                printf("Rent:\n");
                scanf("%f", &ptr[i][j].rent);
                printf("\n");
                ptr[i][j]=Flats;
            }
        }
for(int i=0; i< floors; i++)//Prints read information
        {
            for(int j=0; j< flats_per_floor; j++)
            {
                printf("ID: %d\n", ptr[i][j].Flat_ID);
                printf("Rooms: %d\n", ptr[i][j].count_Rooms);
                printf("Adults: %d\n", ptr[i][j].count_Adults);
                printf("Children: %d\n", ptr[i][j].count_Children);
                printf("Name: %s\n", ptr[i][j].Family_Surname);
                printf("Date of entry: %s\n", ptr[i][j].Date);
                printf("Rent: %0.2f\n", ptr[i][j].rent);

            }
            printf("-----------------");
            printf("\n");
        }
free(ptr);
</code>```

Here is a sample output:
Output

答: You do not check the result of scanf. It was just unsuccessful and the member was not assigned the value.

Body:
So, I have a 2D array of structures. I enter the structure element by element, yet the program prints some random data, instead of the entered information. For example, ptr[0][0].Flat_ID should be 101, yet it prints  8 and as for the other elements, it's total gibberish. Any ideas why it does that?
Structure:

typedef struct
{
   int Flat_ID;
   int count_Rooms;
   int count_Adults;
   int count_Children;
   char Family_Surname[20];
   char Date[15];
   float rent;
}S_Apartament;

And the program inside main():

int floors=1, flats_per_floor=2;
S_Apartament Flats;
S_Apartament **ptr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floors);//Declaring an array of pointers. It has to be dynamic, as per the assignment
        if(ptr == NULL)
        {
            printf("Memory fail");
            free(ptr);
            exit(8);

        }
        for (int i = 0; i <  floors; i++)
        {
            ptr[i] = (S_Apartament *)malloc(sizeof(S_Apartament)*flats_per_floor);//Each pointer from the first array now is an array of its own, with elements being structures
            if(ptr[i] == NULL)
            {
                printf("Memory fail");
                free(ptr);
                exit(8);

            }
        }
        for(int i = 0; i <  floors; i++)
        {
            for(int j = 0; j < flats_per_floor; j++)
            {
                printf("ID:\n");
                scanf("%d", &ptr[i][j].Flat_ID);
                printf("\n");
                printf("Rooms:\n");
                scanf("%d", &ptr[i][j].count_Rooms);
                printf("\n");
                printf("Adults:\n");
                scanf("%d", &ptr[i][j].count_Adults);
                printf("\n");
                printf("Children:\n");
                scanf("%d", &ptr[i][j].count_Children);
                printf("\n");
                printf("Name:\n");
                scanf("%s", ptr[i][j].Family_Surname);
                printf("\n");
                printf("Date of entry: \n");
                scanf("%s", ptr[i][j].Date);
                printf("\n");
                printf("Rent:\n");
                scanf("%f", &ptr[i][j].rent);
                printf("\n");
                ptr[i][j]=Flats;
            }
        }
for(int i=0; i< floors; i++)//Prints read information
        {
            for(int j=0; j< flats_per_floor; j++)
            {
                printf("ID: %d\n", ptr[i][j].Flat_ID);
                printf("Rooms: %d\n", ptr[i][j].count_Rooms);
                printf("Adults: %d\n", ptr[i][j].count_Adults);
                printf("Children: %d\n", ptr[i][j].count_Children);
                printf("Name: %s\n", ptr[i][j].Family_Surname);
                printf("Date of entry: %s\n", ptr[i][j].Date);
                printf("Rent: %0.2f\n", ptr[i][j].rent);

            }
            printf("-----------------");
            printf("\n");
        }
free(ptr);

Here is a sample output:
Output


问:
Naming nested dictionaries in python
A logically nested structure, like a student address has a flat number, a floor number (at least).

Now a student has a name which we can easily map from a monolithic address, using, eg, this convention:

address_to_student

or equivalently:

student_by_address

```<code>student_by_address = {
    "flat 5 floor 4": "sam",
    "flat 2 floor 4": "max",
    "flat 9 floor 1": "tim",
}
</code>```

For efficiency (say if "jen" moves in with "max") I might also want to store addresses as a dictionary indexed by floor.

Based on the overwhelming enthusiasm for the _by_ format in the second linked answer, I've gone with that but for nested dictionaries I'm finding it unintuitive.

```<code>students_by_flat_by_floor = {
    {
        "floor 4": {
            "flat 5": ["sam"],
            "flat 2": ["max", "jen"]
        },
        "floor 1": {
            "flat 9": ["tim"]
        },
    }
}
</code>```

Does anyone else find that unreadable? It would be a class if this wasn't python. Being python I'm keen to avoid that boiler plate. Which is why I'm asking the question, is the alternative more readable or pythonic?

```<code>floor_to_flat_to_students = ...
</code>```

My concerns about the (by) former are:

+It begins by naming the leaf node which is probably what it is required by its clients.

+It was by far the higher rated answer of the 2 questions I referenced above for non-nested cases.

-It feels like the first part needs brackets to read properly (students_by_flat)_by_floor

And the (to) latter:

+It matches the order of keys used to index it.

+In the non-nested case, linked above and specifically for python it is the best answer.

-The strengths of the other.

答:
In the absence of official guidelines I refer myself to Guido's PEP 8, "A Foolish Consistency is the Hobgoblin of Little Minds"

For un-nested dictionaries, I prefer, student_by_address, the to I felt to be more suggestive of a verb as might befit a function identifier.

For nested dictionaries it has to be, floor_to_flat_to_students.

Would be receptive to arguments against, but I think this captures the spirit of python for anyone contemplating these issues.

Title: Naming nested dictionaries in python

Body:
A logically nested structure, like a student address has a flat number, a floor number (at least).

Now a student has a name which we can easily map from a monolithic address, using, eg, this convention:

address_to_student

or equivalently:

student_by_address

student_by_address = {
    "flat 5 floor 4": "sam",
    "flat 2 floor 4": "max",
    "flat 9 floor 1": "tim",
}

For efficiency (say if "jen" moves in with "max") I might also want to store addresses as a dictionary indexed by floor.

Based on the overwhelming enthusiasm for the _by_ format in the second linked answer, I've gone with that but for nested dictionaries I'm finding it unintuitive.

students_by_flat_by_floor = {
    {
        "floor 4": {
            "flat 5": ["sam"],
            "flat 2": ["max", "jen"]
        },
        "floor 1": {
            "flat 9": ["tim"]
        },
    }
}

Does anyone else find that unreadable? It would be a class if this wasn't python. Being python I'm keen to avoid that boiler plate. Which is why I'm asking the question, is the alternative more readable or pythonic?

floor_to_flat_to_students = ...

My concerns about the (by) former are:

+It begins by naming the leaf node which is probably what it is required by its clients.

+It was by far the higher rated answer of the 2 questions I referenced above for non-nested cases.

-It feels like the first part needs brackets to read properly (students_by_flat)_by_floor

And the (to) latter:

+It matches the order of keys used to index it.

+In the non-nested case, linked above and specifically for python it is the best answer.

-The strengths of the other.


问:
Show the Progress Percentage of an operation running inside a FOR-loop in Label.Text
I have the following C# Code:

```<code>for (int i = 0; i < dgItems.Rows.Count - 1; i++)
                    {
                        SqlCommand cmd = new SqlCommand(@"INSERT INTO TBL_OrderQty (SipStyle,SipColor,SipSize,[SipQty(-%5)],SipQty,[SipQty(+%5)]) VALUES('" + dgItems.Rows[i].Cells[0].Value + "','" + dgItems.Rows[i].Cells[1].Value + "','" + dgItems.Rows[i].Cells[2].Value + "','" + dgItems.Rows[i].Cells[3].Value + "','" + dgItems.Rows[i].Cells[4].Value + "','" + dgItems.Rows[i].Cells[5].Value + "')", con);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        progressBar1.Value = i;
                        LB_ProgText.Text = "Progress :%" + (i / 100) * dgItems.Rows.Count;
                        LB_ProgText.Invalidate();
                        LB_ProgText.Update();
                    }
</code>```

I'm trying to show the progress percentage of the whole operation, the progress bar is working just fine but I couldn't get the percentage right; can you please help me.

答:
Use (i / (float)dgItems.Rows.Count) * 100.
You can also format it with this: Math.Round((i / (float)dgItems.Rows.Count) * 100, n) where n is the number of decimals

Body:
I have the following C# Code:

for (int i = 0; i < dgItems.Rows.Count - 1; i++)
                    {
                        SqlCommand cmd = new SqlCommand(@"INSERT INTO TBL_OrderQty (SipStyle,SipColor,SipSize,[SipQty(-%5)],SipQty,[SipQty(+%5)]) VALUES('" + dgItems.Rows[i].Cells[0].Value + "','" + dgItems.Rows[i].Cells[1].Value + "','" + dgItems.Rows[i].Cells[2].Value + "','" + dgItems.Rows[i].Cells[3].Value + "','" + dgItems.Rows[i].Cells[4].Value + "','" + dgItems.Rows[i].Cells[5].Value + "')", con);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        progressBar1.Value = i;
                        LB_ProgText.Text = "Progress :%" + (i / 100) * dgItems.Rows.Count;
                        LB_ProgText.Invalidate();
                        LB_ProgText.Update();
                    }

I'm trying to show the progress percentage of the whole operation, the progress bar is working just fine but I couldn't get the percentage right; can you please help me.


问:
Which standard does VS2005, VS2008 follow?
Do they both follow the C++03 released in 2003?</p>

答:
They both target C++03, yes. But they also both have areas where they fail to comply with the standard. (So does GCC, btw, before any fanboys on either side starts frothing at the mouth).

But keep in mind that C++03 is basically a very small bugfix release, nailing down a few "common sense" things that sensible compilers would have done anyway (for example, in C++98, it was, strictly speaking, possible to have vectors that aren't contiguously allocated. C++03 prohibits that, but every sane compiler vendor would have used contiguous vectors anyway, because that's what vectors are intended for)

GCC doesn't even have a C++03 standard setting. You tell it to target C++98 (with std=c++98), and it actually targets C++03 instead. I'm not aware of a compiler which actually makes a distinction between the two, because the changes are so few, and so obvious.


答:
Use a lambda:

```<code>A::AMethod([this]{B1Method();});
</code>```

It doesn't matter in this case, but if you wanted to store AFunction f and use it after the call to AMethod, you'd have to ensure that the B instance (the address of which is saved in the lambda) says alive as long as you use the function.

C++17 allows you to capture *this instead, which will copy the entire B instance into lambda, but normally it's not what you want.

You could do something similar with std::bind (see the other answer), but lambdas are more flexible.

Title: C++ invalid function type casting

Body:
I've read several topics about that kind of problem - but can't find a simple and good solution. Here is the code:

void SomeFunction() { }

class A {
  public:
    typedef std::function<void(void)> AFunction;
    static void AMethod(AFunction f) { f(); }
};

class B {
  public:
    void B1Method() { }
    void BCorrectCall() { A::AMethod(SomeFunction); }
    void BIncorrectCall() { A::AMethod(B1Method); }
};

Problem is here void BIncorrectCall() { A::AMethod(B1Method); }, where I receive error about invalid casting. What is the simplest way to achieve that kind of behaviour? Thanks a lot for any advice!

Body:
Use a lambda:

A::AMethod([this]{B1Method();});

It doesn't matter in this case, but if you wanted to store AFunction f and use it after the call to AMethod, you'd have to ensure that the B instance (the address of which is saved in the lambda) says alive as long as you use the function.

C++17 allows you to capture *this instead, which will copy the entire B instance into lambda, but normally it's not what you want.

You could do something similar with std::bind (see the other answer), but lambdas are more flexible.


问:
Is/can a resource (js-file) from a CDN be shared across websites/browser tabs?
I'm not finding a definite answer on the web.

Lets say we have two sites both pull jquery from the same CDN.

pageOne.com > mycdn.com/jquery

pageTwo.org > mycdn.com/jquery

Now

I go to pageOne.com.

jquery is downloaded from mycdn.com/jquery.

I go to pageTwo.org (on second tab)

Question:
Is jquery downloaded again for pageTwo.org (its the same CDN and the same jquery js file),
or can I use the browser cache for pageTwo.org? (i have already downloaded it when I was on pageOne.com before)

答:
The single cached version is used for both sites.  The URL for the jQuery library stays the same.  It doesn't matter what references it.

This is one of the main benefits of using a common CDN for common libraries... the fact that the user will probably have cached it already from some other site.


答:
The command ptr[i][j]=Flats; is to be removed at the start of each iteration, because the program does not save the information at the correct location.
The loop should look like this:

```<code>for(int i = 0; i <  floors; i++)
        {
            for(int j = 0; j < flats_per_floor; j++)
            {
                printf("ID:\n");
                scanf("%d", &ptr[i][j].Flat_ID);
                printf("\n");
                printf("Rooms:\n");
                scanf("%d", &ptr[i][j].count_Rooms);
                printf("\n");
                printf("Adults:\n");
                scanf("%d", &ptr[i][j].count_Adults);
                printf("\n");
                printf("Children:\n");
                scanf("%d", &ptr[i][j].count_Children);
                printf("\n");
                printf("Name:\n");
                scanf("%s", ptr[i][j].Family_Surname);
                printf("\n");
                printf("Date of entry: \n");
                scanf("%s", ptr[i][j].Date);
                printf("\n");
                printf("Rent:\n");
                scanf("%f", &ptr[i][j].rent);
                printf("\n");

            }
        }
</code>```

Title: 2D dynamic array of structures does not work as intended

Body:
The command ptr[i][j]=Flats; is to be removed at the start of each iteration, because the program does not save the information at the correct location.
The loop should look like this:

for(int i = 0; i <  floors; i++)
        {
            for(int j = 0; j < flats_per_floor; j++)
            {
                printf("ID:\n");
                scanf("%d", &ptr[i][j].Flat_ID);
                printf("\n");
                printf("Rooms:\n");
                scanf("%d", &ptr[i][j].count_Rooms);
                printf("\n");
                printf("Adults:\n");
                scanf("%d", &ptr[i][j].count_Adults);
                printf("\n");
                printf("Children:\n");
                scanf("%d", &ptr[i][j].count_Children);
                printf("\n");
                printf("Name:\n");
                scanf("%s", ptr[i][j].Family_Surname);
                printf("\n");
                printf("Date of entry: \n");
                scanf("%s", ptr[i][j].Date);
                printf("\n");
                printf("Rent:\n");
                scanf("%f", &ptr[i][j].rent);
                printf("\n");

            }
        }


问:
RSocket Js client not getting elements generated from a Spring Boot RSocket Server
Sample project available on Github: https://github.com/codependent/rsocket-rating-service

A Spring Boot RSocket server message mapping expects a requestResponse request, returning a simple POJO:

```<code>    @MessageMapping("request-rating")
    fun getRatingWebSocket(ratingRequest: RatingRequest): Mono<Rating> {
        return Mono.just(Rating(ratingRequest.songId, (0..10).random())).log()
                .doOnNext {
                    logger.info("Next {}", it)
                }
                .doOnCancel {
                    logger.info("Cancel")
                }
                .doOnSuccess {
                    logger.info("Success {}", it)
                }
                .doOnError { throwable ->
                    logger.error("Error {}", throwable)
                }
                .doOnTerminate { logger.info("Terminate") }
    }
</code>```

On the client side I have the following JS code to connect to the RSocket server and request a value:

```<code>const {
    RSocketClient,
    JsonSerializer,
    IdentitySerializer,
} = require('rsocket-core');
const RSocketWebSocketClient = require('rsocket-websocket-client').default;
const route = 'request-rating';
let client = undefined;
let rSocket = undefined;

function main() {
    if (client !== undefined) {
        client.close();
    }
    client = new RSocketClient({
        serializers: {
            data: JsonSerializer,
            metadata: IdentitySerializer
        },
        setup: {
            // ms btw sending keepalive to server
            keepAlive: 60000,
            // ms timeout if no keepalive response
            lifetime: 180000,
            // format of `data`
            dataMimeType: 'application/json',
            // format of `metadata`
            metadataMimeType: 'message/x.rsocket.routing.v0',
        },
        transport: new RSocketWebSocketClient({
            url: 'ws://localhost:8080/rating-ws'
        }),
    });

    // Open the connection
    client.connect().subscribe({
        onComplete: socket => {
            // socket provides the rsocket interactions fire/forget, request/response,
            // request/stream, etc as well as methods to close the socket.
            rSocket = socket;
        },
        onError: error => {
            console.log("Connection has been refused due to ", error);
        },
        onSubscribe: cancel => {
            /* call cancel() to abort */
        }
    });
    document.getElementById('sendButton').addEventListener('click', requestRating);
}

function requestRating() {
    rSocket.requestResponse({
        data: {
            'songId': document.getElementById("songId").value
        },
        metadata: String.fromCharCode(route.length) + route
    }).subscribe({
        onComplete: () => {
            console.log('Complete')
        },
        onError: error => {
            console.log("Connection has been closed due to " + error);
        },
        onNext: payload => {
            console.log(payload.data);
        },
        onSubscribe: subscription => {
            //subscription.request(1)
            console.log("Subscribed")
        }
    });
}

document.addEventListener('DOMContentLoaded', main);

</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Rating Service</title>
    <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script src="bundle.js"></script>
</head>
<body>
<div>Request your rating</div>
<div>
    <label> ClientId:
        <input id="songId" type="text" name="songId"/>
    </label>
</div>
<div><input id="sendButton" type="button" name="send" value="Send"/></div>
</body>
</html>
</code>```

After accessing http://localhost:8080/index.html enter some text and push send.

The request gets to the server which logs the correct generation of an onNext value:

```<code>[ctor-http-nio-6] reactor.Mono.Just.1                      : | onSubscribe([Synchronous Fuseable] Operators.ScalarSubscription)
[ctor-http-nio-6] reactor.Mono.Just.1                      : | request(1)
[ctor-http-nio-6] reactor.Mono.Just.1                      : | onNext(Rating(songId=asdfas, value=0))
[ctor-http-nio-6] c.c.r.r.c.RatingServiceRestController    : Next Rating(songId=asdfas, value=0)
[ctor-http-nio-6] c.c.r.r.c.RatingServiceRestController    : Success Rating(songId=asdfas, value=0)
[ctor-http-nio-6] c.c.r.r.c.RatingServiceRestController    : Terminate
[ctor-http-nio-6] reactor.Mono.Just.1                      : | onComplete()
</code>```

However on the client-side

```<code>        onNext: payload => {
            console.log(payload.data);
        },
</code>```

is never called, the browser logs only show:

```<code>Subscribed
Complete
</code>```

Why isn't it getting the generated value from the server?

答:
In RSocket JS, unlike in Reactive Streams, the onComplete signal gets data in the requestResponse interaction mode.

This doesn`t seem to follow the protocol spec(https://rsocket.io/about/protocol):

```<code>Both (C)omplete and (N)ext set meaning PAYLOAD contains data and signals stream completion.
    For example: An Observable stream receiving onNext(payload) followed by onComplete().
Just (C)omplete set meaning PAYLOAD contains no data and only signals stream completion.
    For example: An Observable stream receiving onComplete().
Just (N)ext set meaning PAYLOAD contains data stream is NOT completed.
    For example: An Observable stream receiving onNext(payload).
</code>```

To workaround this I had to modify the callback function to this:

```<code>        onComplete: completeData => {
            console.log('Complete '+ completeData.data)
        },
</code>```

Body:
Sample project available on Github: https://github.com/codependent/rsocket-rating-service

A Spring Boot RSocket server message mapping expects a requestResponse request, returning a simple POJO:

    @MessageMapping("request-rating")
    fun getRatingWebSocket(ratingRequest: RatingRequest): Mono<Rating> {
        return Mono.just(Rating(ratingRequest.songId, (0..10).random())).log()
                .doOnNext {
                    logger.info("Next {}", it)
                }
                .doOnCancel {
                    logger.info("Cancel")
                }
                .doOnSuccess {
                    logger.info("Success {}", it)
                }
                .doOnError { throwable ->
                    logger.error("Error {}", throwable)
                }
                .doOnTerminate { logger.info("Terminate") }
    }

On the client side I have the following JS code to connect to the RSocket server and request a value:

const {
    RSocketClient,
    JsonSerializer,
    IdentitySerializer,
} = require('rsocket-core');
const RSocketWebSocketClient = require('rsocket-websocket-client').default;
const route = 'request-rating';
let client = undefined;
let rSocket = undefined;

function main() {
    if (client !== undefined) {
        client.close();
    }
    client = new RSocketClient({
        serializers: {
            data: JsonSerializer,
            metadata: IdentitySerializer
        },
        setup: {
            // ms btw sending keepalive to server
            keepAlive: 60000,
            // ms timeout if no keepalive response
            lifetime: 180000,
            // format of `data`
            dataMimeType: 'application/json',
            // format of `metadata`
            metadataMimeType: 'message/x.rsocket.routing.v0',
        },
        transport: new RSocketWebSocketClient({
            url: 'ws://localhost:8080/rating-ws'
        }),
    });

    // Open the connection
    client.connect().subscribe({
        onComplete: socket => {
            // socket provides the rsocket interactions fire/forget, request/response,
            // request/stream, etc as well as methods to close the socket.
            rSocket = socket;
        },
        onError: error => {
            console.log("Connection has been refused due to ", error);
        },
        onSubscribe: cancel => {
            /* call cancel() to abort */
        }
    });
    document.getElementById('sendButton').addEventListener('click', requestRating);
}

function requestRating() {
    rSocket.requestResponse({
        data: {
            'songId': document.getElementById("songId").value
        },
        metadata: String.fromCharCode(route.length) + route
    }).subscribe({
        onComplete: () => {
            console.log('Complete')
        },
        onError: error => {
            console.log("Connection has been closed due to " + error);
        },
        onNext: payload => {
            console.log(payload.data);
        },
        onSubscribe: subscription => {
            //subscription.request(1)
            console.log("Subscribed")
        }
    });
}

document.addEventListener('DOMContentLoaded', main);

index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Rating Service</title>
    <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">

Request your rating

     ClientId:
        <input id="songId" type="text" name="songId"/>

<input id="sendButton" type="button" name="send" value="Send"/>

After accessing http://localhost:8080/index.html enter some text and push send.

The request gets to the server which logs the correct generation of an onNext value:

[ctor-http-nio-6] reactor.Mono.Just.1                      : | onSubscribe([Synchronous Fuseable] Operators.ScalarSubscription)
[ctor-http-nio-6] reactor.Mono.Just.1                      : | request(1)
[ctor-http-nio-6] reactor.Mono.Just.1                      : | onNext(Rating(songId=asdfas, value=0))
[ctor-http-nio-6] c.c.r.r.c.RatingServiceRestController    : Next Rating(songId=asdfas, value=0)
[ctor-http-nio-6] c.c.r.r.c.RatingServiceRestController    : Success Rating(songId=asdfas, value=0)
[ctor-http-nio-6] c.c.r.r.c.RatingServiceRestController    : Terminate
[ctor-http-nio-6] reactor.Mono.Just.1                      : | onComplete()

However on the client-side

        onNext: payload => {
            console.log(payload.data);
        },

is never called, the browser logs only show:

Subscribed
Complete

Why isn't it getting the generated value from the server?

Body:
In RSocket JS, unlike in Reactive Streams, the onComplete signal gets data in the requestResponse interaction mode.

This doesn`t seem to follow the protocol spec(https://rsocket.io/about/protocol):

Both (C)omplete and (N)ext set meaning PAYLOAD contains data and signals stream completion.
    For example: An Observable stream receiving onNext(payload) followed by onComplete().
Just (C)omplete set meaning PAYLOAD contains no data and only signals stream completion.
    For example: An Observable stream receiving onComplete().
Just (N)ext set meaning PAYLOAD contains data stream is NOT completed.
    For example: An Observable stream receiving onNext(payload).

To workaround this I had to modify the callback function to this:

        onComplete: completeData => {
            console.log('Complete '+ completeData.data)
        },


答:
The root cause of the problem is due to no restriction on 'width' being applied to the image.
The image is very big and hence, it is causing the horizontal scroll bar to appear.

Bootstrap provides a class called 'img-fluid' to resolve this common issue.

The horizontal scroll bar can be avoided by specifying the image class of 'img-fluid', as shown below.

The second problem with the use of container-fluid px-0 can be fixed by specifying the px-lg-5 class instead of px-0.
(px-lg-5 works well for wide sections / outer-most divs)

Working example with 'img-fluid' and container-fluid px-lg-5 classes:

```<code><!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
          crossorigin="anonymous">
    <title>Bootstrap - responsive image</title>
  </head>
  <body>
    <div class="container-fluid px-lg-5">
      <div class="row">
          <div class="col-6">
              Lorem ipsum dolor sit amet, consectetur adipisicing elit.
          </div>
          <div class="col-6">
              <img class="img-fluid"
                   src="https://images.unsplash.com/photo-1585600270404-543d0eac85e1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3042&q=80">
          </div>
      </div>
  </body>
</html>
</code>```

Output:

More information:
https://getbootstrap.com/docs/4.0/content/images/

Title: Problem: horizontal scrollbar appears when I add an image to a column using bootstrap 4 grid system

Body:
I am super new to coding and web development and I am not sure how to solve my issue:

I am trying to add an image to the column that I created using bootstrap 4 grid system. However, as soon as I add the image, a horizontal scrollbar appears on the screen and I'm not sure why.

Here is a screenshot of what happens: https://gyazo.com/c383ecb9180181349363e0636047867c

        Lorem ipsum dolor sit amet, consectetur adipisicing elit.

My second issue is that although the horizontal scrollbar gets removed when I use the "img-fluid" class for my image, however when I change the container to container-fluid so that it covers the entire width of the screen and then use the class "px-0" for my container to remove the extra padding, I once again get horizontal scrollbars appearing on my screen.

        Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Body:
The root cause of the problem is due to no restriction on 'width' being applied to the image.
The image is very big and hence, it is causing the horizontal scroll bar to appear.

Bootstrap provides a class called 'img-fluid' to resolve this common issue.

The horizontal scroll bar can be avoided by specifying the image class of 'img-fluid', as shown below.

The second problem with the use of container-fluid px-0 can be fixed by specifying the px-lg-5 class instead of px-0.
(px-lg-5 works well for wide sections / outer-most divs)

Working example with 'img-fluid' and container-fluid px-lg-5 classes:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
          crossorigin="anonymous">
    <title>Bootstrap - responsive image</title>
  </head>
  <body>
    <div class="container-fluid px-lg-5">
      <div class="row">
          <div class="col-6">
              Lorem ipsum dolor sit amet, consectetur adipisicing elit.
          </div>
          <div class="col-6">
              <img class="img-fluid"
                   src="https://images.unsplash.com/photo-1585600270404-543d0eac85e1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3042&q=80">
          </div>
      </div>
  </body>
</html>

Output:

More information:
https://getbootstrap.com/docs/4.0/content/images/


问:
change the mysql root password.How?
I am new to MySQL. I am trying to change the root credentials for Mysql. I searched for it on many sites but I didn't find anything. I tried it with the help of this site blog. I thought it will help me because my error code was the same as mentioned in this blog. Please help me with this. Thank you in advance</p>

答:
You can do this by cmd, just go to mysql dir and follow the below instructions.
Please check this link:

https://askubuntu.com/questions/679556/how-to-recover-mysql-password?noredirect=1&lq=1

Title: change the mysql root password.How?