问:
If statement not working with .equals in Java and always showing the answer of else statement
I am learning Java myself and am trying to make a sign in like app. The if statement doesn't work but the else statement is always working.

Here is the code:

```<code>package Lessons;

public class Main extends Application {

    Stage window;

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

    @Override
    public void start(Stage primaryStage) {
        window = primaryStage;
        window.setTitle("Sign in");

        TextField nameInput = new TextField();

        Button button = new Button("Sign In");

        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20,20));
        layout.getChildren().addAll(nameInput, button);

        Scene scene = new Scene(layout, 600, 600);
        window.setScene(scene);
        window.show();

        //Checks the username
        String username = "thomas";
        if (nameInput.getText().equals(username)) {
            button.setOnAction(e -> CorrectUsernameReplier.display());}
        else {
            button.setOnAction(e -> WrongUsernameReplier.display());
        }
    }
}
</code>```

I didn't show what I imported because I don't think they are necessary.

This is the code from the CorrectUsernameReplier

```<code>public static void display() {
    Stage window = new Stage();

    //Replies to correct username
    window.setTitle("Correct username");
    window.initModality(Modality.APPLICATION_MODAL);
    StackPane layout = new StackPane();
    Scene scene = new Scene(layout, 200, 200);
    Label label = new Label("Signed In");
    layout.getChildren().add(label);
    window.setScene(scene);
    window.showAndWait();
</code>```

This is the code from the WrongUsernameReplier

```<code>public static void display() {
    Stage window = new Stage();

    //Replies to incorrect username
    window.setTitle("Incorrect username");
    window.initModality(Modality.APPLICATION_MODAL);
    StackPane layout1 = new StackPane();
    Scene scene1 = new Scene(layout1, 200, 200);
    Label label = new Label("Incorrect Username. Please try again.");
    layout1.getChildren().add(label);
    window.setScene(scene1);
    window.showAndWait();
</code>```

Here are the images if what the error is:

"thomas" is in the TextField and the username string in the code above is also "thomas". But it shows the error you see.

This is the second image:

This is the screenshot which I type nothing in it. And the respond here is correct.

Can you please help me figure out what is wrong with my code?

答:
As the if statement is processed when the view is created button.setOnAction(e -> WrongUsernameReplier.display()); is executed every time unconditionally. What you are missing is that the check whether or not the username is correct should only be done when the button has been pressed and not on initializing the UI:

```<code>button.setOnAction(e -> {
    String username = "thomas";

    if (nameInput.getText().equals(username)) {
        CorrectUsernameReplier.display();
    } else {
        WrongUsernameReplier.display();
    }
});
</code>```

or something similar in JavaFX.

Body:
I am learning Java myself and am trying to make a sign in like app. The if statement doesn't work but the else statement is always working.

Here is the code:

package Lessons;

public class Main extends Application {

    Stage window;

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

    @Override
    public void start(Stage primaryStage) {
        window = primaryStage;
        window.setTitle("Sign in");

        TextField nameInput = new TextField();

        Button button = new Button("Sign In");

        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20,20));
        layout.getChildren().addAll(nameInput, button);

        Scene scene = new Scene(layout, 600, 600);
        window.setScene(scene);
        window.show();

        //Checks the username
        String username = "thomas";
        if (nameInput.getText().equals(username)) {
            button.setOnAction(e -> CorrectUsernameReplier.display());}
        else {
            button.setOnAction(e -> WrongUsernameReplier.display());
        }
    }
}

I didn't show what I imported because I don't think they are necessary.

This is the code from the CorrectUsernameReplier

public static void display() {
    Stage window = new Stage();

    //Replies to correct username
    window.setTitle("Correct username");
    window.initModality(Modality.APPLICATION_MODAL);
    StackPane layout = new StackPane();
    Scene scene = new Scene(layout, 200, 200);
    Label label = new Label("Signed In");
    layout.getChildren().add(label);
    window.setScene(scene);
    window.showAndWait();

This is the code from the WrongUsernameReplier

public static void display() {
    Stage window = new Stage();

    //Replies to incorrect username
    window.setTitle("Incorrect username");
    window.initModality(Modality.APPLICATION_MODAL);
    StackPane layout1 = new StackPane();
    Scene scene1 = new Scene(layout1, 200, 200);
    Label label = new Label("Incorrect Username. Please try again.");
    layout1.getChildren().add(label);
    window.setScene(scene1);
    window.showAndWait();

Here are the images if what the error is:

"thomas" is in the TextField and the username string in the code above is also "thomas". But it shows the error you see.

This is the second image:

This is the screenshot which I type nothing in it. And the respond here is correct.

Can you please help me figure out what is wrong with my code?

Body:
As the if statement is processed when the view is created button.setOnAction(e -> WrongUsernameReplier.display()); is executed every time unconditionally. What you are missing is that the check whether or not the username is correct should only be done when the button has been pressed and not on initializing the UI:

button.setOnAction(e -> {
    String username = "thomas";

    if (nameInput.getText().equals(username)) {
        CorrectUsernameReplier.display();
    } else {
        WrongUsernameReplier.display();
    }
});

or something similar in JavaFX.


来源: stackexchange

问:
Does declaring a vector with size offer any improvements over using push_back in C++
Let us say we know the size of a vector we will be needing, (say 'n').

Does using vector<int> Array(n); offer any improvements over using Array.push_back(element) one by one?

Which is recommended and why?

答:
Below is a reference taken from Cplusplus.com :

Internally, vectors use a dynamically allocated array to store their
  elements. This array may need to be reallocated in order to grow in
  size when new elements are inserted, which implies allocating a new
  array and moving all elements to it. This is a relatively expensive
  task in terms of processing time, and thus, vectors do not reallocate
  each time an element is added to the container.

Instead, vector containers may allocate some extra storage to
  accommodate for possible growth, and thus the container may have an
  actual capacity greater than the storage strictly needed to contain
  its elements (i.e., its size).

Now let's look at the difference between the two types :

1. vector<int>arr :

When you declare vector<int>arr, the vector size depends on
implementation which is usually 0. So, the vector in this case will
start at size 0.

Whenever you try to push_back() , the vector will see if the
present capacity is enough to accommodate that element.

If the capacity is already enough to accommodate the element, it just assigns the new element in the next empty memory space.

If the current capacity is full, the vector will reallocate the space. Eg. If you have a current capacity of 4 and it's all used up and you try to pushback an element, then the vector will reallocate the space (for say, 8 elements. The new capacity is almost always doubled than the current capacity) and then push the element into the vector.

If the new space can't be extended at the present memory location itself (maybe because the space adjacent to it is already occupied by some other variables), then the vector is completely shifted from its original location to a new location where we have sufficient amount of needed space. This process involves copying all the elements of vector to the new location which takes up time.

If a reallocation happens, the reallocation is itself up to linear in the entire size.  But the amortized time-complexity of push_back() still remains constant, i.e O(1)

2. vector<int>arr(n) :

This declaration will initialise the vector with space for n elements pre-allocated, at the start itself.

whenever you want to add another element you can just assign the next index using [] operator.

So, say that your n=5 and you have assigned first two index. You can directly use like arr[2]=4 to add a third element. There's no need to use push_back() as you have already allocated the space needed for n elements in your vector.

You can still use push_back() if you want to add more than n elements. But for the first n elements, the assignment is done directly using [ ] operator as vector has already been sized to hold n elements.

Another choice would to use reserve() if you don't want to intialise using vector<int>arr(n).
It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory.
In this case, your initial vector size will be zero and you have to use .push_back() to add any new element. But, first reserving a space and then using push_back will save you from the time-consuming process of reallocation and copying of whole array to new memory location.

Conclusion :

So, since we don't always have to keep allocating new space and copying all the elements of vector using the 2nd type,  therefore the 2nd type of declaration is much more efficient than the first type of declaration of you know the size of vector at the start itself.

The efficiency will be as follows:

vector<int>arr(n); and directly assigning elements at each index using [ ] operator.

arr.reserve(n); after vector declaration and adding new elements using .push_back() method.

vector<int>arr; and adding new elements using .push_back() method.

Hope this answers your question !

ContentLicense: CC BY-SA 4.0


问:
How can I select my agent in microsoft azure CI pipelines using azure-pipelines.yml
I have this script:

```<code>trigger:
- master

pool:
  name: Mobile-Pool
  agent: 'MacMini3-AMS'
  vmImage: 'MacMini3-AMS'

steps:
- task: Gradle@2
  inputs:
    workingDirectory: ''
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx4096m'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'clean assembleDebug testDebugUnitTest'

# Bash
# Run a Bash script on macOS, Linux, or Windows
- task: Bash@3
  inputs:
    targetType: 'filePath'
    filePath: 'run-tests-on-emulator.sh'

- task: Gradle@2
  inputs:
    workingDirectory: ''
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx4096m'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'connectedDebugAndroidTest'
</code>```

I am running my own on-premise hardware. I have a MacMini3 and a MacMini2. The MacMini2 doesn't compile properly, and I want to run on the MacMini3. How can I change the yaml script to do so?

答:
You should use Demands to make sure that the capabilities your pipeline needs are present on the agents that run it.

```<code>pool:
  name: MyPool
  demands:
  - myCustomCapability   # check for existence of capability
  - agent.os -equals Darwin  # check for specific string in capability
</code>```

In your scenario, you can use Agent.Name or Agent.ComputerName demand.

Body:
I have this script:

trigger:
- master

pool:
  name: Mobile-Pool
  agent: 'MacMini3-AMS'
  vmImage: 'MacMini3-AMS'

steps:
- task: Gradle@2
  inputs:
    workingDirectory: ''
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx4096m'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'clean assembleDebug testDebugUnitTest'

# Bash
# Run a Bash script on macOS, Linux, or Windows
- task: Bash@3
  inputs:
    targetType: 'filePath'
    filePath: 'run-tests-on-emulator.sh'

- task: Gradle@2
  inputs:
    workingDirectory: ''
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx4096m'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'connectedDebugAndroidTest'

I am running my own on-premise hardware. I have a MacMini3 and a MacMini2. The MacMini2 doesn't compile properly, and I want to run on the MacMini3. How can I change the yaml script to do so?

Body:
You should use Demands to make sure that the capabilities your pipeline needs are present on the agents that run it.

pool:
  name: MyPool
  demands:
  - myCustomCapability   # check for existence of capability
  - agent.os -equals Darwin  # check for specific string in capability

In your scenario, you can use Agent.Name or Agent.ComputerName demand.


问:
I am updating Angular version from 7 to 8. But getting peer dependency error
I tried using --force , but of no use.

enter image description here

error code -

```<code>    Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to   "@angular/common" (requires "^7.0.0" (extended), would install "9.1.9").
 Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/animations" (requires "6.x" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser" (requires "6.x" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser-dynamic" (requires "^6.0.0" (extended), would install "9.1.9").
                  Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to "@angular/forms" (requires "^7.0.0" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "rxjs" (requires "^5.1.0", would install "6.5.5").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "zone.js" (requires "^0.8.4", would install "0.10.3").
</code>```

答:
Try to below command hopefully, it will be fixed    </p>

```<code>ng update @angular/cli @angular/core
</code>```

Body:
I tried using --force , but of no use.

enter image description here

error code -

    Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to   "@angular/common" (requires "^7.0.0" (extended), would install "9.1.9").
 Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/animations" (requires "6.x" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser" (requires "6.x" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser-dynamic" (requires "^6.0.0" (extended), would install "9.1.9").
                  Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to "@angular/forms" (requires "^7.0.0" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "rxjs" (requires "^5.1.0", would install "6.5.5").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "zone.js" (requires "^0.8.4", would install "0.10.3").

Body:
Try to below command hopefully, it will be fixed

ng update @angular/cli @angular/core


问:
Firestore- Querying Subcollections

```<code>firestore.collection("CATEGORIES").document("HOME").collection("TOP_DEALS")
                .orderBy("index").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                Log.d(TAG, "onComplete: Task Successful? "+task.isSuccessful());
                if (task.isSuccessful()){
                    Log.d(TAG, "onComplete: task.getResult().getDocuments().size() :"+task.getResult().getDocuments().size());
                    for (QueryDocumentSnapshot documentSnapshot:task.getResult()){
                        Log.d(TAG, "onComplete: inside For loop");
                    }
                }else {
                    String error=task.getException().getMessage();
                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                }
            }
        });
</code>```

I want to work with all the documents in the TOP_DEALS subcollection.
Even though the task is successful,task.result() is empty and statements within for each are never executed.
How should i query the all the documents in a subcollection?

答:
Welcome on SO!

If I understand correctly index field is in field of HOME document. According to Google Documentation:

An orderBy() clause also filters for existence of the given fields.
  The result set will not include documents that do not contain the
  given fields.

In the provided code the 'orderBy' is used on TOP_DEALS collection, while the filed is in parent document HOME.

I am not sure what do you want to order here, but I think there 2 ways to solve. 1st you have to move orderby to CATEGORIES collection or 2nd to add index to documents in TOP_DEALS collection.

Title: Firestore- Querying Subcollections

Body:
firestore.collection("CATEGORIES").document("HOME").collection("TOP_DEALS")
                .orderBy("index").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                Log.d(TAG, "onComplete: Task Successful? "+task.isSuccessful());
                if (task.isSuccessful()){
                    Log.d(TAG, "onComplete: task.getResult().getDocuments().size() :"+task.getResult().getDocuments().size());
                    for (QueryDocumentSnapshot documentSnapshot:task.getResult()){
                        Log.d(TAG, "onComplete: inside For loop");
                    }
                }else {
                    String error=task.getException().getMessage();
                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                }
            }
        });

I want to work with all the documents in the TOP_DEALS subcollection.
Even though the task is successful,task.result() is empty and statements within for each are never executed.
How should i query the all the documents in a subcollection?


问:
Getting the value of buffers in Python wrapper of OpenGL
Is it possible to get the buffer to readable array? i.e.
When I call them or print them, only

are shown.
How can I get the value of buffer object to python array?</p>

答:
There are different possibilities. One possibility is to use glGetBufferSubData. The data of a Framebuffer Object can be read by glReadPixels, if the buffer is bound for reading (GL_READ_FRAMEBUFFER). A texture can be read by glGetTexImage. In general a buffer can be accessed by Buffer Mapping (glMapBuffer / glMapBufferRange).

For instance you can use glGetBufferSubData to read floating point values to read the data of a GL_ARRAY_BUFFER. In the following example vbo is a vertex buffer object and no_of_floats is the number of floats you want to read.

glGetBufferSubData returns an array of bytes. You can use numpy to convert the array of bytes to an array of floats:

import numpy as np
```
<pre class="lang-py prettyprint-override"><code>glBindBuffer(GL_ARRAY_BUFFER, vbo)
uint8_data = glGetBufferSubData(GL_ARRAY_BUFFER, 0, no_of_floats * 4)
float32_data = np.frombuffer(uint8_data, dtype=np.float32)
</code>```

Another option is to generate a ctypes array and to read the data directly into the array:

import ctypes
```
<pre class="lang-py prettyprint-override"><code>float32_data = (ctypes.c_float * no_of_floats)() # or (GLfloat * no_of_floats)()
void_ptr = ctypes.c_void_p(ctypes.addressof(float32_data))

glBindBuffer(GL_ARRAY_BUFFER, vbo)
glGetBufferSubData(GL_ARRAY_BUFFER, 0, no_of_floats * 4, void_ptr)
</code>```

Body:
There are different possibilities. One possibility is to use glGetBufferSubData. The data of a Framebuffer Object can be read by glReadPixels, if the buffer is bound for reading (GL_READ_FRAMEBUFFER). A texture can be read by glGetTexImage. In general a buffer can be accessed by Buffer Mapping (glMapBuffer / glMapBufferRange).

For instance you can use glGetBufferSubData to read floating point values to read the data of a GL_ARRAY_BUFFER. In the following example vbo is a vertex buffer object and no_of_floats is the number of floats you want to read.

glGetBufferSubData returns an array of bytes. You can use numpy to convert the array of bytes to an array of floats:

import numpy as np

glBindBuffer(GL_ARRAY_BUFFER, vbo)
uint8_data = glGetBufferSubData(GL_ARRAY_BUFFER, 0, no_of_floats * 4)
float32_data = np.frombuffer(uint8_data, dtype=np.float32)

Another option is to generate a ctypes array and to read the data directly into the array:

import ctypes

float32_data = (ctypes.c_float * no_of_floats)() # or (GLfloat * no_of_floats)()
void_ptr = ctypes.c_void_p(ctypes.addressof(float32_data))

glBindBuffer(GL_ARRAY_BUFFER, vbo)
glGetBufferSubData(GL_ARRAY_BUFFER, 0, no_of_floats * 4, void_ptr)


问:
Howto draw horizontalBar with dynamic thickness (automatic rescale on browser window height resize) in Chart.js 2.9.3?
I use latest Chart.js 2.9.3.

I'm trying to draw a horizontal bar with thickness that depends on browser window size: from 50 when browser window is fullscreen, to 20 when browser window is resized to very small height.

I've tried the following code - but bar is always 50 (https://jsfiddle.net/zg6c54rt/1/):

var ctx = document.getElementById('chart').getContext('2d');
        var chart = new Chart(ctx, {
            type: 'horizontalBar',
            data: {
                labels: ['1', '2', '3', '4'],
                datasets: [{
                    barThickness: 'flex',
                    maxBarThickness: 50,
                    data: [100, 90, 85, 95]
                }]
            },
            options: {
                 scales: {
                    xAxes: [{
                        ticks: {
                            min: 0
                        }
                    }]
                }
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
     <div class="text-center">
            <canvas id="chart"></canvas>
    </div></code>```

Changing barThickness: 'flex', to barThickness: 20, makes bar always 20.

Not defining barThickness results in bar is always 50 (same as barThickness: 'flex').

Howto draw horizontalBar with dynamic thickness?

Thank you in advance.

答:
Instead of using barThickness, you could define categoryPercentage together with barPercentage

```<code>datasets: [{
  categoryPercentage: 1,
  barPercentage: 0.5,
  data: [100, 90, 85, 95]
}]
</code>```

categoryPercentage: Percent (0-1) of the available width each category should be within the sample width.

barPercentage: Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other.

Body:
I use latest Chart.js 2.9.3.

I'm trying to draw a horizontal bar with thickness that depends on browser window size: from 50 when browser window is fullscreen, to 20 when browser window is resized to very small height.

I've tried the following code - but bar is always 50 (https://jsfiddle.net/zg6c54rt/1/):

var ctx = document.getElementById('chart').getContext('2d');
        var chart = new Chart(ctx, {
            type: 'horizontalBar',
            data: {
                labels: ['1', '2', '3', '4'],
                datasets: [{
                    barThickness: 'flex',
                    maxBarThickness: 50,
                    data: [100, 90, 85, 95]
                }]
            },
            options: {
                 scales: {
                    xAxes: [{
                        ticks: {
                            min: 0
                        }
                    }]
                }
            }
        });

            <canvas id="chart"></canvas>

Changing barThickness: 'flex', to barThickness: 20, makes bar always 20.

Not defining barThickness results in bar is always 50 (same as barThickness: 'flex').

Howto draw horizontalBar with dynamic thickness?

Thank you in advance.

Body:
Instead of using barThickness, you could define categoryPercentage together with barPercentage

datasets: [{
  categoryPercentage: 1,
  barPercentage: 0.5,
  data: [100, 90, 85, 95]
}]

categoryPercentage: Percent (0-1) of the available width each category should be within the sample width.

barPercentage: Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other.


问:
How to Display the messages only once?
I have 2 struct arrays. i need to check each array of tempo to each array of buff and if a match is found i shall break our of the entire loop and output the message "a match is found" once and exits. Else "no match" should be outputted.

How to Display the messages only once after checking the two arrays with each other? i need to break out of the loop after a match. else output mismatch.
the output is being displayed multiple times.

```<code>for (int g = 0; g < lines; g++) {
    for (int y = 0; y < lines; y++) {
        if ((strstr(tempo[g], buff[y])) != NULL) //Cheking if enter username and Password Exist in record file.
        {
            printf("A match found on line");
            break;

        } else
        {
            printf("Mismatch in Username or Password");
        }
    }
}
</code>```

答:
Use a variable found as a flag to indicate when a match is found. You can use test that variable and break if it is set to 1.

Then move the print outside the loop and use the flag to determine what to print.

```<code>int found = 0;
for (int g = 0; g < lines; g++) {
    for (int y = 0; y < lines; y++) {
        if ((strstr(tempo[g], buff[y])) != NULL) {
            found = 1;
            break;
        }
    }
    if (found) {
        break;
    }
}

if (found) //Cheking if enter username and Password Exist in record file.
{
    printf("A match found on line");
} else
{
    printf("Mismatch in Username or Password");
}
</code>```

Title: How to Display the messages only once?

Body:
I have 2 struct arrays. i need to check each array of tempo to each array of buff and if a match is found i shall break our of the entire loop and output the message "a match is found" once and exits. Else "no match" should be outputted.

How to Display the messages only once after checking the two arrays with each other? i need to break out of the loop after a match. else output mismatch.
the output is being displayed multiple times.

for (int g = 0; g < lines; g++) {
    for (int y = 0; y < lines; y++) {
        if ((strstr(tempo[g], buff[y])) != NULL) //Cheking if enter username and Password Exist in record file.
        {
            printf("A match found on line");
            break;

        } else
        {
            printf("Mismatch in Username or Password");
        }
    }
}

Body:
Use a variable found as a flag to indicate when a match is found. You can use test that variable and break if it is set to 1.

Then move the print outside the loop and use the flag to determine what to print.

int found = 0;
for (int g = 0; g < lines; g++) {
    for (int y = 0; y < lines; y++) {
        if ((strstr(tempo[g], buff[y])) != NULL) {
            found = 1;
            break;
        }
    }
    if (found) {
        break;
    }
}

if (found) //Cheking if enter username and Password Exist in record file.
{
    printf("A match found on line");
} else
{
    printf("Mismatch in Username or Password");
}


问:
How to replacte whole string or part of string from in Swift4
I'm new to Swift, and stuck in-between development task.

I want to replace existing label string with another string or I want to replace part of string, also need to add this in my existing Swift in-built classes so I can further use it.

I'm very new Swift..please ignore any syntactical issues...

```<code>if str1.contains("ed"){
     str1.replacementObject(for: "MyNewString")
}
</code>```

I'm getting error on this..."cannot convert value from string to expected argument type 'NSKeyedArchiver'"

I'll be more happy, if you could help me.

答:
I'll guide you to implement this in the proper way, so you can reuse it further.

Add this extension outside you class

extension String {
    func replace(string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }
}
```

<ol start="2">
<li>Now you can use it as part of built-in functionality of String, as show below:</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>label1 = "MyOldString"
self.label1.text = self. label1.text?.replace(string: "Old", replacement: "New")

Output :- label1 = "MyNewString"
</code>```

That's it!

Now you can use it anywhere in your project.

Body:
I'm new to Swift, and stuck in-between development task.

I want to replace existing label string with another string or I want to replace part of string, also need to add this in my existing Swift in-built classes so I can further use it.

I'm very new Swift..please ignore any syntactical issues...

if str1.contains("ed"){
     str1.replacementObject(for: "MyNewString")
}

I'm getting error on this..."cannot convert value from string to expected argument type 'NSKeyedArchiver'"

I'll be more happy, if you could help me.

Body:
I'll guide you to implement this in the proper way, so you can reuse it further.

Add this extension outside you class

extension String {
    func replace(string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }
}

Now you can use it as part of built-in functionality of String, as show below:

label1 = "MyOldString"
self.label1.text = self. label1.text?.replace(string: "Old", replacement: "New")

Output :- label1 = "MyNewString"

That's it!

Now you can use it anywhere in your project.


问:
How to prevent transition elements from transitioning every time the browser refresh or open the web page for the first time?
I have two problems.

I am currently designing a mobile website. For the navigation, I decided to use a hamburger approach to links. I am trying to transition the hamburger into an X when you tap on the hamburger using the property transform when the input element is checked. The problem is that when you open the web page for the first time or refresh the browser, the transition elements transition without clicking or taping on hamburger. Is there anyway to fix that.

The second problem occurs if you're view the web-page on Microsoft Edge. In Microsoft Edge, the title "White Bact" is display on two lines. I want the title to be displayed only one line. If you were to view it on Google Chrome, the title is on one line. I designed and tested everything on google chrome. I wanted to be same on every browser.

I have created a link for anyone to download the files from google drive. The files are in a zipped folder, so you would have to extract the files. I wanted to do a JSFiddle, but the problems won't occur.

The main files you should look are the index.css and index.html.

https://drive.google.com/file/d/11N6l8OwcO_waeHcvfdWJyeFgw3O8zE4w/view?usp=sharing

答:
For the first problem, does that you don't want the transition of the hamburger when the page opening? Then I think you can only use the transition when the hamburger clicked:

```<code>span.ham:nth-of-type(2) {
    /*transition: transform 500ms cubic-bezier(0.01, 0.24, 0.28, 1.35);*/
}

...

/* if the hamburger is clicked */
#hamburger:checked ~ label > span.ham:nth-of-type(2) {
    transform: scale(0);
    transition: transform 500ms cubic-bezier(0.01, 0.24, 0.28, 1.35);
}
</code>```

For the second problem, the "White Bact" will display on one line on Edge if you remove width: 180px; in .logo > h1 > a:

```<code>.logo > h1 > a {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    /*width: 180px;*/
    text-align: center;
}
</code>```

Body:
For the first problem, does that you don't want the transition of the hamburger when the page opening? Then I think you can only use the transition when the hamburger clicked:

span.ham:nth-of-type(2) {
    /*transition: transform 500ms cubic-bezier(0.01, 0.24, 0.28, 1.35);*/
}

...

/* if the hamburger is clicked */
#hamburger:checked ~ label > span.ham:nth-of-type(2) {
    transform: scale(0);
    transition: transform 500ms cubic-bezier(0.01, 0.24, 0.28, 1.35);
}

For the second problem, the "White Bact" will display on one line on Edge if you remove width: 180px; in .logo > h1 > a:

.logo > h1 > a {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    /*width: 180px;*/
    text-align: center;
}


问:
Swift 'if let' statement equivalent in Kotlin
In Kotlin is there an equivalent to the Swift code below?</p>
```<code>if let a = b.val {

} else {

}
</code>```

答:
Swift if let statement in Kotlin

The short answer is use simple IF-ELSE as by the time of this comment there is no equivalent in Kotlin LET,

```<code>    if(A.isNull()){
// A is null
    }else{
// A is not null
    }
</code>```

Body:
In Kotlin is there an equivalent to the Swift code below?

if let a = b.val {

} else {

}

Body:
Swift if let statement in Kotlin

The short answer is use simple IF-ELSE as by the time of this comment there is no equivalent in Kotlin LET,

    if(A.isNull()){
// A is null
    }else{
// A is not null
    }


问:
How to avoid handling messages from "child" classes in Symfony Messenger?
I guess I'm missing something in the documentation, but the question is pretty simple.

Let's say I have a message of class MessageOne and MessageTwo which extends MessageOne.

I also have MessageOneHandler which should handle MessageOne:

```<code>__invoke(MessageOne $messageOne)
</code>```

And MessageTwoHandler which should handle only MessageTwo:

```<code>__invoke(MessageTwo $messageTwo)
</code>```

And the problem is when MessageTwo is dispatched it is being handled by both MessageHandlerOne and MessageHandlerTwo. Yes, it is completely sensible due to inheritance and everything is logically correct, but are there any "symfony" ways to prevent that?

Of course, I can solve this issue by reworking of the inheritance of these classes, but is there maybe a better way?

Moreover debug:messenger shows everything as expected, one handler per one message class without inheritance issues.

答:
Inheritance rarely will be a god fit for messages.

If MessageTwo extends MessageOne, then $messageTwo instanceof MessageOne would return true, simple as that.

Also, messages should be very simple and lightweight, so code repetition shouldn't be generally a concern. But if for some reason you do need to reuse some code between message classes, you have a few options:

You could short-circuit the handling so that if get_class($message) !== MessageOne::class then then handler could return without doing any work... but personally I feel it would be a brittle design.

The better options are simply reworking the inheritance model for your messages.

Shared logic between MessageOne and MessageTwo could be moved to a parent AbstractMessage, from which both inherit. Handlers would correctly type-hint the concrete message type, and there would be no confusion.

Depending on the type of code reuse you are going for, you could move the shared code to a Trait or a helper class with static methods. If either of these are any good would depend entirely on the specifics of your application, and in the end would be a matter of opinion.

Body:
I guess I'm missing something in the documentation, but the question is pretty simple.

Let's say I have a message of class MessageOne and MessageTwo which extends MessageOne.

I also have MessageOneHandler which should handle MessageOne:

__invoke(MessageOne $messageOne)

And MessageTwoHandler which should handle only MessageTwo:

__invoke(MessageTwo $messageTwo)

And the problem is when MessageTwo is dispatched it is being handled by both MessageHandlerOne and MessageHandlerTwo. Yes, it is completely sensible due to inheritance and everything is logically correct, but are there any "symfony" ways to prevent that?

Of course, I can solve this issue by reworking of the inheritance of these classes, but is there maybe a better way?

Moreover debug:messenger shows everything as expected, one handler per one message class without inheritance issues.


问:
Credit card validation check in C programming
This a problem from CS50 finding validation of credit card number using luhn's algorithm. I wrote this code but whenever I put any credit card number, the output comes as invalid.Can anyone please help me what my mistake here and how can I move forward with this code.

This is luhn's algorithm formula--
most cards use an algorithm invented by Hans Peter Luhn of IBM. According to Luhn’s algorithm, you can determine if a credit card number is (syntactically) valid as follows:

Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ digits together.
Add the sum to the sum of the digits that weren’t multiplied by 2.
If the total’s last digit is 0 (or, put more formally, if the total modulo 10 is congruent to 0), the number is valid!

```<code>//Project Using Luhn's Algorithm - Credit Card validation

#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main()
{
   long long ccnum = 0;

    int digitcounter = 0 ;
    char result[11] ;
    int sum = 0 ;
    int  divisor = 10 ;

    do
    {
      ccnum = get_long("Enter your credit card number: ") ;
    }
    while (ccnum <= 0) ;

//--------------------CHECKSUM--------------------------------

    //Case-01(Multiply every other digit by 2):

    long long tempccnum = ccnum ;
    while (tempccnum > 0)
    {
        int lastdigit = tempccnum % 10 ;
        sum = sum + lastdigit ;
        tempccnum = tempccnum / 100 ;
    }

    // Case-02(Multiplication every other digit by 2):

    tempccnum = ccnum / 10 ;
    while(tempccnum > 0)
    {
        int secondlastdigit = (tempccnum % 10) ;

        int tempmultiply = secondlastdigit*2 ;

        sum = sum + (tempmultiply % 10) + (tempmultiply / 10)  ;

        tempccnum = tempccnum / 100 ;
    }
//----------first two digit extraction------------

   long long initdigit = 0, tempinitdigit = 0 ;

   while(ccnum)
   {
     initdigit = tempinitdigit  ; // initdigit will hold the first two digits.
     tempinitdigit = ccnum  ;
     ccnum = ccnum/10 ;
   }

//-------------Digit counter----------
    while(ccnum != 0)
    {
          // iterate until ccnum becomes 0
         // remove last digit from ccnum in each iteration
        // increase digitcounter by 1 in each iteration

        ccnum = ccnum / 10 ;
        digitcounter++ ;
    }
  //------------------Final part - Condition checking------------------------

    if(sum % 10 == 0)
    {
        if (digitcounter == 15 && (initdigit == 34 || initdigit == 37))
        {
            strcpy(result, "AMEX\n") ;
        }

        else if (digitcounter == 16 && (initdigit >= 51 && initdigit <=55))
        {
             strcpy(result,"MASTERCARD\n") ;
        }

        else if ((digitcounter == 13 || digitcounter == 16) && tempinitdigit == 4)
        {
             strcpy(result,"VISA\n") ;
        }

        else
        {
             strcpy(result,"INVALID\n") ;
        }

    }

    else
    {
        strcpy(result,"INVALID\n") ;
    }
    printf("%s\n", result) ;
}
</code>```

答:
Your code to extract the first 2 digits is wrong:

```<code>  while(ccnum)
   {
     initdigit = tempinitdigit  ; // initdigit will hold the first two digits.
     tempinitdigit = ccnum  ;
     ccnum = ccnum/10 ;
   }
</code>```

That will just set initdigit to the 2nd digit. However tempinitdigit does hold the 1st digit so you should add this after the while loop:

```<code>   initdigit = initdigit + tempinitdigit * 10;
</code>```

The best way to troubleshoot these kind of problems is to step through the code with a debugger.

Body:
This a problem from CS50 finding validation of credit card number using luhn's algorithm. I wrote this code but whenever I put any credit card number, the output comes as invalid.Can anyone please help me what my mistake here and how can I move forward with this code.

This is luhn's algorithm formula--
most cards use an algorithm invented by Hans Peter Luhn of IBM. According to Luhn’s algorithm, you can determine if a credit card number is (syntactically) valid as follows:

Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ digits together.
Add the sum to the sum of the digits that weren’t multiplied by 2.
If the total’s last digit is 0 (or, put more formally, if the total modulo 10 is congruent to 0), the number is valid!

//Project Using Luhn's Algorithm - Credit Card validation

#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main()
{
   long long ccnum = 0;

    int digitcounter = 0 ;
    char result[11] ;
    int sum = 0 ;
    int  divisor = 10 ;

    do
    {
      ccnum = get_long("Enter your credit card number: ") ;
    }
    while (ccnum <= 0) ;

//--------------------CHECKSUM--------------------------------

    //Case-01(Multiply every other digit by 2):

    long long tempccnum = ccnum ;
    while (tempccnum > 0)
    {
        int lastdigit = tempccnum % 10 ;
        sum = sum + lastdigit ;
        tempccnum = tempccnum / 100 ;
    }

    // Case-02(Multiplication every other digit by 2):

    tempccnum = ccnum / 10 ;
    while(tempccnum > 0)
    {
        int secondlastdigit = (tempccnum % 10) ;

        int tempmultiply = secondlastdigit*2 ;

        sum = sum + (tempmultiply % 10) + (tempmultiply / 10)  ;

        tempccnum = tempccnum / 100 ;
    }
//----------first two digit extraction------------

   long long initdigit = 0, tempinitdigit = 0 ;

   while(ccnum)
   {
     initdigit = tempinitdigit  ; // initdigit will hold the first two digits.
     tempinitdigit = ccnum  ;
     ccnum = ccnum/10 ;
   }

//-------------Digit counter----------
    while(ccnum != 0)
    {
          // iterate until ccnum becomes 0
         // remove last digit from ccnum in each iteration
        // increase digitcounter by 1 in each iteration

        ccnum = ccnum / 10 ;
        digitcounter++ ;
    }
  //------------------Final part - Condition checking------------------------

    if(sum % 10 == 0)
    {
        if (digitcounter == 15 && (initdigit == 34 || initdigit == 37))
        {
            strcpy(result, "AMEX\n") ;
        }

        else if (digitcounter == 16 && (initdigit >= 51 && initdigit <=55))
        {
             strcpy(result,"MASTERCARD\n") ;
        }

        else if ((digitcounter == 13 || digitcounter == 16) && tempinitdigit == 4)
        {
             strcpy(result,"VISA\n") ;
        }

        else
        {
             strcpy(result,"INVALID\n") ;
        }

    }

    else
    {
        strcpy(result,"INVALID\n") ;
    }
    printf("%s\n", result) ;
}

Body:
Your code to extract the first 2 digits is wrong:

  while(ccnum)
   {
     initdigit = tempinitdigit  ; // initdigit will hold the first two digits.
     tempinitdigit = ccnum  ;
     ccnum = ccnum/10 ;
   }

That will just set initdigit to the 2nd digit. However tempinitdigit does hold the 1st digit so you should add this after the while loop:

   initdigit = initdigit + tempinitdigit * 10;

The best way to troubleshoot these kind of problems is to step through the code with a debugger.


问:
Using google fonts with d3.js and SVG
I'm trying to use a custom type face from google fonts:

```<code><link href='http://fonts.googleapis.com/css?family=Karla|Quantico|Audiowide' rel='stylesheet' type='text/css'>
</code>```

I have used them with this css for normal text:

```<code>.customFont{
  font-family: 'Karla' ;
}

<h1 class="customFont"> My text </h1>
</code>```

But when I try to add this type face with d3.js in SVG text elements (e.g. node text in a graph) it removes all other styling I try to add to the class:

```<code>.customFont {
  font-family: 'Karla' ;
  font-weight : bold;
  pointer-events: none;
  stroke:#fff;
  stroke-width:1px;
  fill-opacity: 1;
  fill: #000;
}
</code>```

it changes the font-family to the custom Karla but it doesn't keep all the other properties. How can I get the new type face and the other properties in one class?

答:
Simply add the link in  as in

```<code><head>
href="https://fonts.googleapis.com/css?family=Roboto+Condensed&display=swap" rel="stylesheet">
</head>
</code>```

Next, just add in css.

```<code>.axis text {
fill: #2b2929;
font-family: 'Roboto Condensed';
font-size: 120%;
}
</code>```

That works for me.

ContentLicense: CC BY-SA 3.0

Title: Using google fonts with d3.js and SVG

Body:
I'm trying to use a custom type face from google fonts:

<link href='http://fonts.googleapis.com/css?family=Karla|Quantico|Audiowide' rel='stylesheet' type='text/css'>

I have used them with this css for normal text:

.customFont{
  font-family: 'Karla' ;
}

 My text

But when I try to add this type face with d3.js in SVG text elements (e.g. node text in a graph) it removes all other styling I try to add to the class:

.customFont {
  font-family: 'Karla' ;
  font-weight : bold;
  pointer-events: none;
  stroke:#fff;
  stroke-width:1px;
  fill-opacity: 1;
  fill: #000;
}

it changes the font-family to the custom Karla but it doesn't keep all the other properties. How can I get the new type face and the other properties in one class?

Body:
Simply add the link in  as in

<head>
href="https://fonts.googleapis.com/css?family=Roboto+Condensed&display=swap" rel="stylesheet">
</head>

Next, just add in css.

.axis text {
fill: #2b2929;
font-family: 'Roboto Condensed';
font-size: 120%;
}

That works for me.


问:
Accessing a MySQL database from python
I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is pyodbc but the necessary driver is not available for ppc leopard.

I already know about this.

UPDATE:

I've gotten setuptools to install, but now MySQL-python won't build.

UPDATE:
Now I've gotten sqlalchemy to install but while it will show up when called by the command line it won't import when used in my cgi script.

答:
Try SQL Alchemy.

It is awesome.

OwnerDisplayName: GameFreak

ContentLicense: CC BY-SA 2.5

Title: Accessing a MySQL database from python

LastEditorDisplayName: GameFreak

Body:
Try SQL Alchemy.

It is awesome.

OwnerDisplayName: Matthew Schinckel


问:
UIAlertView raised from background
I'm developing an Alarm App.

When the alarm starts sounding I pop up an UIAlertView in order to offer the user the option to stop it. But when the app is in background the UIAlertView doesn't appears.

How can I do a UIAlert similar to the alert that uses the iOS Alarm?

Thanks!!

答: You could start reading about this: Apple documentation about notifications. You are probably most likely interested in local notification.</p>

Title: UIAlertView raised from background


问:
TypeError: Cannot read property 'RichEmbed' of undefined
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now Took More Than 2 Days To Find A Solution So I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : TypeError: Cannot read property 'RichEmbed' of undefined(18:35)

My Code :

```<code>1:  module.exports.run = async (bot, message, args) => {
2:
3:      let target = message.guild.member(message.mentions.users.first());
4:      let reason = args.slice(1).join(' ');
5:      let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");
6:
7:      // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
8:
9:      if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
10:
11:      if (!target) return message.reply('please specify a member to ban!');
12:      if (!reason) return message.reply('please specify a reason for this ban!');
13:      if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
14:
15:      let embed = new discord.cache.RichEmbed()
16:          .setColor('RANDOM')
17:          .setThumbnail(target.user.avatarURL)
18:          .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
19:          .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
20:          .addField('Banned Time', message.createdAt)
21:          .addField('Banned At', message.channel)
22:          .addField('Banned Reason', reason)
23:          .addFooter('Banned user information', target.user.displayAvatarURL);
24:
25:      message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
26:      target.ban(reason);
27:      logs.send(embed);
28:  };
</code>```

答:
Try this :</p>

```<code>const { RichEmbed } = require ('discord.js');

module.exports.run = async (bot, message, args) => {

let target = message.guild.member(message.mentions.users.first());
let reason = args.slice(1).join(' ');
let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");

// member.guild.channels.cache.find('⚠server_logs', config.logsChannel);

if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');

if (!target) return message.reply('please specify a member to ban!');
if (!reason) return message.reply('please specify a reason for this ban!');
if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);

let embed = new RichEmbed()
.setColor('RANDOM')
.setThumbnail(target.user.avatarURL)
.addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
.addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
.addField('Banned Time', message.createdAt)
.addField('Banned At', message.channel)
.addField('Banned Reason', reason)
.addFooter('Banned user information', target.user.displayAvatarURL);

message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
target.ban(reason);
logs.send(embed);
};
</code>```

Body:
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now Took More Than 2 Days To Find A Solution So I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : TypeError: Cannot read property 'RichEmbed' of undefined(18:35)

My Code :

1:  module.exports.run = async (bot, message, args) => {
2:
3:      let target = message.guild.member(message.mentions.users.first());
4:      let reason = args.slice(1).join(' ');
5:      let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");
6:
7:      // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
8:
9:      if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
10:
11:      if (!target) return message.reply('please specify a member to ban!');
12:      if (!reason) return message.reply('please specify a reason for this ban!');
13:      if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
14:
15:      let embed = new discord.cache.RichEmbed()
16:          .setColor('RANDOM')
17:          .setThumbnail(target.user.avatarURL)
18:          .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
19:          .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
20:          .addField('Banned Time', message.createdAt)
21:          .addField('Banned At', message.channel)
22:          .addField('Banned Reason', reason)
23:          .addFooter('Banned user information', target.user.displayAvatarURL);
24:
25:      message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
26:      target.ban(reason);
27:      logs.send(embed);
28:  };

Body:
Try this :

const { RichEmbed } = require ('discord.js');

module.exports.run = async (bot, message, args) => {

let target = message.guild.member(message.mentions.users.first());
let reason = args.slice(1).join(' ');
let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");

// member.guild.channels.cache.find('⚠server_logs', config.logsChannel);

if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');

if (!target) return message.reply('please specify a member to ban!');
if (!reason) return message.reply('please specify a reason for this ban!');
if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);

let embed = new RichEmbed()
.setColor('RANDOM')
.setThumbnail(target.user.avatarURL)
.addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
.addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
.addField('Banned Time', message.createdAt)
.addField('Banned At', message.channel)
.addField('Banned Reason', reason)
.addFooter('Banned user information', target.user.displayAvatarURL);

message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
target.ban(reason);
logs.send(embed);
};


问:
Can't resolve image into URL: to_model delegated to attachment, but attachment is nil in Rails 5.2
I have the following form:

```<code><%= form_with(model: user, local: true) do |form| %>
  <% if user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.file_field :avatar %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
</code>```

It is being called on my edit page:

```<code><h1>Upload Avatar</h1>
  <%= image_tag(@user.avatar) %>
  <%= render 'form', user: @user %>
<hr>
</code>```

I get the error in the title but I am not sure why the avatar is not being attachd to the user model. I have all the requirements done for active_storage.

has_one_attached :avatar in user model.

In user controller:

```<code>  def identity_params
    params.permit(:email_confirmation, :password, :password_confirmation, :avatar).to_h.symbolize_keys.tap do |params|
      params[:email] = params[:email_confirmation]
    end
  end
</code>```

Also I have all the necessary migrations. Am I missing the actual avatar attaching logic?

答:
I was also facing the same error due to the silly mistake. Actually I added the extra space to local: key. So make sure you are following the proper indentation. And should not miss the configuration. You must declare Active Storage services in config/storage.yml in the following way.

```<code>local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

amazon:
  service: S3
  access_key_id: ""
  secret_access_key: ""
  bucket: ""
  region: "" # e.g. 'us-east-1'
</code>```

Make sure in the environment/development.rb, environment/production.rb and environment/test.rb you have added the following line of code

```<code>config.active_storage.service = :local #environment/development.rb
config.active_storage.service = :amazon ##environment/production.rb
config.active_storage.service = :test #environment/test.rb
</code>```

Body:
I have the following form:

<%= form_with(model: user, local: true) do |form| %>
  <% if user.errors.any? %>

<%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:

      <% user.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= form.file_field :avatar %>

    <%= form.submit %>

<% end %>

It is being called on my edit page:

Upload Avatar

  <%= image_tag(@user.avatar) %>
  <%= render 'form', user: @user %>

I get the error in the title but I am not sure why the avatar is not being attachd to the user model. I have all the requirements done for active_storage.

has_one_attached :avatar in user model.

In user controller:

  def identity_params
    params.permit(:email_confirmation, :password, :password_confirmation, :avatar).to_h.symbolize_keys.tap do |params|
      params[:email] = params[:email_confirmation]
    end
  end

Also I have all the necessary migrations. Am I missing the actual avatar attaching logic?

Body:
I was also facing the same error due to the silly mistake. Actually I added the extra space to local: key. So make sure you are following the proper indentation. And should not miss the configuration. You must declare Active Storage services in config/storage.yml in the following way.

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

amazon:
  service: S3
  access_key_id: ""
  secret_access_key: ""
  bucket: ""
  region: "" # e.g. 'us-east-1'

Make sure in the environment/development.rb, environment/production.rb and environment/test.rb you have added the following line of code

config.active_storage.service = :local #environment/development.rb
config.active_storage.service = :amazon ##environment/production.rb
config.active_storage.service = :test #environment/test.rb


问:
Make angular using CanActive only some path at childRoutes
i'm new with Angular

In my case, i want to use guard in some path

Shell.ts

```<code>export class Shell {
   static childRoutes(routes: Routes): Route {
       return {
           path: '',
           component: ShellComponent, // Component that have a navbar
           children: routes,
           canActivateChild: [AuthenticationGuard],
       };
   }
}
</code>```

shell.component.html

```<code>// some code html of navbar here
<router-outlet></router-outlet>
</code>```

app-routing.module.ts

```<code>const routes: Routes = [
   Shell.childRoutes([
      { path: 'module1', loadChildren: () => import('./module1/module1.module').then(m => m.module1) },
      { path: 'module2', loadChildren: () => import('./module2/module2.module').then(m => m.module2) },
      { path: 'module3', loadChildren: () => import('./module3/module3.module').then(m => m.module3) },
   ]),
];
</code>```

I only want using canActivateChild for module3. How can I do it?

答:
First, you need modify your AuthenticationGuard from CanActivateChild to CanActivate

Second, remove canActivateChild: [AuthenticationGuard] from Shell.ts

Third, if you need using authentication on module1, you just need add canActivate: [AuthenticationGuard] to app-routing.module.ts like this:

```<code>{ path: 'module1', loadChildren: () =>
  import('./module1/module1.module').then(m => m.module1), canActivate: [AuthenticationGuard] },
</code>```

Body:
i'm new with Angular

In my case, i want to use guard in some path

Shell.ts

export class Shell {
   static childRoutes(routes: Routes): Route {
       return {
           path: '',
           component: ShellComponent, // Component that have a navbar
           children: routes,
           canActivateChild: [AuthenticationGuard],
       };
   }
}

shell.component.html

// some code html of navbar here
<router-outlet></router-outlet>

app-routing.module.ts

const routes: Routes = [
   Shell.childRoutes([
      { path: 'module1', loadChildren: () => import('./module1/module1.module').then(m => m.module1) },
      { path: 'module2', loadChildren: () => import('./module2/module2.module').then(m => m.module2) },
      { path: 'module3', loadChildren: () => import('./module3/module3.module').then(m => m.module3) },
   ]),
];

I only want using canActivateChild for module3. How can I do it?

Body:
First, you need modify your AuthenticationGuard from CanActivateChild to CanActivate

Second, remove canActivateChild: [AuthenticationGuard] from Shell.ts

Third, if you need using authentication on module1, you just need add canActivate: [AuthenticationGuard] to app-routing.module.ts like this:

{ path: 'module1', loadChildren: () =>
  import('./module1/module1.module').then(m => m.module1), canActivate: [AuthenticationGuard] },


问:
Match any unicode letter?
In .net you can use \p{L} to match any letter, how can I do the same in Python? Namely, I want to match any uppercase, lowercase, and accented letters.

答:
PyPi regex module supports \p{L} Unicode property class, and many more, see "Unicode codepoint properties, including scripts and blocks" section in the documentation and full list at http://www.unicode.org/Public/UNIDATA/PropList.txt. Using regex module is convenient because you get consistent results across any Python version (mind that the Unicode standard is constantly evolving and the number of supported letters grows).

Install the library using pip install regex (or pip3 install regex) and use

```<code>\p{L}        # To match any Unicode letter
\p{Lu}       # To match any uppercase Unicode letter
\p{Ll}       # To match any lowercase Unicode letter
\p{L}\p{M}*  # To match any Unicode letter and any amount of diacritics after it
</code>```

See some usage examples below:

```<code>import regex
text = r'Abc-++-Абв. It’s “Łąć”!'
# Removing letters:
print( regex.sub(r'\p{L}+', '', text) ) # => -++-. ’ “”!
# Extracting letter chunks:
print( regex.findall(r'\p{L}+', text) ) # => ['Abc', 'Абв', 'It', 's', 'Łąć']
# Removing all but letters:
print( regex.sub(r'\P{L}+', '', text) ) # => AbcАбвItsŁąć
# Removing all letters but ASCII letters:
print( regex.sub(r'[^\P{L}a-zA-Z]+', '', text) ) # => Abc-++-. It’s “”!
</code>```

See a Python demo online

Title: Match any unicode letter?

Body:
PyPi regex module supports \p{L} Unicode property class, and many more, see "Unicode codepoint properties, including scripts and blocks" section in the documentation and full list at http://www.unicode.org/Public/UNIDATA/PropList.txt. Using regex module is convenient because you get consistent results across any Python version (mind that the Unicode standard is constantly evolving and the number of supported letters grows).

Install the library using pip install regex (or pip3 install regex) and use

\p{L}        # To match any Unicode letter
\p{Lu}       # To match any uppercase Unicode letter
\p{Ll}       # To match any lowercase Unicode letter
\p{L}\p{M}*  # To match any Unicode letter and any amount of diacritics after it

See some usage examples below:

import regex
text = r'Abc-++-Абв. It’s “Łąć”!'
# Removing letters:
print( regex.sub(r'\p{L}+', '', text) ) # => -++-. ’ “”!
# Extracting letter chunks:
print( regex.findall(r'\p{L}+', text) ) # => ['Abc', 'Абв', 'It', 's', 'Łąć']
# Removing all but letters:
print( regex.sub(r'\P{L}+', '', text) ) # => AbcАбвItsŁąć
# Removing all letters but ASCII letters:
print( regex.sub(r'[^\P{L}a-zA-Z]+', '', text) ) # => Abc-++-. It’s “”!

See a Python demo online


问:
displaying alert to all the private route when user non logged in user tries to visit private route
I have two route private and public route in my react js application. I want to know is it possible to display alert to all the private route when not logged in user try to visit private route. I don't want to do inside every private component.
I tried by myself but it starts to alert on every page when user is not logged in.

This is my Private route code.

```<code>const PrivateRoute = ({ component: Component, ...rest }) => {
  // console.log("restprivate", rest);
  const { changeBottomNavBar, tansformToButton, changeHeaderForOrder } = rest;
  //console.log("loggedin", Store.getState().user.data.loggedIn);
  return (
    <div style={{ width: "100wv" }}>
      <HeaderContainer
        privateHeader={true}
        changeHeaderForOrder={changeHeaderForOrder}
      />
      <TermsOfUse />
      <PrivacyPolicy />
      <VendorTerms />
      <Route
        {...rest}
        render={(props) =>
          Store.getState().user.data.loggedIn ? (
            <Component {...props} />
          ) : (
            <Component {...props} />
          )
        }
      />
      <Mobile>
        {changeBottomNavBar ? (
          <BottomNavBarContainer />
        ) : (
          <BottomNavBar tansformToButton={tansformToButton} />
        )}
      </Mobile>
      <Desktop>
        <Footer />
      </Desktop>
    </div>
  );
};
</code>```

答:
Refactor the Route component render callback to check the loggedIn value and trigger an alert before returning the component to render.

```<code><Route
  {...rest}
  render={(props) => {
    const { loggedIn } = Store.getState().user.data;
    !loggedIn && alert('This is a private Route');
    return loggedIn ? (
      <Component {...props} />
    ) : (
      <Component {...props} /> // <-- Why return same Component?
    )
  }}
/>
</code>```

Body:
I have two route private and public route in my react js application. I want to know is it possible to display alert to all the private route when not logged in user try to visit private route. I don't want to do inside every private component.
I tried by myself but it starts to alert on every page when user is not logged in.

This is my Private route code.

const PrivateRoute = ({ component: Component, ...rest }) => {
  // console.log("restprivate", rest);
  const { changeBottomNavBar, tansformToButton, changeHeaderForOrder } = rest;
  //console.log("loggedin", Store.getState().user.data.loggedIn);
  return (

      <HeaderContainer
        privateHeader={true}
        changeHeaderForOrder={changeHeaderForOrder}
      />
      <TermsOfUse />
      <PrivacyPolicy />
      <VendorTerms />
      <Route
        {...rest}
        render={(props) =>
          Store.getState().user.data.loggedIn ? (
            <Component {...props} />
          ) : (
            <Component {...props} />
          )
        }
      />
      <Mobile>
        {changeBottomNavBar ? (
          <BottomNavBarContainer />
        ) : (
          <BottomNavBar tansformToButton={tansformToButton} />
        )}
      </Mobile>
      <Desktop>

      </Desktop>

  );
};

Body:
Refactor the Route component render callback to check the loggedIn value and trigger an alert before returning the component to render.

<Route
  {...rest}
  render={(props) => {
    const { loggedIn } = Store.getState().user.data;
    !loggedIn && alert('This is a private Route');
    return loggedIn ? (
      <Component {...props} />
    ) : (
      <Component {...props} /> // <-- Why return same Component?
    )
  }}
/>


问:
Images are not resizing
I am making a gallery website with materializedcss. I am trying to make it so 4 images show up on each row, with them not looking so big, however with what I have written, all the images are displaying in their full size, rather than being minimzed to then be expanded via the materialboxed class. I am unsure if it is a problem with the css I have written, or through the materialboxed class from materialized, but from the jsfiddle, it seems like it is a problem with their class.

https://jsfiddle.net/ptfbkwre/

https://materializecss.com/media.html

```<code><div id="recent">
      <div class="imagetab-grid">
        <img class="materialboxed" src="img/xjErLux.jpg" data-caption="short description. idk. image looks cool!">
      </div>
      <div class="imagetab-grid">
        <img class="materialboxed" src="img/07xoCEp.jpg" data-caption="short description. idk. image looks cool!">
      </div>
      <div class="imagetab-grid">
        <img class="materialboxed" src="img/903IrFQ.jpg" data-caption="short description. idk. image looks cool!">
      </div>
    </div>

.imagetab-grid{
  width: 25%;
  margin: 10px;
  padding: 10px;
}

.imagetab-grid>img {
  width: 100%;
}
</code>```

答:
If you wanted to do this the Materialize way rather than the generic css way, use the provided .reponsive-img utility class to force images to respect the width of their containers:

```<code><img src="" alt="" class="responsive-img">
</code>```

Also, you can easily achieve a 4 column grid using the provided grid system - that's what it's for:

```<code><div class="container">
  <div class="row">
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
  </div>
</div>
</code>```

Codepen.

Title: Images are not resizing

Body:
I am making a gallery website with materializedcss. I am trying to make it so 4 images show up on each row, with them not looking so big, however with what I have written, all the images are displaying in their full size, rather than being minimzed to then be expanded via the materialboxed class. I am unsure if it is a problem with the css I have written, or through the materialboxed class from materialized, but from the jsfiddle, it seems like it is a problem with their class.

https://jsfiddle.net/ptfbkwre/

https://materializecss.com/media.html

.imagetab-grid{
  width: 25%;
  margin: 10px;
  padding: 10px;
}

.imagetab-grid>img {
  width: 100%;
}

Body:
If you wanted to do this the Materialize way rather than the generic css way, use the provided .reponsive-img utility class to force images to respect the width of their containers:

<img src="" alt="" class="responsive-img">

Also, you can easily achieve a 4 column grid using the provided grid system - that's what it's for:

<div class="container">
  <div class="row">
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
    <div class="col s12 m6 l3">
      <img src="" alt="" class="responsive-img">
    </div>
  </div>
</div>

Codepen.


问:
How to yield all possibilities using efficient nesting in Python?
Forex Triangular Arb problem:

I'm currently trying to solve an efficient way on how to yield all of the elements of a Dictionary.items(). Let's suppose the array has N length and I need to acquire a all possible combinations where [[A,B],[A,C],[C,B]...]

Currently, it is not efficient due to nesting

```<code>def Arb(tickers: dict) -> list:
    for first_pair in tickers.items():
        pair1: list = first_pair[0].split("/")

        for second_pair in tickers.items():
            pair2: list = second_pair[0].split("/")

            if pair2[0] == pair1[0] and pair2[1] != pair1[1]:

                for third_pair in tickers.items():
                    pair3: list = third_pair[0].split("/")

                    if pair3[0] == pair2[1] and pair3[1] == pair1[1]:

                      id1 = first_pair[1]["id"]
                      id2 = second_pair[1]["id"]
                      id3 = third_pair[1]["id"]

                      yield [pair1, id1, pair2, id2, pair3, id3]

</code>```

What would be the efficient/pythonic way to return a List with all possible items?

This is an example

```<code>tickers =   {"EZ/TC": {
              "id": 1
            },
            "LM/TH": {
              "id": 2
            },
            "CD/EH": {
              "id": 3
            },
            "EH/TC": {
              "id":4
            },
            "LM/TC": {
              "id": 5
            },
            "CD/TC":{
              "id": 6
            },
            "BT/TH": {
              "id": 7,
            },
            "BT/TX": {
              "id": 8,
            },
            "TX/TH":{
              "id": 9
            }

            }
</code>```

```<code>print(list(Arb(tickers)))

[(['CD', 'TC'], 6, ['CD', 'EH'], 3, ['EH', 'TC'], 4), (['BT', 'TH'], 7, ['BT', 'TX'], 8, ['TX', 'TH'], 9)]

</code>```

The Output is a Single List comprised of "lists" of all possibilities.

答:
You don't to iterate on items() as you don't use the values, just the keys. Then you want use itertools.permutations to get all the combinations in every order of each pair, then keep the ones that matches letters

```<code>def verify(v1, v2, v3):
    return v1[0] == v2[0] and v1[1] == v3[1] and v2[1] == v3[0]

def arb(tickers) -> List:
    c = permutations([x.split("/") for x in tickers], r=3)
    return list(filter(lambda x: verify(*x), c))
</code>```

Body:
Forex Triangular Arb problem:

I'm currently trying to solve an efficient way on how to yield all of the elements of a Dictionary.items(). Let's suppose the array has N length and I need to acquire a all possible combinations where [[A,B],[A,C],[C,B]...]

Currently, it is not efficient due to nesting

def Arb(tickers: dict) -> list:
    for first_pair in tickers.items():
        pair1: list = first_pair[0].split("/")

        for second_pair in tickers.items():
            pair2: list = second_pair[0].split("/")

            if pair2[0] == pair1[0] and pair2[1] != pair1[1]:

                for third_pair in tickers.items():
                    pair3: list = third_pair[0].split("/")

                    if pair3[0] == pair2[1] and pair3[1] == pair1[1]:

                      id1 = first_pair[1]["id"]
                      id2 = second_pair[1]["id"]
                      id3 = third_pair[1]["id"]

                      yield [pair1, id1, pair2, id2, pair3, id3]

What would be the efficient/pythonic way to return a List with all possible items?

This is an example

tickers =   {"EZ/TC": {
              "id": 1
            },
            "LM/TH": {
              "id": 2
            },
            "CD/EH": {
              "id": 3
            },
            "EH/TC": {
              "id":4
            },
            "LM/TC": {
              "id": 5
            },
            "CD/TC":{
              "id": 6
            },
            "BT/TH": {
              "id": 7,
            },
            "BT/TX": {
              "id": 8,
            },
            "TX/TH":{
              "id": 9
            }

            }

print(list(Arb(tickers)))

[(['CD', 'TC'], 6, ['CD', 'EH'], 3, ['EH', 'TC'], 4), (['BT', 'TH'], 7, ['BT', 'TX'], 8, ['TX', 'TH'], 9)]

The Output is a Single List comprised of "lists" of all possibilities.

Body:
You don't to iterate on items() as you don't use the values, just the keys. Then you want use itertools.permutations to get all the combinations in every order of each pair, then keep the ones that matches letters

def verify(v1, v2, v3):
    return v1[0] == v2[0] and v1[1] == v3[1] and v2[1] == v3[0]

def arb(tickers) -> List:
    c = permutations([x.split("/") for x in tickers], r=3)
    return list(filter(lambda x: verify(*x), c))


问:
Rails on Github Pages
I recently set up my own Github Pages site, and I want to extend the functionality. I have a very basic site set up, with some HTML, CSS, Tailwind, and jQuery. I want to use Rails on my site for a blog. I was planning on using Jekyll, but I had some weird installation errors that put me off, and I want to learn Rails and Ruby anyhow, so I can broaden my horizons. Is it possible to host a site with Rails on Github Pages?

Note: I saw the older thread from ~2015 regarding a similar question, but I wasn't sure if those answers are up to date.

Thanks in advance.

答: No, it is not possible since GitHub Pages only provide serverless static site hosting, there is no server to run Rails app.</p>

Title: Rails on Github Pages


问:
Unity2 resolve problem
guys.
We are using MS Unity 2 framework for an application.

We have code similar to described below

```<code>public class Context:IContext
{
    public IFlow Flow {get;set;}
}

public class SomeFlow:IFlow
{
    public IContext Context {get;set;}
}
...
//Some code for getting IContext object
{
     ...
     IContext context = container.Resolve<IContext>();
     ...
}
</code>```

We need to describe the relationship between the classes Context and SomeFlow using Unity. And the problem with constructing is while container is constructing Context object it needs to create SomeFlow object which requires Context object and so on.
In our case SomeFlow object must contain link to the Context object created before. So the algorithm must be next:

```<code>1. Create Context object
2. Create SomeFlow object
3. Point Context.Flow to SomeFlow
4. Point SomeFlow.Context to Context
</code>```

And the question is how could we describe it with unity?

答:
Alternatively to Mark's answer you can register an InjectionFactory that does the wiring for you. Registering the following delegate prevents you from having to change your application design:

```<code>container.Register<IContext>(new InjectionFactory(c =>
{
    var context = container.Resolve<IContext>();
    var flow = container.Resolve<IFlow>();
    context.Flow = flow
    flow.Context = context;
    return context;
}));
</code>```

Title: Unity2 resolve problem

Body:
guys.
We are using MS Unity 2 framework for an application.

We have code similar to described below

public class Context:IContext
{
    public IFlow Flow {get;set;}
}

public class SomeFlow:IFlow
{
    public IContext Context {get;set;}
}
...
//Some code for getting IContext object
{
     ...
     IContext context = container.Resolve<IContext>();
     ...
}

We need to describe the relationship between the classes Context and SomeFlow using Unity. And the problem with constructing is while container is constructing Context object it needs to create SomeFlow object which requires Context object and so on.
In our case SomeFlow object must contain link to the Context object created before. So the algorithm must be next:

1. Create Context object
2. Create SomeFlow object
3. Point Context.Flow to SomeFlow
4. Point SomeFlow.Context to Context

And the question is how could we describe it with unity?

Body:
Alternatively to Mark's answer you can register an InjectionFactory that does the wiring for you. Registering the following delegate prevents you from having to change your application design:

container.Register<IContext>(new InjectionFactory(c =>
{
    var context = container.Resolve<IContext>();
    var flow = container.Resolve<IFlow>();
    context.Flow = flow
    flow.Context = context;
    return context;
}));


问:
How to handle CSV files in this Python script
Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data, without turning it into a dictionary. How do I skip over the header record with the field names?

import os
import csv

# Create a file with data in it
def create_file(filename):
    with open(filename, "w") as file:
        file.write("name,color,type\n")
        file.write("carnation,pink,annual\n")
        file.write("daffodil,yellow,perennial\n")
        file.write("iris,blue,perennial\n")
        file.write("poinsettia,red,perennial\n")
        file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
    return_string = ""
    # Call the function to create the file
    create_file(filename)

    # Open the file
    with open(filename) as file:
        # Read the rows of the file
        rows = csv.reader(file)
        rows = list(rows)
        # Process each row
        for row in rows:
            name, color, ty = row
            # Format the return string for data rows only
            if row != rows[0]:
                return_string += "a {} {} is {}\n".format(name, color, ty)
    return return_string

#Call the function
print(contents_of_file("flowers.csv"))
```

<p>After submitting my answer, the following message is shown:</p>

```Not quite, contents_of_file returned:
a carnation pink is
annual
a daffodil yellow is perennial
a iris blue is
perennial
a poinsettia red is perennial
a sunflower yellow
is annual

The output should be:
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a
red poinsettia is perennial
a yellow sunflower is annual
```

How can I correct this problem?

答:
You can skip a line by reading it in and discarding it before you instantiate the csv.reader object:

```<code>  with open(filename) as file:
    file.readline()  # header row
    for row in csv.reader(file):
      # do stuff
</code>```

or you can just discard the first line by converting to a list and looping from 1:

```<code>  with open(filename) as file:
    for row in list(csv.reader(file))[1:]:
      # do stuff
</code>```

or maybe like this if you want to loop over the iterator without loading all the rows into memory:

```<code>  with open(filename) as file:
    first = True
    for row in csv.reader(file):
      if first:
         first = False
         continue
      # do stuff
</code>```

Or maybe you would prefer to use the dictionary form of the csv reader, so that instead of discarding the header row, you use it to provide dictionary keys:

```<code>  with open(filename) as file:
    for row in csv.DictReader(file):
      # row is now a dictionary, e.g.
      # {'color': 'pink', 'type': 'annual', 'name': 'carnation'}
      # do stuff
</code>```

Body:
Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data, without turning it into a dictionary. How do I skip over the header record with the field names?

import os
import csv

# Create a file with data in it
def create_file(filename):
    with open(filename, "w") as file:
        file.write("name,color,type\n")
        file.write("carnation,pink,annual\n")
        file.write("daffodil,yellow,perennial\n")
        file.write("iris,blue,perennial\n")
        file.write("poinsettia,red,perennial\n")
        file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
    return_string = ""
    # Call the function to create the file
    create_file(filename)

    # Open the file
    with open(filename) as file:
        # Read the rows of the file
        rows = csv.reader(file)
        rows = list(rows)
        # Process each row
        for row in rows:
            name, color, ty = row
            # Format the return string for data rows only
            if row != rows[0]:
                return_string += "a {} {} is {}\n".format(name, color, ty)
    return return_string

#Call the function
print(contents_of_file("flowers.csv"))

After submitting my answer, the following message is shown:

Not quite, contents_of_file returned:
a carnation pink is
annual
a daffodil yellow is perennial
a iris blue is
perennial
a poinsettia red is perennial
a sunflower yellow
is annual

The output should be:
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a
red poinsettia is perennial
a yellow sunflower is annual

How can I correct this problem?

Body:
You can skip a line by reading it in and discarding it before you instantiate the csv.reader object:

  with open(filename) as file:
    file.readline()  # header row
    for row in csv.reader(file):
      # do stuff

or you can just discard the first line by converting to a list and looping from 1:

  with open(filename) as file:
    for row in list(csv.reader(file))[1:]:
      # do stuff

or maybe like this if you want to loop over the iterator without loading all the rows into memory:

  with open(filename) as file:
    first = True
    for row in csv.reader(file):
      if first:
         first = False
         continue
      # do stuff

Or maybe you would prefer to use the dictionary form of the csv reader, so that instead of discarding the header row, you use it to provide dictionary keys:

  with open(filename) as file:
    for row in csv.DictReader(file):
      # row is now a dictionary, e.g.
      # {'color': 'pink', 'type': 'annual', 'name': 'carnation'}
      # do stuff


问:
Use .join() with callback condition
Here is the situation, I'd like to join each elements of an array depending on a condition. I imagine something like a combinaison of join and reduce functions, e.g. :

const SEPARATOR =  ' ';
const array = ['I', 'am', 'coding'];

// my imaginary function (this does not work voluntarily, only for the example)
const output = array.join((previous, current) => {
    // when the function return true, it joins previous with current on the same index, else not
    return (previous + current).length < 6);
}, SEPARATOR);

console.log(output); // expected output : ['I am', 'coding']
```

To be clear, what I'm asking here is is there a way to achieve that with existing logic (for example, using a function similar to join) without recreating a whole logic.

FYI I found a similar question here but does not answer mine, since the goal was only to remove undefined values.

答:
Version with reduce:

const array = ['I', 'am', 'coding'];
const SEPARATOR = ' ';

const result = array.reduce((acc, val) => {
    if (acc.length === 0 || (acc[acc.length - 1] + SEPARATOR + val).length >= 6) {
        acc.push(val);
    } else {
        acc[acc.length - 1] += SEPARATOR + val;
    }

    return acc;
}, []);

console.log(result);```

Title: Use .join() with callback condition

Body:
Here is the situation, I'd like to join each elements of an array depending on a condition. I imagine something like a combinaison of join and reduce functions, e.g. :

const SEPARATOR =  ' ';
const array = ['I', 'am', 'coding'];

// my imaginary function (this does not work voluntarily, only for the example)
const output = array.join((previous, current) => {
    // when the function return true, it joins previous with current on the same index, else not
    return (previous + current).length < 6);
}, SEPARATOR);

console.log(output); // expected output : ['I am', 'coding']

To be clear, what I'm asking here is is there a way to achieve that with existing logic (for example, using a function similar to join) without recreating a whole logic.

FYI I found a similar question here but does not answer mine, since the goal was only to remove undefined values.


问:
CSS transform perspective rotateX with transition rapidly hover in out glitch
Here is my code.

.ground {
        height: 250px;
        width: 250px;
        background-color: tomato;
        margin: 50vh auto;
        transform: translateY(-50%);
    }

    .floor-1 {
        height: 100%;
        width: 100%;
        background-color: turquoise;
        transition: transform 3s;
    }

    .floor-1:hover {
        transform-origin: left center;
        transform: perspective(50em) rotateX(180deg);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ground">
    <div class="floor-1">Hello</div>
</div></code>```

Now when i try hover in and out 5-10 times is 2-3 s it gives me weird behavior. Div floor-1 nearly about to come out of screen. Why this is happening and how to solve it?

答:
You need to have persepctive initially on the element or this one will also have transition creating the bad effect you are getting. Same thing for transform-origin.

.ground {
  height: 250px;
  width: 250px;
  background-color: tomato;
  margin: 50vh auto;
  transform: translateY(-50%);
}

.floor-1 {
  height: 100%;
  width: 100%;
  background-color: turquoise;
  transition: transform 3s;
  transform-origin: left center;
  transform: perspective(50em) rotateX(0deg);
}

.floor-1:hover {
  transform: perspective(50em) rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ground">
  <div class="floor-1">Hello</div>
</div></code>```

You can also add the perspective on the parent element:

.ground {
  height: 250px;
  width: 250px;
  background-color: tomato;
  margin: 50vh auto;
  transform: translateY(-50%);
  perspective:50em;
  perspective-origin:left center;
}

.floor-1 {
  height: 100%;
  width: 100%;
  background-color: turquoise;
  transition: transform 3s;
  transform:  rotateX(0deg);
}

.floor-1:hover {
  transform: rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ground">
  <div class="floor-1">Hello</div>
</div></code>```

Body:
Here is my code.

.ground {
        height: 250px;
        width: 250px;
        background-color: tomato;
        margin: 50vh auto;
        transform: translateY(-50%);
    }

    .floor-1 {
        height: 100%;
        width: 100%;
        background-color: turquoise;
        transition: transform 3s;
    }

    .floor-1:hover {
        transform-origin: left center;
        transform: perspective(50em) rotateX(180deg);
    }

Hello

Now when i try hover in and out 5-10 times is 2-3 s it gives me weird behavior. Div floor-1 nearly about to come out of screen. Why this is happening and how to solve it?

Body:
You need to have persepctive initially on the element or this one will also have transition creating the bad effect you are getting. Same thing for transform-origin.

.ground {
  height: 250px;
  width: 250px;
  background-color: tomato;
  margin: 50vh auto;
  transform: translateY(-50%);
}

.floor-1 {
  height: 100%;
  width: 100%;
  background-color: turquoise;
  transition: transform 3s;
  transform-origin: left center;
  transform: perspective(50em) rotateX(0deg);
}

.floor-1:hover {
  transform: perspective(50em) rotateX(180deg);
}

<div class="ground">
  <div class="floor-1">Hello</div>
</div>

You can also add the perspective on the parent element:

.ground {
  height: 250px;
  width: 250px;
  background-color: tomato;
  margin: 50vh auto;
  transform: translateY(-50%);
  perspective:50em;
  perspective-origin:left center;
}

.floor-1 {
  height: 100%;
  width: 100%;
  background-color: turquoise;
  transition: transform 3s;
  transform:  rotateX(0deg);
}

.floor-1:hover {
  transform: rotateX(180deg);
}

<div class="ground">
  <div class="floor-1">Hello</div>
</div>


问:
Angular app deployment to IIS - Images not displaying (Static URLs)
I am deploying an angular 6 app to IIS. I installed IIS Rewrite module and also updated the web.config file and index.html file with Base URLs and rewrite rules.

Issue is Login page shows up without the logo/images. I tried to see what is wrong.
http://localhost/ATSTV2/#/login (This shows up the login page with controls and without images)

I looked at the image urls referred and it shows up an the source as http://localhost/assets/Logo_White.png which is incorrect.
The correct image link is http://localhost/ATSTV2/assets/Logo_White.png

Apart from changing my web.config and index.html for base URL, should I make some global changes and ensure the static urls are referred correctly?

This whole application works locally just fine with angular CLI ng serve. But when deploying to server I am deploying it to IIS and hence following some suggested approaches in the internet.

答:
make build with command</p>

```<code>ng build --base-href="/ATSTV2/"
</code>```

Body:
make build with command

ng build --base-href="/ATSTV2/"


答:
GitHub Pages only for static sites. Here is the quote from the documentation

GitHub Pages is a static site hosting service that takes HTML, CSS, and JavaScript files straight from a repository on GitHub,

If you want to host Rails-app try Heroku or something similar.

Title: Rails on Github Pages

Body:
I recently set up my own Github Pages site, and I want to extend the functionality. I have a very basic site set up, with some HTML, CSS, Tailwind, and jQuery. I want to use Rails on my site for a blog. I was planning on using Jekyll, but I had some weird installation errors that put me off, and I want to learn Rails and Ruby anyhow, so I can broaden my horizons. Is it possible to host a site with Rails on Github Pages?

Note: I saw the older thread from ~2015 regarding a similar question, but I wasn't sure if those answers are up to date.

Thanks in advance.