问:
Error when checking target: Converting FC layers to Conv2D
I was trying to replace the FC layers at the end of VGG 16 network with Convolutional layers. Below is my code:

```<code>model2= Sequential()
model2.add(Conv2D(4096, kernel_size=(8,8), activation="relu"))
model2.add(Conv2D(4096, kernel_size=(1,1), activation="relu"))
model2.add(Conv2D(16, kernel_size=(1,1), activation="softmax"))

model = applications.VGG16(weights='imagenet', include_top=False, input_shape=inputshape)

F2model = Model(inputs=model.input, outputs=model2(model.output))

for layer in F2model.layers[:25]:
   layer.trainable = False

F2model.compile(optimizer=optimizers.Adam(), loss="binary_crossentropy", metrics=["accuracy"])

batch_size = 128
trainsize = 36000
validsize = 12000

F2model.fit_generator(
    train_generator,
    steps_per_epoch=trainsize // batch_size,
    epochs=5,
    validation_data=valid_generator,
    validation_steps=validsize // batch_size,callbacks=[tensorboard_callback])
</code>```

I train the regular network with FC layers and that runs fine, but when I run the above, I get the below error:

```<code>ValueError                                Traceback (most recent call last)in <module>
  4         epochs=5,
  5         validation_data=valid_generator,
  ----> 6         validation_steps=validsize // batch_size,callbacks=[tensorboard_callback])

ValueError: Error when checking target: expected sequential_1 to have 4 dimensions, but got array with shape (32, 16)
</code>```

At this point I am trying to figure out where those dimensions(32,16) are coming from. ANy help would be appreciated. Thank you

EDIT 1: For Full Traceback:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-15-2702f38208c0> in <module>
      4         epochs=5,
      5         validation_data=valid_generator,
----> 6         validation_steps=validsize // batch_size,callbacks=[tensorboard_callback])

~/anaconda3/lib/python3.7/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1730             use_multiprocessing=use_multiprocessing,
   1731             shuffle=shuffle,
-> 1732             initial_epoch=initial_epoch)
   1733
   1734     @interfaces.legacy_generator_methods_support

~/anaconda3/lib/python3.7/site-packages/keras/engine/training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
    218                                             sample_weight=sample_weight,
    219                                             class_weight=class_weight,
--> 220                                             reset_metrics=False)
    221
    222                 outs = to_list(outs)

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in train_on_batch(self, x, y, sample_weight, class_weight, reset_metrics)
   1506             x, y,
   1507             sample_weight=sample_weight,
-> 1508             class_weight=class_weight)
   1509         if self._uses_dynamic_learning_phase():
   1510             ins = x + y + sample_weights + [1]

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    619                 feed_output_shapes,
    620                 check_batch_axis=False,  # Don't enforce the batch size.
--> 621                 exception_prefix='target')
    622
    623             # Generate sample-wise weight values given the `sample_weight` and

~/anaconda3/lib/python3.7/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    133                         ': expected ' + names[i] + ' to have ' +
    134                         str(len(shape)) + ' dimensions, but got array '
--> 135                         'with shape ' + str(data_shape))
    136                 if not check_batch_axis:
    137                     data_shape = data_shape[1:]

ValueError: Error when checking target: expected conv2d_3 to have 4 dimensions, but got array with shape (32, 16)
</code>```

Edit 2: Inputs Info:

```<code>train_generator=datagen.flow_from_dataframe(dataframe=traindf,directory="data_final",x_col="path",y_col="label",subset="training",batch_size=32,seed=42,shuffle=True,class_mode="categorical",target_size=(256,256))

valid_generator=datagen.flow_from_dataframe(dataframe=traindf,directory="data_final",x_col="path",y_col="label",subset="validation",batch_size=32,seed=42,shuffle=True,class_mode="categorical",target_size=(256,256))

if K.image_data_format()=="channels_first":
  inputshape=(3,imrows,imcols)
else:
  inputshape=(imrows,imcols,3)
</code>```

答:
The functionnal API of keras is better for this kind of problem :

```<code>model = VGG16(weights='imagenet', include_top=False, input_shape=inputshape)
x = model.output
x = Conv2D(4096, kernel_size=(8, 8), activation="relu")(x)
x = Conv2D(4096, kernel_size=(1, 1), activation="relu")(x)
out = Conv2D(16, kernel_size=(1, 1), activation="softmax")(x)

F2model = Model(inputs=model.inputs, outputs=out)

for layer in F2model.layers[:25]:
    layer.trainable = False
</code>```

Moreover i see that you are using binary_crossentropy with a softmax activation, this can lead to some problems:

- Use softmax and categorical_crossentropy

- Use sigmoid and binary_crossentropy

And becarefull with this model, using convolution of 4096 will make your number of parameters really really hudge !!

(165 millions in this case)

EDIT

It looks like your problem only comes from your label array :

Your last layer is a convolutional layer so it expect a 4D array with shape  (batch_size, height, width, channel) but your are giving to it an array of shape (batch_size, 16)

So either change your last layer to be :

out = Dense(16, activation="softmax")(x)
```

Or change your label array to be acceptable to a convolutional layer.

Body:
I was trying to replace the FC layers at the end of VGG 16 network with Convolutional layers. Below is my code:

model2= Sequential()
model2.add(Conv2D(4096, kernel_size=(8,8), activation="relu"))
model2.add(Conv2D(4096, kernel_size=(1,1), activation="relu"))
model2.add(Conv2D(16, kernel_size=(1,1), activation="softmax"))

model = applications.VGG16(weights='imagenet', include_top=False, input_shape=inputshape)

F2model = Model(inputs=model.input, outputs=model2(model.output))

for layer in F2model.layers[:25]:
   layer.trainable = False

F2model.compile(optimizer=optimizers.Adam(), loss="binary_crossentropy", metrics=["accuracy"])

batch_size = 128
trainsize = 36000
validsize = 12000

F2model.fit_generator(
    train_generator,
    steps_per_epoch=trainsize // batch_size,
    epochs=5,
    validation_data=valid_generator,
    validation_steps=validsize // batch_size,callbacks=[tensorboard_callback])

I train the regular network with FC layers and that runs fine, but when I run the above, I get the below error:

ValueError                                Traceback (most recent call last)in <module>
  4         epochs=5,
  5         validation_data=valid_generator,
  ----> 6         validation_steps=validsize // batch_size,callbacks=[tensorboard_callback])

ValueError: Error when checking target: expected sequential_1 to have 4 dimensions, but got array with shape (32, 16)

At this point I am trying to figure out where those dimensions(32,16) are coming from. ANy help would be appreciated. Thank you

EDIT 1: For Full Traceback:

ValueError                                Traceback (most recent call last)
<ipython-input-15-2702f38208c0> in <module>
      4         epochs=5,
      5         validation_data=valid_generator,
----> 6         validation_steps=validsize // batch_size,callbacks=[tensorboard_callback])

~/anaconda3/lib/python3.7/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1730             use_multiprocessing=use_multiprocessing,
   1731             shuffle=shuffle,
-> 1732             initial_epoch=initial_epoch)
   1733
   1734     @interfaces.legacy_generator_methods_support

~/anaconda3/lib/python3.7/site-packages/keras/engine/training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
    218                                             sample_weight=sample_weight,
    219                                             class_weight=class_weight,
--> 220                                             reset_metrics=False)
    221
    222                 outs = to_list(outs)

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in train_on_batch(self, x, y, sample_weight, class_weight, reset_metrics)
   1506             x, y,
   1507             sample_weight=sample_weight,
-> 1508             class_weight=class_weight)
   1509         if self._uses_dynamic_learning_phase():
   1510             ins = x + y + sample_weights + [1]

~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    619                 feed_output_shapes,
    620                 check_batch_axis=False,  # Don't enforce the batch size.
--> 621                 exception_prefix='target')
    622
    623             # Generate sample-wise weight values given the `sample_weight` and

~/anaconda3/lib/python3.7/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    133                         ': expected ' + names[i] + ' to have ' +
    134                         str(len(shape)) + ' dimensions, but got array '
--> 135                         'with shape ' + str(data_shape))
    136                 if not check_batch_axis:
    137                     data_shape = data_shape[1:]

ValueError: Error when checking target: expected conv2d_3 to have 4 dimensions, but got array with shape (32, 16)

Edit 2: Inputs Info:

train_generator=datagen.flow_from_dataframe(dataframe=traindf,directory="data_final",x_col="path",y_col="label",subset="training",batch_size=32,seed=42,shuffle=True,class_mode="categorical",target_size=(256,256))

valid_generator=datagen.flow_from_dataframe(dataframe=traindf,directory="data_final",x_col="path",y_col="label",subset="validation",batch_size=32,seed=42,shuffle=True,class_mode="categorical",target_size=(256,256))

if K.image_data_format()=="channels_first":
  inputshape=(3,imrows,imcols)
else:
  inputshape=(imrows,imcols,3)

Body:
The functionnal API of keras is better for this kind of problem :

model = VGG16(weights='imagenet', include_top=False, input_shape=inputshape)
x = model.output
x = Conv2D(4096, kernel_size=(8, 8), activation="relu")(x)
x = Conv2D(4096, kernel_size=(1, 1), activation="relu")(x)
out = Conv2D(16, kernel_size=(1, 1), activation="softmax")(x)

F2model = Model(inputs=model.inputs, outputs=out)

for layer in F2model.layers[:25]:
    layer.trainable = False

Moreover i see that you are using binary_crossentropy with a softmax activation, this can lead to some problems:

- Use softmax and categorical_crossentropy

- Use sigmoid and binary_crossentropy

And becarefull with this model, using convolution of 4096 will make your number of parameters really really hudge !!

(165 millions in this case)

EDIT

It looks like your problem only comes from your label array :

Your last layer is a convolutional layer so it expect a 4D array with shape  (batch_size, height, width, channel) but your are giving to it an array of shape (batch_size, 16)

So either change your last layer to be :

out = Dense(16, activation="softmax")(x)

Or change your label array to be acceptable to a convolutional layer.


来源: stackexchange

问:
Migrate full table to json/clob column in another table
I want to migrate the data from following table1:

NAME | Surname
-----+---------
Name1| Surname1
Name2| Surname2
```

<p>Into <strong>table2</strong>  as a clob (nclob,nvarchar(max),json.. etc.) column:</p>

<pre class="lang-none prettyprint-override"><code>NAME | JSON_COLUMN
-----+-------------------------------
NAME1| {Name: Name1,Surname: Surname1}
NAME2| {Name: Name2,Surname: Surname2}
</code>```

I wonder what is the best way to do this type of migration ?

Is there a function that can convert a table into json format so I can insert it into the new table?

Something like this:

```<code>insert into table2 (JSON_TABLE) select (table1 as json) from table1
</code>```

答:
In oracle, you can use json_object():

```<code>select
    name,
    json_object('Name' value name, 'Surname' value surname) js
from mytable
</code>```

Demo on DB Fiddle:

```<code>with mytable as (
    select 'Name1' name, 'Surname1' surname from dual
    union all select 'Name2', 'Surname2' from dual
)
select
    name,
    json_object('Name' value name, 'Surname' value surname) js
from mytable
</code>```

```
NAME  | JS
:---- | :------------------------------------
Name1 | {"Name":"Name1","Surname":"Surname1"}
Name2 | {"Name":"Name2","Surname":"Surname2"}
```

ContentLicense: CC BY-SA 4.0

Body:
I want to migrate the data from following table1:

NAME | Surname
-----+---------
Name1| Surname1
Name2| Surname2

Into table2  as a clob (nclob,nvarchar(max),json.. etc.) column:

NAME | JSON_COLUMN
-----+-------------------------------
NAME1| {Name: Name1,Surname: Surname1}
NAME2| {Name: Name2,Surname: Surname2}

I wonder what is the best way to do this type of migration ?

Is there a function that can convert a table into json format so I can insert it into the new table?

Something like this:

insert into table2 (JSON_TABLE) select (table1 as json) from table1

Body:
In oracle, you can use json_object():

select
    name,
    json_object('Name' value name, 'Surname' value surname) js
from mytable

Demo on DB Fiddle:

with mytable as (
    select 'Name1' name, 'Surname1' surname from dual
    union all select 'Name2', 'Surname2' from dual
)
select
    name,
    json_object('Name' value name, 'Surname' value surname) js
from mytable

NAME  | JS
:---- | :------------------------------------
Name1 | {"Name":"Name1","Surname":"Surname1"}
Name2 | {"Name":"Name2","Surname":"Surname2"}


问:
Need to know VMS date to Long conversion
i am trying to find the conversion logic behind VMS date to long data type. for example in RDB database date column is timesatmp. those value passes as VMS date to long conversion.

Date value: 2008-11-13 05:10:39

response long value is : 47332698396532279

Need to know how this date is converted as long . the enoding logic should match with response value

答:
As michaeak wrote: The integer number shows the number of milliseconds after 01.01.1970 00:00:00.

To convert this to a 64 bit integer you need to know the resolution and base of that 64bit integer.


问:
Xamarin XAML file wont change after changing some code
In my XAML File after changing some code inside it and then debug on my phone, the changes I made do not reflect on my phone. It keep showing my old code.

Old code :

```<code><ListView
       ItemsSource="{Binding Allgroups}"
       RowHeight="75"
       IsGroupingEnabled="true">
    <ListView.ItemTemplate>
        <DataTemplate>
             <Label Text="{Binding NameNative}"></Label>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.GroupHeaderTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding TitleWithItemCount}" />
            </ViewCell>
        </DataTemplate>
    </ListView.GroupHeaderTemplate>
</ListView>
</code>```

new code :

```<code> <Label Text="HELOO WORLD  "></Label>
</code>```

I Noticed every time i run the code , it keep showing the list.I have to click the save button then the list disappear and hello world appear .

答:
I reset VS settings and relaunched it .
worked for me</p>

```<code>        <CollectionView ItemsSource="{Binding Categoriesxx}" IsGrouped="True">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical" Span="1" VerticalItemSpacing="5" HorizontalItemSpacing="5"></GridItemsLayout>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout >
                        <Label Text="{Binding NameNative}"></Label>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
            <CollectionView.GroupHeaderTemplate>
                <DataTemplate>
                    <StackLayout BackgroundColor="AliceBlue">
                        <Label Text="{Binding Name}" FontSize="Title"></Label>
                        <Button Image="{Binding StateIcon}"
                                BackgroundColor="Transparent"
                                BorderColor="Transparent"
                                BorderWidth="0"
                                Command="{Binding BindingContext.ExpandCommand ,Source={x:Reference ServiceListPage}}"/>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.GroupHeaderTemplate>
        </CollectionView>
</code>```

Body:
In my XAML File after changing some code inside it and then debug on my phone, the changes I made do not reflect on my phone. It keep showing my old code.

Old code :

<ListView
       ItemsSource="{Binding Allgroups}"
       RowHeight="75"
       IsGroupingEnabled="true">
    <ListView.ItemTemplate>
        <DataTemplate>

        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.GroupHeaderTemplate>
        <DataTemplate>
            <ViewCell>

            </ViewCell>
        </DataTemplate>
    </ListView.GroupHeaderTemplate>
</ListView>

new code :

I Noticed every time i run the code , it keep showing the list.I have to click the save button then the list disappear and hello world appear .

Body:
I reset VS settings and relaunched it .
worked for me

        <CollectionView ItemsSource="{Binding Categoriesxx}" IsGrouped="True">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical" Span="1" VerticalItemSpacing="5" HorizontalItemSpacing="5"></GridItemsLayout>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout >
                        <Label Text="{Binding NameNative}"></Label>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
            <CollectionView.GroupHeaderTemplate>
                <DataTemplate>
                    <StackLayout BackgroundColor="AliceBlue">
                        <Label Text="{Binding Name}" FontSize="Title"></Label>
                        <Button Image="{Binding StateIcon}"
                                BackgroundColor="Transparent"
                                BorderColor="Transparent"
                                BorderWidth="0"
                                Command="{Binding BindingContext.ExpandCommand ,Source={x:Reference ServiceListPage}}"/>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.GroupHeaderTemplate>
        </CollectionView>


问:
Stop input from losing focus on Virtual keyboard click
I've created a custom virtual keyboard for a kiosk application. The problem is every time you click on keyboard keys, input field loses its focus.
Any help would be appreciated. </p>

答:
You can shift the focus back as soon as the input loses out the focus on click on the virtual keyboard.

let input = document.getElementById('input')
input.focus() // focus on input on page load

function handleInput (key) {
 input.value += key // add key value to input
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="handleInput('a')">a</button>
<button onclick="handleInput('b')">b</button>
<button onclick="handleInput('c')">c</button>

<input onfocusout="this.focus()" id="input"/> <!-- focus on input back on onfocusout ie. when user click elsewhere --></code>```

Input is always in focus.

Body:
You can shift the focus back as soon as the input loses out the focus on click on the virtual keyboard.

let input = document.getElementById('input')
input.focus() // focus on input on page load

function handleInput (key) {
 input.value += key // add key value to input
}

<button onclick="handleInput('a')">a</button>
<button onclick="handleInput('b')">b</button>
<button onclick="handleInput('c')">c</button>

<input onfocusout="this.focus()" id="input"/> <!-- focus on input back on onfocusout ie. when user click elsewhere -->

Input is always in focus.


问:
Error class not found when I extends a class
I've two files in one directory named (classes )which contain classes, first one for main class (Database ) which build to connect to the database.
And the second one (Branch ) extends Database class which made to get data from the database.

When I try to run "getBranch" function I got an error says :

Uncaught Error: Class 'Database' not found in C:\xampp\htdocs\branches\classes\branch.php

Please find the codes below and advise what's required.

database.php:

```<code><?php

  class Database {
    private $host;
    private $user;
    private $pwd;
    private $dbName;
    public $conn;

    public function connect() {
      $this->host = "localhost";
      $this->user = "root";
      $this->pwd = "";
      $this->dbName = "branchs";
      //create connection
      $conn = new mysqli($this->host, $this->user, $this->pwd, $this->dbName);
      //chech connection
      if ($conn->connect_error) {
        die("Connection failed :" . $conn->connect_error);
      } else {
        echo "Success";
      }

      return $conn;

    }

  }

?>
</code>```

branch.php :

```<code><?php

    class Branch extends Database {

      public function getBranch() {

      $sql = "SELECT * FROM branches";
      $result = $this->connect()->query($sql);

      if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
          echo "Name :" . $row['brName'] . "City :" . $row['brCity'] . "<br>";
        }
      } else {
        echo "0 results";
      }

      }

    }

?>
</code>```

答:
You need to call database.php file in the branch.php (because Branch Class does not know that Database Class exists) by using require() or include() - depends.
2nd option is to use namespaces and 'use' statements for easier further development.
https://www.php.net/manual/en/language.namespaces.php</p>

Body:
I've two files in one directory named (classes )which contain classes, first one for main class (Database ) which build to connect to the database.
And the second one (Branch ) extends Database class which made to get data from the database.

When I try to run "getBranch" function I got an error says :

Uncaught Error: Class 'Database' not found in C:\xampp\htdocs\branches\classes\branch.php

Please find the codes below and advise what's required.

database.php:

<?php

  class Database {
    private $host;
    private $user;
    private $pwd;
    private $dbName;
    public $conn;

    public function connect() {
      $this->host = "localhost";
      $this->user = "root";
      $this->pwd = "";
      $this->dbName = "branchs";
      //create connection
      $conn = new mysqli($this->host, $this->user, $this->pwd, $this->dbName);
      //chech connection
      if ($conn->connect_error) {
        die("Connection failed :" . $conn->connect_error);
      } else {
        echo "Success";
      }

      return $conn;

    }

  }

?>

branch.php :

<?php

    class Branch extends Database {

      public function getBranch() {

      $sql = "SELECT * FROM branches";
      $result = $this->connect()->query($sql);

      if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
          echo "Name :" . $row['brName'] . "City :" . $row['brCity'] . "
";
        }
      } else {
        echo "0 results";
      }

      }

    }

?>


问:
Comment Blog creating not working symfony
Hello i was trying to add comment in blog everything is fine it shows no error but when i click submit nothing happens i mean it doesn't add it in data base i dont know what im missing
this is what i have in controller

```<code>public function addCommentAction(Request $request, $id)
    {
        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();
        $blog = $em->getRepository(Blog::class)->find($id);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirect($this->generateUrl('blog_details'));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
        ));

    }
</code>```

this is what i have in blog.yml

```<code>comment_new:
    path:     /{id}/details
    defaults: { _controller: "BlogBundle:Blog:addComment" }
    methods:  [GET, POST]
</code>```

and finally this is the twig page

```<code><div class="comments-form">
                                <h4 class="comments-title">Leave A Reply</h4>

                                    <!-- .row -->
                                    <form action="{{ path('comment_new', { 'id': blog.id }) }}" method="post" >

                                        <textarea id="form_comment" name="form[comment]" required="required" class="form-control comments-textarea" placeholder="Comments*"></textarea>

                                        <input type="submit" class="btn btn-default" />

                                </form>
                            </div>
                        </div>
</code>```

答:
i just fixed it i displaying the blog with detailsaction and the form is in addcomment action (i checked with using{{form(form)}} and it didnt work so i had to do all the work in details action now it looks like this

```<code>public function detailsAction(Request $request,Blog $blog){

        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();

        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)
            ->add('ajouter',SubmitType::class)
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
        ));

    }

</code>```

and the twig looks like this :

```<code>  {{ form_start(form) }}
                                <div class="row form-group">

                                    <div class="col col-md-3"><label class=" form-control-label">Votre Commentaire  </label></div>
                                    <div class="col-12 col-md-9">{{ form_widget(form.description) }}<small class="form-text text-muted"></small></div>
                                    <div class="col-12 col-md-9">
                                    </div>
                                </div>
                                    {{ form_end(form) }}
</code>```

anyway thanks for for your help <3

Body:
Hello i was trying to add comment in blog everything is fine it shows no error but when i click submit nothing happens i mean it doesn't add it in data base i dont know what im missing
this is what i have in controller

public function addCommentAction(Request $request, $id)
    {
        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();
        $blog = $em->getRepository(Blog::class)->find($id);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirect($this->generateUrl('blog_details'));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
        ));

    }

this is what i have in blog.yml

comment_new:
    path:     /{id}/details
    defaults: { _controller: "BlogBundle:Blog:addComment" }
    methods:  [GET, POST]

and finally this is the twig page

Leave A Reply

                                    <form action="{{ path('comment_new', { 'id': blog.id }) }}" method="post" >

                                        <textarea id="form_comment" name="form[comment]" required="required" class="form-control comments-textarea" placeholder="Comments*"></textarea>

                                        <input type="submit" class="btn btn-default" />

                                </form>

Body:
i just fixed it i displaying the blog with detailsaction and the form is in addcomment action (i checked with using{{form(form)}} and it didnt work so i had to do all the work in details action now it looks like this

public function detailsAction(Request $request,Blog $blog){

        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();

        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)
            ->add('ajouter',SubmitType::class)
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
        ));

    }

and the twig looks like this :

  {{ form_start(form) }}
                                <div class="row form-group">

                                    <div class="col col-md-3"><label class=" form-control-label">Votre Commentaire  </label></div>
                                    <div class="col-12 col-md-9">{{ form_widget(form.description) }}<small class="form-text text-muted"></small></div>
                                    <div class="col-12 col-md-9">
                                    </div>
                                </div>
                                    {{ form_end(form) }}

anyway thanks for for your help <3


问:
C# Referencing a variable type, name and value in a format string
I have this problem with some code that generates SQL code, for later passing through a database.
But while I have been working on the code, I thought to myself "There must be a better way to do this"

This is the code i have got so far:

```<code>if (invoice.ID is string) SQL.AppendFormat($"{nameof(invoice.ID)} = '{invoice.ID}'").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof(invoice.ID)} = {invoice.ID}").Replace(",", ".").Append(", ");

if (invoice.InvoiceID is string) SQL.AppendFormat($"{nameof(invoice.InvoiceID)} = {invoice.InvoiceID}, ").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof(invoice.InvoiceID)} = {invoice.InvoiceID}").Replace(",", ".").Append(", ");

if (invoice.IssuedDate is string) SQL.AppendFormat($"{nameof(invoice.IssuedDate)} = {invoice.IssuedDate}, ").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof(invoice.IssuedDate)} = {invoice.IssuedDate}").Replace(",", ".").Append(", ");
</code>```

As you can see I have to reference the variable every time, and I want this code to be as dynamic as possible, as I dont know yet how many columns there is going to be when im done.

So my wish is to be able to copy and paste some code in, and only change one or maybe two variables(preferably one) like this:

```<code>if ({0} is string) SQL.AppendFormat($"{nameof({0})} = '{{0}}'").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof({0})} = {{0}}").Replace(",", ".").Append(", ").Format(invoice.ID);
</code>```

I know the above example is not possible, but I hope you can see what I want.

Many thanks in advance, and any help is greatly appreciated

答:
Apart from Marc Gravell's comments, you could have something along these lines:

```<code>    public class SomeInvoiceData
    {
            public int InvoiceID { get; set; }
            public System.DateTime InvoiceDate { get; set; }
            public string InvoiceName { get; set; }
    }

    public static class Value
    {
            public static string Formatted(this object o)
            {
                    if (o is string)
                    {
                            return $"'{o.ToString()}'";
                    }
                    else if(o is DateTime)
                    {
                            return $"'{o.ToString()}'";
                    }
                    else
                    {
                            return $"{o.ToString()}";
                    }
            }
    }

    public class SQLBuilder
    {
            private List<string> List = new List<string>();
            private string Delimiter = ",";
            public void AppendAll(object instance)
            {
                    System.Reflection.PropertyInfo[] listProperty = instance.GetType().GetProperties();
                    foreach (var property in listProperty)
                    {
                            var pvalue = property.GetValue(instance);
                            var statement = $"{property.Name} = {pvalue.Formatted()}";
                            List.Add(statement);
                    }
            }
            public string Get()
            {
                    return String.Join(Delimiter, List);
            }
    }
</code>```

result is
InvoiceID = 123,InvoiceDate = '2/17/2020 10:23:04 AM',InvoiceName = 'invoice for $3.3'

Body:
I have this problem with some code that generates SQL code, for later passing through a database.
But while I have been working on the code, I thought to myself "There must be a better way to do this"

This is the code i have got so far:

if (invoice.ID is string) SQL.AppendFormat($"{nameof(invoice.ID)} = '{invoice.ID}'").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof(invoice.ID)} = {invoice.ID}").Replace(",", ".").Append(", ");

if (invoice.InvoiceID is string) SQL.AppendFormat($"{nameof(invoice.InvoiceID)} = {invoice.InvoiceID}, ").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof(invoice.InvoiceID)} = {invoice.InvoiceID}").Replace(",", ".").Append(", ");

if (invoice.IssuedDate is string) SQL.AppendFormat($"{nameof(invoice.IssuedDate)} = {invoice.IssuedDate}, ").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof(invoice.IssuedDate)} = {invoice.IssuedDate}").Replace(",", ".").Append(", ");

As you can see I have to reference the variable every time, and I want this code to be as dynamic as possible, as I dont know yet how many columns there is going to be when im done.

So my wish is to be able to copy and paste some code in, and only change one or maybe two variables(preferably one) like this:

if ({0} is string) SQL.AppendFormat($"{nameof({0})} = '{{0}}'").Replace(",", ".").Append(", ");
else SQL.AppendFormat($"{nameof({0})} = {{0}}").Replace(",", ".").Append(", ").Format(invoice.ID);

I know the above example is not possible, but I hope you can see what I want.

Many thanks in advance, and any help is greatly appreciated

Body:
Apart from Marc Gravell's comments, you could have something along these lines:

    public class SomeInvoiceData
    {
            public int InvoiceID { get; set; }
            public System.DateTime InvoiceDate { get; set; }
            public string InvoiceName { get; set; }
    }

    public static class Value
    {
            public static string Formatted(this object o)
            {
                    if (o is string)
                    {
                            return $"'{o.ToString()}'";
                    }
                    else if(o is DateTime)
                    {
                            return $"'{o.ToString()}'";
                    }
                    else
                    {
                            return $"{o.ToString()}";
                    }
            }
    }

    public class SQLBuilder
    {
            private List<string> List = new List<string>();
            private string Delimiter = ",";
            public void AppendAll(object instance)
            {
                    System.Reflection.PropertyInfo[] listProperty = instance.GetType().GetProperties();
                    foreach (var property in listProperty)
                    {
                            var pvalue = property.GetValue(instance);
                            var statement = $"{property.Name} = {pvalue.Formatted()}";
                            List.Add(statement);
                    }
            }
            public string Get()
            {
                    return String.Join(Delimiter, List);
            }
    }

result is
InvoiceID = 123,InvoiceDate = '2/17/2020 10:23:04 AM',InvoiceName = 'invoice for $3.3'


问:
RxAndroid network calls makes the app lagging on back navigation
my android application keeps lagging on back navigation after i implemented the network calls.For network calls I'm using rxandroid/retrofit. I've tried to fix it using both single & observable. Both makes the app lagging the same way.This is my code while using observable. Lagging occurs while loading data to recyclerviews. So I have added the adapter class also.</p>

```<code>@Override
    public void onResume() {
        super.onResume();
        getMenuByShopAndCategoryId(categoryRequest.getId(), Utility.getShop(getActivity()));
    }

    private void getMenuByShopAndCategoryId(int categoryId, int shopId){
        Repository.getInstance()
                .getMenuByShopAndCategoryId(categoryId,shopId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<MenuResponse>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable.add(d);
                    }

                    @Override
                    public void onNext(Response<MenuResponse> menuResponse) {
                            //other calculations
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //error handling
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onDestroy() {
        disposable.dispose();
        super.onDestroy();
    }
</code>```

```<code>public Observable<Response<MenuResponse>> getMenuByShopAndCategoryId(@NonNull  int category_id, @NonNull  int shop_id) {
        return apiService.getMenuByShopAndCategoryId(category_id,shop_id);
    }
</code>```

```<code>public class MenuItemsAdapter extends RecyclerView.Adapter<MenuItemsAdapter.ViewHolder> {
    private Context context;
    private ArrayList<MenuResponse.MenuRequest> menuItemArrayList;

    private ListRowMenuItemsBinding binding;
    private MenuItemsAdapterHandler menuItemsAdapterHandler;

    public MenuItemsAdapter(Context context, ArrayList<MenuResponse.MenuRequest> menuItemArrayList) {
        this.context = context;
        this.menuItemArrayList = menuItemArrayList;
    }

    @NonNull
    @Override
    public MenuItemsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.list_row_menu_items, viewGroup, false);
        menuItemsAdapterHandler = new MenuItemsAdapterHandler(context);
        binding.setHandler(menuItemsAdapterHandler);

        configureLabels();

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MenuItemsAdapter.ViewHolder viewHolder, int i) {
        viewHolder.binding.lblItemName.setText(menuItemArrayList.get(i).getMenuName());
        viewHolder.binding.lblPrice.setText("MVR " + String.format("%.2f", Double.valueOf(menuItemArrayList.get(i).getSubTotal())));
        if (menuItemArrayList.get(i).getAvailability().equals(Constants.AVAILABLE)){
            binding.lblAvailability.set(context, HuqTypogrphyStyle.CAPS_BUTTON_GREEN);
            viewHolder.binding.lblAvailability.setText("AVAILABLE");
        } else {
            binding.lblAvailability.set(context, HuqTypogrphyStyle.CAPS_BUTTON_RED);
            viewHolder.binding.lblAvailability.setText("NOT AVAILABLE");
        }
        viewHolder.binding.setMenuItem(menuItemArrayList.get(i));
        viewHolder.binding.executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return menuItemArrayList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ListRowMenuItemsBinding binding;

        public ViewHolder(@NonNull ListRowMenuItemsBinding listRowMenuItemsBinding) {
            super(listRowMenuItemsBinding.getRoot());

            this.binding = listRowMenuItemsBinding;
        }
    }

    private void configureLabels() {
        binding.lblItemName.set(context, HuqTypogrphyStyle.H2_HEADING);
        binding.lblPrice.set(context, HuqTypogrphyStyle.BODY_GRAY);
        binding.lblAvailability.set(context, HuqTypogrphyStyle.BODY_GRAY);
    }
}

</code>```

答: Try moving the api call from on Resume to onCreate. </p>

Body:
my android application keeps lagging on back navigation after i implemented the network calls.For network calls I'm using rxandroid/retrofit. I've tried to fix it using both single & observable. Both makes the app lagging the same way.This is my code while using observable. Lagging occurs while loading data to recyclerviews. So I have added the adapter class also.

@Override
    public void onResume() {
        super.onResume();
        getMenuByShopAndCategoryId(categoryRequest.getId(), Utility.getShop(getActivity()));
    }

    private void getMenuByShopAndCategoryId(int categoryId, int shopId){
        Repository.getInstance()
                .getMenuByShopAndCategoryId(categoryId,shopId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<MenuResponse>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable.add(d);
                    }

                    @Override
                    public void onNext(Response<MenuResponse> menuResponse) {
                            //other calculations
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //error handling
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onDestroy() {
        disposable.dispose();
        super.onDestroy();
    }

public Observable<Response<MenuResponse>> getMenuByShopAndCategoryId(@NonNull  int category_id, @NonNull  int shop_id) {
        return apiService.getMenuByShopAndCategoryId(category_id,shop_id);
    }

public class MenuItemsAdapter extends RecyclerView.Adapter<MenuItemsAdapter.ViewHolder> {
    private Context context;
    private ArrayList<MenuResponse.MenuRequest> menuItemArrayList;

    private ListRowMenuItemsBinding binding;
    private MenuItemsAdapterHandler menuItemsAdapterHandler;

    public MenuItemsAdapter(Context context, ArrayList<MenuResponse.MenuRequest> menuItemArrayList) {
        this.context = context;
        this.menuItemArrayList = menuItemArrayList;
    }

    @NonNull
    @Override
    public MenuItemsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.list_row_menu_items, viewGroup, false);
        menuItemsAdapterHandler = new MenuItemsAdapterHandler(context);
        binding.setHandler(menuItemsAdapterHandler);

        configureLabels();

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MenuItemsAdapter.ViewHolder viewHolder, int i) {
        viewHolder.binding.lblItemName.setText(menuItemArrayList.get(i).getMenuName());
        viewHolder.binding.lblPrice.setText("MVR " + String.format("%.2f", Double.valueOf(menuItemArrayList.get(i).getSubTotal())));
        if (menuItemArrayList.get(i).getAvailability().equals(Constants.AVAILABLE)){
            binding.lblAvailability.set(context, HuqTypogrphyStyle.CAPS_BUTTON_GREEN);
            viewHolder.binding.lblAvailability.setText("AVAILABLE");
        } else {
            binding.lblAvailability.set(context, HuqTypogrphyStyle.CAPS_BUTTON_RED);
            viewHolder.binding.lblAvailability.setText("NOT AVAILABLE");
        }
        viewHolder.binding.setMenuItem(menuItemArrayList.get(i));
        viewHolder.binding.executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return menuItemArrayList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ListRowMenuItemsBinding binding;

        public ViewHolder(@NonNull ListRowMenuItemsBinding listRowMenuItemsBinding) {
            super(listRowMenuItemsBinding.getRoot());

            this.binding = listRowMenuItemsBinding;
        }
    }

    private void configureLabels() {
        binding.lblItemName.set(context, HuqTypogrphyStyle.H2_HEADING);
        binding.lblPrice.set(context, HuqTypogrphyStyle.BODY_GRAY);
        binding.lblAvailability.set(context, HuqTypogrphyStyle.BODY_GRAY);
    }
}


问:
Update combobox with other's combobox selection through JQuery / JS
I have a project with JSP + Struts2 + JQuery with the following functional requirement:

I have n Teachers that should be replaced. Once 1 teacher is selected as "Sick" the user must choose 1 colleague to replace him/her.
But, if more than one teacher are sick, the user must select replacement for all of them ... and 1 replacement CANNOT be on 2 places at a time.

So I need to achieve the following

When 1 option is selected on any combobox, all related combos should remove that option from its lists.

And, if any combo with a selected value is reset to default (value="") then the other combos should add that option to its lists.

First the upper code, just bellow  HTML tag:

```<code><script type="text/javascript" src="//code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">//<![CDATA[

$(window).load(function(){
$(function(){
    $('.selbox1').change(function(){
    var val = $(this).val();
    var sel = $(this);

    if(val !== ""){
       if(sel.data("selected")){
           var oldval = sel.data("selected");
           sel
           .siblings('select')
           .append($('<option/>').attr("value", oldval).text(oldval));
       }
         sel
        .data("selected", val)
        .siblings('select')
        .children('option[value=' + val + ']')
        .remove();
    }
    else if(val === ""){
        if(sel.data("selected")){
           var oldval = sel.data("selected");
           sel
           .removeData("selected")
           .siblings('select')
           .append($('<option/>').attr("value", oldval).text(oldval));
       }
    }
    });
});
});

//]]></script>
</code>```

And now how I create the combobox:

```<code><s:iterator value="listaProfesASustituir" var="listaSustitucionesAInsertar" status="listaProfesASustituirStatus">
    <select name="selectbox<s:property value='#listaProfesASustituirStatus.index'/>" class="selbox1">
        <option value="">--- Selecciona Profesor ---</option>
        <s:iterator value="profesPrimera" status="profesPrimeraStatus">
            <option value="<s:property />"><s:property /></option>
        </s:iterator>
    </select>
</s:iterator>
</code>```

If you need it, here is the HTML code generated after the struts2 is rendered:

```<code><select name="selectbox1" class="selbox1">
    <option value="">--- Selecciona Profesor ---</option>
    <option value="Tera">Tera</option>
    <option value="No necesita sustitución.">No necesita sustitución.</option>
</select>
<select name="selectbox2" class="selbox1">
    <option value="">--- Selecciona Profesor ---</option>
    <option value="Tera">Tera</option>
    <option value="No necesita sustitución.">No necesita sustitución.</option>
</select>
</code>```

Finally, here is almost the complete HTML code that the browser is giving as "source code" of the resulting page (I've removed the menu and other minor stuff to make it shorter and readable):

    <!DOCTYPE html>

    <title>Administración: Sustituciones</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/estilo.css"/>

Sustituciones para el Lunes 20/01/20

            <form id="ListadoSustituciones" name="ListadoSustituciones" action="/TFG_Sustituciones/ListadoSustituciones.action" method="POST">
                <input type="hidden" name="fecha" value="20/01/20" id="ListadoSustituciones_fecha"/>
                <input type="hidden" name="profeSustituido" value="Juan" id="ListadoSustituciones_profeSustituido"/>
                <input type="hidden" name="diaSeleccionado" value="Lunes" id="ListadoSustituciones_diaSeleccionado"/>
                <input type="hidden" name="listaProfesASustituir" value="[ProfeASustituir@6f1d1207, ProfeASustituir@2c592e59]" id="ListadoSustituciones_listaProfesASustituir"/>

 Sustituciones para Juan

                            Hora
                            Profesor Propuesto
                            Profesor Sustituto

                            1ª
                            Locuaz

                                <select name="selectbox1" class="selbox1">
                                    <option value="">--- Selecciona Profesor ---</option>
                                    <option value="Tera">Tera</option>
                                    <option value="No necesita sustitución.">No necesita sustitución.</option>
                                </select>

                            2ª
                            No tiene clase.
                            <input type="hidden" name="profeSustitutoSegunda" value="No tiene clase." id="ListadoSustituciones_profeSustitutoSegunda"/>

                            3ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoTercera" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoTercera"/>

                            4ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoCuarta" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoCuarta"/>

                            5ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoQuinta" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoQuinta"/>

                            6ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoSexta" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoSexta"/>

                <input type="hidden" name="profeSustituido" value="Robustiano" id="ListadoSustituciones_profeSustituido"/>
                <input type="hidden" name="diaSeleccionado" value="Lunes" id="ListadoSustituciones_diaSeleccionado"/>
                <input type="hidden" name="listaProfesASustituir" value="[ProfeASustituir@6f1d1207, ProfeASustituir@2c592e59]" id="ListadoSustituciones_listaProfesASustituir"/>

 Sustituciones para Robustiano

                            Hora
                            Profesor Propuesto
                            Profesor Sustituto

                            1ª
                                fulanito

                                <select name="selectbox2" class="selbox1">
                                    <option value="">--- Selecciona Profesor ---</option>
                                    <option value="Tera">Tera</option>
                                    <option value="No necesita sustitución.">No necesita sustitución.</option>
                                </select>

                            2ª
                                fulanito

                                    <select name="profeSustitutoSegunda" id="ListadoSustituciones_profeSustitutoSegunda" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Tera">Tera</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            3ª
                                fulanito

                                    <select name="profeSustitutoTercera" id="ListadoSustituciones_profeSustitutoTercera" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            4ª
                                fulanito

                                    <select name="profeSustitutoCuarta" id="ListadoSustituciones_profeSustitutoCuarta" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            5ª
                                fulanito

                                    <select name="profeSustitutoQuinta" id="ListadoSustituciones_profeSustitutoQuinta" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            6ª
                                fulanito

                                    <select name="profeSustitutoSexta" id="ListadoSustituciones_profeSustitutoSexta" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

<input type="submit" id="ListadoSustituciones_0" value="Confirmar Sustitutos"/>

            </form>

Thanks in advance!

```

答:
You can use .filter() of jquery.This method will check all the option from other select box and hide the option which is already selected.
Suppose you have selected Tera then this option will get hide from other select-box using hide() method . Working code :

$('select').change(function() {
var oldvar = $(this).attr('data-old') !== typeof undefined ? $(this).attr('data-old') : "";
  var newval = $("option:selected", this).val();
  //adding data-old attribute to select
  $(this).attr('data-old', newval);
  var val = $(this).val();
  var sel = $(this);

  if (val != "") {
    var otherselects = $('select').not(this).find('option');
    //checking if the value of other select option is same if yes then hide them
    otherselects.filter(function() {
      return $(this).text() == val;
    }).hide();
  } else if (val == "") {
    //showing option which is deselected by current select-box
    $('select').not(this).find('option[value="' + oldvar + '"]').show();

  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</head>

<body>
  <table>
    <thead>
      <tr>
        <td colspan="3"> Sustituciones para <b>Robustiano</b></td>
      </tr>
      <tr>
        <td>Hora</td>
        <td id="nowrap">Profesor Propuesto</td>
        <td id="nowrap">Profesor Sustituto</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class='centrado'>1ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="selectbox2" class="selbox1">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>2ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoSegunda" id="ListadoSustituciones_profeSustitutoSegunda" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Tera">Tera</option>
            <option value="Lingüista">Lingüista</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>3ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoTercera" id="ListadoSustituciones_profeSustitutoTercera" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>4ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoCuarta" id="ListadoSustituciones_profeSustitutoCuarta" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>5ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoQuinta" id="ListadoSustituciones_profeSustitutoQuinta" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>6ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoSexta" id="ListadoSustituciones_profeSustitutoSexta" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>
</body>

</html></code>```

Try below code snippet :

$('select').change(function() {
  var oldvar = $(this).attr('data-old') !== typeof undefined ? $(this).attr('data-old') : "";
  var newval = $("option:selected", this).val();
  //adding data-old attribute to select
  $(this).attr('data-old', newval);
  var val = $(this).val();
  var sel = $(this);

  if (val != "") {
    var otherselects = $('select').not(this).find('option');
    //checking if the value of other select option is same if yes then hide them
    otherselects.filter(function() {
      return $(this).text() == val;
    }).hide();
    //add this
     $('select').not(this).find('option[value="' + oldvar + '"]').show();
  } else if (val == "") {
    //showing option which is deselected by current select-box
    $('select').not(this).find('option[value="' + oldvar + '"]').show();

  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<select>
  <option value="">--- Select ---</option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

<select>
  <option value="">--- Select ---</option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select></code>```

Body:
I have a project with JSP + Struts2 + JQuery with the following functional requirement:

I have n Teachers that should be replaced. Once 1 teacher is selected as "Sick" the user must choose 1 colleague to replace him/her.
But, if more than one teacher are sick, the user must select replacement for all of them ... and 1 replacement CANNOT be on 2 places at a time.

So I need to achieve the following

When 1 option is selected on any combobox, all related combos should remove that option from its lists.

And, if any combo with a selected value is reset to default (value="") then the other combos should add that option to its lists.

First the upper code, just bellow  HTML tag:

And now how I create the combobox:

<s:iterator value="listaProfesASustituir" var="listaSustitucionesAInsertar" status="listaProfesASustituirStatus">
    <select name="selectbox<s:property value='#listaProfesASustituirStatus.index'/>" class="selbox1">
        <option value="">--- Selecciona Profesor ---</option>
        <s:iterator value="profesPrimera" status="profesPrimeraStatus">
            <option value="<s:property />"><s:property /></option>
        </s:iterator>
    </select>
</s:iterator>

If you need it, here is the HTML code generated after the struts2 is rendered:

<select name="selectbox1" class="selbox1">
    <option value="">--- Selecciona Profesor ---</option>
    <option value="Tera">Tera</option>
    <option value="No necesita sustitución.">No necesita sustitución.</option>
</select>
<select name="selectbox2" class="selbox1">
    <option value="">--- Selecciona Profesor ---</option>
    <option value="Tera">Tera</option>
    <option value="No necesita sustitución.">No necesita sustitución.</option>
</select>

Finally, here is almost the complete HTML code that the browser is giving as "source code" of the resulting page (I've removed the menu and other minor stuff to make it shorter and readable):

    <!DOCTYPE html>

    <title>Administración: Sustituciones</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/estilo.css"/>

Sustituciones para el Lunes 20/01/20

            <form id="ListadoSustituciones" name="ListadoSustituciones" action="/TFG_Sustituciones/ListadoSustituciones.action" method="POST">
                <input type="hidden" name="fecha" value="20/01/20" id="ListadoSustituciones_fecha"/>
                <input type="hidden" name="profeSustituido" value="Juan" id="ListadoSustituciones_profeSustituido"/>
                <input type="hidden" name="diaSeleccionado" value="Lunes" id="ListadoSustituciones_diaSeleccionado"/>
                <input type="hidden" name="listaProfesASustituir" value="[ProfeASustituir@6f1d1207, ProfeASustituir@2c592e59]" id="ListadoSustituciones_listaProfesASustituir"/>

 Sustituciones para Juan

                            Hora
                            Profesor Propuesto
                            Profesor Sustituto

                            1ª
                            Locuaz

                                <select name="selectbox1" class="selbox1">
                                    <option value="">--- Selecciona Profesor ---</option>
                                    <option value="Tera">Tera</option>
                                    <option value="No necesita sustitución.">No necesita sustitución.</option>
                                </select>

                            2ª
                            No tiene clase.
                            <input type="hidden" name="profeSustitutoSegunda" value="No tiene clase." id="ListadoSustituciones_profeSustitutoSegunda"/>

                            3ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoTercera" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoTercera"/>

                            4ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoCuarta" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoCuarta"/>

                            5ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoQuinta" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoQuinta"/>

                            6ª
                            Se pierde apoyo.
                            <input type="hidden" name="profeSustitutoSexta" value="Se pierde apoyo." id="ListadoSustituciones_profeSustitutoSexta"/>

                <input type="hidden" name="profeSustituido" value="Robustiano" id="ListadoSustituciones_profeSustituido"/>
                <input type="hidden" name="diaSeleccionado" value="Lunes" id="ListadoSustituciones_diaSeleccionado"/>
                <input type="hidden" name="listaProfesASustituir" value="[ProfeASustituir@6f1d1207, ProfeASustituir@2c592e59]" id="ListadoSustituciones_listaProfesASustituir"/>

 Sustituciones para Robustiano

                            Hora
                            Profesor Propuesto
                            Profesor Sustituto

                            1ª
                                fulanito

                                <select name="selectbox2" class="selbox1">
                                    <option value="">--- Selecciona Profesor ---</option>
                                    <option value="Tera">Tera</option>
                                    <option value="No necesita sustitución.">No necesita sustitución.</option>
                                </select>

                            2ª
                                fulanito

                                    <select name="profeSustitutoSegunda" id="ListadoSustituciones_profeSustitutoSegunda" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Tera">Tera</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            3ª
                                fulanito

                                    <select name="profeSustitutoTercera" id="ListadoSustituciones_profeSustitutoTercera" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            4ª
                                fulanito

                                    <select name="profeSustitutoCuarta" id="ListadoSustituciones_profeSustitutoCuarta" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            5ª
                                fulanito

                                    <select name="profeSustitutoQuinta" id="ListadoSustituciones_profeSustitutoQuinta" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

                            6ª
                                fulanito

                                    <select name="profeSustitutoSexta" id="ListadoSustituciones_profeSustitutoSexta" required="true">
                                        <option value="">--- Selecciona Profesor ---</option>
                                        <option value="fulanito">fulanito</option>
                                        <option value="Lingüista">Lingüista</option>
                                        <option value="Locuaz">Locuaz</option>
                                        <option value="Luis">Luis</option>
                                        <option value="Tera">Tera</option>
                                        <option value="No necesita sustitución.">No necesita sustitución.</option>
                                    </select>

<input type="submit" id="ListadoSustituciones_0" value="Confirmar Sustitutos"/>

            </form>

Thanks in advance!

Body:
You can use .filter() of jquery.This method will check all the option from other select box and hide the option which is already selected.
Suppose you have selected Tera then this option will get hide from other select-box using hide() method . Working code :

$('select').change(function() {
var oldvar = $(this).attr('data-old') !== typeof undefined ? $(this).attr('data-old') : "";
  var newval = $("option:selected", this).val();
  //adding data-old attribute to select
  $(this).attr('data-old', newval);
  var val = $(this).val();
  var sel = $(this);

  if (val != "") {
    var otherselects = $('select').not(this).find('option');
    //checking if the value of other select option is same if yes then hide them
    otherselects.filter(function() {
      return $(this).text() == val;
    }).hide();
  } else if (val == "") {
    //showing option which is deselected by current select-box
    $('select').not(this).find('option[value="' + oldvar + '"]').show();

  }
});

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</head>

<body>
  <table>
    <thead>
      <tr>
        <td colspan="3"> Sustituciones para <b>Robustiano</b></td>
      </tr>
      <tr>
        <td>Hora</td>
        <td id="nowrap">Profesor Propuesto</td>
        <td id="nowrap">Profesor Sustituto</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class='centrado'>1ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="selectbox2" class="selbox1">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustituci&oacute;n.">No necesita sustituci&oacute;n.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>2ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoSegunda" id="ListadoSustituciones_profeSustitutoSegunda" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Tera">Tera</option>
            <option value="Lingüista">Lingüista</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>3ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoTercera" id="ListadoSustituciones_profeSustitutoTercera" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>4ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoCuarta" id="ListadoSustituciones_profeSustitutoCuarta" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>5ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoQuinta" id="ListadoSustituciones_profeSustitutoQuinta" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class='centrado'>6ª</td>
        <td class="centrado" id="nowrap">fulanito</td>
        <td class='centrado'>
          <select name="profeSustitutoSexta" id="ListadoSustituciones_profeSustitutoSexta" required="true">
            <option value="">--- Selecciona Profesor ---</option>
            <option value="fulanito">fulanito</option>
            <option value="Lingüista">Lingüista</option>
            <option value="Locuaz">Locuaz</option>
            <option value="Luis">Luis</option>
            <option value="Tera">Tera</option>
            <option value="No necesita sustitución.">No necesita sustitución.</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>
</body>

</html>

Try below code snippet :

$('select').change(function() {
  var oldvar = $(this).attr('data-old') !== typeof undefined ? $(this).attr('data-old') : "";
  var newval = $("option:selected", this).val();
  //adding data-old attribute to select
  $(this).attr('data-old', newval);
  var val = $(this).val();
  var sel = $(this);

  if (val != "") {
    var otherselects = $('select').not(this).find('option');
    //checking if the value of other select option is same if yes then hide them
    otherselects.filter(function() {
      return $(this).text() == val;
    }).hide();
    //add this
     $('select').not(this).find('option[value="' + oldvar + '"]').show();
  } else if (val == "") {
    //showing option which is deselected by current select-box
    $('select').not(this).find('option[value="' + oldvar + '"]').show();

  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<select>
  <option value="">--- Select ---</option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

<select>
  <option value="">--- Select ---</option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>


问:
fe_sendauth: no password supplied in Composer
I'm trying to create a DAG in a new composer environment to test connection to a Postgres db. But I'm getting fe_sendauth: no password supplied error in Airflow. I'm able to connect to this db in our old composer environment using the same conn_id (without password).

```<code>from airflow.operators.postgres_operator import PostgresOperator
from airflow.models import DAG, configuration
from airflow.utils.dates import days_ago

dag_params = {
    'dag_id': 'test_postgres_yellow_connection',
    'start_date': days_ago(1),
    'schedule_interval': None
}

with DAG(**dag_params) as dag:

    check_count =  PostgresOperator(
                     task_id="check_count",
                     postgres_conn_id='postgres_yellow',
                     sql="""
                            select count(1) from db_name.table_name;
                         """
                     )

    check_count
</code>```

Here is the Airflow log:

```<code>[2020-02-17 06:01:17,142] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count [2020-02-17 06:01:17,142] {postgres_operator.py:57} INFO - Executing:
[2020-02-17 06:01:17,143] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count                             select count(1) from db_name.table_name;
[2020-02-17 06:01:17,143] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count
[2020-02-17 06:01:17,165] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count [2020-02-17 06:01:17,165] {base_hook.py:83} INFO - Using connection to: id: postgres_yellow. Host: hotname, Port: xxx, Schema: schema_name, Login: xxxx, Password: None, extra: {}
[2020-02-17 06:01:17,217] {models.py:1846} ERROR - fe_sendauth: no password supplie

Traceback (most recent call last)
  File "/usr/local/lib/airflow/airflow/models.py", line 1714, in _run_raw_tas
    result = task_copy.execute(context=context
  File "/usr/local/lib/airflow/airflow/operators/postgres_operator.py", line 60, in execut
    self.hook.run(self.sql, self.autocommit, parameters=self.parameters
  File "/usr/local/lib/airflow/airflow/hooks/dbapi_hook.py", line 158, in ru
    with closing(self.get_conn()) as conn
  File "/usr/local/lib/airflow/airflow/hooks/postgres_hook.py", line 60, in get_con
    self.conn = psycopg2.connect(**conn_args
  File "/opt/python3.6/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connec
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync
psycopg2.OperationalError: fe_sendauth: no password supplied
</code>```

答:
Probably your old environment user's is set as a trustful user in your pg_hba.conf file. As you can see here in the trust auth method:

Allow the connection unconditionally. This method allows anyone that
  can connect to the PostgreSQL database server to login as any
  PostgreSQL user they wish, without the need for a password or any
  other authentication. See Section 19.3.1 for details.

Please let me know if it helps you

Body:
I'm trying to create a DAG in a new composer environment to test connection to a Postgres db. But I'm getting fe_sendauth: no password supplied error in Airflow. I'm able to connect to this db in our old composer environment using the same conn_id (without password).

from airflow.operators.postgres_operator import PostgresOperator
from airflow.models import DAG, configuration
from airflow.utils.dates import days_ago

dag_params = {
    'dag_id': 'test_postgres_yellow_connection',
    'start_date': days_ago(1),
    'schedule_interval': None
}

with DAG(**dag_params) as dag:

    check_count =  PostgresOperator(
                     task_id="check_count",
                     postgres_conn_id='postgres_yellow',
                     sql="""
                            select count(1) from db_name.table_name;
                         """
                     )

    check_count

Here is the Airflow log:

[2020-02-17 06:01:17,142] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count [2020-02-17 06:01:17,142] {postgres_operator.py:57} INFO - Executing:
[2020-02-17 06:01:17,143] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count                             select count(1) from db_name.table_name;
[2020-02-17 06:01:17,143] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count
[2020-02-17 06:01:17,165] {base_task_runner.py:101} INFO - Job 1403: Subtask check_count [2020-02-17 06:01:17,165] {base_hook.py:83} INFO - Using connection to: id: postgres_yellow. Host: hotname, Port: xxx, Schema: schema_name, Login: xxxx, Password: None, extra: {}
[2020-02-17 06:01:17,217] {models.py:1846} ERROR - fe_sendauth: no password supplie

Traceback (most recent call last)
  File "/usr/local/lib/airflow/airflow/models.py", line 1714, in _run_raw_tas
    result = task_copy.execute(context=context
  File "/usr/local/lib/airflow/airflow/operators/postgres_operator.py", line 60, in execut
    self.hook.run(self.sql, self.autocommit, parameters=self.parameters
  File "/usr/local/lib/airflow/airflow/hooks/dbapi_hook.py", line 158, in ru
    with closing(self.get_conn()) as conn
  File "/usr/local/lib/airflow/airflow/hooks/postgres_hook.py", line 60, in get_con
    self.conn = psycopg2.connect(**conn_args
  File "/opt/python3.6/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connec
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync
psycopg2.OperationalError: fe_sendauth: no password supplied


问:
cmbComboBox.SelectionStart always returns zero irrespective of cursor location
For some reason the "SelectionStart" property behaves differently from TextBox to ComboBox.

Create a TextBox and a ComboBox. Make sure DropDownStyle = DropDown (NOT DropDownList!)

Add these Leave events (same result if you use LostFocus event):

```<code>Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    Debug.Print("Textbox:  " & TextBox1.SelectionStart)
End Sub

Private Sub ComboBox1_Leave(sender As Object, e As EventArgs) Handles ComboBox1.Leave
    Debug.Print("ComboBox: " & ComboBox1.SelectionStart)
End Sub
</code>```

Now type text into each control and change focus from control to control, with the selection cursor in different places in the string.

I get this:

```<code>Textbox:  6
ComboBox: 0
Textbox:  8
ComboBox: 0
Textbox:  5
ComboBox: 0
Textbox:  4
ComboBox: 0
... and so on
</code>```

When the textbox loses focus, it returns the correct SelectionStart.
When the combobox loses focus, it always returns zero.

Is there a reason, solution or reasonable workaround? I cannot seem to intercept this without creating a new variable for each combo control, and storing the SelectionStart on every click and keypress event (assuming the user might click the mouse, use arrow keys or type characters).

答:
When you modify the OnLeave() sub in the class provided by @jmcilhinney it actually works nicely.</p>

```<code>Protected Overrides Sub OnLeave(e As EventArgs)
        'Remember the current selection.
        selectionStartTemp = SelectionStart
        selectionLengthTemp = SelectionLength

        MyBase.OnLeave(e) 'this has to go last because it modifies the SelectionStart...
End Sub
</code>```

Body:
For some reason the "SelectionStart" property behaves differently from TextBox to ComboBox.

Create a TextBox and a ComboBox. Make sure DropDownStyle = DropDown (NOT DropDownList!)

Add these Leave events (same result if you use LostFocus event):

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    Debug.Print("Textbox:  " & TextBox1.SelectionStart)
End Sub

Private Sub ComboBox1_Leave(sender As Object, e As EventArgs) Handles ComboBox1.Leave
    Debug.Print("ComboBox: " & ComboBox1.SelectionStart)
End Sub

Now type text into each control and change focus from control to control, with the selection cursor in different places in the string.

I get this:

Textbox:  6
ComboBox: 0
Textbox:  8
ComboBox: 0
Textbox:  5
ComboBox: 0
Textbox:  4
ComboBox: 0
... and so on

When the textbox loses focus, it returns the correct SelectionStart.
When the combobox loses focus, it always returns zero.

Is there a reason, solution or reasonable workaround? I cannot seem to intercept this without creating a new variable for each combo control, and storing the SelectionStart on every click and keypress event (assuming the user might click the mouse, use arrow keys or type characters).

Body:
When you modify the OnLeave() sub in the class provided by @jmcilhinney it actually works nicely.

Protected Overrides Sub OnLeave(e As EventArgs)
        'Remember the current selection.
        selectionStartTemp = SelectionStart
        selectionLengthTemp = SelectionLength

        MyBase.OnLeave(e) 'this has to go last because it modifies the SelectionStart...
End Sub


问:
How do I Replace a File in the Internal Storage of a Debuggable App?
I've got an android app, which is debuggable.

I can back up its important files to my PC like so:

```<code>adb exec-out run-as org.test.myapp cat files/afile > afile-from-phone
</code>```

But how do I put them back?

I.e. what command with copy the file

afile-from-phone

from my pc to

files/afile

in the storage area that belongs to org.test.myapp on the phone?

答:
If your device allows you to run adb as root you can do:

adb push afile-from-phone data/app/org.test.myapp/

Change "data" for "system" if it's a system app.

Body:
I've got an android app, which is debuggable.

I can back up its important files to my PC like so:

adb exec-out run-as org.test.myapp cat files/afile > afile-from-phone

But how do I put them back?

I.e. what command with copy the file

afile-from-phone

from my pc to

files/afile

in the storage area that belongs to org.test.myapp on the phone?