问:
Checking if an array is a diagonally dominant matrix in C
I have an issue coding a task for my studies - an algorithm that checks if a 2d array is a Diagonally dominant matrix.

To do this i made a function:

```<code>      int dd_test(const int *ptr, int width, int height){

      if (width!=height)
        return -1;

      int sum=0;
      int j;

      for (int i=0;i<width;i++){
          for(j=0;j<height;j++){
            if(i!=j){
              if(*((ptr+i*width)+j)!=0)
                sum+=abs(*((ptr+i*width)+j));
              else
                continue;
            }
          }
          if(*((ptr+i*width)+j)<=sum)
            return 0;
          else if (*((ptr+i*width)+j)>sum)
            sum = 0;
      }
      return 1;
    }
</code>```

At first it checks if it is a square matrix, and than checks if the number on diagonal is the largest in the row. If it is not, algorithm returns 0; if it is algorithm goes to the next row and do it again.
    The main function looks like this:

```<code>    int main(void) {
  int wid=5, he=5;
  int matrix[5][5]={0};
  int *ma=matrix[0];

  puts("Input a 5x5 matrix: ");
  for(int i=0;i<5;i++){
      if(scanf("%d %d %d %d %d",(ma+i*wid),((ma+i*wid)+1),((ma+i*wid)+2),((ma+i*wid)+3),((ma+i*wid)+4))!=5){
        puts("Incorrect input");
        return 1;
      }
  }

  if(dd_test(ma, wid, he)==1)
    puts("YES");
  else if (dd_test(ma, wid,he)==0)
    puts("NO");

  return 0;
}
</code>```

The problem is that it always returns 0.I can't find a bug, please help me. I feel literally burnt out.

Thanks.

答:
You should use ptr[i*width+j] instead of *((ptr+i*width)+j), because it's easier to read your code.

Your condition is not exact:

```<code>          if(*((ptr+i*width)+j)<=sum)
            return 0;
          else if (*((ptr+i*width)+j)>sum)
            sum = 0;
</code>```

It should change to:

```<code>         if(ptr[i*width+i]< sum) // it's similar to if(*((ptr+i*width)+i)< sum)
            return 0;
         else
            sum = 0;
</code>```

You can make your code shorter by removing the if else condition in for loop:

```<code>int dd_test(const int *ptr, int width, int height){

    if (width!=height)
        return -1;
    int j, sum = 0;

    for (int i=0;i<width;i++) {
        sum = 0;
        for(j=0;j<height;j++)
            sum += abs(ptr[i*width+j]);
        sum -= abs(ptr[i*width+i]);

        if(ptr[i*width+i] < sum)
            return 0;
    }
     return 1;
}

</code>```

Body:
I have an issue coding a task for my studies - an algorithm that checks if a 2d array is a Diagonally dominant matrix.

To do this i made a function:

      int dd_test(const int *ptr, int width, int height){

      if (width!=height)
        return -1;

      int sum=0;
      int j;

      for (int i=0;i<width;i++){
          for(j=0;j<height;j++){
            if(i!=j){
              if(*((ptr+i*width)+j)!=0)
                sum+=abs(*((ptr+i*width)+j));
              else
                continue;
            }
          }
          if(*((ptr+i*width)+j)<=sum)
            return 0;
          else if (*((ptr+i*width)+j)>sum)
            sum = 0;
      }
      return 1;
    }

At first it checks if it is a square matrix, and than checks if the number on diagonal is the largest in the row. If it is not, algorithm returns 0; if it is algorithm goes to the next row and do it again.
    The main function looks like this:

    int main(void) {
  int wid=5, he=5;
  int matrix[5][5]={0};
  int *ma=matrix[0];

  puts("Input a 5x5 matrix: ");
  for(int i=0;i<5;i++){
      if(scanf("%d %d %d %d %d",(ma+i*wid),((ma+i*wid)+1),((ma+i*wid)+2),((ma+i*wid)+3),((ma+i*wid)+4))!=5){
        puts("Incorrect input");
        return 1;
      }
  }

  if(dd_test(ma, wid, he)==1)
    puts("YES");
  else if (dd_test(ma, wid,he)==0)
    puts("NO");

  return 0;
}

The problem is that it always returns 0.I can't find a bug, please help me. I feel literally burnt out.

Thanks.

Body:
You should use ptr[i*width+j] instead of *((ptr+i*width)+j), because it's easier to read your code.

Your condition is not exact:

          if(*((ptr+i*width)+j)<=sum)
            return 0;
          else if (*((ptr+i*width)+j)>sum)
            sum = 0;

It should change to:

         if(ptr[i*width+i]< sum) // it's similar to if(*((ptr+i*width)+i)< sum)
            return 0;
         else
            sum = 0;

You can make your code shorter by removing the if else condition in for loop:

int dd_test(const int *ptr, int width, int height){

    if (width!=height)
        return -1;
    int j, sum = 0;

    for (int i=0;i<width;i++) {
        sum = 0;
        for(j=0;j<height;j++)
            sum += abs(ptr[i*width+j]);
        sum -= abs(ptr[i*width+i]);

        if(ptr[i*width+i] < sum)
            return 0;
    }
     return 1;
}


来源: stackexchange

问:
How to find tha't circular list's begin?
I'm trying to implement about list and iterator of list like C++ STL.

The node in list is defined like this:

```<code>struct Node{
  Node *prev,*next;
  value_type data;
};
</code>```

And I want to overloading operator > and < :

```<code>bool list_iterator::operator>(const iterator_impl_base &rhs) const
bool list_iterator::operator<(const iterator_impl_base &rhs) const
</code>```

which means if I need to call next to reach rhs.node , it will return 0 in > and return 1 in <.

if I need to call prev to reach rhs.node , it return 1 in > and return 0 in <.

And I implement list using circular list. Below is one part of list class :

```<code>class List : public ordered_container {
 protected:
  Node* begin_;
  Node* end_;
  size_type size_;
 public:
    List::List() : end_(new Node){
        begin_ = end_->prev = end_->next = end_;
        size_=0;
    }
}
</code>```

So , I don't know how to distinguish whether I just pass the begin_ of list. Can someone help me about that? Thankyou.

答:
An element a is less than another element b iff you can reach b before end by following next.

An element a is greater than another element b iff b is less than a.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement about list and iterator of list like C++ STL.

The node in list is defined like this:

struct Node{
  Node *prev,*next;
  value_type data;
};

And I want to overloading operator > and < :

bool list_iterator::operator>(const iterator_impl_base &rhs) const
bool list_iterator::operator<(const iterator_impl_base &rhs) const

which means if I need to call next to reach rhs.node , it will return 0 in > and return 1 in <.

if I need to call prev to reach rhs.node , it return 1 in > and return 0 in <.

And I implement list using circular list. Below is one part of list class :

class List : public ordered_container {
 protected:
  Node* begin_;
  Node* end_;
  size_type size_;
 public:
    List::List() : end_(new Node){
        begin_ = end_->prev = end_->next = end_;
        size_=0;
    }
}

So , I don't know how to distinguish whether I just pass the begin_ of list. Can someone help me about that? Thankyou.


问:
How to print IP address from Shell Script?
Below is my command line

```<code>$ps -eaf | grep consul_exporter | grep -v grep
root      4020     1  6 Mar20 ?        4-08:51:18 ./consul_exporter --consul.server=10.1.2.133:8500 --kv.prefix=/ --web.listen-address=0.0.0.0:80
</code>```

I want to get output of IP address(10.1.2.133) alone as output. How to write command line for that?

答:
If you don't mind a solution which is not elegant, but does the job, just pipe the output of your grep command into

```<code>... | cut -f 2 -d = | cut -f 1 -d :
</code>```

This splits the line first by the = and then :. If the pattern is not so regular and the IP address can appear anywhere in the line, pipe it into

```<code>... | grep -oE '([0-9]{1,3}[.]){3}[0-9]{1,3}'
</code>```

The -o option just extract the matching pattern(s) from the input.

Body:
Below is my command line

$ps -eaf | grep consul_exporter | grep -v grep
root      4020     1  6 Mar20 ?        4-08:51:18 ./consul_exporter --consul.server=10.1.2.133:8500 --kv.prefix=/ --web.listen-address=0.0.0.0:80

I want to get output of IP address(10.1.2.133) alone as output. How to write command line for that?

Body:
If you don't mind a solution which is not elegant, but does the job, just pipe the output of your grep command into

... | cut -f 2 -d = | cut -f 1 -d :

This splits the line first by the = and then :. If the pattern is not so regular and the IP address can appear anywhere in the line, pipe it into

... | grep -oE '([0-9]{1,3}[.]){3}[0-9]{1,3}'

The -o option just extract the matching pattern(s) from the input.


问:
Common DLL referencing throughout Silverlight project
I have a common silverlight project. This project project, among other things, includes constants and static classes.

The silverlight App i have references this common library.
In addition, i have a handful of external modules that are loaded on-demand (via Prism). Each module is its own .Xap file and they too reference the common library.

So now each Xap in my silverlight application has a reference to the Common.dll.
Does this mean the common.dll is loaded every time a xap is loaded, or does it essentially mean only the main App's common.dll is ever loaded?

The ultimate question im getting at is this:
If i make a code change (bug fix) in the common.dll, do i have to release ALL Xap files or just the main App xap?

Thanks.

答:
If you use Assembly Caching in all projects that reference the common dll then you'll just get one copy downloaded as it's own zip file. This way all the different XAP files will reference the same dll. Otherwise common.dll will be included in each XAP file that references.

You'll need to create a common.extmap.xml file for your common.dll which needs to be in the same folder from where the dll is referenced.

ContentLicense: CC BY-SA 3.0


问:
c# passing inline interface like delegate method
i',m using this syntax in java:

```<code> public interface Interaction
    {
        void onSuccess(String result);
        void onFailure(String error);
    }

    void getData(Interaction interaction)
    {
        //someCode
        interaction.onSuccess("foo");
    }

    void main()
    {
        getData(new Interaction()
        {
            @override
            void onSuccess(String result)
            {
                    //here is sucess part
            }

            @override
            void onFailure(String error)
            {
                   //here is failure part
            }
        })
    }
</code>```

i'm new at c# coding. how can i implement that structure in c#?
does c# support inline instance interface as java?

答:
One way to redesign this is to accept two Action<string> parameters:

```<code>void GetData(Action<string> onSuccess, Action<string> onFailure)
{
    //someCode
    onSuccess("foo");
}

void Main()
{
    GetData(onSuccess: result => {
        // success part...
    }, onFailure: error => {
        // failure part
    });
}
</code>```

Another way is to keep the IInteraction interface:

```<code>public interface IInteraction
{
    void OnSuccess(String result);
    void OnFailure(String error);
}

void GetData(IInteraction interaction)
{
    //someCode
    interaction.OnSuccess("foo");
}
</code>```

But have a concrete class GenericInteraction that implements IInteraction:

```<code>class GenericInteraction : IInteraction {
    private Action<string> onSuccess;
    private Action<string> onFailure;
    public GenericInteraction(Action<string> onSuccess, Action<string> onFailure) {
        this.onSuccess = onSuccess;
        this.onFailure = onFailure;
    }

    public void OnSuccess(String result) { onSuccess(result); }
    public void OnFailure(String error) { onFailure(error); }
}
</code>```

This way, the caller of the method can choose to either pass in onSuccess and onFailure "inline":

```<code>GetData(new GenericInteraction(onSuccess: result => {
    // success part...
}, onFailure: error => {
    // failure part
}));
</code>```

Or pass something else that implements IInteraction:

```<code>GetData(someOtherInteractionICreated);
</code>```

Which is closer to what you could do in Java.

Body:
i',m using this syntax in java:

 public interface Interaction
    {
        void onSuccess(String result);
        void onFailure(String error);
    }

    void getData(Interaction interaction)
    {
        //someCode
        interaction.onSuccess("foo");
    }

    void main()
    {
        getData(new Interaction()
        {
            @override
            void onSuccess(String result)
            {
                    //here is sucess part
            }

            @override
            void onFailure(String error)
            {
                   //here is failure part
            }
        })
    }

i'm new at c# coding. how can i implement that structure in c#?
does c# support inline instance interface as java?

Body:
One way to redesign this is to accept two Action<string> parameters:

void GetData(Action<string> onSuccess, Action<string> onFailure)
{
    //someCode
    onSuccess("foo");
}

void Main()
{
    GetData(onSuccess: result => {
        // success part...
    }, onFailure: error => {
        // failure part
    });
}

Another way is to keep the IInteraction interface:

public interface IInteraction
{
    void OnSuccess(String result);
    void OnFailure(String error);
}

void GetData(IInteraction interaction)
{
    //someCode
    interaction.OnSuccess("foo");
}

But have a concrete class GenericInteraction that implements IInteraction:

class GenericInteraction : IInteraction {
    private Action<string> onSuccess;
    private Action<string> onFailure;
    public GenericInteraction(Action<string> onSuccess, Action<string> onFailure) {
        this.onSuccess = onSuccess;
        this.onFailure = onFailure;
    }

    public void OnSuccess(String result) { onSuccess(result); }
    public void OnFailure(String error) { onFailure(error); }
}

This way, the caller of the method can choose to either pass in onSuccess and onFailure "inline":

GetData(new GenericInteraction(onSuccess: result => {
    // success part...
}, onFailure: error => {
    // failure part
}));

Or pass something else that implements IInteraction:

GetData(someOtherInteractionICreated);

Which is closer to what you could do in Java.


问:
React : data[0].toFixed is not a function. (In 'data[0].toFixed(decimalPlaces)', 'data[0].toFixed' is undefined)
I want to fetch numerical values through API call and represent them in graph using 'react-native-chart-kit', but its producing error  data[0].toFixed is not a function. How to resolve this error?click here to view error

class SecondActivity extends Component {

 constructor(props){
   super(props);
   this.state={a:"",b:""}
 }

 componentDidMount(){
   this.graph = setInterval( () => this.GetGraph(),1000);
 }

 GetGraph(){
   var jsondata;
  fetch('api here', {
    method: 'GET'
 })
 .then((response) => response.json())
 .then((responseJson) => {

   this.setState({
       jsondata: responseJson,
       a:responseJson[0].val,
       b:responseJson[1].val,})
   })
 .catch((error) => {
    console.error(error);
 });   }

  render() {
      if(!this.state.a) {
    return <ActivityIndicator/>
  }
    return (
      <View>
        <LineChart
          data={{
            labels: [
              '1',
              '2', ],
            datasets: [
              {
                data: [
                  this.state.a,
                  this.state.b,
                ],
              },                ],              }}
          width={Dimensions.get('window').width}
          height={250}
          yAxisLabel="a"
          yAxisInterval={1}/>
      </View>);}}```

答:
I don't know react-native-chart-kit but since toFixed() is a method on Number, I suppose responseJson[0].val and/or responseJson[1].val may contain (some?) other values then numbers.

Depending on the data, a workaround may be a conversion to numbers:

this.setState({
    jsondata: responseJson,
    a:responseJson[0].val.map(v => { /* return v converted to number */ },
    b:responseJson[1].val.map(v => { /* return v converted to number */ }
})
```

I won't provide a conversion here. Without knowing the possible values in your data, any proposal could be lossy (or just plain wrong).

Secondly, if the server is expected to send numbers, it should send numbers. This may be a bug, but there may also be a reason for sending numbers, e.g. to be able to submit numbers with high precision or sending fixed point decimals lossless. In this case, you have to be careful how to use these values in JavaScript.

If this is not the solution you should provide the raw JSON response for further inspection.

Body:
I don't know react-native-chart-kit but since toFixed() is a method on Number, I suppose responseJson[0].val and/or responseJson[1].val may contain (some?) other values then numbers.

Depending on the data, a workaround may be a conversion to numbers:

this.setState({
    jsondata: responseJson,
    a:responseJson[0].val.map(v => { /* return v converted to number */ },
    b:responseJson[1].val.map(v => { /* return v converted to number */ }
})

I won't provide a conversion here. Without knowing the possible values in your data, any proposal could be lossy (or just plain wrong).

Secondly, if the server is expected to send numbers, it should send numbers. This may be a bug, but there may also be a reason for sending numbers, e.g. to be able to submit numbers with high precision or sending fixed point decimals lossless. In this case, you have to be careful how to use these values in JavaScript.

If this is not the solution you should provide the raw JSON response for further inspection.


答:
I gave your dd_test a slight modification. You accumulated the non-diagonal components of each row correctly but you ended up asking the wrong value for the diagonal component.

By the time you ask *((ptr+i*width)+j), j will be equal to height. Instead you should use i since the height of the current row is also equal to the position of the diagonal component of the row.

```<code>int dd_test(const int* ptr, int width, int height) {
    if (width != height)
        return -1;

    int sum = 0;

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (i != j) {
                sum += abs(*((ptr + i * width) + j));
            }
        }
        if (*((ptr + i * width) + i) <= sum)
            return 0;
        else if (*((ptr + i * width) + i) > sum)
            sum = 0;
    }
    return 1;
}
</code>```

Hope this helps.

Title: Checking if an array is a diagonally dominant matrix in C

Body:
I gave your dd_test a slight modification. You accumulated the non-diagonal components of each row correctly but you ended up asking the wrong value for the diagonal component.

By the time you ask *((ptr+i*width)+j), j will be equal to height. Instead you should use i since the height of the current row is also equal to the position of the diagonal component of the row.

int dd_test(const int* ptr, int width, int height) {
    if (width != height)
        return -1;

    int sum = 0;

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (i != j) {
                sum += abs(*((ptr + i * width) + j));
            }
        }
        if (*((ptr + i * width) + i) <= sum)
            return 0;
        else if (*((ptr + i * width) + i) > sum)
            sum = 0;
    }
    return 1;
}

Hope this helps.


问:
XGboost python - classifier class weight option?
Is there a way to set different class weights for xgboost classifier? For example in sklearn RandomForestClassifier this is done by the "class_weight" parameter. </p>

答:
```<code>from sklearn.utils.class_weight import compute_sample_weight
xgb_classifier.fit(X, y, sample_weight=compute_sample_weight("balanced", y))
</code>```


问:
Android Studio 3.6 always select the first build variant
I've just updated to Android Studio 3.6 stable version. After that, every time I open my project. The Android Studio changes my selected build variant to the first item in the variant list. Then I have to change the selected variant and sync gradle again. :(

Anyone have solution for this?

答:
I think it is problem of upgrading android studio from version <= 3.5

My solution for this is to push your project to any VCS. Then you clone it as a new project and use android studio to open it. You will find the build variant is working again.


问:
How do I set a color for a function in a callgraph?
A doxygen callgraph usually colors a single function as gray and all other functions in the call-tree as white. Unfortunately, I need to color several functions in special color for my use case. For example, the following main.c

/**
 * @file main.c
*/

/// @brief Foos around
void foo() {}

/// @brief Bars around
void bar() { foo(); }

/// @brief Quux around
void quux() {}

/// @brief System entry point
int main() {
   foo();
   bar();
   quux();
}
```

<p>together with the following Doxygen configuration </p>

```EXTRACT_ALL            = YES
CALL_GRAPH             = YES
```

generates  the following tree:

While this is fine in general, some internal rules need bar to be always colored orange, as it is a "unsafe" function. Similarly, I have to color foo as teal to signalize that it is safe. Something I envision is

Is it possible to set the color in Doxygen's generated graphs via Doxygen commands? E.g. some magic command like the non-existing @dotnodecolor green? Or do I need to post-process all graphs by hand?

答:
In doxygen there is no way to set the node color, so unfortunately you will have to post process the relevant graphs yourself.

There might be a way around this by redefining the dot command (it is a bit mean)

read the doxygen dot file

manipulate the required field

write the file back

run the real dot command.

By means of doxygen -d extcmd you can see the used arguments in the call to e.g. dot.

For your case te output of the later would be (DOT_IMAGE_FORMAT = png):

```<code>Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tpng -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.png"`
Executing external command `dot ".../html/graph_legend.dot" -Tpng -o "D:/speeltuin/_stack/quest_color_dot/html/graph_legend.png"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tpng -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.png"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tcmapx -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.map"`
Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tcmapx -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.map"`
</code>```

and in case: DOT_IMAGE_FORMAT = svg

```<code>Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tsvg -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.svg"`
Executing external command `dot ".../html/graph_legend.dot" -Tsvg -o ".../html/graph_legend.svg"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tsvg -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.svg"`
Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tcmapx -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.map"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tcmapx -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.map"`
</code>```

Body:
A doxygen callgraph usually colors a single function as gray and all other functions in the call-tree as white. Unfortunately, I need to color several functions in special color for my use case. For example, the following main.c

/**
 * @file main.c
*/

/// @brief Foos around
void foo() {}

/// @brief Bars around
void bar() { foo(); }

/// @brief Quux around
void quux() {}

/// @brief System entry point
int main() {
   foo();
   bar();
   quux();
}

together with the following Doxygen configuration

EXTRACT_ALL            = YES
CALL_GRAPH             = YES

generates  the following tree:

While this is fine in general, some internal rules need bar to be always colored orange, as it is a "unsafe" function. Similarly, I have to color foo as teal to signalize that it is safe. Something I envision is

Is it possible to set the color in Doxygen's generated graphs via Doxygen commands? E.g. some magic command like the non-existing @dotnodecolor green? Or do I need to post-process all graphs by hand?

Body:
In doxygen there is no way to set the node color, so unfortunately you will have to post process the relevant graphs yourself.

There might be a way around this by redefining the dot command (it is a bit mean)

read the doxygen dot file

manipulate the required field

write the file back

run the real dot command.

By means of doxygen -d extcmd you can see the used arguments in the call to e.g. dot.

For your case te output of the later would be (DOT_IMAGE_FORMAT = png):

Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tpng -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.png"`
Executing external command `dot ".../html/graph_legend.dot" -Tpng -o "D:/speeltuin/_stack/quest_color_dot/html/graph_legend.png"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tpng -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.png"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tcmapx -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.map"`
Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tcmapx -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.map"`

and in case: DOT_IMAGE_FORMAT = svg

Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tsvg -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.svg"`
Executing external command `dot ".../html/graph_legend.dot" -Tsvg -o ".../html/graph_legend.svg"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tsvg -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.svg"`
Executing external command `dot ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.dot" -Tcmapx -o ".../html/main_8c_a49a4b11e50430aa0a78de989ea99e082_cgraph.map"`
Executing external command `dot ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.dot" -Tcmapx -o ".../html/main_8c_ae66f6b31b5ad750f1fe042a706a4e3d4_cgraph.map"`


问:
Classloader getResource failed when running Wildfly inside Docker
I have a JavaEE application deployed on Wildfly and running correctly on both Ubuntu and Windows OS. However, when I try to Dockerized the application it fails.

Here is the part of the code that fails:

```<code>File templateFile = new File(ESGenerator.class.getClassLoader().getResource("/endpoint-js-template/get-template.js").getFile());
// ...
endpointJSInterface.setTemplate(FileUtils.readFileToString(templateFile));
</code>```

Here are the file location when I tried to log:

// Ok - Ubuntu
/home/czetsuya/java/jboss/wildfly-15.0.1.Final/standalone/deployments/myApp.war/WEB-INF/lib/myApp-admin-ejbs-6.9.0-SNAPSHOT.jar/endpoint-js-template/get-template.js

// Ok - Windows
c:\Java\Jboss\wildfly-15.0.1.Final\standalone\deployments\myApp.war\WEB-INF\lib\myApp-admin-ejbs-6.9.0-SNAPSHOT.jar\endpoint-js-template\get-template.js

// Ko - Docker
/content/myApp.war/WEB-INF/lib/myApp-admin-ejbs-6.9.0-SNAPSHOT.jar/endpoint-js-template/get-template.js

Where does '/content' comes from and what's the best way to solve this issue?

答:
The solution would be to avoid using new File operation.

Here's how I fix this issue.

```<code>// get the URL of the resource from the jar file
URL templateUrl = ESGenerator.class.getClassLoader().getResource("/endpoint-js-template/get-template.js");
// load as string using IOUtils
endpointJSInterface.setTemplate(IOUtils.toString(templateUrl));
</code>```

Body:
I have a JavaEE application deployed on Wildfly and running correctly on both Ubuntu and Windows OS. However, when I try to Dockerized the application it fails.

Here is the part of the code that fails:

File templateFile = new File(ESGenerator.class.getClassLoader().getResource("/endpoint-js-template/get-template.js").getFile());
// ...
endpointJSInterface.setTemplate(FileUtils.readFileToString(templateFile));

Here are the file location when I tried to log:

// Ok - Ubuntu
/home/czetsuya/java/jboss/wildfly-15.0.1.Final/standalone/deployments/myApp.war/WEB-INF/lib/myApp-admin-ejbs-6.9.0-SNAPSHOT.jar/endpoint-js-template/get-template.js

// Ok - Windows
c:\Java\Jboss\wildfly-15.0.1.Final\standalone\deployments\myApp.war\WEB-INF\lib\myApp-admin-ejbs-6.9.0-SNAPSHOT.jar\endpoint-js-template\get-template.js

// Ko - Docker
/content/myApp.war/WEB-INF/lib/myApp-admin-ejbs-6.9.0-SNAPSHOT.jar/endpoint-js-template/get-template.js

Where does '/content' comes from and what's the best way to solve this issue?

Body:
The solution would be to avoid using new File operation.

Here's how I fix this issue.

// get the URL of the resource from the jar file
URL templateUrl = ESGenerator.class.getClassLoader().getResource("/endpoint-js-template/get-template.js");
// load as string using IOUtils
endpointJSInterface.setTemplate(IOUtils.toString(templateUrl));


问:
Quickly determine CPU usage of all processes of a specific user on terminal server
I'm looking for a quick way to find out the cumulative CPU usage of all processes of a specific user on a Terminal Server, as displayed by the TaskManager in the tab "Users".

The solutions via PerformanceCounters, which I have looked at so far, are all much too slow and require a relatively large amount of CPU time themselves.

My questions:

How do I determine all processes for a specific TS Session?

How do I determine the total CPU load of these processes?

If someone had something there, I would be very grateful.

Greetings

Ken

What I've already tried:

I looked at various solutions, but they were all much too slow.

答:
I was able to solve my problem via Cassia for now.
But:
it's not efficient.
To determine the processes of a session, Cassia uses the WTS way to determine all processes on the server and then filter out those that belong to a specific session.

This is not very fast on a terminal server with many users and many processes.

That's why I asked for a fast and less CPU intensive solution.

My program via Cassia uses 17% of the CPU, while TaskManager needs only 0.6% CPU time for the same detection.

My question: How does TaskManager do this? And can I implement this in my C# program?

Or is that even magic?

Greetings

Ken


问:
Writing images and text to files using python
I am trying to use beautiful soup to scrape images from multiple URLs, and then write the URLs and the images to a file. The file format would look like:

TEXT OF URL_1

img_1 (ACTUAL IMAGE SHOWN)

img_2 (ACTUAL IMAGE SHOWN)

TEXT OF URL_2

img_1 (ACTUAL IMAGE SHOWN)

The first few lines of my output file right now looks like:

```<code>Company : Firehydrant     URL : https://www.firehydrant.io/âPNG

IHDRLf9ÃŒ∫   pHYsöúYiTXtXML:com.adobe.xmp<?xpacket begin="Ôªø" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c148 79.164036, 2019/08/13-01:06:57

...
</code>```

How can I view my file with the images actually showing instead of the binary? Or is there a different way of doing this? Sorry if this is a really stupid question!!

Here is my code right now for 1 website:

```<code>
with open(file_name, 'wb') as img_file:

    option = webdriver.ChromeOptions()
    option.add_argument(" — incognito")
    browser = webdriver.Chrome(executable_path='./chromedriver', chrome_options=option)

    url = 'https://www.firehydrant.io/'

    browser.get(url)
    timeout = 10
    WebDriverWait(browser, timeout)

    soup = BeautifulSoup(browser.page_source, 'html.parser')
    images = soup.find_all("img")

    found_first_image = False
    for image in images:
        src = image['src']
        if(found_first_image == False): # ADD THE TEXT FOR THE COMPANY/URL
            found_first_image = True
            string = ("URL : " + url).encode('utf-8')
            img_file.write(string)

        # removing everything after the '?' if there is one in the src tag
        src = urljoin(url, src)
        if("?" in src):
            pos = src.index("?")
            src = src[:pos]
        parsed = urlparse(src)
        if(bool(parsed.netloc) and bool(parsed.scheme)): # download the image and write it to the file
            response = requests.get(src)
            URLFile.write(response.content)
</code>```

答:
Store your images as image files outside rather than putting them here as text. Just keep a unique id for the image when you write it and put that unique id in your text file instead of the image. For saving image, cv2.imread can be used and for generating unique number use:

```<code>import uuid

uuid.uuid1().hex
</code>```

Body:
I am trying to use beautiful soup to scrape images from multiple URLs, and then write the URLs and the images to a file. The file format would look like:

TEXT OF URL_1

img_1 (ACTUAL IMAGE SHOWN)

img_2 (ACTUAL IMAGE SHOWN)

TEXT OF URL_2

img_1 (ACTUAL IMAGE SHOWN)

The first few lines of my output file right now looks like:

Company : Firehydrant     URL : https://www.firehydrant.io/âPNG

IHDRLf9ÃŒ∫   pHYsöúYiTXtXML:com.adobe.xmp<?xpacket begin="Ôªø" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c148 79.164036, 2019/08/13-01:06:57

...

How can I view my file with the images actually showing instead of the binary? Or is there a different way of doing this? Sorry if this is a really stupid question!!

Here is my code right now for 1 website:

with open(file_name, 'wb') as img_file:

    option = webdriver.ChromeOptions()
    option.add_argument(" — incognito")
    browser = webdriver.Chrome(executable_path='./chromedriver', chrome_options=option)

    url = 'https://www.firehydrant.io/'

    browser.get(url)
    timeout = 10
    WebDriverWait(browser, timeout)

    soup = BeautifulSoup(browser.page_source, 'html.parser')
    images = soup.find_all("img")

    found_first_image = False
    for image in images:
        src = image['src']
        if(found_first_image == False): # ADD THE TEXT FOR THE COMPANY/URL
            found_first_image = True
            string = ("URL : " + url).encode('utf-8')
            img_file.write(string)

        # removing everything after the '?' if there is one in the src tag
        src = urljoin(url, src)
        if("?" in src):
            pos = src.index("?")
            src = src[:pos]
        parsed = urlparse(src)
        if(bool(parsed.netloc) and bool(parsed.scheme)): # download the image and write it to the file
            response = requests.get(src)
            URLFile.write(response.content)

Body:
Store your images as image files outside rather than putting them here as text. Just keep a unique id for the image when you write it and put that unique id in your text file instead of the image. For saving image, cv2.imread can be used and for generating unique number use:

import uuid

uuid.uuid1().hex


问:
Why does mysql_query() return TRUE with a SELECT statement?
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

```<code>if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}
</code>```

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

答:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

(from http://php.net/manual/en/function.mysql-query.php)

You say that SELECTs are returning boolean true?  Not just a resource that isn't zero :) ?

Body:
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...


问:
What sets column width / distribution in Yii2's DetailView?
The same view, the same DetailView, the same code, different model, different end result:

What sets column width in this case? Why it is shifting with each record? Is this a Bootstrap or Yii2 issue? I tried to analyse generated code with Chrome Dev Tools, but got no conclusions. As you can see, there is a lot of empty spaces in both columns, so column width shifting should not occur.

Most important -- how to prevent that? How to make sure, that every view will look exactly the same, no matter what data will be printed inside DetailView?

答:
Also you can use the public propetry template to achieve this. For example:

```<code><?= DetailView::widget([
   'model' => ...,
   'attributes' => [[...], [...]],
   'template' => "<tr><th style='width: 15%;'>{label}</th><td>{value}.</td></tr>"
]) ?>
</code>```

In this case I have two columns where I am forcing the widht of first to 15% of total.

You can also use this approach to apply more style of your generated table.

Body:
Also you can use the public propetry template to achieve this. For example:

<?= DetailView::widget([
   'model' => ...,
   'attributes' => [[...], [...]],
   'template' => "<tr><th style='width: 15%;'>{label}</th><td>{value}.</td></tr>"
]) ?>

In this case I have two columns where I am forcing the widht of first to 15% of total.

You can also use this approach to apply more style of your generated table.


问:
Regex match chars not between 2 specific chars or words
i'm trying to make this regex work but i only had an half-success.

So far i could make this work:

match every ';' that is not between '[]'

with this regex: ;(?![^\[]*\])

But now comes my problem... i should also add this limitation:

match every ';' that is not between '[' and ']' or 'XXX' and 'ZZZ'

So for example in this text:

```<code>aaa **;** bbb **;** [ ccc *;* ddd ] eee **;** XXX qweasd *;* qwesad ZZZ
</code>```

the third and last ';' should not match

答:
If (*SKIP)(*FAIL) is an option (PHP, PyPi Regex the like), you might get along with

```<code>(?:\[[^][]+\]|XXX.+?ZZZ)(*SKIP)(*FAIL)|;
</code>```

See a demo on regex101.com.

Explanation:

```<code>(?:             # non-capturing parenthesis
    \[[^][]+\]  # anything between [ and ]
    |           # or
    XXX.+?ZZZ   # XXX ... ZZZ
)(*SKIP)(*FAIL) # all of this should be skipped
|               # ... or ...
;               # match a ;
</code>```

Body:
i'm trying to make this regex work but i only had an half-success.

So far i could make this work:

match every ';' that is not between '[]'

with this regex: ;(?![^\[]*\])

But now comes my problem... i should also add this limitation:

match every ';' that is not between '[' and ']' or 'XXX' and 'ZZZ'

So for example in this text:

aaa **;** bbb **;** [ ccc *;* ddd ] eee **;** XXX qweasd *;* qwesad ZZZ

the third and last ';' should not match

Body:
If (*SKIP)(*FAIL) is an option (PHP, PyPi Regex the like), you might get along with

(?:\[[^][]+\]|XXX.+?ZZZ)(*SKIP)(*FAIL)|;

See a demo on regex101.com.

Explanation:

(?:             # non-capturing parenthesis
    \[[^][]+\]  # anything between [ and ]
    |           # or
    XXX.+?ZZZ   # XXX ... ZZZ
)(*SKIP)(*FAIL) # all of this should be skipped
|               # ... or ...
;               # match a ;


问:
Is there a way I can pass a variable in PHP on buttonclick?
I'm having a problem with passing a variable to a PHP function. So what I'm doing in html or actually PHP but I make a part of my HTML code with PHP is this:

```<code><form action=\"\" method=\"post\">
    <textarea name=\"textarea\" rows=\"8\" cols=\"40\"></textarea>
    <button type=\"button\" class=\"button\" name=\"enterText\" value=\"".$row['Wagon_ID']."\">
        Enter
    </button>
</form>
</code>```

Now this takes place in a while loop as long as there are more Wagon_ID's in the row array.
What I want to do concretely is call a function on this button click but I must be able to pass along the Wagon_ID.
I can do this easily by using the <input type="submit"...and make the value the Wagon_ID but my problem with this is because the value is the Wagon_ID, that the text on the button will also become the Wagon_ID and the text needs to remain enter.
So what I tried is using the button type and setting the value to the Wagon_ID, but now the PHP function isn't even called.
Does anyone know a trick so I can use this type of button, or to maintain my "Enter" text on the type of button I previously used ?
Thanks in advance!

This is how I call the buttonclick in PHP:

```<code>if (isset($_POST['enterText']))
    {
        $text= $_POST['textarea'];
        $wagon=$_POST['enterText'];
        mysqli_query($_SESSION['conn'], "INSERT INTO description (Wagon_ID, textdescription) VALUES ('$wagon','$text')");
    }
</code>```

答:
I think the key part of your question is here:

I can do this easily by using the <input type="submit "...and make the
  value the Wagon_ID but my problem with this is because the value is
  the Wagon_ID, that the text on the button will also become the
  Wagon_ID and the text needs to remain enter.

This situation is what hidden fields are for. Don't wrap actual form data in a UI element like a button. Try it like this:

```<code>echo '<form action="" method="post">
    <textarea name="textarea" rows="8" cols="40"></textarea>
    <input type="hidden" name="wagonID" value="'.$row['Wagon_ID'].'"/>
    <input type="submit" class="button" name="enterText" value="Enter text" />
</form>';
</code>```

And in the PHP change

```<code>$wagon=$_POST['enterText'];
</code>```

to

```<code>$wagon = $_POST['wagonID'];
</code>```

Documentation on hidden fields: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden

P.S. As you can see, you can get rid of all the messy escaping of double-quotes by echoing the string from PHP inside single quotes, and it's much more readable and less error-prone.

P.P.S.

Warning: Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.

https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped input values.

Body:
I'm having a problem with passing a variable to a PHP function. So what I'm doing in html or actually PHP but I make a part of my HTML code with PHP is this:

<form action=\"\" method=\"post\">
    <textarea name=\"textarea\" rows=\"8\" cols=\"40\"></textarea>
    <button type=\"button\" class=\"button\" name=\"enterText\" value=\"".$row['Wagon_ID']."\">
        Enter
    </button>
</form>

Now this takes place in a while loop as long as there are more Wagon_ID's in the row array.
What I want to do concretely is call a function on this button click but I must be able to pass along the Wagon_ID.
I can do this easily by using the <input type="submit"...and make the value the Wagon_ID but my problem with this is because the value is the Wagon_ID, that the text on the button will also become the Wagon_ID and the text needs to remain enter.
So what I tried is using the button type and setting the value to the Wagon_ID, but now the PHP function isn't even called.
Does anyone know a trick so I can use this type of button, or to maintain my "Enter" text on the type of button I previously used ?
Thanks in advance!

This is how I call the buttonclick in PHP:

if (isset($_POST['enterText']))
    {
        $text= $_POST['textarea'];
        $wagon=$_POST['enterText'];
        mysqli_query($_SESSION['conn'], "INSERT INTO description (Wagon_ID, textdescription) VALUES ('$wagon','$text')");
    }

Body:
I think the key part of your question is here:

I can do this easily by using the <input type="submit "...and make the
  value the Wagon_ID but my problem with this is because the value is
  the Wagon_ID, that the text on the button will also become the
  Wagon_ID and the text needs to remain enter.

This situation is what hidden fields are for. Don't wrap actual form data in a UI element like a button. Try it like this:

echo '<form action="" method="post">
    <textarea name="textarea" rows="8" cols="40"></textarea>
    <input type="hidden" name="wagonID" value="'.$row['Wagon_ID'].'"/>
    <input type="submit" class="button" name="enterText" value="Enter text" />
</form>';

And in the PHP change

$wagon=$_POST['enterText'];

to

$wagon = $_POST['wagonID'];

Documentation on hidden fields: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden

P.S. As you can see, you can get rid of all the messy escaping of double-quotes by echoing the string from PHP inside single quotes, and it's much more readable and less error-prone.

P.P.S.

Warning: Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.

https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped input values.


问:
R function that counts rows where conditions are met
I am trying to create a new column that counts each column where criteria are met. That is because I want to summarize the number of correct answers by each participant in my master thesis. I am really new to R and in desperate need for help, even on easy tasks.

For Example:

(Participant,    Task1,     Task2,     Task3;   COUNT)

1                  4         8         1    ;   1|

2                  3         8         7    ;   1|

3                  1         3         4    ;   2|

4                  5         6         4    ;   1|

5                  1         8         4    ;   3

The column COUNT should count all correct answers of the rows Task1-Task3. If the correct answers are (1, 8, 4), the COUNT row should result in the numbers shown in the example above.

Can anybody tell me how to create such a variable?

Really appreciated, thanks
Luca

答:
We can use pmap_int from purrr to count number of correct answers.

```<code>library(dplyr)

df %>% mutate(COUNT = purrr::pmap_int(select(., starts_with('Task')),
                               ~sum(c(...) == c(1, 8, 4))))

#  Participant Task1 Task2 Task3 COUNT
#1           1     4     8     1     1
#2           2     3     8     7     1
#3           3     1     3     4     2
#4           4     5     6     4     1
#5           5     1     8     4     3
</code>```

Another option is to get data in long format, calculate the number of correct answers for each Participant and join the data back.

```<code>df1 %>%
  tidyr::pivot_longer(cols = starts_with('Task')) %>%
  group_by(Participant) %>%
  summarise(COUNT = sum(value == c(1, 8, 4))) %>%
  left_join(df1, by = 'Participant')
</code>```

Body:
We can use pmap_int from purrr to count number of correct answers.

library(dplyr)

df %>% mutate(COUNT = purrr::pmap_int(select(., starts_with('Task')),
                               ~sum(c(...) == c(1, 8, 4))))

#  Participant Task1 Task2 Task3 COUNT
#1           1     4     8     1     1
#2           2     3     8     7     1
#3           3     1     3     4     2
#4           4     5     6     4     1
#5           5     1     8     4     3

Another option is to get data in long format, calculate the number of correct answers for each Participant and join the data back.

df1 %>%
  tidyr::pivot_longer(cols = starts_with('Task')) %>%
  group_by(Participant) %>%
  summarise(COUNT = sum(value == c(1, 8, 4))) %>%
  left_join(df1, by = 'Participant')


问:
Diagnosing ASP.NET Azure WebApp issue
since a month one of our web application hosted as WebApp on Azure is having some kind of problem and I cannot find the root cause of that.
This WebApp is hosted on Azure on a 2 x B2 App Service Plan. On the same App Service Plan there is another WebApp that is currently working without any issue.

This WebApp is an ASP.NET WebApi application and exposes a REST set of API.

Effect: without any apparent sense (at least for what I know by now), the ThreadCount metric starts to spin up, sometimes very slowly, sometimes in few minutes. What happens is that no requests seems to be served and the service is dead.

Solution: a simple restart of the application (an this means a restart of the AppPool) causes an immediate obvious drop of the ThreadCount and everything starts as usual.

Other observations: there is no "periodicity" in this event. It happened in the evening, in the morning and in the afternoon. It seems that evening is a preferred timeframe, but I won't say there is any correlation.

What I measured through Azure Monitoring Metric:
- Request Count seems to oscillate normally. There is no peak that causes that increase in ThreadCount
- CPU and Memory seems to be normal, nothing strange.
- Response time, like the others metrics
- Connections (that should be related to sockets) oscillates normally. So I'd exclude something related to DB connections.

What may I do in order to understand what's going on?

答:
After a lot of research, this happened to be related to a wrong usage of Dependency Injection (using Ninject) and an application that wasn't designed to use it.

In order to diagnose, I discovered a very helpful feature in Azure. You can reach it by entering into the app that is having the problem, click on "Diagnose and solve problems" then click on "Diagnostic tools" and then select "Collect .NET profiler report". In that panel, after configuring the storage for the diagnostic files, you can select "Add thread report".
In those report you can easily understand what's going wrong.

Hope this helps.

Title: Diagnosing ASP.NET Azure WebApp issue


问:
In a .NET console app, is it possible to have a line of text stay visible in the console all the time?
I was thinking of adding a simple bandwidth monitor to a console application and I was wondering if it would be possible to keep a line in the console window visible at all times. I could set something up manually to pass new console output into a method that would get the contents of the console, clear the console, add the bandwidth data on the first row, then rewrite each line of previous information back to the console, etc.. but that seems like a really hacky way to go about it, and I'd be limited to the amount of rows visible at once in the console window (no scrolling).

Any idea?  Any built in functionality for this?   Example:

```<code>STATS: Downloaded: 2599b, Uploaded: 754b  <- this always stays at the top
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
</code>```

答:
You can use the other members of the Console class, such as CursorTop and CursorLeft to "move around" the cursor.  If you move the cursor to the beginning of a line, and then use Console.Write, it will "overwrite" the data at that location.

This lets you create situations like you're describing (by moving the cursor, writing, then moving back).

That being said, I typically would recommend using a GUI application as soon as you need to have multiple items being presented in a specific manner.  You'll have much more flexibility (and it will likely be simpler).

Body:
I was thinking of adding a simple bandwidth monitor to a console application and I was wondering if it would be possible to keep a line in the console window visible at all times. I could set something up manually to pass new console output into a method that would get the contents of the console, clear the console, add the bandwidth data on the first row, then rewrite each line of previous information back to the console, etc.. but that seems like a really hacky way to go about it, and I'd be limited to the amount of rows visible at once in the console window (no scrolling).

Any idea?  Any built in functionality for this?   Example:

STATS: Downloaded: 2599b, Uploaded: 754b  <- this always stays at the top
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text


问:
tensorflow 2 install on mac by conda
Hi i'm trying to install tensorflow but getting package conflicts due to existing packages as numpy for example

Thanks for your help

This is part of the error massage:

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Output in format: Requested package -> Available versions

```<code>Package numpy conflicts for:
tensorflow-base -> keras-applications[version='>=1.0.8'] -> numpy[version='>=1.13.3|>=1.9.1']
tensorflow-estimator -> numpy[version='>=1.13.3']
tensorflow-estimator -> tensorflow-base[version='>=2.0.0,<2.1.0a0'] -> numpy[version='>=1.14.6,<2.0a0|>=1.16.5,<2.0a0']
tensorflow-hub -> numpy[version='>=1.12.0']
tensorflow-datasets -> numpy
tensorflow -> tensorboard[version='>=2.0.0'] -> numpy[version='>=1.12|>=1.12.0|>=1.16|>=1.16.5,<2.0a0|>=1.14.6,<2.0a0|>=1.13.3,<2.0a0']
tensorflow-probability -> numpy[version='>=1.13.3']
tensorflow-probability -> tensorflow-base[version='>=1.15.0'] -> numpy[version='>=1.14.6,<2.0a0|>=1.16.5,<2.0a0']
keras -> numpy[version='>=1.9.1']
keras -> h5py -> numpy[version='>=1.11.3,<2.0a0|>=1.16.6,<2.0a0|>=1.14.6,<2.0a0|>=1.15.1,<2.0a0|>=1.9.3,<2.0a0']
keras-gpu -> keras-base=2.3.1 -> numpy[version='>=1.9.1']
tensorflow-base -> numpy[version='>=1.13.3,<2.0a0|>=1.14.6,<2.0a0|>=1.16.5,<2.0a0']

Package tensorflow conflicts for:
tensorflow-probability -> tensorflow[version='>=1.14.0']
tensorflow
tensorflow-eigen -> tensorflow[version='1.10.0|1.11.0|1.12.0|1.13.1|1.15.0|2.0.0|1.9.0']
keras -> tensorflow[version='<2.0']
tensorflow-datasets -> tensorflow[version='>=1.14']
tensorflow-mkl -> tensorflow[version='1.11.0|1.12.0|1.13.1|1.15.0|2.0.0|1.9.0']
tensorflow-hub -> tensorflow[version='>=1.14.0|>=1.7.0']
tensorflow-datasets -> tensorflow-metadata -> tensorflow
tensorflow-metadata -> tensorflow
</code>```

答:
Conda is designed to prevent these kinds of conflicts by creating separate, self-contained Python environments for different projects. Run these commands in your Terminal app:

```<code>conda create -n tf-env # create new environment named tf-env
conda activate tf-env
pip install --upgrade pip # upgrade to latest version of pip
pip install tensorflow
</code>```

That will install all of the packages you need, with the versions required by TensorFlow.

When you're done working in TensorFlow and want to go back to your normal Python environment, run conda deactivate. To return to the TensorFlow environment, run conda activate tf-env again.

Title: tensorflow 2 install on mac by conda

Body:
Hi i'm trying to install tensorflow but getting package conflicts due to existing packages as numpy for example

Thanks for your help

This is part of the error massage:

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Output in format: Requested package -> Available versions

Package numpy conflicts for:
tensorflow-base -> keras-applications[version='>=1.0.8'] -> numpy[version='>=1.13.3|>=1.9.1']
tensorflow-estimator -> numpy[version='>=1.13.3']
tensorflow-estimator -> tensorflow-base[version='>=2.0.0,<2.1.0a0'] -> numpy[version='>=1.14.6,<2.0a0|>=1.16.5,<2.0a0']
tensorflow-hub -> numpy[version='>=1.12.0']
tensorflow-datasets -> numpy
tensorflow -> tensorboard[version='>=2.0.0'] -> numpy[version='>=1.12|>=1.12.0|>=1.16|>=1.16.5,<2.0a0|>=1.14.6,<2.0a0|>=1.13.3,<2.0a0']
tensorflow-probability -> numpy[version='>=1.13.3']
tensorflow-probability -> tensorflow-base[version='>=1.15.0'] -> numpy[version='>=1.14.6,<2.0a0|>=1.16.5,<2.0a0']
keras -> numpy[version='>=1.9.1']
keras -> h5py -> numpy[version='>=1.11.3,<2.0a0|>=1.16.6,<2.0a0|>=1.14.6,<2.0a0|>=1.15.1,<2.0a0|>=1.9.3,<2.0a0']
keras-gpu -> keras-base=2.3.1 -> numpy[version='>=1.9.1']
tensorflow-base -> numpy[version='>=1.13.3,<2.0a0|>=1.14.6,<2.0a0|>=1.16.5,<2.0a0']

Package tensorflow conflicts for:
tensorflow-probability -> tensorflow[version='>=1.14.0']
tensorflow
tensorflow-eigen -> tensorflow[version='1.10.0|1.11.0|1.12.0|1.13.1|1.15.0|2.0.0|1.9.0']
keras -> tensorflow[version='<2.0']
tensorflow-datasets -> tensorflow[version='>=1.14']
tensorflow-mkl -> tensorflow[version='1.11.0|1.12.0|1.13.1|1.15.0|2.0.0|1.9.0']
tensorflow-hub -> tensorflow[version='>=1.14.0|>=1.7.0']
tensorflow-datasets -> tensorflow-metadata -> tensorflow
tensorflow-metadata -> tensorflow

Body:
Conda is designed to prevent these kinds of conflicts by creating separate, self-contained Python environments for different projects. Run these commands in your Terminal app:

conda create -n tf-env # create new environment named tf-env
conda activate tf-env
pip install --upgrade pip # upgrade to latest version of pip
pip install tensorflow

That will install all of the packages you need, with the versions required by TensorFlow.

When you're done working in TensorFlow and want to go back to your normal Python environment, run conda deactivate. To return to the TensorFlow environment, run conda activate tf-env again.


问:
Flask POST request form data without refreshing page
I am building a small web application that allows the user to enter a transaction through a couple form input fields (such as date, transaction amount, description, etc.). Each time the user clicks a "submit" button a new table row will be created with one column for each input field. In addition to building this table, I want the input data to be sent to my Flask app.

The problem I have is that when the user clicks "submit", the page refreshes and all the table rows are gone. The solution I tried for this is to just have a <button type="button"></button> tag with an id, and when the user clicks it my Javascript code adds a table row without refreshing the page. However, this doesn't work because it doesn't send the data to my Flask app. I also tried using sessionStorage.setItem in Javascript but I don't know how to make that work with my specific code, as the user could click the button 3 times for 3 different transactions and each time the page would refresh.

So my question is, how can I create and display the table rows on the page while ALSO sending the form input data to my Flask app?

For simplification, I have only included 2 input fields here, but there are 8.

HTML:

```<code><form method="POST">
  <div class="list-group-item">
    <label>Date</label>
    <input class="form-control" id="datepicker" type="text" name=expDate value="">
  </div>
  <div class="list-group-item">
    <label>Amount Withdrawn</label>
    <input class="form-control" id="withAmount" type="text" name=expAmountWith value="">
  </div>
  <button id="submit-btn" type="submit" class="btn btn-light submit-btn">Submit</button>
</form>
</code>```

Javascript:

```<code>d3.selectAll('#submit-btn').on('click', buildTable);

function buildTable() {
    var dateInput = d3.select('#datepicker').property('value');
    var withAmount = d3.select('#withAmount').property('value');

    var tableArray = []
    tableArray.push(dateInput, withAmount)

    var row = d3.select('tbody').append('tr');

    tableArray.forEach(function(x) {

        var cell = row.append('td');
        cell.text(x);
    });

};
</code>```

Python:

```<code>app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def record_transaction():

    form = request.form

    if request.method == 'POST':
        expDate = request.form['expDate']
        expAmountWith = request.form['expAmountWith']

    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

答:
You can start by getting the form element in your JavaScript code, by assigning an id and using getElementById, or in a way more consistent with the rest of your code (seeing as you are using jQuery, but I prefer vanilla JS). Then, instead of using <button type="button">, you can attach the event listener to the form's submit event, then preventDefault so the page doesn't refresh, and send the data to your backend inside the callback. Here is an example:

form.addEventListener('submit', function(event) {
    event.preventDefault();    // prevent page from refreshing
    const formData = new FormData(form);  // grab the data inside the form fields
    fetch('/', {   // assuming the backend is hosted on the same server
        method: 'POST',
        body: formData,
    }).then(function(response) {
        // do something with the response if needed.
        // If you want the table to be built only after the backend handles the request and replies, call buildTable() here.
    });
});
```

And I suggest using the same formData object in your buildTable() function so that you don't have to assign an ID to each element and retrieve the value that way, but instead use formData.get(name).

Also, change your Python function to return something at the end of the if request.method == 'POST' branch so it doesn't return the HTML to the AJAX request. Perhaps a "204 - No content" is appriopriate in your simple case.

I trust you know how to replace the plain JS here with jQuery

Body:
I am building a small web application that allows the user to enter a transaction through a couple form input fields (such as date, transaction amount, description, etc.). Each time the user clicks a "submit" button a new table row will be created with one column for each input field. In addition to building this table, I want the input data to be sent to my Flask app.

The problem I have is that when the user clicks "submit", the page refreshes and all the table rows are gone. The solution I tried for this is to just have a <button type="button"></button> tag with an id, and when the user clicks it my Javascript code adds a table row without refreshing the page. However, this doesn't work because it doesn't send the data to my Flask app. I also tried using sessionStorage.setItem in Javascript but I don't know how to make that work with my specific code, as the user could click the button 3 times for 3 different transactions and each time the page would refresh.

So my question is, how can I create and display the table rows on the page while ALSO sending the form input data to my Flask app?

For simplification, I have only included 2 input fields here, but there are 8.

HTML:

<form method="POST">

    Date
    <input class="form-control" id="datepicker" type="text" name=expDate value="">

    Amount Withdrawn
    <input class="form-control" id="withAmount" type="text" name=expAmountWith value="">

  <button id="submit-btn" type="submit" class="btn btn-light submit-btn">Submit</button>
</form>

Javascript:

d3.selectAll('#submit-btn').on('click', buildTable);

function buildTable() {
    var dateInput = d3.select('#datepicker').property('value');
    var withAmount = d3.select('#withAmount').property('value');

    var tableArray = []
    tableArray.push(dateInput, withAmount)

    var row = d3.select('tbody').append('tr');

    tableArray.forEach(function(x) {

        var cell = row.append('td');
        cell.text(x);
    });

};

Python:

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def record_transaction():

    form = request.form

    if request.method == 'POST':
        expDate = request.form['expDate']
        expAmountWith = request.form['expAmountWith']

    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

Body:
You can start by getting the form element in your JavaScript code, by assigning an id and using getElementById, or in a way more consistent with the rest of your code (seeing as you are using jQuery, but I prefer vanilla JS). Then, instead of using <button type="button">, you can attach the event listener to the form's submit event, then preventDefault so the page doesn't refresh, and send the data to your backend inside the callback. Here is an example:

form.addEventListener('submit', function(event) {
    event.preventDefault();    // prevent page from refreshing
    const formData = new FormData(form);  // grab the data inside the form fields
    fetch('/', {   // assuming the backend is hosted on the same server
        method: 'POST',
        body: formData,
    }).then(function(response) {
        // do something with the response if needed.
        // If you want the table to be built only after the backend handles the request and replies, call buildTable() here.
    });
});

And I suggest using the same formData object in your buildTable() function so that you don't have to assign an ID to each element and retrieve the value that way, but instead use formData.get(name).

Also, change your Python function to return something at the end of the if request.method == 'POST' branch so it doesn't return the HTML to the AJAX request. Perhaps a "204 - No content" is appriopriate in your simple case.

I trust you know how to replace the plain JS here with jQuery


问:
How to use usestate and setstate instead of this.setState using react and typescript?
i want to implement a DragAndDrop component using react and typescript and i am new to using react redux.

Below is how the DragAndDrop component looks like,

```<code>class DragAndDrop extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dragging: false,
        };
    }

    componentDidMount() {
        this.drag_counter = 0;
        this.enable_drag_event_listeners();
    }

    componentWillUnmount() {
        this.disable_drag_event_listeners();
    }

    enable_drag_event_listeners = () => {
        document.addEventListener('dragenter', this.handle_drag_in);
        document.addEventListener('dragleave', this.handle_drag_out);
        document.addEventListener('dragover', this.handle_drag);
        document.addEventListener('drop', this.handle_drop);
    }

    disable_drag_event_listeners = () => {
        document.removeEventListener('dragenter', this.handle_drag_in);
        document.removeEventListener('dragleave', this.handle_drag_out);
        document.removeEventListener('dragover', this.handle_drag);
        document.removeEventListener('drop', this.handle_drop);
    }

    handle_drag = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
        }
    }

    handle_drag_in = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter++;
            if (e.dataTransfer.files) {
                this.setState({dragging: true});
            }
        }
    }

    handle_drag_out = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter--;
            if (this.drag_counter === 0) {
                this.setState({dragging: false});
            }
        }
    }

    handle_drop = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.setState({dragging: false});
            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                this.props.handle_drop(e);
                e.dataTransfer.clearData();
                this.drag_counter = 0;
            }
        }
    }

    render() {
        return (
            <div>
                {this.state.dragging &&
                    <div>
                        <div className="drop_zone">
                            <div className="drop_zone_overlay"/>
                            <div className="drop_zone_text">
                            <div>Drop your files here</div>
                        </div>
                    </div>
                }
                {this.props.children}
            </div>
        )
    }
}
</code>```

As you see from above code, i have used this.state and this.setState, componentdidmount, componentdidupdate and componentwillunmount.

I want to use react redux usestate, setstate and other things.

How can i change the above code to use usestate and setstate and how do i implement the componentdidmount, componentdidupdate, componentwillunmount hooks.

what i have tried?

```<code>function DragAndDrop() {
    const [isdragging, setIsDragging] = React.useState(false);
    handle_drag = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
        }
    }

    handle_drag_in = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter++; //how do i set this with react redux and also this is not a class

            if (e.dataTransfer.files) {
                setIsDragging(true);
            }
        }
    }

    handle_drag_out = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter--; // how to keep track of this counter
            if (this.drag_counter === 0) {
                setIsDragging(false);
            }
        }
    }

    handle_drop = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            setIsDragging(false);
            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                this.props.handle_drop(e);
                e.dataTransfer.clearData();
                this.drag_counter = 0; //how to keep track of this
            }
        }
    }

    render() {
        return (
            <div>
                {isdragging &&
                    <div>
                        <div className="drop_zone">
                            <div className="drop_zone_overlay"/>
                            <div className="drop_zone_text">
                                <div>Drop files here</div>
                            </div>
                        </div>
                    </div>
                }
                {this.props.children}
            </div>
        )
    }
}
</code>```

Could someone help me with this. thanks. how to consider componentdidmount, componentdidupdate,componentwillunmount in react redux.

thanks.

答:
```<code>
const DragAndDrop: React.FC<any> = (props) => {
  const [dragging, setDragging] = React.useState(false);
  const [drag_counter, setDrag_counter] = React.useState(0);
  React.useEffect(() => {
    // componentDidMount()
    setDrag_counter(0);
    enable_drag_event_listeners();
    return () => {
      // componentWillUnmount()
      disable_drag_event_listeners();
    }
  }, []);

  function enable_drag_event_listeners() {
    document.addEventListener('dragenter', handle_drag_in);
    document.addEventListener('dragleave', handle_drag_out);
    document.addEventListener('dragover', handle_drag);
    document.addEventListener('drop', handle_drop);
  }

  function disable_drag_event_listeners() {
    document.removeEventListener('dragenter', handle_drag_in);
    document.removeEventListener('dragleave', handle_drag_out);
    document.removeEventListener('dragover', handle_drag);
    document.removeEventListener('drop', handle_drop);
  }

  function handle_drag(e) {
    if (!props.loading) {
      e.preventDefault();
      e.stopPropagation();
    }
  }

  function handle_drag_in(e) {
    if (!props.loading) {
      e.preventDefault();
      e.stopPropagation();
      setDrag_counter((prev)=>prev+1);
      if (e.dataTransfer.files) {
        setDragging(true);
      }
    }
  }

  function handle_drag_out(e) {
    if (!props.loading) {
      e.preventDefault();
      e.stopPropagation();
      setDrag_counter((prev)=>prev-1);
      if (drag_counter === 0) {
        setDragging(false);
      }
    }
  }

  function handle_drop(e) {
    if (!props.loading) {
      e.preventDefault();
      e.stopPropagation();
      setDragging(false);
      if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
        props.handle_drop(e);
        e.dataTransfer.clearData();
        setDrag_counter(0);
      }
    }
  }
  return (
    <div>
    {dragging &&
      <div>
      <div className = "drop_zone" >
        <div className = "drop_zone_overlay" / >
        <div className = "drop_zone_text" >
          <div> Drop your files here </div>
        </div>
      </div>
    }
    {
      props.children
    }
    </div>
  )

}
</code>```

Body:
i want to implement a DragAndDrop component using react and typescript and i am new to using react redux.

Below is how the DragAndDrop component looks like,

class DragAndDrop extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dragging: false,
        };
    }

    componentDidMount() {
        this.drag_counter = 0;
        this.enable_drag_event_listeners();
    }

    componentWillUnmount() {
        this.disable_drag_event_listeners();
    }

    enable_drag_event_listeners = () => {
        document.addEventListener('dragenter', this.handle_drag_in);
        document.addEventListener('dragleave', this.handle_drag_out);
        document.addEventListener('dragover', this.handle_drag);
        document.addEventListener('drop', this.handle_drop);
    }

    disable_drag_event_listeners = () => {
        document.removeEventListener('dragenter', this.handle_drag_in);
        document.removeEventListener('dragleave', this.handle_drag_out);
        document.removeEventListener('dragover', this.handle_drag);
        document.removeEventListener('drop', this.handle_drop);
    }

    handle_drag = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
        }
    }

    handle_drag_in = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter++;
            if (e.dataTransfer.files) {
                this.setState({dragging: true});
            }
        }
    }

    handle_drag_out = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter--;
            if (this.drag_counter === 0) {
                this.setState({dragging: false});
            }
        }
    }

    handle_drop = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.setState({dragging: false});
            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                this.props.handle_drop(e);
                e.dataTransfer.clearData();
                this.drag_counter = 0;
            }
        }
    }

    render() {
        return (

                {this.state.dragging &&

Drop your files here

                }
                {this.props.children}

        )
    }
}

As you see from above code, i have used this.state and this.setState, componentdidmount, componentdidupdate and componentwillunmount.

I want to use react redux usestate, setstate and other things.

How can i change the above code to use usestate and setstate and how do i implement the componentdidmount, componentdidupdate, componentwillunmount hooks.

what i have tried?

function DragAndDrop() {
    const [isdragging, setIsDragging] = React.useState(false);
    handle_drag = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
        }
    }

    handle_drag_in = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter++; //how do i set this with react redux and also this is not a class

            if (e.dataTransfer.files) {
                setIsDragging(true);
            }
        }
    }

    handle_drag_out = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            this.drag_counter--; // how to keep track of this counter
            if (this.drag_counter === 0) {
                setIsDragging(false);
            }
        }
    }

    handle_drop = (e) => {
        if (!this.props.loading) {
            e.preventDefault();
            e.stopPropagation();
            setIsDragging(false);
            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                this.props.handle_drop(e);
                e.dataTransfer.clearData();
                this.drag_counter = 0; //how to keep track of this
            }
        }
    }

    render() {
        return (

                {isdragging &&

Drop files here

                }
                {this.props.children}

        )
    }
}

Could someone help me with this. thanks. how to consider componentdidmount, componentdidupdate,componentwillunmount in react redux.

thanks.


问:
Noob Question How would I update a print a function's output without creating a new line in my term in python3?
I'm not exactly sure how to word this to be honest, but here's a simplified version of my current code.

```<code>for idx in range(0,11):
    print('Failed:',idx)
</code>```

This outputs:

```<code>Failed: 0
Failed: 1
Failed: 2
Failed: 3
Failed: 4
Failed: 5
Failed: 6
Failed: 7
Failed: 8
Failed: 9
Failed: 10
</code>```

I'm trying to replace the original int with the next int in the range instead of spamming my terminal with a new line for every int in the range.

How could I update "Failed: 1" to "Failed: 2" without creating a new line for "Failed: 2"?

Sorry if this is poorly worded, if you're willing to help me but like me to elaborate further please say so and I will try my best.

答:
There is a second parameter that the function print takes to to specify what should print do at the end of line</p>

```<code>print("Text here", end="")
</code>```

Body:
I'm not exactly sure how to word this to be honest, but here's a simplified version of my current code.

for idx in range(0,11):
    print('Failed:',idx)

This outputs:

Failed: 0
Failed: 1
Failed: 2
Failed: 3
Failed: 4
Failed: 5
Failed: 6
Failed: 7
Failed: 8
Failed: 9
Failed: 10

I'm trying to replace the original int with the next int in the range instead of spamming my terminal with a new line for every int in the range.

How could I update "Failed: 1" to "Failed: 2" without creating a new line for "Failed: 2"?

Sorry if this is poorly worded, if you're willing to help me but like me to elaborate further please say so and I will try my best.

Body:
There is a second parameter that the function print takes to to specify what should print do at the end of line

print("Text here", end="")


问:
how to Progress bar show before image load.?
I want to show a progress bar before image loading. I am getting an image from firebase storage. some time image taking more time to load and show .. ... That's why I am trying to input progressbar before load image..... I have tried but now working. Can anyone help me to solve this issue????

Please check my code below:-

```<code>  public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

        public Context mContext;
        private List <Post>mPost;
        private FirebaseUser firebaseUser;
        ProgressBar progressBar;

        public PostAdapter(Context mContext, List<Post> mPost) {
            this.mContext = mContext;
            this.mPost = mPost;
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);

            return new PostAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {

            firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
            final Post post=mPost.get(position);

            try {
                Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(holder.post_image);

            }catch (Exception e)
            {

            }

            //holder.time.setText(post.getTime());
            Get_Time_ago getTimeAgo=new Get_Time_ago();

            long lastTime=Long.parseLong(String.valueOf(post.timestamp));
            String last_seen_time=getTimeAgo.getTimeAgo(lastTime,mContext);
           holder. time.setText(last_seen_time);
                       /*SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                       String time=sfd.format(new Date(lastseenonline));
                       mLast_seenview.setText(time);*/

            if(post.getDescription().equals("")){
                holder.description.setVisibility(View.GONE);

            }else {
                holder.description.setVisibility(View.VISIBLE);
                holder.description.setText(post.getDescription());

            }

            publisherInfo(holder.image_profile,holder.username,holder.blood,holder.publisher,post.getPublisher());

            if(post.getPublisher().equals(firebaseUser.getUid())){
                holder.delete.setVisibility(View.VISIBLE);

            }else {
                holder.delete.setVisibility(View.GONE);

            }

            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                        alertDialog.setTitle("Confirm Delete?");
                        alertDialog.setMessage("Do you want to delete your post?");
                        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
                                notify();

                            }
                        });
                        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        alertDialog.show();
                    }

            });

        }

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

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView image_profile,post_image,like,dislike,comment,save,delete;
            public TextView username,blood,likes,dislikes,comments, description,publisher,time;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                image_profile=itemView.findViewById(R.id.image_profile);
                post_image=itemView.findViewById(R.id.post_image);
                like=itemView.findViewById(R.id.like);
                comment=itemView.findViewById(R.id.comment);
                save=itemView.findViewById(R.id.save);
                delete=itemView.findViewById(R.id.delete);

                username=itemView.findViewById(R.id.username);
                blood=itemView.findViewById(R.id.blood);
                time=itemView.findViewById(R.id.time);

                likes=itemView.findViewById(R.id.likes);
                dislikes=itemView.findViewById(R.id.dislikes);
                dislike=itemView.findViewById(R.id.dislike);
                comments=itemView.findViewById(R.id.comments);
                description=itemView.findViewById(R.id.description);
                publisher=itemView.findViewById(R.id.publisher);
                progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);

            }
        }

        private void publisherInfo (final ImageView image_profile, final TextView username,final  TextView blood, final TextView publisher, final String userId ){
            DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    try {
                        User user=dataSnapshot.getValue(User.class);
                        Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(image_profile);

                        username.setText(user.getUsername());
                        blood.setText(user.getBlood());

                        publisher.setText(user.getUsername());

                    }catch (Exception e){

                    }

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }

    }
</code>```

答:
Like this in Java:    </p>

```<code>private void loadImage(ImageView yourImageView, String imageUri) {
    CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(yourImageView.getContext())
    circularProgressDrawable.setStrokeWidth(5f)
    circularProgressDrawable.setCenterRadius(30f)
    circularProgressDrawable.start()

    Glide.with(yourImageView.getContext())
        .load(imageUri)
        .placeholder(circularProgressDrawable)
        .error(R.drawable.ic_close_black)
        .override(200, 300)
        .into(yourImageView);
}
</code>```

Body:
I want to show a progress bar before image loading. I am getting an image from firebase storage. some time image taking more time to load and show .. ... That's why I am trying to input progressbar before load image..... I have tried but now working. Can anyone help me to solve this issue????

Please check my code below:-

  public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

        public Context mContext;
        private List <Post>mPost;
        private FirebaseUser firebaseUser;
        ProgressBar progressBar;

        public PostAdapter(Context mContext, List<Post> mPost) {
            this.mContext = mContext;
            this.mPost = mPost;
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);

            return new PostAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {

            firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
            final Post post=mPost.get(position);

            try {
                Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(holder.post_image);

            }catch (Exception e)
            {

            }

            //holder.time.setText(post.getTime());
            Get_Time_ago getTimeAgo=new Get_Time_ago();

            long lastTime=Long.parseLong(String.valueOf(post.timestamp));
            String last_seen_time=getTimeAgo.getTimeAgo(lastTime,mContext);
           holder. time.setText(last_seen_time);
                       /*SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                       String time=sfd.format(new Date(lastseenonline));
                       mLast_seenview.setText(time);*/

            if(post.getDescription().equals("")){
                holder.description.setVisibility(View.GONE);

            }else {
                holder.description.setVisibility(View.VISIBLE);
                holder.description.setText(post.getDescription());

            }

            publisherInfo(holder.image_profile,holder.username,holder.blood,holder.publisher,post.getPublisher());

            if(post.getPublisher().equals(firebaseUser.getUid())){
                holder.delete.setVisibility(View.VISIBLE);

            }else {
                holder.delete.setVisibility(View.GONE);

            }

            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                        alertDialog.setTitle("Confirm Delete?");
                        alertDialog.setMessage("Do you want to delete your post?");
                        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                FirebaseDatabase.getInstance().getReference("posts").child(post.getPostid()).removeValue();
                                notify();

                            }
                        });
                        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        alertDialog.show();
                    }

            });

        }

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

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView image_profile,post_image,like,dislike,comment,save,delete;
            public TextView username,blood,likes,dislikes,comments, description,publisher,time;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                image_profile=itemView.findViewById(R.id.image_profile);
                post_image=itemView.findViewById(R.id.post_image);
                like=itemView.findViewById(R.id.like);
                comment=itemView.findViewById(R.id.comment);
                save=itemView.findViewById(R.id.save);
                delete=itemView.findViewById(R.id.delete);

                username=itemView.findViewById(R.id.username);
                blood=itemView.findViewById(R.id.blood);
                time=itemView.findViewById(R.id.time);

                likes=itemView.findViewById(R.id.likes);
                dislikes=itemView.findViewById(R.id.dislikes);
                dislike=itemView.findViewById(R.id.dislike);
                comments=itemView.findViewById(R.id.comments);
                description=itemView.findViewById(R.id.description);
                publisher=itemView.findViewById(R.id.publisher);
                progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);

            }
        }

        private void publisherInfo (final ImageView image_profile, final TextView username,final  TextView blood, final TextView publisher, final String userId ){
            DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    try {
                        User user=dataSnapshot.getValue(User.class);
                        Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(image_profile);

                        username.setText(user.getUsername());
                        blood.setText(user.getBlood());

                        publisher.setText(user.getUsername());

                    }catch (Exception e){

                    }

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }

    }

Body:
Like this in Java:

private void loadImage(ImageView yourImageView, String imageUri) {
    CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(yourImageView.getContext())
    circularProgressDrawable.setStrokeWidth(5f)
    circularProgressDrawable.setCenterRadius(30f)
    circularProgressDrawable.start()

    Glide.with(yourImageView.getContext())
        .load(imageUri)
        .placeholder(circularProgressDrawable)
        .error(R.drawable.ic_close_black)
        .override(200, 300)
        .into(yourImageView);
}


问:
How to get django queryset results with formatted datetime field
I've Django model which has foreign keys associated with other models. Each model is having same field names(attributes) created_at and updated_at

In every django queryset results I'll be getting datetime values.

```<code>Model.objects.all().values('created_at')
</code>```

But I want to format the datetime field to "DD-MM-YYYY HH:MM:SS" and trim down the milliseconds in the django query results.

If I use "extra" and and date_trunc_sql like the following command

```<code>dt = connection.ops.date_trunc_sql('day','created_date')
objects.extra({'date':dt}).values('date')
</code>```

Which works fine. But If I query like the following, its raising ambiguous statement error.

```<code>objects.extra({'date':dt}).values('date', 'x', 'y', 'z')
</code>```

How to overcome this problem?

答:
Solved it via @Yannics answer at: https://stackoverflow.com/a/60924664/5804947

This also avoids using extra which should be "a last resort" due to Django docs.

```<code>from django.db.models import F, Func, Value, CharField

qs.annotate(
  formatted_date=Func(
    F('created_at'),
    Value('DD-MM-YYYY HH:MM:SS'),
    function='to_char',
    output_field=CharField()
  )
)
</code>```

Body:
I've Django model which has foreign keys associated with other models. Each model is having same field names(attributes) created_at and updated_at

In every django queryset results I'll be getting datetime values.

Model.objects.all().values('created_at')

But I want to format the datetime field to "DD-MM-YYYY HH:MM:SS" and trim down the milliseconds in the django query results.

If I use "extra" and and date_trunc_sql like the following command

dt = connection.ops.date_trunc_sql('day','created_date')
objects.extra({'date':dt}).values('date')

Which works fine. But If I query like the following, its raising ambiguous statement error.

objects.extra({'date':dt}).values('date', 'x', 'y', 'z')

How to overcome this problem?

Body:
Solved it via @Yannics answer at: https://stackoverflow.com/a/60924664/5804947

This also avoids using extra which should be "a last resort" due to Django docs.

from django.db.models import F, Func, Value, CharField

qs.annotate(
  formatted_date=Func(
    F('created_at'),
    Value('DD-MM-YYYY HH:MM:SS'),
    function='to_char',
    output_field=CharField()
  )
)


问:
How to check if element in groovy array/hash/collection/list?
How do I figure out if an array contains an element?
I thought there might be something like [1, 2, 3].includes(1) which would evaluate as true.

答:
Some syntax sugar</p>

```<code>1 in [1,2,3]
</code>```

Body:
Some syntax sugar

1 in [1,2,3]

OwnerDisplayName: dahernan


问:
How to insert data from html form into database without using HTML POST method?
Hi I would like to know if there is any other way using javascript or something to enter the user input directly to database without using POST method.</p>

答: If the page is being viewed from a machine that has access to the database, then you can ask javascript to create an instance of the ADO activex objects (anone remember those?  mebe I'm showing my age) and then your js code can talk direct to the database.  Again, this only works for machines that can hit the db directly (local machine/network).</p>

OwnerDisplayName: johnnaples

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Boo


问:
Tomcat 5.5 won't start in eclipse - Timeout after 5 minutes
My tomcat 5.5 start fine when I start it by itself. When I try to start it in eclipse, it times out. It just sits at "Starting Tomcat v5.5...at localhost". I even changed the timeout to 5 minutes and it still won't start. I've tried reinstalling my tomcat in eclipse multiple times and that hasn't helped at all. Please help.</p>

答: After days of messing with this, I finally figured out that it was a specific project that I had added to the server. It somehow caused the server to never start. When I switched the jdk from the workbench default, to version 6 which I downloaded, it worked fine. I'm still not exactly sure if there is a jar in that project that is causing the problem.</p>