问:
How can I re-render an instance of an element generated while mapping an array in react js?
I'm working on this trivia game, fetching the trivia from Trivia Open DB API. The questions are multiple choice, the correct_answer is a key / value pair, while the incorrect_answer is a key with a value of an array with three incorrect answers, therefore I created a new array with the incorrect answer and randomly inserted the correct answer to that array.

I mapped that array to render once instance for each element of the array and I want to only re-render (change the background color) of the clicked answer, but can't figure out how to do this. I console logged my solution to determine if you clicked the correct answer or not, and it works, but can't figure out how to re-render just the instance that was clicked instead of all the jsx elements of the array. Here's my code:

```<code>import React, {useState, useEffect} from 'react'
import { nanoid } from 'nanoid'

export default function Question(){
    const [questions, setQuestions] = useState("")

    useEffect(function() {

    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
        .then(res => res.json())
        .then(data => setQuestions(data.results.map(triviaQuestion =>{

        const randomPosition = Math.floor(Math.random()*4)
        const questionDisplayed = triviaQuestion.question;
        const incorrectAnswersArray = triviaQuestion.incorrect_answers;
        incorrectAnswersArray.splice(randomPosition, 0, triviaQuestion.correct_answer)
        const possibleAnsewrs = incorrectAnswersArray.map(answer => answer)
        function selectAnswer(event){
            event.target.id == possibleAnsewrs.indexOf(triviaQuestion.correct_answer) ? console.log("Correct!!") : console.log("Incorrect, the answer is: "+triviaQuestion.correct_answer + " " + possibleAnsewrs.indexOf(triviaQuestion.correct_answer))
                }
        const allAnswers = incorrectAnswersArray.map(answer =>
            <p
                id={possibleAnsewrs.indexOf(answer)}
                key={nanoid()}
                onClick={selectAnswer}
                className="question--answers"
                >
                {answer}
            </p>)

        return (
        <div
            key={nanoid()} className='question--container'
            >
            <h3 key={nanoid()} className="question" >{questionDisplayed}</h3>
            <div
                key={nanoid()} className='question--answer-container'>
            {allAnswers}
            </div>
        </div>
        )
    }
        )))
},[])
    return(
            <div>
             {questions}
            </div>
    )
}
</code>```

答:
You should not store JSX in state, store only the data and render the JSX from state. When an answer is clicked you update the state. When state is updated it will trigger a rerender of your UI. What you update is up to you.

Example:

```<code>function Question() {
  const [questions, setQuestions] = useState([]);

  useEffect(function () {
    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
      .then((res) => res.json())
      .then((data) => {
        setQuestions(
          data.results.map((question) => ({
            id: nanoid(),
            ...question,
            answers: [
              ...question.incorrect_answers,
              question.correct_answer
            ].sort(() => Math.random() - 0.5)
          }))
        );
      });
  }, []);

  const selectAnswer = (question) => (event) => {
    event.target.id === question.correct_answer
      ? console.log("Correct!!")
      : console.log("Incorrect, the answer is: " + question.correct_answer);

    setQuestions((questions) =>
      questions.map((el) =>
        el.id === question.id
          ? {
              ...el,
              answered: event.target.id,
              isCorrect: event.target.id === question.correct_answer
            }
          : el
      )
    );
  };

  return (
    <div>
      {questions.map((question) => {
        return (
          <div key={question.id} className="question--container">
            <h3
              className="question"
              dangerouslySetInnerHTML={{ __html: question.question }}
            />
            <div className="question--answer-container">
              {question.answers.map((answer) => (
                <p
                  key={answer}
                  id={answer}
                  onClick={selectAnswer(question)}
                  className={[
                    "question--answers",
                    question.answered === answer &&
                      (question.isCorrect ? "correct" : "incorrect")
                  ]
                    .filter(Boolean)
                    .join(" ")}
                >
                  {answer}
                </p>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}
</code>```

CSS

```<code>correct {
  background-color: lightgreen;
  border: 1px solid green;
  border-radius: 1rem;
}

.incorrect {
  background-color: lightcoral;
  border: 1px solid red;
  border-radius: 1rem;
}
</code>```

Body:
I'm working on this trivia game, fetching the trivia from Trivia Open DB API. The questions are multiple choice, the correct_answer is a key / value pair, while the incorrect_answer is a key with a value of an array with three incorrect answers, therefore I created a new array with the incorrect answer and randomly inserted the correct answer to that array.

I mapped that array to render once instance for each element of the array and I want to only re-render (change the background color) of the clicked answer, but can't figure out how to do this. I console logged my solution to determine if you clicked the correct answer or not, and it works, but can't figure out how to re-render just the instance that was clicked instead of all the jsx elements of the array. Here's my code:

import React, {useState, useEffect} from 'react'
import { nanoid } from 'nanoid'

export default function Question(){
    const [questions, setQuestions] = useState("")

    useEffect(function() {

    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
        .then(res => res.json())
        .then(data => setQuestions(data.results.map(triviaQuestion =>{

        const randomPosition = Math.floor(Math.random()*4)
        const questionDisplayed = triviaQuestion.question;
        const incorrectAnswersArray = triviaQuestion.incorrect_answers;
        incorrectAnswersArray.splice(randomPosition, 0, triviaQuestion.correct_answer)
        const possibleAnsewrs = incorrectAnswersArray.map(answer => answer)
        function selectAnswer(event){
            event.target.id == possibleAnsewrs.indexOf(triviaQuestion.correct_answer) ? console.log("Correct!!") : console.log("Incorrect, the answer is: "+triviaQuestion.correct_answer + " " + possibleAnsewrs.indexOf(triviaQuestion.correct_answer))
                }
        const allAnswers = incorrectAnswersArray.map(answer =>

                {answer}

)

        return (

{questionDisplayed}

            {allAnswers}

        )
    }
        )))
},[])
    return(

             {questions}

    )
}

Body:
You should not store JSX in state, store only the data and render the JSX from state. When an answer is clicked you update the state. When state is updated it will trigger a rerender of your UI. What you update is up to you.

Example:

function Question() {
  const [questions, setQuestions] = useState([]);

  useEffect(function () {
    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
      .then((res) => res.json())
      .then((data) => {
        setQuestions(
          data.results.map((question) => ({
            id: nanoid(),
            ...question,
            answers: [
              ...question.incorrect_answers,
              question.correct_answer
            ].sort(() => Math.random() - 0.5)
          }))
        );
      });
  }, []);

  const selectAnswer = (question) => (event) => {
    event.target.id === question.correct_answer
      ? console.log("Correct!!")
      : console.log("Incorrect, the answer is: " + question.correct_answer);

    setQuestions((questions) =>
      questions.map((el) =>
        el.id === question.id
          ? {
              ...el,
              answered: event.target.id,
              isCorrect: event.target.id === question.correct_answer
            }
          : el
      )
    );
  };

  return (
    <div>
      {questions.map((question) => {
        return (
          <div key={question.id} className="question--container">
            <h3
              className="question"
              dangerouslySetInnerHTML={{ __html: question.question }}
            />
            <div className="question--answer-container">
              {question.answers.map((answer) => (
                <p
                  key={answer}
                  id={answer}
                  onClick={selectAnswer(question)}
                  className={[
                    "question--answers",
                    question.answered === answer &&
                      (question.isCorrect ? "correct" : "incorrect")
                  ]
                    .filter(Boolean)
                    .join(" ")}
                >
                  {answer}
                </p>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

CSS

correct {
  background-color: lightgreen;
  border: 1px solid green;
  border-radius: 1rem;
}

.incorrect {
  background-color: lightcoral;
  border: 1px solid red;
  border-radius: 1rem;
}


来源: stackexchange

问:
How can I import kotlin functions to java classes?
I am currently using KotlinModule class in my java file by importing import com.fasterxml.jackson.module.kotlin.KotlinModule;, but in recent jackson library upgrade (using 2.13) it is has been depricated. I was looking for the new convention, and came across this https://github.com/FasterXML/jackson-module-kotlin#usage

however I am not able to load the recommended functions in java file, i think that only works in Kotlin file. Is there an alternative?

答:
This module uses Kotlin extension functions, they are all defined in an Extensions.kt file and as such are accessible by importing the ExtensionsKt class. For example :

```<code>import com.fasterxml.jackson.module.kotlin.ExtensionsKt;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = ExtensionsKt.jacksonObjectMapper();
</code>```

If the method extends a type, for example in Kotlin :

```<code>val mapper = ObjectMapper().registerKotlinModule()
</code>```

The method is defined in kotlin as :

```<code>fun ObjectMapper.registerKotlinModule(): ObjectMapper
</code>```

It will be converted in java to :

```<code>public static final ObjectMapper registerKotlinModule(@NotNull ObjectMapper $this$registerKotlinModule)
</code>```

So to use it, you need to pass the extended type :

```<code>ObjectMapper mapper = ExtensionsKt.registerKotlinModule(new ObjectMapper());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This module uses Kotlin extension functions, they are all defined in an Extensions.kt file and as such are accessible by importing the ExtensionsKt class. For example :

import com.fasterxml.jackson.module.kotlin.ExtensionsKt;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = ExtensionsKt.jacksonObjectMapper();

If the method extends a type, for example in Kotlin :

val mapper = ObjectMapper().registerKotlinModule()

The method is defined in kotlin as :

fun ObjectMapper.registerKotlinModule(): ObjectMapper

It will be converted in java to :

public static final ObjectMapper registerKotlinModule(@NotNull ObjectMapper $this$registerKotlinModule)

So to use it, you need to pass the extended type :

ObjectMapper mapper = ExtensionsKt.registerKotlinModule(new ObjectMapper());


问:
MenuItem's checked state is not shown correctly by its icon
I have MenuItem defined this way:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_starred"
        android:icon="@drawable/btn_star"
        android:title="@string/description_star"
        android:checkable="true"
        android:checked="true"
        android:orderInCategory="1"
        android:showAsAction="always" />
</menu>
</code>```

and btn_star.xml defined this way:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="false"
        android:drawable="@drawable/btn_star_off_normal" />
    <item
        android:state_checked="true"
        android:drawable="@drawable/btn_star_on_normal" />
</selector>
</code>```

When I create an options menu using this, however, the icon is never shown in its checked state, even if the MenuItem's isChecked() property is true.

I'm using the ActionBarSherlock control, however, I'm getting the same result if I simply create a normal options menu and call setChecked(true). It still displays the btn_star_off drawable regardless of the checked state of the item.

The onOptionsItemSelected() method is being called correctly, and I can successfully change the checked property:

```<code>@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.isCheckable()) {
            item.setChecked(!item.isChecked());
        }
        return super.onOptionsItemSelected(item);
}
</code>```

Setting a breakpoint here shows the isChecked property being changed, but the icon itself is not updated to reflect the correct state.

Is there something I'm missing here? Am I doing this incorrectly? I can't figure out why this wouldn't be working correctly.

答:
According to the official document at http://developer.android.com/guide/topics/ui/menus.html

Note: Menu items in the Icon Menu (from the Options Menu) cannot
  display a checkbox or radio button. If you choose to make items in the
  Icon Menu checkable, you must manually indicate the checked state by
  swapping the icon and/or text each time the state changes.

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I have MenuItem defined this way:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_starred"
        android:icon="@drawable/btn_star"
        android:title="@string/description_star"
        android:checkable="true"
        android:checked="true"
        android:orderInCategory="1"
        android:showAsAction="always" />
</menu>

and btn_star.xml defined this way:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="false"
        android:drawable="@drawable/btn_star_off_normal" />
    <item
        android:state_checked="true"
        android:drawable="@drawable/btn_star_on_normal" />
</selector>

When I create an options menu using this, however, the icon is never shown in its checked state, even if the MenuItem's isChecked() property is true.

I'm using the ActionBarSherlock control, however, I'm getting the same result if I simply create a normal options menu and call setChecked(true). It still displays the btn_star_off drawable regardless of the checked state of the item.

The onOptionsItemSelected() method is being called correctly, and I can successfully change the checked property:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.isCheckable()) {
            item.setChecked(!item.isChecked());
        }
        return super.onOptionsItemSelected(item);
}

Setting a breakpoint here shows the isChecked property being changed, but the icon itself is not updated to reflect the correct state.

Is there something I'm missing here? Am I doing this incorrectly? I can't figure out why this wouldn't be working correctly.


问: Understanding the "type" attribute in a

Title: Understanding the "type" attribute in a <script> tag

Body: I'm seeking a clear explanation of the type attribute inside an html

Body:
Simple:

Browser engine just understand type="type/javascript" then run JS code.

You can add your custom type like type="type/f*ckjs" but browser skip script element ! :)

When add transformer library to HTML file like bablejs, babeljs decide read any <script> tags with define explicit type like type/babel or type/jsx and read src file and transform code to JS executable.


问:
Turbo C gives a totally different output than GCC, although the same code
So, here I wanted to add 2 polynomials using a linked-list in C. It gave a perfect output when compiled with GCC, but when compiled with TurboC++, it messed up...

The output it gave in GCC was:

Polynomial 1:   6x^3 + 10x^2 + 0x + 5
Polynomial 2:   4x^2 + 2x + 1
Added Polynomial :      6x^3 + 14x^2 + 2x + 6
```
<p>The Output it  gave in TurboC++:</p>
<pre class="lang-none prettyprint-override"><code>Polynomial 1:   6x^3 + <br>
Polynomial 2:   4x^2  <br>
Added Polynomial : 6x^3 + 4x
</code>```

Here is the code:

```<code>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct node {
    int coeff;
    int power;
    struct node *next;
};

void display_poly(struct node *exp);
void addnode(int coeff, int power, struct node **prev_node);
void addpoly(struct node *poly1, struct node *poly2, struct node *result);

void main() {

    struct node *poly1 = NULL, *poly2 = NULL, *result = NULL;

    addnode(6, 3, &poly1);
    addnode(10, 2, &poly1);
    addnode(0, 1, &poly1);
    addnode(5, 0, &poly1);

    printf("\nPolynomial 1:\t");
    display_poly(poly1);

    addnode(4, 2, &poly2);
    addnode(2, 1, &poly2);
    addnode(1, 0, &poly2);

    printf("\nPolynomial 2:\t");
    display_poly(poly2);

    result = (struct node *)malloc(sizeof(struct node));

    addpoly(poly1, poly2, result);

    printf("\nAdded Polynomial :\t");
    display_poly(result);

    return;
}

void addnode(int coeff, int power, struct node **prev_node) {

    struct node *node1, *node2;

    node2 = *prev_node;
    if (node2 == NULL) {
        node1 = (struct node *)malloc(sizeof(struct node));
        node1->coeff = coeff;
        node1->power = power;
        *prev_node = node1;
        node1->next = (struct node *)malloc(sizeof(struct node));
        node1 = node1->next;
        node1->next = NULL;
    } else {
        node1->coeff = coeff;
        node1->power = power;
        node1->next = (struct node *)malloc(sizeof(struct node));
        node1 = node1->next;
        node1->next = NULL;
    }
    return;
}

void display_poly(struct node *exp) {
    while (exp->next) {

        if (exp->power == 0) {
            printf("%d", exp->coeff);
        } else if (exp->power == 1) {
            printf("%dx", exp->coeff);
        } else {
            printf("%dx^%d", exp->coeff, exp->power);
        }

        exp = exp->next;

        if (exp->coeff >= 0 && exp->next != NULL) {
            printf(" + ");
        } else {
            printf("  ");
        }
    }
    return;
}

void addpoly(struct node *poly1, struct node *poly2, struct node *result){

    while (poly1->next && poly2->next) {

        if (poly1->power > poly2->power) {
            result->power = poly1->power;
            result->coeff = poly1->coeff;
            poly1 = poly1->next;
        } else if (poly2->power > poly1->power) {
            result->power = poly2->power;
            result->coeff = poly2->coeff;
            poly2 = poly2->next;
        } else {
            result->power = poly1->power;
            result->coeff = poly1->coeff + poly2->coeff;
            poly1 = poly1->next;
            poly2 = poly2->next;
        }

        result->next = (struct node *)malloc(sizeof(struct node));
        result = result->next;
        result->next = NULL;
    }

    while (poly1->next || poly2->next) {
        if (poly1->next) {
            result->power = poly1->power;
            result->coeff = poly1->coeff;
            poly1 = poly1->next;
        }
        if (poly2->next) {
            result->power = poly2->power;
            result->coeff = poly2->coeff;
            poly2 = poly2 -> next;
        }
        result->next = (struct node *)malloc(sizeof(struct node));
        result = result->next;
        result->next = NULL;
    }
}
</code>```

答:
Your code has undefined behaviour:

```<code>void addnode(int coeff, int power, struct node** prev_node)
{
  struct node* node1, * node2;  // <<< node1 is not initialized

  node2 = *prev_node;
  if (node2 == NULL) {
    node1 = (struct node*)malloc(sizeof(struct node));
    node1->coeff = coeff;
    node1->power = power;
    *prev_node = node1;
    node1->next = (struct node*)malloc(sizeof(struct node));
    node1 = node1->next;
    node1->next = NULL;
  }
  else {
    node1->coeff = coeff;  // <<<< here node1 is not initialized
    node1->power = power;
    node1->next = (struct node*)malloc(sizeof(struct node));
    node1 = node1->next;
    node1->next = NULL;
  }
  return;
}
</code>```

node1 has not been initialized (see comment in the code above), and dereferencing an uninitialized pointer is undefined behaviour (google that term). Change struct node* node1 to struct node* node1 = NULL and run the program again. This time you'll most likely get a segfault with gcc. With Turbo C I don't know what is going to happen.

You probably want this:

```<code>void addnode(int coeff, int power, struct node** prev_node) {

  struct node* node1 = NULL , *node2;

  node2 = *prev_node;
  node1 = malloc(sizeof(struct node));
  node1->coeff = coeff;
  node1->power = power;
  node1->next = malloc(sizeof(struct node));

  if (node2 == NULL) {
    *prev_node = node1;
    node1 = node1->next;
    node1->next = NULL;

  }
  else {
    node1 = node1->next;
    node1->next = NULL;
  }
  return;
}
</code>```

BTW: the (struct node*) of malloc are useless, you can simply drop them.

That being said, don't use Turbo C, this is an antiquated piece of software that is most likely older than you.

There may be other problems in your code though.

Body:
So, here I wanted to add 2 polynomials using a linked-list in C. It gave a perfect output when compiled with GCC, but when compiled with TurboC++, it messed up...

The output it gave in GCC was:

Polynomial 1:   6x^3 + 10x^2 + 0x + 5
Polynomial 2:   4x^2 + 2x + 1
Added Polynomial :      6x^3 + 14x^2 + 2x + 6

The Output it  gave in TurboC++:

Polynomial 1:   6x^3 +

Polynomial 2:   4x^2

Added Polynomial : 6x^3 + 4x

Here is the code:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct node {
    int coeff;
    int power;
    struct node *next;
};

void display_poly(struct node *exp);
void addnode(int coeff, int power, struct node **prev_node);
void addpoly(struct node *poly1, struct node *poly2, struct node *result);

void main() {

    struct node *poly1 = NULL, *poly2 = NULL, *result = NULL;

    addnode(6, 3, &poly1);
    addnode(10, 2, &poly1);
    addnode(0, 1, &poly1);
    addnode(5, 0, &poly1);

    printf("\nPolynomial 1:\t");
    display_poly(poly1);

    addnode(4, 2, &poly2);
    addnode(2, 1, &poly2);
    addnode(1, 0, &poly2);

    printf("\nPolynomial 2:\t");
    display_poly(poly2);

    result = (struct node *)malloc(sizeof(struct node));

    addpoly(poly1, poly2, result);

    printf("\nAdded Polynomial :\t");
    display_poly(result);

    return;
}

void addnode(int coeff, int power, struct node **prev_node) {

    struct node *node1, *node2;

    node2 = *prev_node;
    if (node2 == NULL) {
        node1 = (struct node *)malloc(sizeof(struct node));
        node1->coeff = coeff;
        node1->power = power;
        *prev_node = node1;
        node1->next = (struct node *)malloc(sizeof(struct node));
        node1 = node1->next;
        node1->next = NULL;
    } else {
        node1->coeff = coeff;
        node1->power = power;
        node1->next = (struct node *)malloc(sizeof(struct node));
        node1 = node1->next;
        node1->next = NULL;
    }
    return;
}

void display_poly(struct node *exp) {
    while (exp->next) {

        if (exp->power == 0) {
            printf("%d", exp->coeff);
        } else if (exp->power == 1) {
            printf("%dx", exp->coeff);
        } else {
            printf("%dx^%d", exp->coeff, exp->power);
        }

        exp = exp->next;

        if (exp->coeff >= 0 && exp->next != NULL) {
            printf(" + ");
        } else {
            printf("  ");
        }
    }
    return;
}

void addpoly(struct node *poly1, struct node *poly2, struct node *result){

    while (poly1->next && poly2->next) {

        if (poly1->power > poly2->power) {
            result->power = poly1->power;
            result->coeff = poly1->coeff;
            poly1 = poly1->next;
        } else if (poly2->power > poly1->power) {
            result->power = poly2->power;
            result->coeff = poly2->coeff;
            poly2 = poly2->next;
        } else {
            result->power = poly1->power;
            result->coeff = poly1->coeff + poly2->coeff;
            poly1 = poly1->next;
            poly2 = poly2->next;
        }

        result->next = (struct node *)malloc(sizeof(struct node));
        result = result->next;
        result->next = NULL;
    }

    while (poly1->next || poly2->next) {
        if (poly1->next) {
            result->power = poly1->power;
            result->coeff = poly1->coeff;
            poly1 = poly1->next;
        }
        if (poly2->next) {
            result->power = poly2->power;
            result->coeff = poly2->coeff;
            poly2 = poly2 -> next;
        }
        result->next = (struct node *)malloc(sizeof(struct node));
        result = result->next;
        result->next = NULL;
    }
}

Body:
Your code has undefined behaviour:

void addnode(int coeff, int power, struct node** prev_node)
{
  struct node* node1, * node2;  // <<< node1 is not initialized

  node2 = *prev_node;
  if (node2 == NULL) {
    node1 = (struct node*)malloc(sizeof(struct node));
    node1->coeff = coeff;
    node1->power = power;
    *prev_node = node1;
    node1->next = (struct node*)malloc(sizeof(struct node));
    node1 = node1->next;
    node1->next = NULL;
  }
  else {
    node1->coeff = coeff;  // <<<< here node1 is not initialized
    node1->power = power;
    node1->next = (struct node*)malloc(sizeof(struct node));
    node1 = node1->next;
    node1->next = NULL;
  }
  return;
}

node1 has not been initialized (see comment in the code above), and dereferencing an uninitialized pointer is undefined behaviour (google that term). Change struct node* node1 to struct node* node1 = NULL and run the program again. This time you'll most likely get a segfault with gcc. With Turbo C I don't know what is going to happen.

You probably want this:

void addnode(int coeff, int power, struct node** prev_node) {

  struct node* node1 = NULL , *node2;

  node2 = *prev_node;
  node1 = malloc(sizeof(struct node));
  node1->coeff = coeff;
  node1->power = power;
  node1->next = malloc(sizeof(struct node));

  if (node2 == NULL) {
    *prev_node = node1;
    node1 = node1->next;
    node1->next = NULL;

  }
  else {
    node1 = node1->next;
    node1->next = NULL;
  }
  return;
}

BTW: the (struct node*) of malloc are useless, you can simply drop them.

That being said, don't use Turbo C, this is an antiquated piece of software that is most likely older than you.

There may be other problems in your code though.


问:
How to put IF condition in where section of select command in SQL?
I declare some filters on a form and pass them into my SP in SQL for running a select command and this is how I did that, but it didn't work:

```<code>DECLARE @Confirm_Filter AS BIT=NULL,
@ReciveDate_Filter AS NCHAR(10) = NULL
....
select * from .......
where
(@Confirm_Filter IS NOT NULL AND InterviewConfirm = @Confirm_Filter)
AND
(@ReciveDate_Filter  IS NOT NULL AND ReciveDate BETWEEN GETDATE() AND @ReciveDate_Filter)
</code>```

and in the where section I want to do:

```<code>where
if @Confirm_Filter IS NOT NULL Then (Select * from ... where InterviewConfirm = @Confirm_Filter)
AND
if @ReciveDate_Filter  IS NOT NULL Then (select * from .... where ReciveDate BETWEEN GETDATE() AND @ReciveDate_Filter)
</code>```

and I know above form is totally mistake but how could I do it?

答:
Your problem is called dynamic search conditions. It is solved either by using dynamic SQL, or the following pattern (which is similar to your first version, but with a few changes):</p>
```<code>select * from .......
where
(@Confirm_Filter IS NULL OR InterviewConfirm = @Confirm_Filter)
AND
(@ReciveDate_Filter  IS NULL OR ReciveDate BETWEEN GETDATE() AND @ReciveDate_Filter)
</code>```

Body:
I declare some filters on a form and pass them into my SP in SQL for running a select command and this is how I did that, but it didn't work:

DECLARE @Confirm_Filter AS BIT=NULL,
@ReciveDate_Filter AS NCHAR(10) = NULL
....
select * from .......
where
(@Confirm_Filter IS NOT NULL AND InterviewConfirm = @Confirm_Filter)
AND
(@ReciveDate_Filter  IS NOT NULL AND ReciveDate BETWEEN GETDATE() AND @ReciveDate_Filter)

and in the where section I want to do:

where
if @Confirm_Filter IS NOT NULL Then (Select * from ... where InterviewConfirm = @Confirm_Filter)
AND
if @ReciveDate_Filter  IS NOT NULL Then (select * from .... where ReciveDate BETWEEN GETDATE() AND @ReciveDate_Filter)

and I know above form is totally mistake but how could I do it?

Body:
Your problem is called dynamic search conditions. It is solved either by using dynamic SQL, or the following pattern (which is similar to your first version, but with a few changes):

select * from .......
where
(@Confirm_Filter IS NULL OR InterviewConfirm = @Confirm_Filter)
AND
(@ReciveDate_Filter  IS NULL OR ReciveDate BETWEEN GETDATE() AND @ReciveDate_Filter)


问:
how to extend default running timeout for azure pipeline
I want to extend timeout for azure pipeline , my pipeline is always been canceled in 60minus

wondering how to re-set timeout on yaml for pipeline , I search one solution, but didn't work

screenshot#2

答:
See the official docs:

For free tier:

Private project: One free parallel job that can run for up to 60 minutes each time, until you've used 1,800 minutes (30 hours) per month.


问:
What is the exact list of Ansible setup min?
According to the Ansible documentation, the setup module is

This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks. It can also be executed directly by /usr/bin/ansible to check what variables are available to a host. Ansible provides many facts about the system, automatically.

And there are some parameters which include gather_subset.

If supplied, restrict the additional facts collected to the given subset. Possible values: all, min, hardware, network, virtual, ohai, and facter. Can specify a list of values to specify a larger subset. Values can also be used with an initial ! to specify that that specific subset should not be collected. For instance: !hardware,!network,!virtual,!ohai,!facter. If !all is specified then only the min subset is collected. To avoid collecting even the min subset, specify !all,!min. To collect only specific facts, use !all,!min, and specify the particular fact subsets. Use the filter parameter if you do not want to display some collected facts.

I want to know the exact list of fact that min subset would collect.

Thanks

答:
It will depend on your environment and setup what is available and can be collected.

You could just have a short test with

---
- hosts: localhost
  become: false

  gather_facts: true
  gather_subset:
    - "min"

  tasks:

  - name: Show Gathered Facts
    debug:
      msg: "{{ ansible_facts }}"
```
<p>and check the output, in example for a RHEL system the keys are</p>
<pre class="lang-yaml prettyprint-override"><code>_ansible_facts_gathered: true
ansible_apparmor:
  status:
ansible_architecture:
ansible_cmdline:
  BOOT_IMAGE:
  LANG:
  elevator:
  quiet:
  rhgb:
  ro:
  root:
ansible_date_time:
  date: ''
  day: ''
  epoch: ''
  hour:
  iso8601: ''
  iso8601_basic:
  iso8601_basic_short:
  iso8601_micro: ''
  minute: ''
  month: ''
  second: ''
  time:
  tz:
  tz_offset: ''
  weekday:
  weekday_number: ''
  weeknumber: ''
  year: ''
ansible_distribution:
ansible_distribution_file_parsed:
ansible_distribution_file_path:
ansible_distribution_file_search_string:
ansible_distribution_file_variety:
ansible_distribution_major_version: ''
ansible_distribution_release:
ansible_distribution_version: ''
ansible_dns:
  nameservers:
  -
  search:
  -
ansible_domain:
ansible_effective_group_id:
ansible_effective_user_id:
ansible_env:
  HISTCONTROL:
  HISTSIZE: ''
  HOME:
  HOSTNAME:
  KRB5CCNAME:
  LANG:
  LESSOPEN: ''
  LOGNAME:
  LS_COLORS:
  MAIL:
  PATH:
  PWD:
  SELINUX_LEVEL_REQUESTED: ''
  SELINUX_ROLE_REQUESTED: ''
  SELINUX_USE_CURRENT_RANGE: ''
  SHELL:
  SHLVL: ''
  SSH_CLIENT:
  SSH_CONNECTION:
  SSH_TTY:
  TERM:
  TZ:
  USER:
  XDG_RUNTIME_DIR:
  XDG_SESSION_ID: ''
  _:
ansible_fips:
ansible_fqdn:
ansible_hostname:
ansible_kernel:
ansible_kernel_version: ''
ansible_local: {}
ansible_lsb: {}
ansible_machine:
ansible_machine_id:
ansible_nodename:
ansible_os_family:
ansible_pkg_mgr:
ansible_proc_cmdline:
  BOOT_IMAGE:
  LANG:
  elevator:
  quiet:
  rhgb:
  ro:
  root:
ansible_python:
  executable:
  has_sslcontext:
  type:
  version:
    major:
    micro:
    minor:
    releaselevel:
    serial:
  version_info:
  -
ansible_python_version:
ansible_real_group_id:
ansible_real_user_id:
ansible_selinux:
  config_mode:
  mode:
  policyvers:
  status:
  type:
ansible_selinux_python_present:
ansible_service_mgr:
ansible_ssh_host_key_ecdsa_public:
ansible_ssh_host_key_ed25519_public:
ansible_ssh_host_key_rsa_public:
ansible_system:
ansible_system_capabilities:
- ''
ansible_system_capabilities_enforced: ''
ansible_user_dir:
ansible_user_gecos:
ansible_user_gid:
ansible_user_id:
ansible_user_shell:
ansible_user_uid:
ansible_userspace_architecture:
ansible_userspace_bits: ''
gather_subset:
- min
module_setup: true
</code>```

For min the /ansible/modules/setup.py tries to gather information from

minimal_gather_subset = frozenset(['apparmor', 'caps', 'cmdline', 'date_time',
                                   'distribution', 'dns', 'env', 'fips', 'local',
                                   'lsb', 'pkg_mgr', 'platform', 'python', 'selinux',
                                   'service_mgr', 'ssh_pub_keys', 'user'])
```

so that can be considered as

the exact list of fact that min subset would collect.

As one can see, blocks of the information are coming from different modules, in example for ansible_distribution from facts/system/distribution.py.

In my case in example, the module for ansible_env, facts/system/env.py will create keys which can not be found in any other environment.

For more background information of what is collected for specific environments and setups you have a look into /ansible/module_utils/facts.

Further Q&A

How Ansible gather_facts and sets variables

Getting full name of the OS using ansible_facts

Body:
It will depend on your environment and setup what is available and can be collected.

You could just have a short test with

---
- hosts: localhost
  become: false

  gather_facts: true
  gather_subset:
    - "min"

  tasks:

  - name: Show Gathered Facts
    debug:
      msg: "{{ ansible_facts }}"

and check the output, in example for a RHEL system the keys are

_ansible_facts_gathered: true
ansible_apparmor:
  status:
ansible_architecture:
ansible_cmdline:
  BOOT_IMAGE:
  LANG:
  elevator:
  quiet:
  rhgb:
  ro:
  root:
ansible_date_time:
  date: ''
  day: ''
  epoch: ''
  hour:
  iso8601: ''
  iso8601_basic:
  iso8601_basic_short:
  iso8601_micro: ''
  minute: ''
  month: ''
  second: ''
  time:
  tz:
  tz_offset: ''
  weekday:
  weekday_number: ''
  weeknumber: ''
  year: ''
ansible_distribution:
ansible_distribution_file_parsed:
ansible_distribution_file_path:
ansible_distribution_file_search_string:
ansible_distribution_file_variety:
ansible_distribution_major_version: ''
ansible_distribution_release:
ansible_distribution_version: ''
ansible_dns:
  nameservers:
  -
  search:
  -
ansible_domain:
ansible_effective_group_id:
ansible_effective_user_id:
ansible_env:
  HISTCONTROL:
  HISTSIZE: ''
  HOME:
  HOSTNAME:
  KRB5CCNAME:
  LANG:
  LESSOPEN: ''
  LOGNAME:
  LS_COLORS:
  MAIL:
  PATH:
  PWD:
  SELINUX_LEVEL_REQUESTED: ''
  SELINUX_ROLE_REQUESTED: ''
  SELINUX_USE_CURRENT_RANGE: ''
  SHELL:
  SHLVL: ''
  SSH_CLIENT:
  SSH_CONNECTION:
  SSH_TTY:
  TERM:
  TZ:
  USER:
  XDG_RUNTIME_DIR:
  XDG_SESSION_ID: ''
  _:
ansible_fips:
ansible_fqdn:
ansible_hostname:
ansible_kernel:
ansible_kernel_version: ''
ansible_local: {}
ansible_lsb: {}
ansible_machine:
ansible_machine_id:
ansible_nodename:
ansible_os_family:
ansible_pkg_mgr:
ansible_proc_cmdline:
  BOOT_IMAGE:
  LANG:
  elevator:
  quiet:
  rhgb:
  ro:
  root:
ansible_python:
  executable:
  has_sslcontext:
  type:
  version:
    major:
    micro:
    minor:
    releaselevel:
    serial:
  version_info:
  -
ansible_python_version:
ansible_real_group_id:
ansible_real_user_id:
ansible_selinux:
  config_mode:
  mode:
  policyvers:
  status:
  type:
ansible_selinux_python_present:
ansible_service_mgr:
ansible_ssh_host_key_ecdsa_public:
ansible_ssh_host_key_ed25519_public:
ansible_ssh_host_key_rsa_public:
ansible_system:
ansible_system_capabilities:
- ''
ansible_system_capabilities_enforced: ''
ansible_user_dir:
ansible_user_gecos:
ansible_user_gid:
ansible_user_id:
ansible_user_shell:
ansible_user_uid:
ansible_userspace_architecture:
ansible_userspace_bits: ''
gather_subset:
- min
module_setup: true

For min the /ansible/modules/setup.py tries to gather information from

minimal_gather_subset = frozenset(['apparmor', 'caps', 'cmdline', 'date_time',
                                   'distribution', 'dns', 'env', 'fips', 'local',
                                   'lsb', 'pkg_mgr', 'platform', 'python', 'selinux',
                                   'service_mgr', 'ssh_pub_keys', 'user'])

so that can be considered as

the exact list of fact that min subset would collect.

As one can see, blocks of the information are coming from different modules, in example for ansible_distribution from facts/system/distribution.py.

In my case in example, the module for ansible_env, facts/system/env.py will create keys which can not be found in any other environment.

For more background information of what is collected for specific environments and setups you have a look into /ansible/module_utils/facts.

Further Q&A

How Ansible gather_facts and sets variables

Getting full name of the OS using ansible_facts


问:
git stash can't apply untracked file
I stashed my files, including a new file src/***/Microservices.jsx. Now I see it on my stash:

> git stash show
 src/***/***.jsx                 |  5 ++---
 src/***/table-view/***.jsx  |  4 ++--
 src/***/table-view/SubGroup.jsx | 37 -------------------------------------
 src/***/views.js                |  2 ++
 4 files changed, 6 insertions(+), 42 deletions(-)

> git stash show --include-untracked
 src/***/***.jsx                                    |  5 +--
 src/***/Microservices.jsx                          | 48 ++++++++++++++++++++++
 src/***/{table-view => microservices}/SubGroup.jsx | 14 ++++---
 src/***/table-view/***.jsx                     |  4 +-
 src/***/views.js                                   |  2 +
 5 files changed, 63 insertions(+), 10 deletions(-)
```

But no matter what I tried (applying by git stash apply [--index], git stash pop or from the git extension below), I can't apply this file.

What should I do to continue to work on this file?

Screenshot from Git Graph VSCode Extension:

You can see the Microservices.jsx file, and I can click on it and see the diff of this file inside the stash.

答:
This happens because your new file is not tracked. You can stash untracked files with

```<code>git stash --include-untracked
</code>```

There is a new feature in git v.2.35 which allows you to work with stash just like as commit

```<code>git add -A
git stash --staged
</code>```

So you first add to staging area all the files you want to stash, than check and stash it.

Title: git stash can't apply untracked file

Body:
I stashed my files, including a new file src/***/Microservices.jsx. Now I see it on my stash:

> git stash show
 src/***/***.jsx                 |  5 ++---
 src/***/table-view/***.jsx  |  4 ++--
 src/***/table-view/SubGroup.jsx | 37 -------------------------------------
 src/***/views.js                |  2 ++
 4 files changed, 6 insertions(+), 42 deletions(-)

> git stash show --include-untracked
 src/***/***.jsx                                    |  5 +--
 src/***/Microservices.jsx                          | 48 ++++++++++++++++++++++
 src/***/{table-view => microservices}/SubGroup.jsx | 14 ++++---
 src/***/table-view/***.jsx                     |  4 +-
 src/***/views.js                                   |  2 +
 5 files changed, 63 insertions(+), 10 deletions(-)

But no matter what I tried (applying by git stash apply [--index], git stash pop or from the git extension below), I can't apply this file.

What should I do to continue to work on this file?

Screenshot from Git Graph VSCode Extension:

You can see the Microservices.jsx file, and I can click on it and see the diff of this file inside the stash.

Body:
This happens because your new file is not tracked. You can stash untracked files with

git stash --include-untracked

There is a new feature in git v.2.35 which allows you to work with stash just like as commit

git add -A
git stash --staged

So you first add to staging area all the files you want to stash, than check and stash it.


问:
How to change object's Y projection axis and color via C# rather than XAML
I'm working on a Silverlight project where I will be 'flipping' rectangles by rotating them on the Y projection axis. I will also change to color in the middle of the animation so that it looks like the back side of the rectangle is a different color. I can do this in XAML no problem however I need to do this via code because I want to dynamically flip different rectangles. I don't want to have to create an animation for each rectangle on the grid. Here's what my XAML looks like:

```<code><Storyboard x:Name="Flip1">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)" Storyboard.TargetName="rectangle">
                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="rectangle">
                <EasingColorKeyFrame KeyTime="0:0:0.5" Value="Blue"/>
                <EasingColorKeyFrame KeyTime="0:0:0.6" Value="Red"/>
            </ColorAnimationUsingKeyFrames>
        </Storyboard>
</code>```

I've created storyboards from code several times however this one is leaving me a bit stumped with the EasingDoubleKeyFrames. Any ideas how to go about doing this?

答:
This should be the translation of the first animation:

```<code>var anim = new DoubleAnimationUsingKeyFrames();
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0), Value = 0 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0.5), Value = -90 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0.6), Value = -90 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(1), Value = 0 });
Storyboard.SetTarget(anim, rectangle);
Storyboard.SetTargetProperty(anim, new PropertyPath("Projection.RotationY"));
</code>```

When using Storyboards you further need to register the target in a namescope, i recommend reading the whole reference of the Storyboard class.

Body:
I'm working on a Silverlight project where I will be 'flipping' rectangles by rotating them on the Y projection axis. I will also change to color in the middle of the animation so that it looks like the back side of the rectangle is a different color. I can do this in XAML no problem however I need to do this via code because I want to dynamically flip different rectangles. I don't want to have to create an animation for each rectangle on the grid. Here's what my XAML looks like:

<Storyboard x:Name="Flip1">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)" Storyboard.TargetName="rectangle">
                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="rectangle">
                <EasingColorKeyFrame KeyTime="0:0:0.5" Value="Blue"/>
                <EasingColorKeyFrame KeyTime="0:0:0.6" Value="Red"/>
            </ColorAnimationUsingKeyFrames>
        </Storyboard>

I've created storyboards from code several times however this one is leaving me a bit stumped with the EasingDoubleKeyFrames. Any ideas how to go about doing this?

Body:
This should be the translation of the first animation:

var anim = new DoubleAnimationUsingKeyFrames();
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0), Value = 0 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0.5), Value = -90 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(0.6), Value = -90 });
anim.KeyFrames.Add(new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(1), Value = 0 });
Storyboard.SetTarget(anim, rectangle);
Storyboard.SetTargetProperty(anim, new PropertyPath("Projection.RotationY"));

When using Storyboards you further need to register the target in a namescope, i recommend reading the whole reference of the Storyboard class.


问:
Download the latest artifacts of failed gitlab pipeline
I want to automatically load test results of my gitlab pipeline (basically one xml file) into my project management application. No direct connection between these two is possible. However the gitlab API offers the following options to download artifacts of a pipeline:

all artifacts of the latest successful pipeline run (selected by job name)

GET /projects/:id/jobs/artifacts/:ref_name/download?job=name`

all artifacts of a specific job (selected by job id)

GET /projects/:id/jobs/:job_id/artifacts

a single artifact file (selected by job id)

GET /projects/:id/jobs/:job_id/artifacts/*artifact_path

My current situation is following:

I have test reports which are saved inside the job artifacts when running the pipeline. The artifacts are created on every run of the pipeline independent of its outcome

gitlab-ci.yaml

```<code>...
artifacts:

     when: always
...
</code>```

The artifact I am trying to download has a dynamic name

./reports/junit/test-results-${CI_JOB_ID}.xml

If I now want to download the latest test results to a different server than the gitlab server, I have to realize that I don't know the latest job ID, which means:

I can't access the artifact directly because it has a dynamic name

I can't access the artifacts of a specific job

I can access the artifacts of the latest job, but only if it was successful

This leaves me with the situation, that i only get to download the latest test results, if nothing went wrong while testing. To put it mildly, this is suboptimal.

Is there some way to download the artifacts from the latest job run (without knowing the job ID), independent of its outcome?

答:
Is there some way to download the artifacts from the latest job run
(without knowing the job ID), independent of its outcome?

In order to achieve this we will use the Gitlab API in combination with the jq package.

Let's break down this question into components.

Firstly, we need to find out the id of the last executed pipeline for this project. https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines

```<code>GET /projects/:id/pipelines
</code>```

For this call you will need your access token, if you don't have one already check
https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#create-a-personal-access-token
https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html#create-a-project-access-token

You will also need the Project ID

```<code>LAST_PIPELINE_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines | jq '.[0].id')
</code>```

Next we will retrieve the job id by providing the job name by using the following API
https://docs.gitlab.com/ee/api/jobs.html#list-pipeline-jobs

```<code>GET /projects/:id/pipelines/:pipeline_id/jobs
</code>```

In your case you need to change the following example with your job's name, in this example let's call it my_job

```<code>JOB_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines/$LAST_PIPELINE_ID/jobs | jq '.[] | select(.name=="my_job") | .id')
</code>```

Now we are ready to actually retrieve the artifacts, with the following API

```<code>GET /projects/:id/jobs/:job_id/artifacts
</code>```

https://docs.gitlab.com/ee/api/job_artifacts.html#get-job-artifacts

```<code>wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.17 (KHTML,like Gecko) Ubuntu/11.04 Chromium/11.0.654.0 Chrome/11.0.654.0 Safari/534.17" --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/<project_id>/jobs/$JOB_ID/artifacts" -O artifacts.zip
</code>```

The artifacts are available as artifacts.zip in the folder you executed wget from

Combining them here for clarity

```<code>LAST_PIPELINE_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines | jq '.[0].id')
JOB_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines/$LAST_PIPELINE_ID/jobs | jq '.[] | select(.name=="my_job") | .id')
wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.17 (KHTML,like Gecko) Ubuntu/11.04 Chromium/11.0.654.0 Chrome/11.0.654.0 Safari/534.17" --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/<project_id>/jobs/$JOB_ID/artifacts" -O artifacts.zip
</code>```

Body:
I want to automatically load test results of my gitlab pipeline (basically one xml file) into my project management application. No direct connection between these two is possible. However the gitlab API offers the following options to download artifacts of a pipeline:

all artifacts of the latest successful pipeline run (selected by job name)

GET /projects/:id/jobs/artifacts/:ref_name/download?job=name`

all artifacts of a specific job (selected by job id)

GET /projects/:id/jobs/:job_id/artifacts

a single artifact file (selected by job id)

GET /projects/:id/jobs/:job_id/artifacts/*artifact_path

My current situation is following:

I have test reports which are saved inside the job artifacts when running the pipeline. The artifacts are created on every run of the pipeline independent of its outcome

gitlab-ci.yaml

...
artifacts:

     when: always
...

The artifact I am trying to download has a dynamic name

./reports/junit/test-results-${CI_JOB_ID}.xml

If I now want to download the latest test results to a different server than the gitlab server, I have to realize that I don't know the latest job ID, which means:

I can't access the artifact directly because it has a dynamic name

I can't access the artifacts of a specific job

I can access the artifacts of the latest job, but only if it was successful

This leaves me with the situation, that i only get to download the latest test results, if nothing went wrong while testing. To put it mildly, this is suboptimal.

Is there some way to download the artifacts from the latest job run (without knowing the job ID), independent of its outcome?

Body:
Is there some way to download the artifacts from the latest job run
(without knowing the job ID), independent of its outcome?

In order to achieve this we will use the Gitlab API in combination with the jq package.

Let's break down this question into components.

Firstly, we need to find out the id of the last executed pipeline for this project. https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines

GET /projects/:id/pipelines

For this call you will need your access token, if you don't have one already check
https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#create-a-personal-access-token
https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html#create-a-project-access-token

You will also need the Project ID

LAST_PIPELINE_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines | jq '.[0].id')

Next we will retrieve the job id by providing the job name by using the following API
https://docs.gitlab.com/ee/api/jobs.html#list-pipeline-jobs

GET /projects/:id/pipelines/:pipeline_id/jobs

In your case you need to change the following example with your job's name, in this example let's call it my_job

JOB_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines/$LAST_PIPELINE_ID/jobs | jq '.[] | select(.name=="my_job") | .id')

Now we are ready to actually retrieve the artifacts, with the following API

GET /projects/:id/jobs/:job_id/artifacts

https://docs.gitlab.com/ee/api/job_artifacts.html#get-job-artifacts

wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.17 (KHTML,like Gecko) Ubuntu/11.04 Chromium/11.0.654.0 Chrome/11.0.654.0 Safari/534.17" --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/<project_id>/jobs/$JOB_ID/artifacts" -O artifacts.zip

The artifacts are available as artifacts.zip in the folder you executed wget from

Combining them here for clarity

LAST_PIPELINE_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines | jq '.[0].id')
JOB_ID=$(curl -s --header "PRIVATE-TOKEN: <access_token>" https://gitlab.com/api/v4/projects/<project_id>/pipelines/$LAST_PIPELINE_ID/jobs | jq '.[] | select(.name=="my_job") | .id')
wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.17 (KHTML,like Gecko) Ubuntu/11.04 Chromium/11.0.654.0 Chrome/11.0.654.0 Safari/534.17" --header "PRIVATE-TOKEN: <access_token>" "https://gitlab.com/api/v4/projects/<project_id>/jobs/$JOB_ID/artifacts" -O artifacts.zip


问:
Very long line in VIM does not show up without having the cursor on it
I'm using VIM version 8.2

When I'm on the line above the very long line, it appears as if there is no line below it. (Refer Below Image)

But as soon as I move down, I get to see everything in that line. (Refer Below Image)

Is there a way to make the very long line appear whithout having the cursor on it?

答:
You can set display+=truncate or set display+=lastline, which tell Vim to display the last line but put @@@ in the first or last column to indicate the rest is not displayed.

Also see https://vim.fandom.com/wiki/Working_with_long_lines


问:
jQuery UI dialog and columnizer plugin bug
I use jQuery UI dialog and Columnizer plugin to open up dialog modal window and show tables in columns (if needed). All is working great, but.. only first time I click. When I click second time on the link (whitch must open dialog), columnizer is not working, but is called.
   Where can be the problem?

```<code>$('#link_to_click').live('click', function(e) {
  e.preventDefault();

  // How much items per column
  var items_per_column = 15;

  var _dialog_id = '_modal_dialog_box_1';
  var $dialog = $('<div id="'+_dialog_id+'"></div>');

  /*
  * There is getting and parsing data from JSON
  * var data is parsed and created HTML
  */

  // This is wrapper what I will tell columnizer to columnize <div's> inside this wrapper
  data = $('<div/>', {id: 'wrapper', 'class': 'table'}).html(data);

  $dialog.html(data).dialog({
    closeOnEscape: true,
    modal:true,
    title: $(this).attr('title'),
    resizable: false,
    width: 1000
  });

  // Columnizing (columns variable is calculated by items in JSON)
  if(columns > 1) {
    $('#wrapper').columnize({columns:columns,lastNeverTallest:true});
  }
  // Fixing bug that UI dialog is not centred after showing
  $('#'+_dialog_id).dialog("option", "position", "center");

  return false;
});
</code>```

So when I wirst time click to  all is good - dialog shows up, data is columnized and I am happy. Then I close dialog and click once more on the #link_to_click. Dialog is shown, but columnizer does not work...

Any ideas?

答:
I found the bug and solution for that. I don't know why but if dialog is two times called, it needs to remove dynamicaly created element. So I added one line BEFORE string

```<code>var _dialog_id = '_modal_dialog_box_1';
$('#'+_dialog_id).remove(); // Need to remove else on dublicate click will not load columnizer
var $dialog = $('<div id="'+_dialog_id+'"></div>');
</code>```

Now all is working fine.

Maybe someone can explain why is that?

Thanks!

Body:
I use jQuery UI dialog and Columnizer plugin to open up dialog modal window and show tables in columns (if needed). All is working great, but.. only first time I click. When I click second time on the link (whitch must open dialog), columnizer is not working, but is called.
   Where can be the problem?

$('#link_to_click').live('click', function(e) {
  e.preventDefault();

  // How much items per column
  var items_per_column = 15;

  var _dialog_id = '_modal_dialog_box_1';
  var $dialog = $('

');

  /*
  * There is getting and parsing data from JSON
  * var data is parsed and created HTML
  */

  // This is wrapper what I will tell columnizer to columnize
 inside this wrapper
  data = $('
', {id: 'wrapper', 'class': 'table'}).html(data);

  $dialog.html(data).dialog({
    closeOnEscape: true,
    modal:true,
    title: $(this).attr('title'),
    resizable: false,
    width: 1000
  });

  // Columnizing (columns variable is calculated by items in JSON)
  if(columns > 1) {
    $('#wrapper').columnize({columns:columns,lastNeverTallest:true});
  }
  // Fixing bug that UI dialog is not centred after showing
  $('#'+_dialog_id).dialog("option", "position", "center");

  return false;
});

So when I wirst time click to  all is good - dialog shows up, data is columnized and I am happy. Then I close dialog and click once more on the #link_to_click. Dialog is shown, but columnizer does not work...

Any ideas?

Body:
I found the bug and solution for that. I don't know why but if dialog is two times called, it needs to remove dynamicaly created element. So I added one line BEFORE string

var _dialog_id = '_modal_dialog_box_1';
$('#'+_dialog_id).remove(); // Need to remove else on dublicate click will not load columnizer
var $dialog = $('<div id="'+_dialog_id+'"></div>');

Now all is working fine.

Maybe someone can explain why is that?

Thanks!


问:
Very slow filtering with multiple conditions in pandas dataframe
UPDATE: I have edited the question (and code) to make the problem clearer. I use here synthetic data but imagine a large df of floods and a small one of significant floods. I want add a reference to every row (of the large_df) if it is somewhat close to the significant flood.

I have 2 pandas dataframes (1 large and 1 small).
In every iteration I want to create a subset of the small dataframe based on a few conditions that are dependent on each row (of the large df):

```<code>import numpy as np
import pandas as pd
import time

SOME_THRESHOLD = 10.5

MUMBER_OF_ROWS = 2e4
large_df = pd.DataFrame(index=np.arange(MUMBER_OF_ROWS), data={'a': np.arange(MUMBER_OF_ROWS)})
small_df = large_df.loc[np.random.randint(0, MUMBER_OF_ROWS, 5)]
large_df['past_index'] = None

count_time = 0
for ind, row in large_df.iterrows():
  start = time.time()
  # This line takes forever.
  df_tmp = small_df[(small_df.index<ind) & (small_df['a']>(row['a']-SOME_THRESHOLD)) & (small_df['a']<(row['a']+SOME_THRESHOLD))]
  count_time += time.time()-start
  if not df_tmp.empty:
    past_index = df_tmp.loc[df_tmp.index.max()]['a']
    large_df.loc[ind, 'similar_past_flood_tag'] = f'Similar to the large flood of {past_index}'

print(f'The total time of creating the subset df for 2e4 rows is: {count_time} seconds.')
</code>```

The line that creates the subset takes a long time to compute:

The total time of creating the subset df for 2e4 rows is: 18.276793956756592 seconds.

This seems to me to be an too long. I have found similar questions but non of the answers seemed to work (e.g query and numpy conditions).
Is there a way to optimize this?

Note: the code does what is expected - just very slow.

答:
In pandas for loops are much slower than column operations. So changing the calculation to loop over small_df instead of large_df will already give a big improvement:

```<code>for ind, row in small_df.iterrows():
    df_tmp = large_df[ <some condition> ]
    # ... some other processing
</code>```

Even better for your case is to use a merge rather than a condition on large_df. The problem is your merge is not on equal columns but on approximately equal. To use this approach, you should truncate your column and use that for the merge. Here's a hacky example.

```<code>small_df['a_rounded'] = (small_df['a'] / SOME_THRESHOLD / 2).astype(int)
large_df['a_rounded'] = (large_df['a'] / SOME_THRESHOLD / 2).astype(int)
merge_result = small_df.merge(large_df, on='a_rounded')

small_df['a_rounded2'] = ((small_df['a'] + SOME_THRESHOLD) / SOME_THRESHOLD / 2).astype(int)
large_df['a_rounded2'] = ((large_df['a'] + SOME_THRESHOLD) / SOME_THRESHOLD / 2).astype(int)
merge_result2 = small_df.merge(large_df, on='a_rounded2')

total_merge_result = pd.concat([merge_result, merge_result2])
# Now remove duplicates and impose additional filters.
</code>```

You can impose the additional filters on the result later.

Body:
UPDATE: I have edited the question (and code) to make the problem clearer. I use here synthetic data but imagine a large df of floods and a small one of significant floods. I want add a reference to every row (of the large_df) if it is somewhat close to the significant flood.

I have 2 pandas dataframes (1 large and 1 small).
In every iteration I want to create a subset of the small dataframe based on a few conditions that are dependent on each row (of the large df):

import numpy as np
import pandas as pd
import time

SOME_THRESHOLD = 10.5

MUMBER_OF_ROWS = 2e4
large_df = pd.DataFrame(index=np.arange(MUMBER_OF_ROWS), data={'a': np.arange(MUMBER_OF_ROWS)})
small_df = large_df.loc[np.random.randint(0, MUMBER_OF_ROWS, 5)]
large_df['past_index'] = None

count_time = 0
for ind, row in large_df.iterrows():
  start = time.time()
  # This line takes forever.
  df_tmp = small_df[(small_df.index<ind) & (small_df['a']>(row['a']-SOME_THRESHOLD)) & (small_df['a']<(row['a']+SOME_THRESHOLD))]
  count_time += time.time()-start
  if not df_tmp.empty:
    past_index = df_tmp.loc[df_tmp.index.max()]['a']
    large_df.loc[ind, 'similar_past_flood_tag'] = f'Similar to the large flood of {past_index}'

print(f'The total time of creating the subset df for 2e4 rows is: {count_time} seconds.')

The line that creates the subset takes a long time to compute:

The total time of creating the subset df for 2e4 rows is: 18.276793956756592 seconds.

This seems to me to be an too long. I have found similar questions but non of the answers seemed to work (e.g query and numpy conditions).
Is there a way to optimize this?

Note: the code does what is expected - just very slow.

Body:
In pandas for loops are much slower than column operations. So changing the calculation to loop over small_df instead of large_df will already give a big improvement:

for ind, row in small_df.iterrows():
    df_tmp = large_df[ <some condition> ]
    # ... some other processing

Even better for your case is to use a merge rather than a condition on large_df. The problem is your merge is not on equal columns but on approximately equal. To use this approach, you should truncate your column and use that for the merge. Here's a hacky example.

small_df['a_rounded'] = (small_df['a'] / SOME_THRESHOLD / 2).astype(int)
large_df['a_rounded'] = (large_df['a'] / SOME_THRESHOLD / 2).astype(int)
merge_result = small_df.merge(large_df, on='a_rounded')

small_df['a_rounded2'] = ((small_df['a'] + SOME_THRESHOLD) / SOME_THRESHOLD / 2).astype(int)
large_df['a_rounded2'] = ((large_df['a'] + SOME_THRESHOLD) / SOME_THRESHOLD / 2).astype(int)
merge_result2 = small_df.merge(large_df, on='a_rounded2')

total_merge_result = pd.concat([merge_result, merge_result2])
# Now remove duplicates and impose additional filters.

You can impose the additional filters on the result later.


问:
How do you create a method in objects that finds the highest number using hashmap?
I'm new with hashmap and I'm trying to find the most populous continent using hashmap and I don't know where to go from here.

These are my fields and I want to put the continent in the key section and population in the value section

```<code>private String name;
private int population;
private double area;
private String continent;
</code>```

This is my attempt for creating that method but it's incomplete.

```<code>public void findMostPopulousContinent() {
    /* Hashmap<Key, Value> */
    HashMap<String, Integer> dummy = new HashMap<String, Integer>();

    for (int i = 0; i < size; i++) {
        if (dummy.containsKey(catalogue[i].getContinent())) {
            Integer pop = dummy.get(catalogue[i].getContinent());
            pop = pop + catalogue[i].getPopulation();

        }
        else {
            dummy.put(catalogue[i].getContinent(), catalogue[i].getPopulation());
        }
    }
}
</code>```

What I wanted to happen is to put my instances in the hashmap, and if my instances have the same continent then add their population and then compare that with others and then print the continent with the highest population like

```<code>North America, 100000000
</code>```

答:
You need to aggregate the population, which you can use Map's merge() method for.

But you don't need all that code:

Given:

```<code>record Country(String continent, Integer population) {}
Country[] catalog;
</code>```

then:

```<code>Map<String, Integer> continentPopulations = Arrays.stream(catalog)
    .collect(groupingBy(Country::continent, summingInt(Country::population)));
</code>```

The secret sauce is using the groupingBy(classifier, downstream) collector:

```<code>groupingBy(Country::continent, summingInt(Country::population))
</code>```

To get the most populous continent, you can skip the reference to the map and use a stream to find the max based on population for you:

```<code>String mostPopulousContinentName = Arrays.stream(catalog)
    .collect(groupingBy(Country::continent, summingInt(Country::population)))
    .entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .get().getKey();
</code>```

Body:
I'm new with hashmap and I'm trying to find the most populous continent using hashmap and I don't know where to go from here.

These are my fields and I want to put the continent in the key section and population in the value section

private String name;
private int population;
private double area;
private String continent;

This is my attempt for creating that method but it's incomplete.

public void findMostPopulousContinent() {
    /* Hashmap<Key, Value> */
    HashMap<String, Integer> dummy = new HashMap<String, Integer>();

    for (int i = 0; i < size; i++) {
        if (dummy.containsKey(catalogue[i].getContinent())) {
            Integer pop = dummy.get(catalogue[i].getContinent());
            pop = pop + catalogue[i].getPopulation();

        }
        else {
            dummy.put(catalogue[i].getContinent(), catalogue[i].getPopulation());
        }
    }
}

What I wanted to happen is to put my instances in the hashmap, and if my instances have the same continent then add their population and then compare that with others and then print the continent with the highest population like

North America, 100000000

Body:
You need to aggregate the population, which you can use Map's merge() method for.

But you don't need all that code:

Given:

record Country(String continent, Integer population) {}
Country[] catalog;

then:

Map<String, Integer> continentPopulations = Arrays.stream(catalog)
    .collect(groupingBy(Country::continent, summingInt(Country::population)));

The secret sauce is using the groupingBy(classifier, downstream) collector:

groupingBy(Country::continent, summingInt(Country::population))

To get the most populous continent, you can skip the reference to the map and use a stream to find the max based on population for you:

String mostPopulousContinentName = Arrays.stream(catalog)
    .collect(groupingBy(Country::continent, summingInt(Country::population)))
    .entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .get().getKey();


问:
What's difference between these two generic methods?
Sorry for too abstract title, but I have no idea how to compress this question into a single sentence.

I cannot figure out why call1 is failed to be compiled while call2 works well. Aren't call1 and call2 logically same?

public class Test {
    @AllArgsConstructor
    @Getter
    private static class Parent {
        private String name;
    }

    private static class Child extends Parent {
        Child(final String name) {
            super(name);
        }
    }

    private void call1(final List<List<? extends Parent>> testList) {
        System.out.println(testList.get(0).get(0).getName());
    }

    private <T extends Parent> void call2(final List<List<T>> testList) {
        System.out.println(testList.get(0).get(0).getName());
    }

    public void show() {
        final List<List<Parent>> nestedList1 = List.of(List.of(new Parent("P1")));
        final List<List<Child>> nestedList2 = List.of(List.of(new Child("C1")));

        call1(nestedList1); // compile error
        call1(nestedList2); // compile error
        call2(nestedList1); // okay
        call2(nestedList2); // okay
    }
}
```

答:
This might be indeed a surprising behavior, because both methods produce exactly the same bytecode (except the signature of the methods). Why then the first call produces a compile-time error

```<code>incompatible types: List<List<Parent>> cannot be converted to List<List<? extends Parent>>
</code>```

First of all, when you call a method you must be able to assign the actual parameters to the arguments of the method. So, if you have a method

void method(SomeClass arg) {}
```
<p>and you call it as</p>
<pre class="lang-java prettyprint-override"><code>method(someArgument);
</code>```

then the following assignment must be valid:

SomeClass arg = someArgument;
```
<p>This assignment is possible only if the type of <code>someArgument</code> is a subclass of <code>SomeClass</code>.</p>
<p>Now, arrays in Java are covariant, if some <code>subClass</code> is a subclass of some <code>superClass</code>, then <code>subClass[]</code> is a subclass of <code>superClass[]</code>. That means that the following method</p>
<pre class="lang-java prettyprint-override"><code>void method(superClass[] arg) {}
</code>```

can be called with argument of class subClass[].

However, generics in Java are invariant. For any two different types T and U the classes List<T> and List are neither subclasses nor superclasses  of each other, even if such relation exists between the original types T and U. As you know you can pass a List argument to a method by using a wildcard:

void method(List<?> arg) {}
```
<p>But what does this mean? As we have seen, in order for the call to work the following assignment must be valid:</p>
<pre class="lang-java prettyprint-override"><code>List<?> arg = ListOfAnyType;
</code>```

That means, that List<?> becomes a superclass for all possible lists. This is an important point. The type of List<?> is not any type of any list, because none of them can be assigned to each other, it's a special type, which is assignable from any list. Compare the following two types: List<?> and List<Object>. The first one can contain any type of list, while the second one can contain list of any type of objects. So, if you have two methods:

void method1(List<?> arg) {}
void <T> method2(List<T> arg) {}
```
<p>then the first one will accept any list as an argument, while the second one will accept as an argument the list of any type of objects. Well, both methods work in the same way, but the difference becomes important when we add a new level of generics:</p>
<pre class="lang-java prettyprint-override"><code>void method1(List<List<?>> arg1) {}
void <T> method2(List<List<T>> arg2) {}
</code>```

The second case is simple. The type of arg2 is a list, which contains elements, whose type is a list of some (unknown) type. Because of that we can pass any list of lists to method2. The argument arg1 of the first method, however, has a more complex type. It's a list of elements, which have a very special type which is a superclass of any list. Again, while superclass of any list can be assigned from any list, it is not a list itself. And, because the generics in Java is invariant, it means that since List<?> differs from any type of a list, the type of List<List<?>> differs from any List<List<of_any_type>>. That's the meaning of the compile error

```<code>incompatible types: List<List<Parent>> cannot be converted to List<List<? extends Parent>>
</code>```

The type list of lists of some type is different from list of superclass of all lists, because list of some type is different from superclass of all lists.

Now, if you understood all of this you can find a way to make the call to the first method work. What you need is another wildcard:

private void call1(final List<? extends List<? extends Parent>> testList)
```
<p>Now the calls to this method will compile.</p>
<p><strong>UPDATE</strong></p>
<p>Maybe a graphical representation of types' dependences will help to understand it easier. Consider two classes: Parent, and Child which extends Parent.</p>
```Parent <--- Child
```
<p>You can have a list of Parent, and a list of Child, but because of generics invariance these classes are not related to each other:</p>
```List<Parent>
List<Child>
```
<p>When you create a parameterized method</p>
<pre class="lang-java prettyprint-override"><code><T extends Parent> void method1(List<T> arg1)
</code>```

you tell Java that the argument arg1 will be either List<Parent> or List<Child>:

```<code>List<Parent> - possible type for arg1
List<Child>  - possible type for arg1
</code>```

However, when you create a method with a wildcard argument

void method2(List<? extends Parent> arg2)
```
<p>you tell Java to create a new special type, which is a supertype for both <code>List<Parent></code> and <code>List<Child></code>, and make <code>arg2</code> a variable of this type:</p>
```                        List<Parent>
                       /
                      /
List<? extends Parent>
          ^           \
          |            \
          |             List<Child>
          |
 the exact type of arg2
```
<p>Because the type of <code>arg2</code> is a supertype of both <code>List<Parent></code> and <code>List<Child></code>, you can pass either of these lists to method2.</p>
<p>Now let's introduce the next level of generics. When we wrap the above diagram into a new List, we break all the superclass-subclass dependencies (remember the invariance of generics):</p>
```List<List<Parent>>                   all of these three classes
List<List<Child>>                    are independent
List<List<? extends Parent>>         of each other
```
<p>When we create the following method:</p>
```<T extends Parent> void method3(List<List<T>> arg3)
```
<p>we tell Java, that <code>arg3</code> can be either <code>List<List<Parent>></code> or <code>List<List<Child>></code>:</p>
```List<List<Parent>>              - possible type for arg3
List<List<Child>>               - possible type for arg3
List<List<? extends Parent>>
```
<p>Thus, we can pass either of the list of lists to method3. However, the following declaration:</p>
```void method4(List<List<? extends Parent>> arg4)
```
<p>allows only the last type to be the argument for method4:</p>
```List<List<Parent>>
List<List<Child>>
List<List<? extends Parent>>    - possible type for arg4
```
<p>Consequently, we cannot pass either of the list of lists to method4.
We can use another wildcard to create a new superclass for all three types:</p>
```                                        List<List<Parent>>
                                       /
                                      /
List<? extends List<? extends Parent>> --- List<List<Child>>
                                      \
                                       \
                                        List<List<? extends Parent>>

```
<p>Now if we use this type as an argument to our method</p>
<pre class="lang-java prettyprint-override"><code>void method5(List<? extends List<? extends Parent>> arg5)
</code>```

we'll be able to pass either of the lists of lists to method5.

To summarize: while looking similarly, declarations <T extends SomeClass> List<T> and List<? extends SomeClass> are working very differently. The first declaration says that the variable can have one of possible types List<SubClass1 of SomeClass>, or List<SubClass2 of SomeClass>, or List<SubClass3 of SomeClass>, etc. The second declaration creates a single special type, which becomes a superclass of all of List<SubClass1 of SomeClass>, and List<SubClass2 of SomeClass>, and List<SubClass3 of SomeClass>, etc.

Body:
This might be indeed a surprising behavior, because both methods produce exactly the same bytecode (except the signature of the methods). Why then the first call produces a compile-time error

incompatible types: List<List<Parent>> cannot be converted to List<List<? extends Parent>>

First of all, when you call a method you must be able to assign the actual parameters to the arguments of the method. So, if you have a method

void method(SomeClass arg) {}

and you call it as

method(someArgument);

then the following assignment must be valid:

SomeClass arg = someArgument;

This assignment is possible only if the type of someArgument is a subclass of SomeClass.

Now, arrays in Java are covariant, if some subClass is a subclass of some superClass, then subClass[] is a subclass of superClass[]. That means that the following method

void method(superClass[] arg) {}

can be called with argument of class subClass[].

However, generics in Java are invariant. For any two different types T and U the classes List<T> and List<U> are neither subclasses nor superclasses  of each other, even if such relation exists between the original types T and U. As you know you can pass a List argument to a method by using a wildcard:

void method(List<?> arg) {}

But what does this mean? As we have seen, in order for the call to work the following assignment must be valid:

List<?> arg = ListOfAnyType;

That means, that List<?> becomes a superclass for all possible lists. This is an important point. The type of List<?> is not any type of any list, because none of them can be assigned to each other, it's a special type, which is assignable from any list. Compare the following two types: List<?> and List<Object>. The first one can contain any type of list, while the second one can contain list of any type of objects. So, if you have two methods:

void method1(List<?> arg) {}
void <T> method2(List<T> arg) {}

then the first one will accept any list as an argument, while the second one will accept as an argument the list of any type of objects. Well, both methods work in the same way, but the difference becomes important when we add a new level of generics:

void method1(List<List<?>> arg1) {}
void <T> method2(List<List<T>> arg2) {}

The second case is simple. The type of arg2 is a list, which contains elements, whose type is a list of some (unknown) type. Because of that we can pass any list of lists to method2. The argument arg1 of the first method, however, has a more complex type. It's a list of elements, which have a very special type which is a superclass of any list. Again, while superclass of any list can be assigned from any list, it is not a list itself. And, because the generics in Java is invariant, it means that since List<?> differs from any type of a list, the type of List<List<?>> differs from any List<List<of_any_type>>. That's the meaning of the compile error

incompatible types: List<List<Parent>> cannot be converted to List<List<? extends Parent>>

The type list of lists of some type is different from list of superclass of all lists, because list of some type is different from superclass of all lists.

Now, if you understood all of this you can find a way to make the call to the first method work. What you need is another wildcard:

private void call1(final List<? extends List<? extends Parent>> testList)

Now the calls to this method will compile.

UPDATE

Maybe a graphical representation of types' dependences will help to understand it easier. Consider two classes: Parent, and Child which extends Parent.

Parent <--- Child

You can have a list of Parent, and a list of Child, but because of generics invariance these classes are not related to each other:

List<Parent>
List<Child>

When you create a parameterized method

<T extends Parent> void method1(List<T> arg1)

you tell Java that the argument arg1 will be either List<Parent> or List<Child>:

List<Parent> - possible type for arg1
List<Child>  - possible type for arg1

However, when you create a method with a wildcard argument

void method2(List<? extends Parent> arg2)

you tell Java to create a new special type, which is a supertype for both List<Parent> and List<Child>, and make arg2 a variable of this type:

                        List<Parent>
                       /
                      /
List<? extends Parent>
          ^           \
          |            \
          |             List<Child>
          |
 the exact type of arg2

Because the type of arg2 is a supertype of both List<Parent> and List<Child>, you can pass either of these lists to method2.

Now let's introduce the next level of generics. When we wrap the above diagram into a new List, we break all the superclass-subclass dependencies (remember the invariance of generics):

List<List<Parent>>                   all of these three classes
List<List<Child>>                    are independent
List<List<? extends Parent>>         of each other

When we create the following method:

<T extends Parent> void method3(List<List<T>> arg3)

we tell Java, that arg3 can be either List<List<Parent>> or List<List<Child>>:

List<List<Parent>>              - possible type for arg3
List<List<Child>>               - possible type for arg3
List<List<? extends Parent>>

Thus, we can pass either of the list of lists to method3. However, the following declaration:

void method4(List<List<? extends Parent>> arg4)

allows only the last type to be the argument for method4:

List<List<Parent>>
List<List<Child>>
List<List<? extends Parent>>    - possible type for arg4

Consequently, we cannot pass either of the list of lists to method4.
We can use another wildcard to create a new superclass for all three types:

                                        List<List<Parent>>
                                       /
                                      /
List<? extends List<? extends Parent>> --- List<List<Child>>
                                      \
                                       \
                                        List<List<? extends Parent>>

Now if we use this type as an argument to our method

void method5(List<? extends List<? extends Parent>> arg5)

we'll be able to pass either of the lists of lists to method5.

To summarize: while looking similarly, declarations <T extends SomeClass> List<T> and List<? extends SomeClass> are working very differently. The first declaration says that the variable can have one of possible types List<SubClass1 of SomeClass>, or List<SubClass2 of SomeClass>, or List<SubClass3 of SomeClass>, etc. The second declaration creates a single special type, which becomes a superclass of all of List<SubClass1 of SomeClass>, and List<SubClass2 of SomeClass>, and List<SubClass3 of SomeClass>, etc.


问:
Layouts are not including in controller definition
I am using Rails3 I have many layouts in my project, I am defining layout'layout_name' at the top of my controller. I am facing problem like all the layouts are rendering but only one layout is not rendering .. Can anybody say what is the reason?</p>

答:
Have a look at the tutorial about rendering, especially the section 2.2.13 "Finding Layout". There are the different options listed:

Find the layout for all actions of one controller

Name the layout in the directory  app/views/layouts as your controller. So when your controller is named WorkItemsController, the corresponding layout is named work_items.htmlerb

You may change that convention in your controller with the following code, that will search for a layout named work.html.erb:
class WorkItemsController < ApplicationController; layout "work"; ...

There are even variations which allow the dynamic dispatch or even a layout by action.

Have a look at the API for layout to see all options possible here.


问:
How to fix NameError error when calling a function that was already defined?
I have a simple calculator program in Python and I keep getting the NameError even though I already declared the function. And I am not sure why this is occurring. Also, I have another error at Line 25 of the code at the elif statement and it's showing me the invalid syntax error. However, I have checked the indentation and the elif statement and I'm not sure what is wrong with it. Thus, does anyone know what is the reason why this 2 errors occur and how can I fix them? Thank you.

Code:

'''

```<code>def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():

    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if (operator == "+") :
        result = add(first_num,second_num)
    print(first_num, operator ,second_num, "=" ,result)

    elif (operator == '-'): #invalid syntax error encountered here
        result = subtract(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '*'):
        result = multiply(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):
        result = divide(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    else:
        print("Invalid operator entered")
</code>```

'''

Screenshot of errors encountered:

NameError when calling the calculator function in the console

答:
your code should be like this :

```<code>def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():
    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if operator == "+":
        result = add(first_num, second_num)
    elif operator == '-':  # invalid syntax error encountered here
        result = subtract(first_num, second_num)
    elif operator == '*':
        result = multiply(first_num, second_num)
    elif operator == '-':
        result = divide(first_num, second_num)
    else:
        result = None
        print("Invalid operator entered")
    print(first_num, operator, second_num, "=", result)
</code>```

OR

```<code>def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():
    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if (operator == "+"):
        result = add(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):  # invalid syntax error encountered here
        result = subtract(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    elif (operator == '*'):
        result = multiply(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):
        result = divide(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    else:
        print("Invalid operator entered")
</code>```

You should not print any print between if and elif. If you need to print it, it should be in an if or elif block (in Python, blocks are expressed with carriage returns).

Body:
I have a simple calculator program in Python and I keep getting the NameError even though I already declared the function. And I am not sure why this is occurring. Also, I have another error at Line 25 of the code at the elif statement and it's showing me the invalid syntax error. However, I have checked the indentation and the elif statement and I'm not sure what is wrong with it. Thus, does anyone know what is the reason why this 2 errors occur and how can I fix them? Thank you.

Code:

'''

def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():

    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if (operator == "+") :
        result = add(first_num,second_num)
    print(first_num, operator ,second_num, "=" ,result)

    elif (operator == '-'): #invalid syntax error encountered here
        result = subtract(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '*'):
        result = multiply(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):
        result = divide(first_num,second_num)
    print(first_num, operator, second_num, "=", result)

    else:
        print("Invalid operator entered")

'''

Screenshot of errors encountered:

NameError when calling the calculator function in the console

Body:
your code should be like this :

def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():
    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if operator == "+":
        result = add(first_num, second_num)
    elif operator == '-':  # invalid syntax error encountered here
        result = subtract(first_num, second_num)
    elif operator == '*':
        result = multiply(first_num, second_num)
    elif operator == '-':
        result = divide(first_num, second_num)
    else:
        result = None
        print("Invalid operator entered")
    print(first_num, operator, second_num, "=", result)

OR

def add(first_num, second_num):
    return float(first_num) + float(second_num)

def subtract(first_num, second_num):
    return float(first_num) - float(second_num)

def multiply(first_num, second_num):
    return float(first_num) * float(second_num)

def divide(first_num, second_num):
    return float(first_num) / float(second_num)

def calculator():
    operator = input("Select an operation (+-*/): ")
    first_num = input("Enter the first number: ")
    second_num = input("Enter the second number: ")

    if (operator == "+"):
        result = add(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):  # invalid syntax error encountered here
        result = subtract(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    elif (operator == '*'):
        result = multiply(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    elif (operator == '-'):
        result = divide(first_num, second_num)
        print(first_num, operator, second_num, "=", result)

    else:
        print("Invalid operator entered")

You should not print any print between if and elif. If you need to print it, it should be in an if or elif block (in Python, blocks are expressed with carriage returns).


问:
How to return only one closest value?
I have a table, which looks like this:

aircraft
flight
check_schedule
next_flight_schedule

Boeing
123
10.02.2022 21:00
11.02.2022 14:30

Boeing
234
10.02.2022 19:00
11.02.2022 22:50

Boeing
345
10.02.2022 21:00
11.02.2022 04:30

Airbus
789
21.02.2022 16:30
22.02.2022 01:20

Airbus
890
21.02.2022 22:30
22.02.2022 02:20

I need to extract only one row with the closest 'next_flight_schedule' that happened after 'check_schedule'. Like this:

aircraft
flight
check_schedule
next_flight_schedule

Boeing
345
10.02.2022 21:00
11.02.2022 04:30

Airbus
789
21.02.2022 16:30
22.02.2022 01:20

One column for each aircraft, but with the smallest date which happened after check_schedule. All columns should be displayed in the query.

答:
One option might be this (read comments within code):

```<code>SQL> with test (aircraft, flight, check_schedule, next_flight_schedule) as
  2  -- sample data
  3  (select 'Boeing', 123, to_date('10.02.2022 21:00', 'dd.mm.yyyy hh24:mi'), to_date('11.02.2022 14:30', 'dd.mm.yyyy hh24:mi') from dual union all
  4   select 'Boeing', 234, to_date('10.02.2022 19:00', 'dd.mm.yyyy hh24:mi'), to_date('11.02.2022 22:50', 'dd.mm.yyyy hh24:mi') from dual union all
  5   select 'Boeing', 345, to_date('10.02.2022 21:00', 'dd.mm.yyyy hh24:mi'), to_date('11.02.2022 04:30', 'dd.mm.yyyy hh24:mi') from dual union all
  6   select 'Airbus', 789, to_date('21.02.2022 16:30', 'dd.mm.yyyy hh24:mi'), to_date('22.02.2022 01:20', 'dd.mm.yyyy hh24:mi') from dual union all
  7   select 'Airbus', 890, to_date('21.02.2022 22:30', 'dd.mm.yyyy hh24:mi'), to_date('22.02.2022 02:20', 'dd.mm.yyyy hh24:mi') from dual
  8  ),
  9  --
</code>```

```<code> 10  temp as
 11  -- MAX CHECK_SCHEDULE per aircraft
 12  (select aircraft, max(check_schedule) max_check_schedule
 13   from test
 14   group by aircraft
 15  )
 16  select t.*
 17  from test t join temp a on a.aircraft = t.aircraft
 18  where t.next_flight_schedule =
 19                                 -- the 1st NEXT_FLIGHT_SCHEDULE that follows the MAX CHECK_SCHEDULE
 20                                (select min(t1.next_flight_schedule)
 21                                  from test t1
 22                                  where t1.aircraft = t.aircraft
 23                                    and t1.next_flight_schedule > a.max_check_schedule
 24                                 );

AIRCRA     FLIGHT CHECK_SCHEDULE   NEXT_FLIGHT_SCHE
------ ---------- ---------------- ----------------
Boeing        345 10.02.2022 21:00 11.02.2022 04:30
Airbus        789 21.02.2022 16:30 22.02.2022 01:20

SQL>
</code>```

Title: How to return only one closest value?

Body:
One option might be this (read comments within code):

SQL> with test (aircraft, flight, check_schedule, next_flight_schedule) as
  2  -- sample data
  3  (select 'Boeing', 123, to_date('10.02.2022 21:00', 'dd.mm.yyyy hh24:mi'), to_date('11.02.2022 14:30', 'dd.mm.yyyy hh24:mi') from dual union all
  4   select 'Boeing', 234, to_date('10.02.2022 19:00', 'dd.mm.yyyy hh24:mi'), to_date('11.02.2022 22:50', 'dd.mm.yyyy hh24:mi') from dual union all
  5   select 'Boeing', 345, to_date('10.02.2022 21:00', 'dd.mm.yyyy hh24:mi'), to_date('11.02.2022 04:30', 'dd.mm.yyyy hh24:mi') from dual union all
  6   select 'Airbus', 789, to_date('21.02.2022 16:30', 'dd.mm.yyyy hh24:mi'), to_date('22.02.2022 01:20', 'dd.mm.yyyy hh24:mi') from dual union all
  7   select 'Airbus', 890, to_date('21.02.2022 22:30', 'dd.mm.yyyy hh24:mi'), to_date('22.02.2022 02:20', 'dd.mm.yyyy hh24:mi') from dual
  8  ),
  9  --

 10  temp as
 11  -- MAX CHECK_SCHEDULE per aircraft
 12  (select aircraft, max(check_schedule) max_check_schedule
 13   from test
 14   group by aircraft
 15  )
 16  select t.*
 17  from test t join temp a on a.aircraft = t.aircraft
 18  where t.next_flight_schedule =
 19                                 -- the 1st NEXT_FLIGHT_SCHEDULE that follows the MAX CHECK_SCHEDULE
 20                                (select min(t1.next_flight_schedule)
 21                                  from test t1
 22                                  where t1.aircraft = t.aircraft
 23                                    and t1.next_flight_schedule > a.max_check_schedule
 24                                 );

AIRCRA     FLIGHT CHECK_SCHEDULE   NEXT_FLIGHT_SCHE
------ ---------- ---------------- ----------------
Boeing        345 10.02.2022 21:00 11.02.2022 04:30
Airbus        789 21.02.2022 16:30 22.02.2022 01:20

SQL>


问:
Creating the XML file on the Another Website
I am working on a Web Site, which have 2 domain one for end users(www.test.com) and for Admin Panel(www.admin.test.com), I am creating the Site map from my Admin section(www.admin.test.com), Now I want when I will create(save) the Site map then My XML file will generate on the Root of the main website(www.test.com).

Can any one suggest me how I am achieve this, I am newbie in asp.net.

答:
If you think both of the domains will be in same physical server, then you can just add path to your physical folder in the test.com site and create xml using it.

If you think that will not be the case, you can simply create a web service on front end that will take care of it.

In most of the cases, first cases is true and you can easily generate xml in www.test.com folder without any problems.

Thanks
Prashant