问:
How to wait for the end of a long process (on another thread)?
I'm writing an application (for personal use) that allows me to send a string over usb to an Arduino.

I wrote this method for sending the data:

```<code>    /**
     * Sends the data to the Arduino.
     * A new Thread is created for sending the data.
     * A transmission cool-down is started before send() method can be used again.
     * @param data the data to send to the Arduino
     */
    public void send(String data) {
        if (connected && !sending) {
            // Set 'sending' to true so only 1 Thread can be active at a time
            sending = true;
            // Create a new thread for sending the data
            Thread thread = new Thread(() -> {
                // Send the data
                PrintWriter output = new PrintWriter(chosenPort.getOutputStream());
                output.print(data);
                System.out.println("Data sended");
                output.flush();
                // Wait for the transmission cool-down and set 'sending' to false to allow for another Thread to send data
                try { Thread.sleep(transmissionCoolDown); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); }
                sending = false;
                System.out.println("cooldown is over");
            });
            thread.start();
        }
    }
</code>```

sending is a boolean value that I use to indicate whether a Thread is sending data. The transmissionCooldown is simply to enforce a certain waiting period before data can be sent again.

And this is where the method is being used:

```<code>    @FXML
    private void sendClicked() {
        // Only do something if a connection is active and an image is selected.
        // Should be unnecessary since the send button is only enables when both are true.
        if (connected && selectedIV.getImage() != null) {
            if (!sending) {
                // Save the original text of the send button and disable the disconnect button
                String ogText = sendButton.getText();
                System.out.println(ogText);
                connectButton.setDisable(true);
                // If the data has not been saved before, get the data by formatting the image
                if (data == null) {
                    data = imgCon.toStringFormat(true);
                }
                ardComm.send(data);
                // While the ArduinoCommunicator is busy sending, change the text on the send button to indicate the data is being transmitted
                sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);
                connectButton.setDisable(false);
            }
        }
    }
</code>```

sendButton is the JavaFX Button that calls the sendClicked() method and ardCom is and instance of the class that contains the send() method. isSending() simply returns the sending attribute of the ardCom, which is set to true at the start of the send() method and set to false when the Thread is done sending.

The problem is with this piece of code:

```<code>    sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);
</code>```

I'm trying to set the sendButton's text to busy to indicate that the data is being sent, then loop until the data transmission is finished (sending is set to false) and end it with changing the text on the sendButton back to the original text. I know this is probably not the best way to achieve this, but I was playing around and could not figure out why this is not working as expected.

The problem is that for some reason, the while loop never ends.

答:
Think of JavaFx Application as an application that runs on a single thread.

When this thread is busy with running the long while loop (while (ardComm.isSending()), it does not update the gui. The gui becomes unresponsive (freezes).

For more information see Implementing long-running tasks on the JavaFX Application thread inevitably makes an application UI unresponsive.

Consider listening to change events rather than waiting on the JavaFx application thread:

```<code>import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class Main extends Application {

    private Button sendButton;

    @Override
    public void start(Stage primaryStage) throws Exception{

        ArdCom ardComm = new ArdCom();
        sendButton = new Button("Send");
        sendButton.setOnAction(event-> ardComm.send());
        ardComm.isSending().addListener((observable, oldValue, newValue) -> {
            if(newValue){
                Platform.runLater (() ->sendButton.setText("Busy"));
            }else{
                Platform.runLater (() ->sendButton.setText("Send"));
            }
        });
        AnchorPane root = new AnchorPane(sendButton);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

class ArdCom {

    private final ReadOnlyBooleanWrapper sending = new ReadOnlyBooleanWrapper(false);

    void send() {//synchronize if accessed from multi thread

        if (! sending.get() ) {
            sending.set(true);
            Thread thread = new Thread(() -> {
                System.out.println("Send started");
                try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
                sending.set(false);
                System.out.println("Send completed");
            });
            thread.start();
        }
    }

    SimpleBooleanProperty isSending(){
        return sending;
    }
}
</code>```

Body:
I'm writing an application (for personal use) that allows me to send a string over usb to an Arduino.

I wrote this method for sending the data:

    /**
     * Sends the data to the Arduino.
     * A new Thread is created for sending the data.
     * A transmission cool-down is started before send() method can be used again.
     * @param data the data to send to the Arduino
     */
    public void send(String data) {
        if (connected && !sending) {
            // Set 'sending' to true so only 1 Thread can be active at a time
            sending = true;
            // Create a new thread for sending the data
            Thread thread = new Thread(() -> {
                // Send the data
                PrintWriter output = new PrintWriter(chosenPort.getOutputStream());
                output.print(data);
                System.out.println("Data sended");
                output.flush();
                // Wait for the transmission cool-down and set 'sending' to false to allow for another Thread to send data
                try { Thread.sleep(transmissionCoolDown); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); }
                sending = false;
                System.out.println("cooldown is over");
            });
            thread.start();
        }
    }

sending is a boolean value that I use to indicate whether a Thread is sending data. The transmissionCooldown is simply to enforce a certain waiting period before data can be sent again.

And this is where the method is being used:

    @FXML
    private void sendClicked() {
        // Only do something if a connection is active and an image is selected.
        // Should be unnecessary since the send button is only enables when both are true.
        if (connected && selectedIV.getImage() != null) {
            if (!sending) {
                // Save the original text of the send button and disable the disconnect button
                String ogText = sendButton.getText();
                System.out.println(ogText);
                connectButton.setDisable(true);
                // If the data has not been saved before, get the data by formatting the image
                if (data == null) {
                    data = imgCon.toStringFormat(true);
                }
                ardComm.send(data);
                // While the ArduinoCommunicator is busy sending, change the text on the send button to indicate the data is being transmitted
                sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);
                connectButton.setDisable(false);
            }
        }
    }

sendButton is the JavaFX Button that calls the sendClicked() method and ardCom is and instance of the class that contains the send() method. isSending() simply returns the sending attribute of the ardCom, which is set to true at the start of the send() method and set to false when the Thread is done sending.

The problem is with this piece of code:

    sendButton.setText("busy");
                while (ardComm.isSending()) {

                }
                // Restore the text on the send button
                sendButton.setText(ogText);

I'm trying to set the sendButton's text to busy to indicate that the data is being sent, then loop until the data transmission is finished (sending is set to false) and end it with changing the text on the sendButton back to the original text. I know this is probably not the best way to achieve this, but I was playing around and could not figure out why this is not working as expected.

The problem is that for some reason, the while loop never ends.

Body:
Think of JavaFx Application as an application that runs on a single thread.

When this thread is busy with running the long while loop (while (ardComm.isSending()), it does not update the gui. The gui becomes unresponsive (freezes).

For more information see Implementing long-running tasks on the JavaFX Application thread inevitably makes an application UI unresponsive.

Consider listening to change events rather than waiting on the JavaFx application thread:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class Main extends Application {

    private Button sendButton;

    @Override
    public void start(Stage primaryStage) throws Exception{

        ArdCom ardComm = new ArdCom();
        sendButton = new Button("Send");
        sendButton.setOnAction(event-> ardComm.send());
        ardComm.isSending().addListener((observable, oldValue, newValue) -> {
            if(newValue){
                Platform.runLater (() ->sendButton.setText("Busy"));
            }else{
                Platform.runLater (() ->sendButton.setText("Send"));
            }
        });
        AnchorPane root = new AnchorPane(sendButton);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

class ArdCom {

    private final ReadOnlyBooleanWrapper sending = new ReadOnlyBooleanWrapper(false);

    void send() {//synchronize if accessed from multi thread

        if (! sending.get() ) {
            sending.set(true);
            Thread thread = new Thread(() -> {
                System.out.println("Send started");
                try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
                sending.set(false);
                System.out.println("Send completed");
            });
            thread.start();
        }
    }

    SimpleBooleanProperty isSending(){
        return sending;
    }
}


来源: stackexchange

问:
How do I enter a new line/move to the next line without executing command while in a shell or bash if the command has more than 1 line?
so i'm trying to follow a tutorial on creating an Azure VM and the entire tutorial is from the CLI. It is specifically using bash. I know next to nothing about using CLI so it is pretty intimdating. Anyways all the commands look like this in the tutorial:

```<code>az vm create \
  --resource-group myResourceGroup \
  --name myVM \
  --image UbuntuLTS \
  --admin-username azureuser \
  --generate-ssh-keys
</code>```

But when I try to make a new line and go to that new line to enter in the argument/parameter it keeps trying to execute the command and i cant execute anything since obviously what im typing in is missing parameters:

```<code>az vm create \ --resource-group ShahVMAzureUB \ --name ShahVM \ --imageUbuntuLTS \ --admin-username shahjacob \ --generate-ssh-keysaz vm create
: error: the following arguments are required: --name/-n, --resource-group/-g
</code>```

答:
Quoteth the bash man page

If a \<newline> pair appears, and the backslash is not  itself
         quoted, the \<newline> is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).

So, you literally need a newline (press ENTER) after you type the \ to tell the shell you want to enter more parameters but on a separate line.

Generally this is used for print (or even Stackoverflow answers) so you don't have one mega-line that's hard to grok.  If you want it all on one line, remove the \ between the parameters.

ContentLicense: CC BY-SA 4.0

Body:
so i'm trying to follow a tutorial on creating an Azure VM and the entire tutorial is from the CLI. It is specifically using bash. I know next to nothing about using CLI so it is pretty intimdating. Anyways all the commands look like this in the tutorial:

az vm create \
  --resource-group myResourceGroup \
  --name myVM \
  --image UbuntuLTS \
  --admin-username azureuser \
  --generate-ssh-keys

But when I try to make a new line and go to that new line to enter in the argument/parameter it keeps trying to execute the command and i cant execute anything since obviously what im typing in is missing parameters:

az vm create \ --resource-group ShahVMAzureUB \ --name ShahVM \ --imageUbuntuLTS \ --admin-username shahjacob \ --generate-ssh-keysaz vm create
: error: the following arguments are required: --name/-n, --resource-group/-g


问:
How to find the first and last of one of several characters in a list of strings?
So I have a list of strings such as this:

```<code>my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
</code>```

I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last.

I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it.

The output I wanted was something like this:

```<code>first_positions=[3,2,10,1,4]
last_positions=[17,7,25,11,23]
</code>```

Thanks in advance for any answer

答:
Check string is alphabet or not and then add index of string in the list. if you want to find first positions then by default function takes first then it returns the first indexes of string else it returns the last indexes

```<code>my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
def get_index(string,find='first'):
  index_lt=[]
  for idx,char in enumerate(string):
    if char.isalpha():
      index_lt.append(idx)
  return index_lt[0] if find=='first' else index_lt[-1]

print([get_index(string) for string in my_list])
#[3, 2, 10, 1, 4]
print([get_index(string,find='last') for string in my_list])
#[17, 7, 25, 10, 23]
</code>```

Body:
So I have a list of strings such as this:

my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]

I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last.

I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it.

The output I wanted was something like this:

first_positions=[3,2,10,1,4]
last_positions=[17,7,25,11,23]

Thanks in advance for any answer

Body:
Check string is alphabet or not and then add index of string in the list. if you want to find first positions then by default function takes first then it returns the first indexes of string else it returns the last indexes

my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
def get_index(string,find='first'):
  index_lt=[]
  for idx,char in enumerate(string):
    if char.isalpha():
      index_lt.append(idx)
  return index_lt[0] if find=='first' else index_lt[-1]

print([get_index(string) for string in my_list])
#[3, 2, 10, 1, 4]
print([get_index(string,find='last') for string in my_list])
#[17, 7, 25, 10, 23]


问:
Does GAS support string literals as numeric constants like NASM does?
In NASM (Intel), I can write this:

```<code>mov rax, `Hello!\n`
</code>```

And it's equivalent to this:

```<code>mov rax, 0xa216f6c6c6548
</code>```

Does GAS (AT&T) support any equivalent shorthand for that, or am I stuck writing this?

```<code>movabsq $0xa216f6c6c6548, %rax
</code>```

答: Unfortunately GAS doesn't have such a feature. Given that GAS was really designed for assembly language output by compilers, my best guess is this feature was probably never seen as something that added much value. Had GAS originally been designed for humans to generate assembly code then such a feature likely would have been added.</p>

Body:
In NASM (Intel), I can write this:

mov rax, `Hello!\n`

And it's equivalent to this:

mov rax, 0xa216f6c6c6548

Does GAS (AT&T) support any equivalent shorthand for that, or am I stuck writing this?

movabsq $0xa216f6c6c6548, %rax


问:
DevExpress GridControl seletcted rows belong to Parent View or Child View in Master-Details mode
I'm using Dev-express GridControl in my Win-forms project.

How can I detect that selected rows belongs to a Parent View or a Child View in Master-Details mode?

答: To get a GridView instance in which a user just selected a row, use the GridControl.FocusedView property.</p>


问:
Parse string in nodejs to an array
How can I convert following string into an array in nodejs?

```<code>"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"
</code>```

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?

答:
I know people does't like to use eval(), but for doing some kind of things is useful.

Check this:

var string = "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]";
var array = eval(string);

console.log(array);```

Title: Parse string in nodejs to an array

Body:
How can I convert following string into an array in nodejs?

"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?


问:
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255
I moved my project from desk to another.

When I run php artisan it does not work.

I tried to run composer update, but it returns the error

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 255

答:
Same issue when I update laravel from 6.x to 7.x

I tried the most voted answer but it didn't work, then I used php artisan serve I noticed that:

```<code>RuntimeException

In order to use the Auth::routes() method, please install the laravel/ui package.
</code>```

Try composer require laravel/ui maybe it will work.

Body:
Same issue when I update laravel from 6.x to 7.x

I tried the most voted answer but it didn't work, then I used php artisan serve I noticed that:

RuntimeException

In order to use the Auth::routes() method, please install the laravel/ui package.

Try composer require laravel/ui maybe it will work.


问:
How restart a stopped docker container
I launch a docker container from an image with the following command:

```<code>$ docker run -d myimage /bin/bash -c "mycommand"
</code>```

When "mycommand" is finished, the container is stopped (I suppose it is stopped), but it is not deleted, because I can see it with this command:

```<code>$ docker ps -a
</code>```

Is there any way to restart this container with the same parameters and keep data generated by mycommand?

答:
It should be</p>

```<code>$ docker restart container_id # OR
$ docker restart container_name
</code>```

ContentLicense: CC BY-SA 3.0

Title: How restart a stopped docker container

Body:
I launch a docker container from an image with the following command:

$ docker run -d myimage /bin/bash -c "mycommand"

When "mycommand" is finished, the container is stopped (I suppose it is stopped), but it is not deleted, because I can see it with this command:

$ docker ps -a

Is there any way to restart this container with the same parameters and keep data generated by mycommand?

Body:
It should be

$ docker restart container_id # OR
$ docker restart container_name


问:
How to find the total disk space in chef?
I wanted to find the total disk space available in the machine through chef. I could find a way to find individual partition space via node['filesystem']['device_name'], but is there any way to find total disk space?

答: you can use the command df -Th --total and last line of this command print the total assigned space and total used.</p>


问:
AWS SNS not giving mobile option
I am trying to use AWS SNS along with FCM to send push notification to my android application.

AWS documentation says:

Create a platform application in Amazon SNS

Open the Amazon SNS console.

Open the left navigation pane, expand Mobile, and then choose Push notifications.

But on my Amazon SNS page, I can not see Mobile in the left navigation pane.

Am I missing something?

Somewhere I read that Amazon SNS to mobiles are not supported in UK. Is it true?

答:
Depending upon your screen size, the left navigation pane might be hidden.

Click the "three lines" on the left side of the screen. It should expand into a menu:

Title: AWS SNS not giving mobile option


问:
Want’s to Marshall different set of POJO fields based on Spring Profile
I have a POJO Deatils having following fields.
    1. String Name
    2. String Add
    3. String Phone
.
For profile ‘x’ first two fields should marshal in XML and for other profile first and last field should marshal in XML.
Note: no field will be null for any profile.

答:
I feel like it would be better to leave the Marshaller alone. It may be tricky to extend and customize the marshaller to fit your needs per Spring profile.

If our goal is to serialize different payloads depending on Spring profile, I'd recommend maybe a converter/factory that takes in the POJO (that has all the fields) and spits out a Data Transfer Object (DTO) for the specific profile.

Perhaps the following could work unless there is another end-goal in mind.

public class Details { ... }
```

<pre class="lang-java prettyprint-override"><code>// essentially a marker interface
public interface MyDto {
}

public class DtoA implements MyDto {
   private String name;
   private String add;
}

public class DtoB implements MyDto {
   private String name;
   private String phone;
}
</code>```

public interface DtoConverter {
   MyDto convert(Details details);
}

public class DtoConverterA implements DtoConverter { ... }
public class DtoConverterB implements DtoConverter { ... }
```

<pre class="lang-java prettyprint-override"><code>@Configuration
public class MyConfiguration {
   @Bean
   @Profile("a")
   public DtoConverter dtoConverterA() {
       return new DtoConverterA();
   }

   @Bean
   @Profile("b")
   public DtoConverter dtoConverterB() {
      return new DtoConverterB();
   }
}
</code>```

Body:
I feel like it would be better to leave the Marshaller alone. It may be tricky to extend and customize the marshaller to fit your needs per Spring profile.

If our goal is to serialize different payloads depending on Spring profile, I'd recommend maybe a converter/factory that takes in the POJO (that has all the fields) and spits out a Data Transfer Object (DTO) for the specific profile.

Perhaps the following could work unless there is another end-goal in mind.

public class Details { ... }

// essentially a marker interface
public interface MyDto {
}

public class DtoA implements MyDto {
   private String name;
   private String add;
}

public class DtoB implements MyDto {
   private String name;
   private String phone;
}

public interface DtoConverter {
   MyDto convert(Details details);
}

public class DtoConverterA implements DtoConverter { ... }
public class DtoConverterB implements DtoConverter { ... }

@Configuration
public class MyConfiguration {
   @Bean
   @Profile("a")
   public DtoConverter dtoConverterA() {
       return new DtoConverterA();
   }

   @Bean
   @Profile("b")
   public DtoConverter dtoConverterB() {
      return new DtoConverterB();
   }
}


问:
Hovering another instance makes my text move
So i remade my website, and now i´m using flex layout, which makes my work a lot easier, i got a hover effect upon my input, so every time i hover a icon my input get shown but this input is moving to the right, when it was supposed to move to the left, which in case is making my layout move along with it
sorry for poor english, still learning,
here´s my code:

@import url("./src/assets/fonts/Roboto.zip");
@import url("./src/assets/fonts/Open_Sans.zip");
@import url("./src/assets/fonts/Playfair_Display.zip");

* {
    margin: 0;
    padding: 0;
    outline: none;
    box-sizing: border-box;
}

body {
    width: 90%;
    margin: 0 auto;
}

header {
    display: flex;
    background-color: red;
}

header ul {
    list-style: none;
}

header h1 {
    font-family: 'Playfair_Display', serif;
}

header #search-box {
    display: flex;
}

/*POSIÇÃO DOS ÍCONES*/
header #barsPosition {
    margin: auto 0 auto 3%;
}

header #search-box {
    margin: auto 0 auto 15%;
}

header #inputBar {
    margin: 6% 0 auto 0;
}

header #searchPosition {
    margin: auto 0 auto 2%;
}

header h1 {
    margin: auto;
}

header #shopPosition {
    margin: auto 3% auto auto;
}
/*POSIÇÃO DOS ÍCONES*/

/*ATRIBUTO DOS ICONES*/
.barsMenu, .searchIcon, .shoppingBag {
    width: 32px;
    height:32px;
    display: flex;
    cursor: pointer;
}
/*ATRIBUTO DOS ICONES*/

/*RESPONSIVIDADE DO SITE*/
@media screen and (max-width: 2560px) {
    header h1 {
      font-size: 3.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu40px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search40px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag40px.svg");}
    /*ÍCONES*/
    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 40px;
        height:40px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1440px) {
    header h1 {
      font-size: 2.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu32px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search32px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag32px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 32px;
        height:32px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1024px) {
    header h1 {
      font-size: 2.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu24px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search24px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag24px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 24px;
        height:24px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 768px) {
    header h1 {
      font-size: 1.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu16px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search16px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag16px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 16px;
        height:16px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 425px) {
    header h1 {
        font-size: 1.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu12px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search12px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag12px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 12px;
        height:12px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 375px) {
    header h1 {
      font-size: 0.5em;
    }

}

@media screen and (max-width: 320px) {
    header h1 {
      font-size: 0.5em;
    }

}
/*RESPONSIVIDADE DO SITE*/

/*HEADER INPUT BAR*/
input {
    width: 0px;
    border: none;
    outline: none;
    color: white;
    background: none;
    transition: 0.4s ease-in;
    border-bottom: 0.3px solid black;
}

header input#inputBar {
    color: black;
    font-weight: 300;
    font-family: 'Roboto', sans-serif;
    font-size: 1em;
}

#search-box:hover > .inputBar {
    width: 200px;
}
/*HEADER INPUT BAR*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-BR">
  <head>
      <title>Bunny&copy</title>

      <meta charset="UTF-8">
      <meta name="author" content="Vitor N">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <link rel="stylesheet" href="./global.css">
      <link rel="icon" href="./src/assets/image/logo.jpg">
      <link rel="stylesheet" href="./src/styles/index.css">
  </head>

  <body>
      <header>
              <i id="barsPosition" class="barsMenu"></i>

              <div id="search-box">
                  <input type="text" placeholder="Pesquise" class="inputBar">
                  <i id="searchPosition" class="searchIcon"></i>
              </div>

              <h1>BUNNY</h1>

              <i id="shopPosition" class="shoppingBag"></i>
      </header>
      <hr>
      <main>
      </main>
      <footer class="red"></footer>
  </body>
</html></code>```

Well what it should do is go to the left instead of right

答:
Give it width already and use transform: scale property to get this done.
Increase or decrease the input width as per your need, and make sure it always have the sufficient width on left to grow.

@import url("./src/assets/fonts/Roboto.zip");
@import url("./src/assets/fonts/Open_Sans.zip");
@import url("./src/assets/fonts/Playfair_Display.zip");

* {
    margin: 0;
    padding: 0;
    outline: none;
    box-sizing: border-box;
}

body {
    width: 90%;
    margin: 0 auto;
}

header {
    display: flex;
    background-color: red;
}

header ul {
    list-style: none;
}

header h1 {
    font-family: 'Playfair_Display', serif;
}

header #search-box {
    display: flex;
}

/*POSIÇÃO DOS ÍCONES*/
header #barsPosition {
    margin: auto 0 auto 3%;
}

header #search-box {
    margin: auto 0 auto 15%;
}

header #inputBar {
    margin: 6% 0 auto 0;
}

header #searchPosition {
    margin: auto 0 auto 2%;
}

header h1 {
    margin: auto;
}

header #shopPosition {
    margin: auto 3% auto auto;
}
/*POSIÇÃO DOS ÍCONES*/

/*ATRIBUTO DOS ICONES*/
.barsMenu, .searchIcon, .shoppingBag {
    width: 32px;
    height:32px;
    display: flex;
    cursor: pointer;
}
/*ATRIBUTO DOS ICONES*/

/*RESPONSIVIDADE DO SITE*/
@media screen and (max-width: 2560px) {
    header h1 {
      font-size: 3.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu40px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search40px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag40px.svg");}
    /*ÍCONES*/
    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 40px;
        height:40px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1440px) {
    header h1 {
      font-size: 2.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu32px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search32px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag32px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 32px;
        height:32px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1024px) {
    header h1 {
      font-size: 2.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu24px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search24px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag24px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 24px;
        height:24px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 768px) {
    header h1 {
      font-size: 1.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu16px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search16px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag16px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 16px;
        height:16px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 425px) {
    header h1 {
        font-size: 1.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu12px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search12px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag12px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 12px;
        height:12px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 375px) {
    header h1 {
      font-size: 0.5em;
    }

}

@media screen and (max-width: 320px) {
    header h1 {
      font-size: 0.5em;
    }

}
/*RESPONSIVIDADE DO SITE*/

/*HEADER INPUT BAR*/
input {
position: absolute;
    width: 100px;
    border: none;
    outline: none;
    color: white;
    background: none;
    transition: 0.4s ease-in;
    border-bottom: 0.3px solid black;
    transform-origin: right;
    transform: scaleX(0);
    right: 0;
}
header #search-box {
    position: relative;
}
header input#inputBar {
    color: black;
    font-weight: 300;
    font-family: 'Roboto', sans-serif;
    font-size: 1em;
}

#search-box:hover > .inputBar {
    transform: scale(1);
}
/*HEADER INPUT BAR*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-BR">
  <head>
      <title>Bunny&copy</title>

      <meta charset="UTF-8">
      <meta name="author" content="Vitor N">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <link rel="stylesheet" href="./global.css">
      <link rel="icon" href="./src/assets/image/logo.jpg">
      <link rel="stylesheet" href="./src/styles/index.css">
  </head>

  <body>
      <header>
              <i id="barsPosition" class="barsMenu"></i>

              <div id="search-box">
                  <input type="text" placeholder="Pesquise" class="inputBar">
                  <i id="searchPosition" class="searchIcon"></i>
              </div>

              <h1>BUNNY</h1>

              <i id="shopPosition" class="shoppingBag"></i>
      </header>
      <hr>
      <main>
      </main>
      <footer class="red"></footer>
  </body>
</html></code>```

Body:
So i remade my website, and now i´m using flex layout, which makes my work a lot easier, i got a hover effect upon my input, so every time i hover a icon my input get shown but this input is moving to the right, when it was supposed to move to the left, which in case is making my layout move along with it
sorry for poor english, still learning,
here´s my code:

@import url("./src/assets/fonts/Roboto.zip");
@import url("./src/assets/fonts/Open_Sans.zip");
@import url("./src/assets/fonts/Playfair_Display.zip");

* {
    margin: 0;
    padding: 0;
    outline: none;
    box-sizing: border-box;
}

body {
    width: 90%;
    margin: 0 auto;
}

header {
    display: flex;
    background-color: red;
}

header ul {
    list-style: none;
}

header h1 {
    font-family: 'Playfair_Display', serif;
}

header #search-box {
    display: flex;
}

/*POSIÇÃO DOS ÍCONES*/
header #barsPosition {
    margin: auto 0 auto 3%;
}

header #search-box {
    margin: auto 0 auto 15%;
}

header #inputBar {
    margin: 6% 0 auto 0;
}

header #searchPosition {
    margin: auto 0 auto 2%;
}

header h1 {
    margin: auto;
}

header #shopPosition {
    margin: auto 3% auto auto;
}
/*POSIÇÃO DOS ÍCONES*/

/*ATRIBUTO DOS ICONES*/
.barsMenu, .searchIcon, .shoppingBag {
    width: 32px;
    height:32px;
    display: flex;
    cursor: pointer;
}
/*ATRIBUTO DOS ICONES*/

/*RESPONSIVIDADE DO SITE*/
@media screen and (max-width: 2560px) {
    header h1 {
      font-size: 3.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu40px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search40px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag40px.svg");}
    /*ÍCONES*/
    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 40px;
        height:40px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1440px) {
    header h1 {
      font-size: 2.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu32px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search32px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag32px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 32px;
        height:32px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1024px) {
    header h1 {
      font-size: 2.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu24px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search24px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag24px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 24px;
        height:24px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 768px) {
    header h1 {
      font-size: 1.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu16px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search16px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag16px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 16px;
        height:16px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 425px) {
    header h1 {
        font-size: 1.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu12px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search12px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag12px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 12px;
        height:12px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 375px) {
    header h1 {
      font-size: 0.5em;
    }

}

@media screen and (max-width: 320px) {
    header h1 {
      font-size: 0.5em;
    }

}
/*RESPONSIVIDADE DO SITE*/

/*HEADER INPUT BAR*/
input {
    width: 0px;
    border: none;
    outline: none;
    color: white;
    background: none;
    transition: 0.4s ease-in;
    border-bottom: 0.3px solid black;
}

header input#inputBar {
    color: black;
    font-weight: 300;
    font-family: 'Roboto', sans-serif;
    font-size: 1em;
}

#search-box:hover > .inputBar {
    width: 200px;
}
/*HEADER INPUT BAR*/

<!DOCTYPE html>

      <title>Bunny&copy</title>

      <meta charset="UTF-8">
      <meta name="author" content="Vitor N">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <link rel="stylesheet" href="./global.css">
      <link rel="icon" href="./src/assets/image/logo.jpg">
      <link rel="stylesheet" href="./src/styles/index.css">

                  <input type="text" placeholder="Pesquise" class="inputBar">
                  

BUNNY

              

Well what it should do is go to the left instead of right

Body:
Give it width already and use transform: scale property to get this done.
Increase or decrease the input width as per your need, and make sure it always have the sufficient width on left to grow.

@import url("./src/assets/fonts/Roboto.zip");
@import url("./src/assets/fonts/Open_Sans.zip");
@import url("./src/assets/fonts/Playfair_Display.zip");

* {
    margin: 0;
    padding: 0;
    outline: none;
    box-sizing: border-box;
}

body {
    width: 90%;
    margin: 0 auto;
}

header {
    display: flex;
    background-color: red;
}

header ul {
    list-style: none;
}

header h1 {
    font-family: 'Playfair_Display', serif;
}

header #search-box {
    display: flex;
}

/*POSIÇÃO DOS ÍCONES*/
header #barsPosition {
    margin: auto 0 auto 3%;
}

header #search-box {
    margin: auto 0 auto 15%;
}

header #inputBar {
    margin: 6% 0 auto 0;
}

header #searchPosition {
    margin: auto 0 auto 2%;
}

header h1 {
    margin: auto;
}

header #shopPosition {
    margin: auto 3% auto auto;
}
/*POSIÇÃO DOS ÍCONES*/

/*ATRIBUTO DOS ICONES*/
.barsMenu, .searchIcon, .shoppingBag {
    width: 32px;
    height:32px;
    display: flex;
    cursor: pointer;
}
/*ATRIBUTO DOS ICONES*/

/*RESPONSIVIDADE DO SITE*/
@media screen and (max-width: 2560px) {
    header h1 {
      font-size: 3.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu40px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search40px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag40px.svg");}
    /*ÍCONES*/
    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 40px;
        height:40px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1440px) {
    header h1 {
      font-size: 2.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu32px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search32px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag32px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 32px;
        height:32px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1024px) {
    header h1 {
      font-size: 2.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu24px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search24px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag24px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 24px;
        height:24px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 768px) {
    header h1 {
      font-size: 1.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu16px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search16px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag16px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 16px;
        height:16px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 425px) {
    header h1 {
        font-size: 1.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu12px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search12px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag12px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 12px;
        height:12px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 375px) {
    header h1 {
      font-size: 0.5em;
    }

}

@media screen and (max-width: 320px) {
    header h1 {
      font-size: 0.5em;
    }

}
/*RESPONSIVIDADE DO SITE*/

/*HEADER INPUT BAR*/
input {
position: absolute;
    width: 100px;
    border: none;
    outline: none;
    color: white;
    background: none;
    transition: 0.4s ease-in;
    border-bottom: 0.3px solid black;
    transform-origin: right;
    transform: scaleX(0);
    right: 0;
}
header #search-box {
    position: relative;
}
header input#inputBar {
    color: black;
    font-weight: 300;
    font-family: 'Roboto', sans-serif;
    font-size: 1em;
}

#search-box:hover > .inputBar {
    transform: scale(1);
}
/*HEADER INPUT BAR*/

<!DOCTYPE html>
<html lang="pt-BR">
  <head>
      <title>Bunny&copy</title>

      <meta charset="UTF-8">
      <meta name="author" content="Vitor N">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <link rel="stylesheet" href="./global.css">
      <link rel="icon" href="./src/assets/image/logo.jpg">
      <link rel="stylesheet" href="./src/styles/index.css">
  </head>

  <body>
      <header>
              <i id="barsPosition" class="barsMenu"></i>

              <div id="search-box">
                  <input type="text" placeholder="Pesquise" class="inputBar">
                  <i id="searchPosition" class="searchIcon"></i>
              </div>

              <h1>BUNNY</h1>

              <i id="shopPosition" class="shoppingBag"></i>
      </header>
      <hr>
      <main>
      </main>
      <footer class="red"></footer>
  </body>
</html>


问:
ValueError: Cannot feed value of shape (1, 260, 540, 3) for Tensor 'input_image: 0', which has shape '(?, 160, 160, 3)'
iam new to tensorflow, i am geeting this value error for some images while on other images works fine. is there anything wrong with the code?

error:

ValueError: Cannot feed value of shape (1, 260, 540, 3) for Tensor 'input_image: 0', which has shape '(?, 160, 160, 3)'
tensorflow version==1.14

dlib version==1.19

code:

```<code>import argparse
import os

import cv2
import dlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
from numpy import array
import inception_resnet_v1

os.environ['CUDA_VISIBLE_DEVICES'] = ''

def eval(aligned_images, model_path):
    with tf.Graph().as_default():
        sess = tf.Session()
        images_pl = tf.placeholder(tf.float32, shape=[None, 160, 160, 3], name='input_image')
        images = tf.map_fn(lambda frame: tf.reverse_v2(frame, [-1]), images_pl) #BGR TO RGB
        images_norm = tf.map_fn(lambda frame: tf.image.per_image_standardization(frame), images)
        train_mode = tf.placeholder(tf.bool)
        age_logits, gender_logits, _ = inception_resnet_v1.inference(images_norm, keep_probability=0.8,
                                                                     phase_train=train_mode,
                                                                     weight_decay=1e-5)
        gender = tf.argmax(tf.nn.softmax(gender_logits), 1)
        age_ = tf.cast(tf.constant([i for i in range(0, 101)]), tf.float32)
        age = tf.reduce_sum(tf.multiply(tf.nn.softmax(age_logits), age_), axis=1)
        init_op = tf.group(tf.global_variables_initializer(),
                           tf.local_variables_initializer())
        sess.run(init_op)
        saver = tf.train.Saver()
        ckpt = tf.train.get_checkpoint_state(model_path)
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)
            print("restore and continue training!")
        else:
            pass
        return sess.run([age, gender], feed_dict={images_pl: aligned_images, train_mode: False})

def load_image(image_path, shape_predictor):
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor(shape_predictor)
    fa = FaceAligner(predictor, desiredFaceWidth=160)
    image = cv2.imread(image_path, cv2.IMREAD_COLOR)

    # image = imutils.resize(image, width=256)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    rects = detector(gray, 2)
    rect_nums = len(rects)
    XY, aligned_images = [], []
    if rect_nums == 0:
        aligned_images.append(image)
        return aligned_images, image, rect_nums, XY
    else:
        for i in range(rect_nums):
            aligned_image = fa.align(image, gray, rects[i])
            aligned_images.append(aligned_image)
            (x, y, w, h) = rect_to_bb(rects[i])
            image = cv2.rectangle(image, (x, y), (x + w, y + h), color=(255, 0, 0), thickness=2)
            XY.append((x, y))
        return np.array(aligned_images), image, rect_nums, XY

# def draw_label(image, point, ages, genders, font=cv2.FONT_HERSHEY_COMPLEX, font_scale=1, thickness=1):
#     for i in range(len(point)):
#         label = "{}, {}".format(int(ages[i]), "F" if genders[i] == 0 else "M")
#         size = cv2.getTextSize(label, font, font_scale, thickness)[0]
#         x, y = point[i]
#         # cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
#         cv2.putText(image, label, (x, np.max(y - 5, 0)), font, font_scale, (255, 255, 255), thickness)

def draw_label(image, point, ages, genders,font=cv2.FONT_HERSHEY_SIMPLEX,
               font_scale=1, thickness=2):
    for i in range(len(point)):
        label = "{}, {}".format(int(ages[i]), "F" if genders[i] == 0 else "M")
        size = cv2.getTextSize(label, font, font_scale, thickness)[0]
        x, y = point[i]
        cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
        cv2.putText(image, label, point[i], font, font_scale, (255, 255, 255), thickness)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--image_path", "--I", required=True, type=str, help="Image Path")
    parser.add_argument("--model_path", "--M", default="./models", type=str, help="Model Path")
    parser.add_argument("--shape_detector", "--S", default="shape_predictor_68_face_landmarks.dat", type=str,
                        help="Shape Detector Path")
    parser.add_argument("--cuda", default=False, action="store_true",
                        help="Set this flag will use cuda when testing.")
    parser.add_argument("--font_scale", type=int, default=1, help="Control font size of text on picture.")
    parser.add_argument("--thickness", type=int, default=1, help="Control thickness of texton picture.")
    args = parser.parse_args()
    if not args.cuda:
        os.environ['CUDA_VISIBLE_DEVICES'] = ''
    aligned_image, image, rect_nums, XY = load_image(args.image_path, args.shape_detector)
    ages, genders = eval(aligned_image, args.model_path)
    print(ages, genders)
    draw_label(image, XY, ages, genders, font_scale=args.font_scale, thickness=args.thickness)
    plt.imshow(image[:, :, (2, 1, 0)])
    plt.show()
</code>```

thanks in advance

答:
The problem is when you specific shape=[None, 160, 160, 3] in images_pl. This means the input images have to be 160x160 but from the error you're trying to feed the model with a 540x260 image.

So the solution is either

Change None, 160, 160, 3 to None, None, None, 3. This will makes the model accept image with any size as long as it's 3 channels. Note that some layers need the input to be a specific size so this might not work sometime and if you train only on 160x160 the result won't be good.

Resize the image to 160x160.

Edit

Just a guesswork but I suppose these lines

```<code>if rect_nums == 0:
        aligned_images.append(image)
        return aligned_images, image, rect_nums, XY
</code>```

When rect_nums == 0 (no face detected?) it will return the original image without any resize. So either change aligned_images.append(image) to aligned_images.append(cv2.resize(image, (160, 160))) but this probably doesn't work as you don't have the faces there anyway or just print something like "No face detected".

For example

1 Raise the error if no face

```<code>if rect_nums == 0:
   raise ValueError('No face detected in this image')
</code>```

2 Return None and imshow the raw image

```<code>if rect_nums == 0:
    aligned_images.append(image)
    return None, None, None, None
</code>```

and change here

```<code>if aligned_image is not None:
    ages, genders = eval(aligned_image, args.model_path)
    print(ages, genders)
    draw_label(image, XY, ages, genders, font_scale=args.font_scale, thickness=args.thickness)
</code>```

P.S.

Just a tip but you can change plt.imshow(image[:, :, (2, 1, 0)]) to plt.imshow(image[..., ::-1]) and get the same result.

Body:
iam new to tensorflow, i am geeting this value error for some images while on other images works fine. is there anything wrong with the code?

error:

ValueError: Cannot feed value of shape (1, 260, 540, 3) for Tensor 'input_image: 0', which has shape '(?, 160, 160, 3)'
tensorflow version==1.14

dlib version==1.19

code:

import argparse
import os

import cv2
import dlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
from numpy import array
import inception_resnet_v1

os.environ['CUDA_VISIBLE_DEVICES'] = ''

def eval(aligned_images, model_path):
    with tf.Graph().as_default():
        sess = tf.Session()
        images_pl = tf.placeholder(tf.float32, shape=[None, 160, 160, 3], name='input_image')
        images = tf.map_fn(lambda frame: tf.reverse_v2(frame, [-1]), images_pl) #BGR TO RGB
        images_norm = tf.map_fn(lambda frame: tf.image.per_image_standardization(frame), images)
        train_mode = tf.placeholder(tf.bool)
        age_logits, gender_logits, _ = inception_resnet_v1.inference(images_norm, keep_probability=0.8,
                                                                     phase_train=train_mode,
                                                                     weight_decay=1e-5)
        gender = tf.argmax(tf.nn.softmax(gender_logits), 1)
        age_ = tf.cast(tf.constant([i for i in range(0, 101)]), tf.float32)
        age = tf.reduce_sum(tf.multiply(tf.nn.softmax(age_logits), age_), axis=1)
        init_op = tf.group(tf.global_variables_initializer(),
                           tf.local_variables_initializer())
        sess.run(init_op)
        saver = tf.train.Saver()
        ckpt = tf.train.get_checkpoint_state(model_path)
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)
            print("restore and continue training!")
        else:
            pass
        return sess.run([age, gender], feed_dict={images_pl: aligned_images, train_mode: False})

def load_image(image_path, shape_predictor):
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor(shape_predictor)
    fa = FaceAligner(predictor, desiredFaceWidth=160)
    image = cv2.imread(image_path, cv2.IMREAD_COLOR)

    # image = imutils.resize(image, width=256)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    rects = detector(gray, 2)
    rect_nums = len(rects)
    XY, aligned_images = [], []
    if rect_nums == 0:
        aligned_images.append(image)
        return aligned_images, image, rect_nums, XY
    else:
        for i in range(rect_nums):
            aligned_image = fa.align(image, gray, rects[i])
            aligned_images.append(aligned_image)
            (x, y, w, h) = rect_to_bb(rects[i])
            image = cv2.rectangle(image, (x, y), (x + w, y + h), color=(255, 0, 0), thickness=2)
            XY.append((x, y))
        return np.array(aligned_images), image, rect_nums, XY

# def draw_label(image, point, ages, genders, font=cv2.FONT_HERSHEY_COMPLEX, font_scale=1, thickness=1):
#     for i in range(len(point)):
#         label = "{}, {}".format(int(ages[i]), "F" if genders[i] == 0 else "M")
#         size = cv2.getTextSize(label, font, font_scale, thickness)[0]
#         x, y = point[i]
#         # cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
#         cv2.putText(image, label, (x, np.max(y - 5, 0)), font, font_scale, (255, 255, 255), thickness)

def draw_label(image, point, ages, genders,font=cv2.FONT_HERSHEY_SIMPLEX,
               font_scale=1, thickness=2):
    for i in range(len(point)):
        label = "{}, {}".format(int(ages[i]), "F" if genders[i] == 0 else "M")
        size = cv2.getTextSize(label, font, font_scale, thickness)[0]
        x, y = point[i]
        cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
        cv2.putText(image, label, point[i], font, font_scale, (255, 255, 255), thickness)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--image_path", "--I", required=True, type=str, help="Image Path")
    parser.add_argument("--model_path", "--M", default="./models", type=str, help="Model Path")
    parser.add_argument("--shape_detector", "--S", default="shape_predictor_68_face_landmarks.dat", type=str,
                        help="Shape Detector Path")
    parser.add_argument("--cuda", default=False, action="store_true",
                        help="Set this flag will use cuda when testing.")
    parser.add_argument("--font_scale", type=int, default=1, help="Control font size of text on picture.")
    parser.add_argument("--thickness", type=int, default=1, help="Control thickness of texton picture.")
    args = parser.parse_args()
    if not args.cuda:
        os.environ['CUDA_VISIBLE_DEVICES'] = ''
    aligned_image, image, rect_nums, XY = load_image(args.image_path, args.shape_detector)
    ages, genders = eval(aligned_image, args.model_path)
    print(ages, genders)
    draw_label(image, XY, ages, genders, font_scale=args.font_scale, thickness=args.thickness)
    plt.imshow(image[:, :, (2, 1, 0)])
    plt.show()

thanks in advance

Body:
The problem is when you specific shape=[None, 160, 160, 3] in images_pl. This means the input images have to be 160x160 but from the error you're trying to feed the model with a 540x260 image.

So the solution is either

Change None, 160, 160, 3 to None, None, None, 3. This will makes the model accept image with any size as long as it's 3 channels. Note that some layers need the input to be a specific size so this might not work sometime and if you train only on 160x160 the result won't be good.

Resize the image to 160x160.

Edit

Just a guesswork but I suppose these lines

if rect_nums == 0:
        aligned_images.append(image)
        return aligned_images, image, rect_nums, XY

When rect_nums == 0 (no face detected?) it will return the original image without any resize. So either change aligned_images.append(image) to aligned_images.append(cv2.resize(image, (160, 160))) but this probably doesn't work as you don't have the faces there anyway or just print something like "No face detected".

For example

1 Raise the error if no face

if rect_nums == 0:
   raise ValueError('No face detected in this image')

2 Return None and imshow the raw image

if rect_nums == 0:
    aligned_images.append(image)
    return None, None, None, None

and change here

if aligned_image is not None:
    ages, genders = eval(aligned_image, args.model_path)
    print(ages, genders)
    draw_label(image, XY, ages, genders, font_scale=args.font_scale, thickness=args.thickness)

P.S.

Just a tip but you can change plt.imshow(image[:, :, (2, 1, 0)]) to plt.imshow(image[..., ::-1]) and get the same result.


问:
Can we use derived class in place for anywhere requiring the base class? (In the context of templates)
I'm am quite new to C++ but I could not seem to find an answer to this question.

If I have a class template <Type> with a constructor taking in object type of ClassA<Type>, and I have another class derived in the following manner:
class ClassB : public ClassA<Animal>, am I able to pass in an object of type classB into the first constructor?

答:
That depends entirely whether the constructor takes its argument by reference/pointer.  If it does not, the object will be sliced into a ClassA<Type>.

```<code>#include <memory>

template <typename Type>
class ClassA {};

class ClassB : public ClassA<Animal> {};

template <typename Type>
class ClassUser1 {
public:
    explicit ClassUser1(ClassA<Type>);
}

template <typename Type>
class ClassUser2 {
public:
    explicit ClassUser2(std::unique_ptr<ClassA<Type>>);
}
</code>```

In this setup, calling ClassUser1<Animal>::ClassUser1{ClassB{}} will construct a temporary ClassB, which will be used to move-construct a ClassA<Animal> (slicing the object).

Calling ClassUser2<Animal>::ClassUser2{std::make_unique<ClassB>()} will work as you would expect; the pointed-to instance remains a ClassB.

Body:
That depends entirely whether the constructor takes its argument by reference/pointer.  If it does not, the object will be sliced into a ClassA<Type>.

#include <memory>

template <typename Type>
class ClassA {};

class ClassB : public ClassA<Animal> {};

template <typename Type>
class ClassUser1 {
public:
    explicit ClassUser1(ClassA<Type>);
}

template <typename Type>
class ClassUser2 {
public:
    explicit ClassUser2(std::unique_ptr<ClassA<Type>>);
}

In this setup, calling ClassUser1<Animal>::ClassUser1{ClassB{}} will construct a temporary ClassB, which will be used to move-construct a ClassA<Animal> (slicing the object).

Calling ClassUser2<Animal>::ClassUser2{std::make_unique<ClassB>()} will work as you would expect; the pointed-to instance remains a ClassB.


问:
Django Forms: Foreign Key in Hidden Field
My form:

```<code>class PlanForm(forms.ModelForm):
    owner = forms.ModelChoiceField(label="",
                                  queryset=Profile.objects.all(),
                                  widget=forms.HiddenInput())
    etc...

    class Meta:
        model = Plan
</code>```

Owner, in the model, is a ForeignKey to a Profile.

When I set this form, I set the value of "owner" to be a Profile object.

But when this comes out on the form, it seems to contain the name of the Profile like this:

```<code><input type="hidden" name="owner" value="phil" id="id_owner" />
</code>```

When the form is submitted and gets back to my views.py I try to handle it like this:

```<code>    form = PlanForm(request.POST)
    ...
    if form.is_valid():
        plan = form.save()
        return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
</code>```

However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.

So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form?

答:
There's usually no need to put related object into form field.  There's a better way and this is specifying parent id in form URL.

Let's assume you need to render a form for new Plan object and then create one when form is bubmitted.  Here's how your urlconf would look like:

```<code>(r"/profile/(?P<profile_id>\d+)/plan/new", view.new_plan), # uses profile_id to define proper form action
(r"/profile/(?P<profile_id>\d+)/plan/create", view.create_plan) # uses profile_id as a Plan field
</code>```

And if you're changing existing object, all you need is plan_id, you can deduce any related record from it.

OwnerDisplayName: interstar

Body:
My form:

class PlanForm(forms.ModelForm):
    owner = forms.ModelChoiceField(label="",
                                  queryset=Profile.objects.all(),
                                  widget=forms.HiddenInput())
    etc...

    class Meta:
        model = Plan

Owner, in the model, is a ForeignKey to a Profile.

When I set this form, I set the value of "owner" to be a Profile object.

But when this comes out on the form, it seems to contain the name of the Profile like this:

<input type="hidden" name="owner" value="phil" id="id_owner" />

When the form is submitted and gets back to my views.py I try to handle it like this:

    form = PlanForm(request.POST)
    ...
    if form.is_valid():
        plan = form.save()
        return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST

However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.

So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form?

Body:
There's usually no need to put related object into form field.  There's a better way and this is specifying parent id in form URL.

Let's assume you need to render a form for new Plan object and then create one when form is bubmitted.  Here's how your urlconf would look like:

(r"/profile/(?P<profile_id>\d+)/plan/new", view.new_plan), # uses profile_id to define proper form action
(r"/profile/(?P<profile_id>\d+)/plan/create", view.create_plan) # uses profile_id as a Plan field

And if you're changing existing object, all you need is plan_id, you can deduce any related record from it.

OwnerDisplayName: Alex Lebedev

ContentLicense: CC BY-SA 2.5


问:
LINQ equivalent of foreach for IEnumerable<T>
I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

```<code>IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
</code>```

What is the real syntax?

答:
Now we have the option of...

```<code>        ParallelOptions parallelOptions = new ParallelOptions();
        parallelOptions.MaxDegreeOfParallelism = 4;
#if DEBUG
        parallelOptions.MaxDegreeOfParallelism = 1;
#endif
        Parallel.ForEach(bookIdList, parallelOptions, bookID => UpdateStockCount(bookID));
</code>```

Of course, this opens up a whole new can of threadworms.

ps (Sorry about the fonts, it's what the system decided)

Body:
I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());

What is the real syntax?

Body:
Now we have the option of...

        ParallelOptions parallelOptions = new ParallelOptions();
        parallelOptions.MaxDegreeOfParallelism = 4;
#if DEBUG
        parallelOptions.MaxDegreeOfParallelism = 1;
#endif
        Parallel.ForEach(bookIdList, parallelOptions, bookID => UpdateStockCount(bookID));

Of course, this opens up a whole new can of threadworms.

ps (Sorry about the fonts, it's what the system decided)


问:
Left Join to the latest row using django
I have two tables.
Products [id, name, category]
Sales [product, date, price]

I want to get every Product with the latest row from Sales. If there is no row in sales, I still want to get that product row. The rows are foreign key related.

What is the Django way of doing such a left join?

答:
you can get the Sales object in view and render the object in template. for example you can do this.

models.py

```<code>class Course(models.Model):

  name = models.CharField(max_length=100)
  category = models.CharField(max_length=100)

def __str__(self):
    return self.title

class Sales(models.Model):

  product = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
  price = models.IntegerField()
  date = models.DateTimeField(auto_now_add=True, null=True)

def __str__(self):
    return self.product.title
</code>```

views.py

order_by(-date) gets you the latest item from the database

```<code>def sales_view(request):

   sales = Sales.objects.all().order_by(-date)

return render(request, 'template.html', {'sales':sales})
</code>```

Now, in your template you can load the template.

```<code>{% for sale in sales %}

  {{sale.product.name}}
  {{sale.price}}
  {{sale.date}}

{% endfor %}
</code>```

This way you get the product object even if there are no sales object. Hope you get some idea from it.

Body:
you can get the Sales object in view and render the object in template. for example you can do this.

models.py

class Course(models.Model):

  name = models.CharField(max_length=100)
  category = models.CharField(max_length=100)

def __str__(self):
    return self.title

class Sales(models.Model):

  product = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
  price = models.IntegerField()
  date = models.DateTimeField(auto_now_add=True, null=True)

def __str__(self):
    return self.product.title

views.py

order_by(-date) gets you the latest item from the database

def sales_view(request):

   sales = Sales.objects.all().order_by(-date)

return render(request, 'template.html', {'sales':sales})

Now, in your template you can load the template.

{% for sale in sales %}

  {{sale.product.name}}
  {{sale.price}}
  {{sale.date}}

{% endfor %}

This way you get the product object even if there are no sales object. Hope you get some idea from it.


问:
Where can I learn the basics of writing a lexer?
I want to learn how to write a lexer. My university course had an assignment where we had to write a parser (and a lexer to go along with it) but this was given to us with no instruction or feedback (beyond the mark) so I didn't really learn much from it.

After searching for this topic, I can only find fairly advanced write ups which focus on areas which I feel are a few steps ahead of where I am at. I want a discussion on the basics of writing a lexer for a very simple language which I can use as a basis for investigating tokenising more complex languages.

At this stage I'm not really interested in best practices or optimisation techniques but instead prefer a focus on the essentials. What are some good resources to get me started?

答:
Basically there are two main approaches to writing a lexer:

Creating a hand-written one in which case I recommend this small tutorial.

Using some lexer generator tools such as lex. In this case, I recommend reading the tutorials to the particular tool of choice.

Also I would like to recommend the Kaleidoscope tutorial from the LLVM documentation. It runs through the implementation of a simple language and in particular demonstrates how to write a small lexer. There is a C++ and an Objective Caml version of the tutorial.

The classical textbook on the subject is Compilers: Principles, Techniques, and Tools also known as the Dragon Book. However this probably falls under the category of "fairly advanced write ups".


问:
Warning 1261 Row n doesn't contain data for all columns
I have a requirement to load data from a CSV file into a Mysql Table in Windows 10.
The command I am using in MySQL Workbench 8.0.20 is:

LOAD DATA INFILE "C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/Sample.txt" IGNORE INTO TABLE TableA
FIELDS OPTIONALLY ENCLOSED BY '"'
TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(col1, col2, col3, col4, col5, col6, col7, col8,
 col9, col10, col11, col12, col13, col14, col15,
 dummy_1, dummy_2, dummy_3, dummy_4, dummy_5) ;
```

The original input file was Sample.csv.
When I ran the LOAD cmd I got the error

Error 1261    Row 1 doesn't contain data for all columns.

Similar error for Rows 2 - 13.

I saved the CSV file as a Text file ( Sample.txt ) using Notepad. I got the same errors for the text file. It is only giving errors for the first 13 rows in the text file. So I deleted the first 13 rows and ran the LOAD again. I still get the same warnings for rows 1 to 13 only.

FYI, Each row does not have the same number of Fields.
Any help in resolving this would be appreciated.

答:
The error message is pretty clear and just says that some of the lines in your CSV text file do not have 20 data points.  You may try using the following regex pattern to highlight rows in the file which do not match:

```<code>^(?!(?:[^,]*,){19}[^,]*$).*$
</code>```

Demo

Body:
I have a requirement to load data from a CSV file into a Mysql Table in Windows 10.
The command I am using in MySQL Workbench 8.0.20 is:

LOAD DATA INFILE "C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/Sample.txt" IGNORE INTO TABLE TableA
FIELDS OPTIONALLY ENCLOSED BY '"'
TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(col1, col2, col3, col4, col5, col6, col7, col8,
 col9, col10, col11, col12, col13, col14, col15,
 dummy_1, dummy_2, dummy_3, dummy_4, dummy_5) ;

The original input file was Sample.csv.
When I ran the LOAD cmd I got the error

Error 1261    Row 1 doesn't contain data for all columns.

Similar error for Rows 2 - 13.

I saved the CSV file as a Text file ( Sample.txt ) using Notepad. I got the same errors for the text file. It is only giving errors for the first 13 rows in the text file. So I deleted the first 13 rows and ran the LOAD again. I still get the same warnings for rows 1 to 13 only.

FYI, Each row does not have the same number of Fields.
Any help in resolving this would be appreciated.

Body:
The error message is pretty clear and just says that some of the lines in your CSV text file do not have 20 data points.  You may try using the following regex pattern to highlight rows in the file which do not match:

^(?!(?:[^,]*,){19}[^,]*$).*$

Demo


问:
how to clone an azure dev ops git repo using PAT with command line git or sourcetree?
ok, our org has the code in an azure dev ops repo.

I have been trying to clone it via git command line on the mac, via sourcetree on the mac and via sourcetree on windows, with no luck.

I created a PAT in the azure git web UI.

on the mac, if I do:

```<code>$ git clone https://ourorg.visualstudio.com/CMS/_git/ourProj
Cloning into 'ourProj'...
Username for 'https://ourorg.visualstudio.com': xxx
Password for 'https://xxx@ourorg.visualstudio.com':
fatal: Authentication failed for 'https://ourorg.visualstudio.com/CMS/_git/ourProj/'
</code>```

For user, I tried my azure user, and I also tried the PAT.
For pass, I tired my azure pass, and also the PAT.

None of these options work.

For sourcetree, I have also tried these combinations o PAT/PAT user/PAT user/pass etc. with no luck.  Any suggestions?

This is the page I used to create the PAT:

https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops

This doc says to use the PAT as the user and pass, but this simply doesnt work.

the doc also says you can do this:

```<code>git clone https://anything:{yourPAT}@dev.azure.com/yourOrgName/yourProjectName/_git/yourRepoName
</code>```

But this does not work either.

e.g. If I do this (fixed thanks to jessejouwing):

```<code>$ git clone https://asdf:{myPATgoesHERE}@dev.azure.com/ourorg/CMS/_git/ourProj
</code>```

On windows I always get:

Cloning into 'ourProj'...
fatal: Authentication failed for 'https://dev.azure.com/ourorg/CMS/_git/ourProj/'

The PAT is 100% correct.

Unfortunately, "alternative credentials" is disabled in our org, so we have to use PAT.  PAT is not working, so I cant work.

答:
```<code>git clone https://{yourPAT}@dev.azure.com/yourOrgName/yourProjectName/_git/yourRepoName
</code>```

That should suffice.

Body:
ok, our org has the code in an azure dev ops repo.

I have been trying to clone it via git command line on the mac, via sourcetree on the mac and via sourcetree on windows, with no luck.

I created a PAT in the azure git web UI.

on the mac, if I do:

$ git clone https://ourorg.visualstudio.com/CMS/_git/ourProj
Cloning into 'ourProj'...
Username for 'https://ourorg.visualstudio.com': xxx
Password for 'https://xxx@ourorg.visualstudio.com':
fatal: Authentication failed for 'https://ourorg.visualstudio.com/CMS/_git/ourProj/'

For user, I tried my azure user, and I also tried the PAT.
For pass, I tired my azure pass, and also the PAT.

None of these options work.

For sourcetree, I have also tried these combinations o PAT/PAT user/PAT user/pass etc. with no luck.  Any suggestions?

This is the page I used to create the PAT:

https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops

This doc says to use the PAT as the user and pass, but this simply doesnt work.

the doc also says you can do this:

git clone https://anything:{yourPAT}@dev.azure.com/yourOrgName/yourProjectName/_git/yourRepoName

But this does not work either.

e.g. If I do this (fixed thanks to jessejouwing):

$ git clone https://asdf:{myPATgoesHERE}@dev.azure.com/ourorg/CMS/_git/ourProj

On windows I always get:

Cloning into 'ourProj'...
fatal: Authentication failed for 'https://dev.azure.com/ourorg/CMS/_git/ourProj/'

The PAT is 100% correct.

Unfortunately, "alternative credentials" is disabled in our org, so we have to use PAT.  PAT is not working, so I cant work.

Body:
git clone https://{yourPAT}@dev.azure.com/yourOrgName/yourProjectName/_git/yourRepoName

That should suffice.


问:
Loading Image in RecycleView
Collecting images from json in recyclerview. How to load the next pages when we get to the end? I am only learning to use retrofit2, rxjava2. I ask you not to judge strictly and suggest what I am doing wrong. I hang the listener in onBind inside the adapter:

```<code>@Override public void onBindViewHolder(@NonNull ImageViewHolder holder, final int position) {
Hit hit = hits.get(position);
Picasso.get().load(hit.getLargeImageURL())
        .into(holder.imageViewPreview);
if (loadMoreListener != null && !isLoading && !noMore && position == getItemCount() - 1) {
    isLoading = true;
    loadMoreListener.loadMore();
}
</code>```

I am trying to implement the activation of loading the next page by passing its number to the parameters:

```<code>adapter.setLoadMoreListener(new ImageAdapter.LoadMoreListener() {
        @Override
        public void loadMore() {
            Toast.makeText(MainActivity.this, "Конец", Toast.LENGTH_SHORT).show();
            page++;
            viewModel.loadImages(searchQuery, page);

            adapter.endLoading();
            adapter.setNoMore(true);
            adapter.notifyDataSetChanged();
        }
    });
</code>```

Startup error occurs - Cannot call this method while RecyclerView is computing a layout or scrolling androidx.recyclerview.widget.RecyclerView

LoadImages () method code:

```<code> public void loadImages(String query, int page){
NetworkService networkService  =  NetworkService.getInstance();
compositeDisposable = new CompositeDisposable();
Disposable disposable = networkService.getJSONApi()
        .getResponse(query, page)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<Response>() {
            @Override
            public void accept(Response response) throws Exception {
                deleteHits();
                insertHits(response.getHits());
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Toast.makeText(getApplication(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

compositeDisposable.add(disposable);
</code>```

}

答:
Try to notify the adapter with the following code:

```<code>recyclerview.post(new Runnable() {
     @Override
     public void run() {
         myadapter.notifyDataSetChanged();
     }
});
</code>```

also check: https://www.journaldev.com/24041/android-recyclerview-load-more-endless-scrolling

Title: Loading Image in RecycleView

Body:
Collecting images from json in recyclerview. How to load the next pages when we get to the end? I am only learning to use retrofit2, rxjava2. I ask you not to judge strictly and suggest what I am doing wrong. I hang the listener in onBind inside the adapter:

@Override public void onBindViewHolder(@NonNull ImageViewHolder holder, final int position) {
Hit hit = hits.get(position);
Picasso.get().load(hit.getLargeImageURL())
        .into(holder.imageViewPreview);
if (loadMoreListener != null && !isLoading && !noMore && position == getItemCount() - 1) {
    isLoading = true;
    loadMoreListener.loadMore();
}

I am trying to implement the activation of loading the next page by passing its number to the parameters:

adapter.setLoadMoreListener(new ImageAdapter.LoadMoreListener() {
        @Override
        public void loadMore() {
            Toast.makeText(MainActivity.this, "Конец", Toast.LENGTH_SHORT).show();
            page++;
            viewModel.loadImages(searchQuery, page);

            adapter.endLoading();
            adapter.setNoMore(true);
            adapter.notifyDataSetChanged();
        }
    });

Startup error occurs - Cannot call this method while RecyclerView is computing a layout or scrolling androidx.recyclerview.widget.RecyclerView

LoadImages () method code:

 public void loadImages(String query, int page){
NetworkService networkService  =  NetworkService.getInstance();
compositeDisposable = new CompositeDisposable();
Disposable disposable = networkService.getJSONApi()
        .getResponse(query, page)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<Response>() {
            @Override
            public void accept(Response response) throws Exception {
                deleteHits();
                insertHits(response.getHits());
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Toast.makeText(getApplication(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

compositeDisposable.add(disposable);

}

Body:
Try to notify the adapter with the following code:

recyclerview.post(new Runnable() {
     @Override
     public void run() {
         myadapter.notifyDataSetChanged();
     }
});

also check: https://www.journaldev.com/24041/android-recyclerview-load-more-endless-scrolling


问:
Android seekbar solution
Is it possible to have the seekbar move only when the thumb is moved.
Right now the seekbar moves even on finger touch in the
progressdrawable. How do we disable the movement of the seekbar on
finger touch of the progressdrawable?

Thanks.

答:
Here's a Kotlin version of awy's answer with the caveat that absolutely no movement happens when you tap outside the drawable. The whole point is that you don't want users to be able to skip.</p>

```<code>import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatSeekBar

class NoSkipSeekBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : AppCompatSeekBar(context, attrs, defStyle) {

    private var isDragging = false

    private fun isWithinThumb(event: MotionEvent): Boolean {
        return thumb.bounds.contains(event.x.toInt(), event.y.toInt())
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (!isEnabled || thumb == null) return super.onTouchEvent(event)

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                if (isWithinThumb(event)) {
                    isDragging = true
                    return super.onTouchEvent(event)
                } else {
                    return true
                }
            }
            MotionEvent.ACTION_UP -> {
                isDragging = false

                return when {
                    isWithinThumb(event) -> super.onTouchEvent(event)
                    else -> true
                }
            }
            MotionEvent.ACTION_MOVE -> if (!isDragging) return true
            MotionEvent.ACTION_CANCEL -> isDragging = false
        }
        return super.onTouchEvent(event)
    }
}
</code>```

Title: Android seekbar solution

Body:
Here's a Kotlin version of awy's answer with the caveat that absolutely no movement happens when you tap outside the drawable. The whole point is that you don't want users to be able to skip.

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatSeekBar

class NoSkipSeekBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : AppCompatSeekBar(context, attrs, defStyle) {

    private var isDragging = false

    private fun isWithinThumb(event: MotionEvent): Boolean {
        return thumb.bounds.contains(event.x.toInt(), event.y.toInt())
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (!isEnabled || thumb == null) return super.onTouchEvent(event)

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                if (isWithinThumb(event)) {
                    isDragging = true
                    return super.onTouchEvent(event)
                } else {
                    return true
                }
            }
            MotionEvent.ACTION_UP -> {
                isDragging = false

                return when {
                    isWithinThumb(event) -> super.onTouchEvent(event)
                    else -> true
                }
            }
            MotionEvent.ACTION_MOVE -> if (!isDragging) return true
            MotionEvent.ACTION_CANCEL -> isDragging = false
        }
        return super.onTouchEvent(event)
    }
}


答:
Firstly, good job, you're doing great! I like your semantic HTML. A few things to notice:

You wanna give a max-width to your search input, force it to be 100% of width and remove the unnecessary margin, like so:

```<code>    #search-box{
        max-width: 200px;
        width: 100%;
        margin: 0;
    }
</code>```

Make sure to adjust the values for mobile as well. Also, take a look at flex-grow, it will suit your journey.

Click here to view your updated code on Codepen.

Title: Hovering another instance makes my text move

Body:
So i remade my website, and now i´m using flex layout, which makes my work a lot easier, i got a hover effect upon my input, so every time i hover a icon my input get shown but this input is moving to the right, when it was supposed to move to the left, which in case is making my layout move along with it
sorry for poor english, still learning,
here´s my code:

@import url("./src/assets/fonts/Roboto.zip");
@import url("./src/assets/fonts/Open_Sans.zip");
@import url("./src/assets/fonts/Playfair_Display.zip");

* {
    margin: 0;
    padding: 0;
    outline: none;
    box-sizing: border-box;
}

body {
    width: 90%;
    margin: 0 auto;
}

header {
    display: flex;
    background-color: red;
}

header ul {
    list-style: none;
}

header h1 {
    font-family: 'Playfair_Display', serif;
}

header #search-box {
    display: flex;
}

/*POSIÇÃO DOS ÍCONES*/
header #barsPosition {
    margin: auto 0 auto 3%;
}

header #search-box {
    margin: auto 0 auto 15%;
}

header #inputBar {
    margin: 6% 0 auto 0;
}

header #searchPosition {
    margin: auto 0 auto 2%;
}

header h1 {
    margin: auto;
}

header #shopPosition {
    margin: auto 3% auto auto;
}
/*POSIÇÃO DOS ÍCONES*/

/*ATRIBUTO DOS ICONES*/
.barsMenu, .searchIcon, .shoppingBag {
    width: 32px;
    height:32px;
    display: flex;
    cursor: pointer;
}
/*ATRIBUTO DOS ICONES*/

/*RESPONSIVIDADE DO SITE*/
@media screen and (max-width: 2560px) {
    header h1 {
      font-size: 3.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu40px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search40px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag40px.svg");}
    /*ÍCONES*/
    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 40px;
        height:40px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1440px) {
    header h1 {
      font-size: 2.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu32px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search32px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag32px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 32px;
        height:32px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 1024px) {
    header h1 {
      font-size: 2.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu24px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search24px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag24px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 24px;
        height:24px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 768px) {
    header h1 {
      font-size: 1.5em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu16px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search16px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag16px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 16px;
        height:16px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 425px) {
    header h1 {
        font-size: 1.0em;
    }

    /*ÍCONES*/
    .barsMenu {background: url("./src/assets/icons/menu/menu12px.svg");}

    .searchIcon {background: url("./src/assets/icons/search/search12px.svg");}

    .shoppingBag {background: url("./src/assets/icons/shoppingbag/shopping-bag12px.svg");}
    /*ÍCONES*/

    /*ATRIBUTO DOS ICONES*/
    .barsMenu, .searchIcon, .shoppingBag {
        width: 12px;
        height:12px;
        display: flex;
        cursor: pointer;
    }
    /*ATRIBUTO DOS ICONES*/
}

@media screen and (max-width: 375px) {
    header h1 {
      font-size: 0.5em;
    }

}

@media screen and (max-width: 320px) {
    header h1 {
      font-size: 0.5em;
    }

}
/*RESPONSIVIDADE DO SITE*/

/*HEADER INPUT BAR*/
input {
    width: 0px;
    border: none;
    outline: none;
    color: white;
    background: none;
    transition: 0.4s ease-in;
    border-bottom: 0.3px solid black;
}

header input#inputBar {
    color: black;
    font-weight: 300;
    font-family: 'Roboto', sans-serif;
    font-size: 1em;
}

#search-box:hover > .inputBar {
    width: 200px;
}
/*HEADER INPUT BAR*/

<!DOCTYPE html>

      <title>Bunny&copy</title>

      <meta charset="UTF-8">
      <meta name="author" content="Vitor N">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <link rel="stylesheet" href="./global.css">
      <link rel="icon" href="./src/assets/image/logo.jpg">
      <link rel="stylesheet" href="./src/styles/index.css">

                  <input type="text" placeholder="Pesquise" class="inputBar">
                  

BUNNY

              

Well what it should do is go to the left instead of right

Body:
Firstly, good job, you're doing great! I like your semantic HTML. A few things to notice:

You wanna give a max-width to your search input, force it to be 100% of width and remove the unnecessary margin, like so:

    #search-box{
        max-width: 200px;
        width: 100%;
        margin: 0;
    }

Make sure to adjust the values for mobile as well. Also, take a look at flex-grow, it will suit your journey.

Click here to view your updated code on Codepen.