问:
Translating np.einsum() to MATLAB
I am having trouble understanding the documentation of np.einsum(). How are subscripts interpreted?

I am trying to write np.einsum('a...c,b...c', Y, conj(Y)) where Y is a matrix of shape C, F, T on the original python. Also, due to previous implementation differences my MATLAB Y is of size [F, T, C].

What does 'a...c,b...c' index in each component? I am confused.

How do I write the same instructions in MATLAB?

答:
Quoting from the einsum documentation page:

To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b).

Later, an example is given:

>>> a = np.arange(25).reshape(5,5)
>>> np.einsum('...j->...', a)
array([ 10,  35,  60,  85, 110])
```

<p>The equivalent MATLAB code to this example would be:</p>

<pre class="lang-matlab prettyprint-override"><code>>> a = reshape(0:24, [5,5]).';
>> sum(a,2).'
ans =
    10    35    60    85   110
</code>```

Several things to note:

The ellipsis operator (...) should not be understood as "range", but as "whatever needs to be there".

"Broadcasting" refers to automatic replication of an array along the relevant dimension so that the mathematical operation is defined. This is a feature that exists in MATLAB since R2016b (called "implicit expansion").

You may notice several transpose operations (.') in the MATLAB equivalent. This is because numpy arrays are row-major while MATLAB array are column-major. Practically, while the underlying data has the same sequential order, a numpy array appears transposed compared to MATLAB. The transpositions were done so that arrays appear the same in intermediate stages.

Another example from these docs is:

>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('k...,jk', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
```

<p>Which can be written as follows in MATLAB:</p>

<pre class="lang-matlab prettyprint-override"><code>A = reshape(0:5, [2 3]).';
B = reshape(0:11, [3 4]).';

A.' * B.'
permute(sum( permute(A, [3 1 2]) .* B,2), [3 1 2])
shiftdim(sum( shiftdim(A, -1) .* B, 2), 2)
</code>```

Several things to note:

When going from np.einsum('ki,jk->ij', a, b) to np.einsum('ki,...k->i...', a, b) you can see that the j-th dimension is replaced with .... The fact that both these examples have a -> in them, means it's in explicit mode.

When going from np.einsum('ki,jk->ij', a, b) to np.einsum('k...,jk', a, b), you can see that now the i-th dimension is replaced with .... The omission of ->...j simply demonstrates implicit mode (where the output dimensions are ordered alphabetically).

Title: Translating np.einsum() to MATLAB

Body:
Quoting from the einsum documentation page:

To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b).

Later, an example is given:

>>> a = np.arange(25).reshape(5,5)
>>> np.einsum('...j->...', a)
array([ 10,  35,  60,  85, 110])

The equivalent MATLAB code to this example would be:

>> a = reshape(0:24, [5,5]).';
>> sum(a,2).'
ans =
    10    35    60    85   110

Several things to note:

The ellipsis operator (...) should not be understood as "range", but as "whatever needs to be there".

"Broadcasting" refers to automatic replication of an array along the relevant dimension so that the mathematical operation is defined. This is a feature that exists in MATLAB since R2016b (called "implicit expansion").

You may notice several transpose operations (.') in the MATLAB equivalent. This is because numpy arrays are row-major while MATLAB array are column-major. Practically, while the underlying data has the same sequential order, a numpy array appears transposed compared to MATLAB. The transpositions were done so that arrays appear the same in intermediate stages.

Another example from these docs is:

>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('k...,jk', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])

Which can be written as follows in MATLAB:

A = reshape(0:5, [2 3]).';
B = reshape(0:11, [3 4]).';

A.' * B.'
permute(sum( permute(A, [3 1 2]) .* B,2), [3 1 2])
shiftdim(sum( shiftdim(A, -1) .* B, 2), 2)

Several things to note:

When going from np.einsum('ki,jk->ij', a, b) to np.einsum('ki,...k->i...', a, b) you can see that the j-th dimension is replaced with .... The fact that both these examples have a -> in them, means it's in explicit mode.

When going from np.einsum('ki,jk->ij', a, b) to np.einsum('k...,jk', a, b), you can see that now the i-th dimension is replaced with .... The omission of ->...j simply demonstrates implicit mode (where the output dimensions are ordered alphabetically).


来源: stackexchange

问:
Combine 2 lists into one using map & arrow function
I have 2 lists and I want to combine them so that I can populate them into a list. I know this can be done using nested for loops but, I'm trying to avoid for loops because of the amount of data I'll have to loop on. I would like to achieve this using the arrow functions or anything else.

List One:

```<code>let fields = [
    {
        field: "Name",
        fieldType: "Text"
    },
    {
        field: "Active__c",
        fieldType: "Boolean"
    },
    {
        field: "Contact",
        fieldType: "Relationship"
    }
];
</code>```

List Two:

```<code>let rows = [
    {
        contact: {
            Name: "Joe",
            Active__c: true,
            Contact: "SomeContact"
        }
    },
    {
        contact: {
            Name: "Rachel",
            Active__c: true
        }
    },
    {
        contact: {
            Name: "Ross",
            Active__c: true
        }
    },
    {
        contact: {
            Name: "Monica",
            Active__c: true
        }
    }
];
</code>```

Current code:

```<code>let output = rows.map(row => ({
    id: row.Id,
    data: {
        value: fields.map(field => (row.contact[field.field])),
        field: fields.map(field => field.field)
    }
}));
</code>```

The output of this code:

```<code>[
    {
        "data": {
            "value": [
                "Joe",
                true,
                "SomeContact"
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Rachel",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Ross",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Monica",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    }
]
</code>```

Desired output:

```<code>[
    data : [
        [
            {
                field : "Name",
                type: "Text",
                value : "Joe"
            },
            {
                field : "Active__c",
                type: "Boolean",
                value : true
            },
            {
                field : "Contact",
                type: "Relationship",
                value : "SomeContact"
            }
        ],
        [
            {
                field : "Name",
                type: "Text",
                value : "Rachel"
            },
            {
                field : "Active__c",
                type: "Boolean",
                value : false
            },
            {
                field : "Contact",
                type: "Relationship",
                value : "SomeContact Two"
            }
        ],
        [
            ...
        ],
        [
            ...
        ]
    ]
]
</code>```

How can I achieve this?

答:
The data property is unique and it has to be defined inline creating an object (not an array as you have in your desired output). You have to map fields array to each element of rows and then fill each field data with the row data if they exist. Also, I can't see an Id field on any row object inside rows array. This code sets null if a field does not exists:

let output = {
  data: rows.map(({ contact }) =>
    fields.map(({ field, fieldType: type }) => ({
      field,
      type,
      value: field in contact ? contact[field] : null // Set null if contact has no field
    }))
  )
}
```

<p>Run this code snippet to see the results:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let fields = [
  {
    field: "Name",
    fieldType: "Text"
  },
  {
    field: "Active__c",
    fieldType: "Boolean"
  },
  {
    field: "Contact",
    fieldType: "Relationship"
  }
];

let rows = [
  {
    contact: {
      Name: "Joe",
      Active__c: true,
      Contact: "SomeContact"
    }
  },
  {
    contact: {
      Name: "Rachel",
      Active__c: true
    }
  },
  {
    contact: {
      Name: "Ross",
      Active__c: true
    }
  },
  {
    contact: {
      Name: "Monica",
      Active__c: true
    }
  }
];

let output = {
  data: rows.map(({ contact }) =>
    fields.map(({ field, fieldType: type }) => ({
      field,
      type,
      value: field in contact ? contact[field] : null
    }))
  )
}

document.getElementById('output').appendChild(
  document.createTextNode(JSON.stringify(output, null, 2))
);</code>```

```</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 2 lists and I want to combine them so that I can populate them into a list. I know this can be done using nested for loops but, I'm trying to avoid for loops because of the amount of data I'll have to loop on. I would like to achieve this using the arrow functions or anything else.

List One:

let fields = [
    {
        field: "Name",
        fieldType: "Text"
    },
    {
        field: "Active__c",
        fieldType: "Boolean"
    },
    {
        field: "Contact",
        fieldType: "Relationship"
    }
];

List Two:

let rows = [
    {
        contact: {
            Name: "Joe",
            Active__c: true,
            Contact: "SomeContact"
        }
    },
    {
        contact: {
            Name: "Rachel",
            Active__c: true
        }
    },
    {
        contact: {
            Name: "Ross",
            Active__c: true
        }
    },
    {
        contact: {
            Name: "Monica",
            Active__c: true
        }
    }
];

Current code:

let output = rows.map(row => ({
    id: row.Id,
    data: {
        value: fields.map(field => (row.contact[field.field])),
        field: fields.map(field => field.field)
    }
}));

The output of this code:

[
    {
        "data": {
            "value": [
                "Joe",
                true,
                "SomeContact"
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Rachel",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Ross",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Monica",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    }
]

Desired output:

[
    data : [
        [
            {
                field : "Name",
                type: "Text",
                value : "Joe"
            },
            {
                field : "Active__c",
                type: "Boolean",
                value : true
            },
            {
                field : "Contact",
                type: "Relationship",
                value : "SomeContact"
            }
        ],
        [
            {
                field : "Name",
                type: "Text",
                value : "Rachel"
            },
            {
                field : "Active__c",
                type: "Boolean",
                value : false
            },
            {
                field : "Contact",
                type: "Relationship",
                value : "SomeContact Two"
            }
        ],
        [
            ...
        ],
        [
            ...
        ]
    ]
]

How can I achieve this?

Body:
The data property is unique and it has to be defined inline creating an object (not an array as you have in your desired output). You have to map fields array to each element of rows and then fill each field data with the row data if they exist. Also, I can't see an Id field on any row object inside rows array. This code sets null if a field does not exists:

let output = {
  data: rows.map(({ contact }) =>
    fields.map(({ field, fieldType: type }) => ({
      field,
      type,
      value: field in contact ? contact[field] : null // Set null if contact has no field
    }))
  )
}

Run this code snippet to see the results:

let fields = [
  {
    field: "Name",
    fieldType: "Text"
  },
  {
    field: "Active__c",
    fieldType: "Boolean"
  },
  {
    field: "Contact",
    fieldType: "Relationship"
  }
];

let rows = [
  {
    contact: {
      Name: "Joe",
      Active__c: true,
      Contact: "SomeContact"
    }
  },
  {
    contact: {
      Name: "Rachel",
      Active__c: true
    }
  },
  {
    contact: {
      Name: "Ross",
      Active__c: true
    }
  },
  {
    contact: {
      Name: "Monica",
      Active__c: true
    }
  }
];

let output = {
  data: rows.map(({ contact }) =>
    fields.map(({ field, fieldType: type }) => ({
      field,
      type,
      value: field in contact ? contact[field] : null
    }))
  )
}

document.getElementById('output').appendChild(
  document.createTextNode(JSON.stringify(output, null, 2))
);

<pre id="output"></pre>


问:
Website not loading CSS, Webpage not loading Images
CSS is perfectly loading on the offline webpage (localhost) but on the live website, CSS is not loading.

I am using hosting and domain from the biz.nf website.
I used bootstrap 4 on this website.

My index.html head code:

```<code>   <!DOCTYPE html>
   <html>
   <head>

    <title> </title>
    <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
     <link rel="stylesheet" type="text/css" href="http://www.site.c1.biz/css/style.css" media="screen" />
     <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
   </head>
</code>```

答:
I saw your website in the inspect mode
its showing style.css is 403 forbidden in the network tab

Check with it

you can check here ERROR 403 in loading resources like CSS and JS in my index.php

Body:
CSS is perfectly loading on the offline webpage (localhost) but on the live website, CSS is not loading.

I am using hosting and domain from the biz.nf website.
I used bootstrap 4 on this website.

My index.html head code:

   <!DOCTYPE html>

    <title> </title>
    <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
     <link rel="stylesheet" type="text/css" href="http://www.site.c1.biz/css/style.css" media="screen" />
     <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">


问:
How can i post image with dio in flutter
i want to send image to server by jpg format by dio package ,
how can i do this ?

choose image method :

```<code>  void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
  file = file;
  print(file);
});
</code>```

upload image method :

```<code>  void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
  "image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
  print(json.decode(onValue));
});
</code>```

Anyone help me ?

thanks

答:
Please try this  </p>

```<code>       Future<dynamic> _upload() async {
            if (file == null) return;
            String fileName = file.path.split('/').last;
            Map<String, dynamic> formData = {
              "image": await MultipartFile.fromFile(file.path,filename: fileName),
            };
           return await Dio()
        .post(url,data:formData).
    then((dynamic result){
    print(result.toString());
});
}
</code>```

Body:
i want to send image to server by jpg format by dio package ,
how can i do this ?

choose image method :

  void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
  file = file;
  print(file);
});

upload image method :

  void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
  "image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
  print(json.decode(onValue));
});

Anyone help me ?

thanks

Body:
Please try this

       Future<dynamic> _upload() async {
            if (file == null) return;
            String fileName = file.path.split('/').last;
            Map<String, dynamic> formData = {
              "image": await MultipartFile.fromFile(file.path,filename: fileName),
            };
           return await Dio()
        .post(url,data:formData).
    then((dynamic result){
    print(result.toString());
});
}


问:
Handling overlap of divs
I want the inner part of the red circle to be white while overlapping with the blue circle and transparent for the rest so that you can see the green color.

I would be happy if someone knows how to handle this.

#bigCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 380px;
    height: 380px;
    border-radius: 50%;
    background-color: rgba(11, 122, 30, 0.8);
}

#middleCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 240px;
    height: 240px;
    border-radius: 50%;
    background-color: rgba(0,0,250,0.5);
}

.smallCircle {
    margin-top: -244px;
    margin-left: 1px;
    border: solid rgb(226, 85, 20);
    width: 13px;
    height: 13px;
    border-radius: 50%;
    background-color:rgba(255,255,255,0);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div id="bigCircle">
                <div id="middleCircle">
                    <div class="smallCircle" />
                </div>
        </div ></code>```

答:
If i understood your question then might be it'll help.

css

```<code>#bigCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 380px;
    height: 380px;
    border-radius: 50%;
    background-color: rgba(11, 122, 30, 0.8);
}

#middleCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 240px;
    height: 240px;
    border-radius: 50%;
    background-color: rgba(0,0,250,0.5);
}

.smallCircle {
    margin-top: -244px;
    margin-left: 1px;
    border: solid rgb(226, 85, 20);
    width: 13px;
    height: 13px;
    border-radius: 50%;
    background-color:rgba(255,255,255,0);
  }
</code>```

Title: Handling overlap of divs

Body:
If i understood your question then might be it'll help.

css

#bigCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 380px;
    height: 380px;
    border-radius: 50%;
    background-color: rgba(11, 122, 30, 0.8);
}

#middleCircle {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 240px;
    height: 240px;
    border-radius: 50%;
    background-color: rgba(0,0,250,0.5);
}

.smallCircle {
    margin-top: -244px;
    margin-left: 1px;
    border: solid rgb(226, 85, 20);
    width: 13px;
    height: 13px;
    border-radius: 50%;
    background-color:rgba(255,255,255,0);
  }


问:
Javascript : Increase a Date object by a year
I'm assign a new date object to my object attribute like that :

giftObject.purshasedDate = new Date()

which give a date format :

Date Thu Feb 20 2020 13:36:37 GMT+0100 (heure normale d’Europe
  centrale)

I want to increase this date by one year, I tried :

new Date().setFullYear(giftObject.purshasedDate.getFullYear() + 1) but it give a number serial like this : 1613824899244

I do not understand what that number serial mean! it's a date or should a try some thing else ?

答:
Please use this one:</p>

```<code>    purshasedDate = new Date();
    purshasedDate = new Date(purshasedDate.setFullYear(purshasedDate.getFullYear() + 1));
</code>```

Body:
Please use this one:

    purshasedDate = new Date();
    purshasedDate = new Date(purshasedDate.setFullYear(purshasedDate.getFullYear() + 1));


问:
Excel file not being downloaded when function is called via ajax method
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />
```

<p>This is the code which downloads the file. It was a simple button I added.</p>

<pre class="lang-js prettyprint-override"><code>function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}
</code>```

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}
```

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

答:
I've had a similar problem here, and it did solve with a dynamic button as well. I just had to include a responseType:'blob' in my request.
And get the response to the button:

```<code>var link = document.createElement('a');
link.href = window.URL.createObjectURL(response.data);
link.download='filename.xlsx';

document.body.appendChild(link);
link.click();
document.body.removeChild(link);
</code>```

And my Controller writes to a output stream and produces a "application/xls"

```<code>response.setContentType("application/xls");
response.setHeader("Content-disposition", "attachment;");
response.getOutputStream().write(content);
</code>```

Body:
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />

This is the code which downloads the file. It was a simple button I added.

function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

Body:
I've had a similar problem here, and it did solve with a dynamic button as well. I just had to include a responseType:'blob' in my request.
And get the response to the button:

var link = document.createElement('a');
link.href = window.URL.createObjectURL(response.data);
link.download='filename.xlsx';

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

And my Controller writes to a output stream and produces a "application/xls"

response.setContentType("application/xls");
response.setHeader("Content-disposition", "attachment;");
response.getOutputStream().write(content);


问:
Convert a secure string to plain text
I'm working in PowerShell and I have code that successfully converts a user entered password into plain text:

```<code>$SecurePassword = Read-Host -AsSecureString  "Enter password" | convertfrom-securestring | out-file C:\Users\tmarsh\Documents\securePassword.txt
</code>```

I've been tried several ways to convert it back, but none of them seem to work properly. Most recently, I've tried with the following:

```<code>$PlainPassword = Get-Content C:\Users\tmarsh\Documents\securePassword.txt

#convert the SecureString object to plain text using PtrToString and SecureStringToBSTR
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) #this is an important step to keep things secure
</code>```

This gives me an error as well.

```<code>Cannot convert argument "s", with value: "01000000d08c9ddf0115d1118c7a00c04fc297eb0100000026a5b6067d53fd43801a9ef3f8ef9e43000000000200000000000366000
0c0000000100000008118fdea02bfb57d0dda41f9748a05f10000000004800000a000000010000000c50f5093f3b87fbf9ee57cbd17267e0a10000000833d1d712cef01497872a3457bc8
bc271400000038c731cb8c47219399e4265515e9569438d8e8ed", for "SecureStringToBSTR" to type "System.Security.SecureString": "Cannot convert the "01000000
d08c9ddf0115d1118c7a00c04fc297eb0100000026a5b6067d53fd43801a9ef3f8ef9e430000000002000000000003660000c0000000100000008118fdea02bfb57d0dda41f9748a05f10
000000004800000a000000010000000c50f5093f3b87fbf9ee57cbd17267e0a10000000833d1d712cef01497872a3457bc8bc271400000038c731cb8c47219399e4265515e9569438d8e8
ed" value of type "System.String" to type "System.Security.SecureString"."
At C:\Users\tmarsh\Documents\Scripts\Local Admin Script\PlainTextConverter1.ps1:14 char:1
+ $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassw ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Cannot find an overload for "PtrToStringAuto" and the argument count: "1".
At C:\Users\tmarsh\Documents\Scripts\Local Admin Script\PlainTextConverter1.ps1:15 char:1
+ $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Cannot convert argument "s", with value: "", for "ZeroFreeBSTR" to type "System.IntPtr": "Cannot convert null to type "System.IntPtr"."
At C:\Users\tmarsh\Documents\Scripts\Local Admin Script\PlainTextConverter1.ps1:16 char:1
+ [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) #this is an important ste ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Password is:  01000000d08c9ddf0115d1118c7a00c04fc297eb0100000026a5b6067d53fd43801a9ef3f8ef9e430000000002000000000003660000c0000000100000008118fdea02bfb57d0dda41f97
48a05f10000000004800000a000000010000000c50f5093f3b87fbf9ee57cbd17267e0a10000000833d1d712cef01497872a3457bc8bc271400000038c731cb8c47219399e4265515e9569
438d8e8ed
</code>```

Does anyone know of a way that will work for this?

答:
In PS 7, you can use ConvertFrom-SecureString and -AsPlainText:

```<code>#Requires -Version 7.0

$UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText
</code>```

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/ConvertFrom-SecureString?view=powershell-7#parameters

```<code>ConvertFrom-SecureString
           [-SecureString] <SecureString>
           [-AsPlainText]
           [<CommonParameters>]
</code>```

Title: Convert a secure string to plain text

Body:
I'm working in PowerShell and I have code that successfully converts a user entered password into plain text:

$SecurePassword = Read-Host -AsSecureString  "Enter password" | convertfrom-securestring | out-file C:\Users\tmarsh\Documents\securePassword.txt

I've been tried several ways to convert it back, but none of them seem to work properly. Most recently, I've tried with the following:

$PlainPassword = Get-Content C:\Users\tmarsh\Documents\securePassword.txt

#convert the SecureString object to plain text using PtrToString and SecureStringToBSTR
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) #this is an important step to keep things secure

This gives me an error as well.

Cannot convert argument "s", with value: "01000000d08c9ddf0115d1118c7a00c04fc297eb0100000026a5b6067d53fd43801a9ef3f8ef9e43000000000200000000000366000
0c0000000100000008118fdea02bfb57d0dda41f9748a05f10000000004800000a000000010000000c50f5093f3b87fbf9ee57cbd17267e0a10000000833d1d712cef01497872a3457bc8
bc271400000038c731cb8c47219399e4265515e9569438d8e8ed", for "SecureStringToBSTR" to type "System.Security.SecureString": "Cannot convert the "01000000
d08c9ddf0115d1118c7a00c04fc297eb0100000026a5b6067d53fd43801a9ef3f8ef9e430000000002000000000003660000c0000000100000008118fdea02bfb57d0dda41f9748a05f10
000000004800000a000000010000000c50f5093f3b87fbf9ee57cbd17267e0a10000000833d1d712cef01497872a3457bc8bc271400000038c731cb8c47219399e4265515e9569438d8e8
ed" value of type "System.String" to type "System.Security.SecureString"."
At C:\Users\tmarsh\Documents\Scripts\Local Admin Script\PlainTextConverter1.ps1:14 char:1
+ $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassw ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Cannot find an overload for "PtrToStringAuto" and the argument count: "1".
At C:\Users\tmarsh\Documents\Scripts\Local Admin Script\PlainTextConverter1.ps1:15 char:1
+ $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Cannot convert argument "s", with value: "", for "ZeroFreeBSTR" to type "System.IntPtr": "Cannot convert null to type "System.IntPtr"."
At C:\Users\tmarsh\Documents\Scripts\Local Admin Script\PlainTextConverter1.ps1:16 char:1
+ [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR) #this is an important ste ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Password is:  01000000d08c9ddf0115d1118c7a00c04fc297eb0100000026a5b6067d53fd43801a9ef3f8ef9e430000000002000000000003660000c0000000100000008118fdea02bfb57d0dda41f97
48a05f10000000004800000a000000010000000c50f5093f3b87fbf9ee57cbd17267e0a10000000833d1d712cef01497872a3457bc8bc271400000038c731cb8c47219399e4265515e9569
438d8e8ed

Does anyone know of a way that will work for this?

Body:
In PS 7, you can use ConvertFrom-SecureString and -AsPlainText:

#Requires -Version 7.0

$UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/ConvertFrom-SecureString?view=powershell-7#parameters

ConvertFrom-SecureString
           [-SecureString] <SecureString>
           [-AsPlainText]
           [<CommonParameters>]


问:
make ng-select width adjust to selected items / available options?
I'm using ng-select in an Ionic3 / Angular5 project and I'm using its multiple selection configuration. The presentation of the select input is always considerably wider than it needs to be to contain the selected items or any of the available options.

I'd like it to be sized such that the width is at least the maximum width the component would have if any one of the available options were selected, and such that the otherwise the width is whatever is required to contain the actively selected options.

Is it possible to get ng-select to behave in that way?

答:
adding ng-select { .ng-dropdown-panel { width: auto !important; } } in CSS, it works but I would like to suggest adding a tooltip while hovering making a substring than adding css. </p>

```<code><ng-template ng-option-tmp let-item="item">
        <div [ngbTooltip]="item.length > 15 ? item : ''" container="body">
          {{item.length > 15 ? (item| slice:0:15) + '..' : item}}
        </div>
</ng-template>
</code>```

Body:
adding ng-select { .ng-dropdown-panel { width: auto !important; } } in CSS, it works but I would like to suggest adding a tooltip while hovering making a substring than adding css.

<ng-template ng-option-tmp let-item="item">
        <div [ngbTooltip]="item.length > 15 ? item : ''" container="body">
          {{item.length > 15 ? (item| slice:0:15) + '..' : item}}
        </div>
</ng-template>


问:
Using a4j:support to update the model and view, ready for the next button/submit action

The Problem

We have a swing based front end for an enterprise application and now are implementing a (for now simpler) JSF/Seam/Richfaces front end for it.

Some of the pages include fields that, when edited, should cause other fields to change as a result. We need this change to be shown to the user immediately (i.e. they should not have to press a button or anything).

I have implemented this successfully using h:commandButton and by adding onchange="submit()" to the fields that cause other fields to change. That way, a form submit occurs when they edit the field, and the other fields are updated as a result.

This works fine functionally, but especially when the server is under significant load (which happens often) the form submits can take a long time and our users have been continuing to edit fields in the meantime which then get reverted when the responses to the onchange="submit()" requests are rendered.

To solve this problem, I was hoping to achieve something where:

Upon editing the field, if required, only that field is processed and only the fields it modifies are re-rendered (so that any other edits the user has made in the meantime do not get lost).

Upon pressing a button, all fields are processed and re-rendered as normal.

The (Unstable) Solution

Okay, I think it might be easiest to show a bit of my page first. Note that this is only an excerpt and that some pages will have many fields and many buttons.

```<code><a4j:form id="mainForm">
    ...
    <a4j:commandButton id="calculateButton" value="Calculate" action="#{illustrationManager.calculatePremium()}" reRender="mainForm" />
    ...
    <h:outputLabel for="firstName" value=" First Name" />
    <h:inputText id="firstName" value="#{life.firstName}" />
    ...
    <h:outputLabel for="age" value=" Age" />
    <h:inputText id="age" value="#{life.age}">
        <f:convertNumber type="number" integerOnly="true" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="dob" />
    </h:inputText>
    <h:outputLabel for="dob" value=" DOB" />
    <h:inputText id="dob" value="#{life.dateOfBirth}" styleClass="date">
        <f:convertDateTime pattern="dd/MM/yyyy" timeZone="#{userPreference.timeZone}" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="age,dob" />
    </h:inputText>
    ...
</a4j:form>
</code>```

Changing the value of age causes the value of dob to change in the model and vice versa. I use reRender="dob" and reRender="age,dob" to display the changed values from the model. This works fine.

I am also using the global queue to ensure ordering of AJAX requests.

However, the onchange event does not occur until I click somewhere else on the page or press tab or something. This causes problems when the user enters a value in say, age, and then presses calculateButton without clicking somewhere else on the page or pressing tab.

The onchange event does appear to occur first as I can see the value of dob change but the two values are then reverted when the calculateButton request is performed.

So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them? Why is that not happening already since I am using the AJAX queue?

The Workarounds

There are two strategies to get around this limitation but they both require bloat in the facelet code which could be confusing to other developers and cause other problems.

Workaround 1: Using a4j:support

This strategy is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the a4j:support tag with the ajaxSingle="true" attribute to firstName.

The first step ensures that calculateButton does not overwrite the values in age or dob since it no longer processes them. Unfortunately it has the side effect that it no longer processes firstName either. The second step is added to counter this side effect by processing firstName before calculateButton is pressed.

Keep in mind though that there could be 20+ fields like firstName. A user filling out a form could then cause 20+ requests to the server! Like I mentioned before this is also bloat that may confuse other developers.

Workaround 2: Using the process list

Thanks to @DaveMaple and @MaxKatz for suggesting this strategy, it is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the process="firstName" attribute to calculateButton.

The first step achieves the same as it did in the first workaround but has the same side effect. This time the second step ensures that firstName is processed with calculateButton when it is pressed.

Again, keep in mind though that there could be 20+ fields like firstName to include in this list. Like I mentioned before this is also bloat that may confuse other developers, especially since the list must include some fields but not others.

Age and DOB Setters and Getters (just in case they are the cause of the issue)

```<code>public Number getAge() {
    Long age = null;

    if (dateOfBirth != null) {
        Calendar epochCalendar = Calendar.getInstance();
        epochCalendar.setTimeInMillis(0L);
        Calendar dobCalendar = Calendar.getInstance();
        dobCalendar.setTimeInMillis(new Date().getTime() - dateOfBirth.getTime());
        dobCalendar.add(Calendar.YEAR, epochCalendar.get(Calendar.YEAR) * -1);

        age = new Long(dobCalendar.get(Calendar.YEAR));
    }

    return (age);
}

public void setAge(Number age) {
    if (age != null) {
        // This only gives a rough date of birth at 1/1/<this year minus <age> years>.
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR) - age.intValue(), Calendar.JANUARY, 1, 0, 0, 0);

        setDateOfBirth(calendar.getTime());
    }
}

public Date getDateOfBirth() {
    return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
    if (notEqual(this.dateOfBirth, dateOfBirth)) {
        // If only two digits were entered for the year, provide useful defaults for the decade.
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateOfBirth);
        if (calendar.get(Calendar.YEAR) < 50) {
            // If the two digits entered are in the range 0-49, default the decade 2000.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 2000);
        } else if (calendar.get(Calendar.YEAR) < 100) {
            // If the two digits entered are in the range 50-99, default the decade 1900.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1900);
        }
        dateOfBirth = calendar.getTime();

        this.dateOfBirth = dateOfBirth;
        changed = true;
    }
}
</code>```

答:
So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them?

What you could do is disable the submit button from the time you initiate your ajax request until your ajax request completes. This will effectively prevent the user from pressing the submit button until it resolves:

```<code><a4j:support
    event="onblur"
    ajaxSingle="true"
    onsubmit="jQuery('#mainForm\\:calculateButton').attr('disabled', 'disabled');"
    oncomplete="jQuery('#mainForm\\:calculateButton').removeAttr('disabled');" />
</code>```

One thing that is additionally helpful with this approach is if you display an "ajaxy" image to the end user while this is happening so that they intuitively understand that stuff is happening that will resolve soon. You can show this image in the onsubmit method as well and then hide it oncomplete.

EDIT:
The issue may just be that you need to add the process attribute to your a4j:commandButton. This attribute specifies the components by id that should participate in the model update phase:

```<code><a4j:commandButton
    id="calculateButton"
    value="Calculate"
    action="#{illustrationManager.calculatePremium()}"
    process="firstName"
    reRender="mainForm" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The Problem

We have a swing based front end for an enterprise application and now are implementing a (for now simpler) JSF/Seam/Richfaces front end for it.

Some of the pages include fields that, when edited, should cause other fields to change as a result. We need this change to be shown to the user immediately (i.e. they should not have to press a button or anything).

I have implemented this successfully using h:commandButton and by adding onchange="submit()" to the fields that cause other fields to change. That way, a form submit occurs when they edit the field, and the other fields are updated as a result.

This works fine functionally, but especially when the server is under significant load (which happens often) the form submits can take a long time and our users have been continuing to edit fields in the meantime which then get reverted when the responses to the onchange="submit()" requests are rendered.

To solve this problem, I was hoping to achieve something where:

Upon editing the field, if required, only that field is processed and only the fields it modifies are re-rendered (so that any other edits the user has made in the meantime do not get lost).

Upon pressing a button, all fields are processed and re-rendered as normal.

The (Unstable) Solution

Okay, I think it might be easiest to show a bit of my page first. Note that this is only an excerpt and that some pages will have many fields and many buttons.

<a4j:form id="mainForm">
    ...
    <a4j:commandButton id="calculateButton" value="Calculate" action="#{illustrationManager.calculatePremium()}" reRender="mainForm" />
    ...
    <h:outputLabel for="firstName" value=" First Name" />
    <h:inputText id="firstName" value="#{life.firstName}" />
    ...
    <h:outputLabel for="age" value=" Age" />
    <h:inputText id="age" value="#{life.age}">
        <f:convertNumber type="number" integerOnly="true" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="dob" />
    </h:inputText>
    <h:outputLabel for="dob" value=" DOB" />
    <h:inputText id="dob" value="#{life.dateOfBirth}" styleClass="date">
        <f:convertDateTime pattern="dd/MM/yyyy" timeZone="#{userPreference.timeZone}" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="age,dob" />
    </h:inputText>
    ...
</a4j:form>

Changing the value of age causes the value of dob to change in the model and vice versa. I use reRender="dob" and reRender="age,dob" to display the changed values from the model. This works fine.

I am also using the global queue to ensure ordering of AJAX requests.

However, the onchange event does not occur until I click somewhere else on the page or press tab or something. This causes problems when the user enters a value in say, age, and then presses calculateButton without clicking somewhere else on the page or pressing tab.

The onchange event does appear to occur first as I can see the value of dob change but the two values are then reverted when the calculateButton request is performed.

So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them? Why is that not happening already since I am using the AJAX queue?

The Workarounds

There are two strategies to get around this limitation but they both require bloat in the facelet code which could be confusing to other developers and cause other problems.

Workaround 1: Using a4j:support

This strategy is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the a4j:support tag with the ajaxSingle="true" attribute to firstName.

The first step ensures that calculateButton does not overwrite the values in age or dob since it no longer processes them. Unfortunately it has the side effect that it no longer processes firstName either. The second step is added to counter this side effect by processing firstName before calculateButton is pressed.

Keep in mind though that there could be 20+ fields like firstName. A user filling out a form could then cause 20+ requests to the server! Like I mentioned before this is also bloat that may confuse other developers.

Workaround 2: Using the process list

Thanks to @DaveMaple and @MaxKatz for suggesting this strategy, it is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the process="firstName" attribute to calculateButton.

The first step achieves the same as it did in the first workaround but has the same side effect. This time the second step ensures that firstName is processed with calculateButton when it is pressed.

Again, keep in mind though that there could be 20+ fields like firstName to include in this list. Like I mentioned before this is also bloat that may confuse other developers, especially since the list must include some fields but not others.

Age and DOB Setters and Getters (just in case they are the cause of the issue)

public Number getAge() {
    Long age = null;

    if (dateOfBirth != null) {
        Calendar epochCalendar = Calendar.getInstance();
        epochCalendar.setTimeInMillis(0L);
        Calendar dobCalendar = Calendar.getInstance();
        dobCalendar.setTimeInMillis(new Date().getTime() - dateOfBirth.getTime());
        dobCalendar.add(Calendar.YEAR, epochCalendar.get(Calendar.YEAR) * -1);

        age = new Long(dobCalendar.get(Calendar.YEAR));
    }

    return (age);
}

public void setAge(Number age) {
    if (age != null) {
        // This only gives a rough date of birth at 1/1/<this year minus <age> years>.
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR) - age.intValue(), Calendar.JANUARY, 1, 0, 0, 0);

        setDateOfBirth(calendar.getTime());
    }
}

public Date getDateOfBirth() {
    return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
    if (notEqual(this.dateOfBirth, dateOfBirth)) {
        // If only two digits were entered for the year, provide useful defaults for the decade.
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateOfBirth);
        if (calendar.get(Calendar.YEAR) < 50) {
            // If the two digits entered are in the range 0-49, default the decade 2000.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 2000);
        } else if (calendar.get(Calendar.YEAR) < 100) {
            // If the two digits entered are in the range 50-99, default the decade 1900.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1900);
        }
        dateOfBirth = calendar.getTime();

        this.dateOfBirth = dateOfBirth;
        changed = true;
    }
}

Body:
So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them?

What you could do is disable the submit button from the time you initiate your ajax request until your ajax request completes. This will effectively prevent the user from pressing the submit button until it resolves:

<a4j:support
    event="onblur"
    ajaxSingle="true"
    onsubmit="jQuery('#mainForm\\:calculateButton').attr('disabled', 'disabled');"
    oncomplete="jQuery('#mainForm\\:calculateButton').removeAttr('disabled');" />

One thing that is additionally helpful with this approach is if you display an "ajaxy" image to the end user while this is happening so that they intuitively understand that stuff is happening that will resolve soon. You can show this image in the onsubmit method as well and then hide it oncomplete.

EDIT:
The issue may just be that you need to add the process attribute to your a4j:commandButton. This attribute specifies the components by id that should participate in the model update phase:

<a4j:commandButton
    id="calculateButton"
    value="Calculate"
    action="#{illustrationManager.calculatePremium()}"
    process="firstName"
    reRender="mainForm" />


问:
Installation nginx-ingress for Kubernetes Cluster On Premise with CentOS7
I don't sure which installation section is relevant for Cluster On-Premise with CentOS7
in below link
https://kubernetes.github.io/ingress-nginx/deploy/

I tried to install via helm chart, but the service created with type=LoadBalance although the cluster is not on cloud

my questions is:

Helm is the only option to install Nginx not for could (or maybe bare-metal is correct in my case)?

In case of the helm which parameters should be overridden when the helm is installed (service.type etc ...)?

thanks

答:
Using helm you can set controller.service.type to NodePort. That way for nginx ingress controller a NodePort service will be created and you can use NodeIP and NodePort to access backend kubernetes services by creating ingress resource.

Having said that there is no default configuration provided in helm chart for it to work on bare metal. So you need to try it few times. Otherwise you can use the standard yaml provided for bare metal which uses NodePort.


问:
Initializing a 2D array of pointer of type double through double pointer with structure
I am doing something like following;

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

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm->arr = (double **)malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = (double *)malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}
</code>```

It is giving me seg fault error. Please tell me how can I define a 2D array through double-pointer method with structure just like I am trying to do in above code?

答:
You have to allocate the memory for comm variable like the allocation of arr. Because comm is pointer, the defaut value may be NULL. So, you cannot point to the array arr inside of the struct communication.

Add this code below, your program will be work well:

```<code> communication *comm = (communication *) malloc (sizeof(communication));
</code>```

Body:
I am doing something like following;

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

typedef struct
{
 double **arr;
}communication;

int main()
{
    int r = 3, c = 4, i, j, count;

    communication *comm;
    comm->arr = (double **)malloc(r * sizeof(double *));
    for (i=0; i<r; i++)
         comm->arr[i] = (double *)malloc(c * sizeof(double));

    count = 1;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         comm->arr[i][j] = count*2.0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%lf ", *(comm->arr[i]+j));

   return 0;
}

It is giving me seg fault error. Please tell me how can I define a 2D array through double-pointer method with structure just like I am trying to do in above code?

Body:
You have to allocate the memory for comm variable like the allocation of arr. Because comm is pointer, the defaut value may be NULL. So, you cannot point to the array arr inside of the struct communication.

Add this code below, your program will be work well:

 communication *comm = (communication *) malloc (sizeof(communication));


问:
C#: How do I call a static method of a base class from a static method of a derived class?
In C#, I have base class Product and derived class Widget.

Product contains a static method MyMethod().

I want to call static method Product.MyMethod() from static method Widget.MyMethod().

I can't use the base keyword, because that only works with instance methods.

I can call Product.MyMethod() explicitly, but if I later change Widget to derive from another class, I have to revise the method.

Is there some syntax in C# similar to base that allows me to call a static method from a base class from a static method of a derived class?

答:
Having into account that a Static method shoudn't relay in instance data... you should have a static "MyMethod" that behaves diferent based on a parameter or something like that.

Remember that the static method defined in one class is just a way to order your code... but it is the same if that method is placed elsewhere... because it don't relay on the object where it is placed.

EDIT: I think your best choise is to use Product.MyMethod explicitly... If you think it... it should't be probable that your Widget change its base clase... and also in that case it is a minor change in code.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Romias

LastEditorDisplayName: Romias


问:
NSScrollView clipping overlaid UI elements
I have a button that sits on top of an NSScrollView, not within. When the scrollview scrolls, the button get's clipped with part of the button going along with the scrolling and the other part staying positioned.

To better describe the issue here's a video of the issue:

http://dl.dropbox.com/u/170068/ScrollTest.mov

The planned goal was to have a button sit in the top right corner of a text view but stay there when the text view scrolls. So if anyone has any thoughts on how to achieve this it would be greatly appreciated.

答: Overlapping views isn't recommended for non-layer-backed views. I think Interface Builder will even warn you about this. The easiest way to work around this would be to make your button layer-backed.</p>


问:
Jenkins Pipeline Job with file parameter
I'm putting together a Jenkins pipeline job which will take a file parameter. I can trigger the job and point it at a file however I can't find where the file has ended up (In an ordinary freestyle job it would be in the workspace). </p>

<p>Where has the uploaded file gone? Or do file parameters not currently work with pipelines? </p>

答:
Tried what Christoph suggested and it didnt work for me. Here is what worked for me and the setup which I have, his should help others figure out what to do.

Problem:
I am executing my pipeline on dedicated nodes and use sanitized workspaces. After some research and troubleshooting I found out that by default the file upload only works with Master node. I realized this after digging through the file system and finding the file I am uploading in the workspace on the master

Solution:

```<code>stage('Upload Key') {
    agent { label 'master' }
    steps {
        script {
            // Uploads file via master node and stases it for other nodes to access
            def inputFile = input message: 'Upload file', parameters: [file(name: "key.p12")]
            new hudson.FilePath(new File("${workspace}/key.p12")).copyFrom(inputFile)
            inputFile.delete()
        }
        stash name: 'key.p12' , includes: "key.p12"
    }
}
    stage('Register') {
        steps {
            ws (sanitizedWorkspaceName) {
                echo "Registering"
                unstash 'key.p12'
            }
        }
    }
</code>```

Execute the suggested file copy solution by Christoph. This stores the file in the job workspace on the master node

Allow the scripts in Manage Jenkins > In Process Script approval

use the stash step to stash the uploaded file

In the target stage "running on a different node" use the unstash

Hope this helps

Body:
I'm putting together a Jenkins pipeline job which will take a file parameter. I can trigger the job and point it at a file however I can't find where the file has ended up (In an ordinary freestyle job it would be in the workspace).

Where has the uploaded file gone? Or do file parameters not currently work with pipelines?

Body:
Tried what Christoph suggested and it didnt work for me. Here is what worked for me and the setup which I have, his should help others figure out what to do.

Problem:
I am executing my pipeline on dedicated nodes and use sanitized workspaces. After some research and troubleshooting I found out that by default the file upload only works with Master node. I realized this after digging through the file system and finding the file I am uploading in the workspace on the master

Solution:

stage('Upload Key') {
    agent { label 'master' }
    steps {
        script {
            // Uploads file via master node and stases it for other nodes to access
            def inputFile = input message: 'Upload file', parameters: [file(name: "key.p12")]
            new hudson.FilePath(new File("${workspace}/key.p12")).copyFrom(inputFile)
            inputFile.delete()
        }
        stash name: 'key.p12' , includes: "key.p12"
    }
}
    stage('Register') {
        steps {
            ws (sanitizedWorkspaceName) {
                echo "Registering"
                unstash 'key.p12'
            }
        }
    }

Execute the suggested file copy solution by Christoph. This stores the file in the job workspace on the master node

Allow the scripts in Manage Jenkins > In Process Script approval

use the stash step to stash the uploaded file

In the target stage "running on a different node" use the unstash

Hope this helps


问:
Storing Output of Azure CLI command as variable
I need to store the output of an AZ cli commands that fetches my private IPs as a variable.

I am using the following in a bash script:

```<code>echo "Fetching Monitoring Server IP"
SERVER_IP=$(az vm show -n ${THIS_VM_NAME} -g ${RSC_GRP_NAME} --query privateIps -o tsv)
echo "$SERVER_IP
</code>```

It would appear that this isnt working as when I echo the variable, it comes back empty.

```<code>+ THIS_VM_NAME=XXXX-XX-XX-XX-XX
+ echo 'Fetching Monitoring Server IP'
Fetching Monitoring Server IP
++ az vm show -n XXXX-XX-XX-XX-XX3 -g XXXX-XX-XX-XX-XX --query privateIps -o tsv
+ SERVER_IP=
+ echo ''
</code>```

I will appreciate any pointers on this

答:
A solution to my similar problem in Azure Cloud Shell was putting a dollar sign before your SERVER_IP variable if Powershell in chosen.

```<code>$SERVER_IP=$(az vm show --name vmname --resource-group rgname --show-details --query [publicIps] --output tsv)
</code>```

Body:
I need to store the output of an AZ cli commands that fetches my private IPs as a variable.

I am using the following in a bash script:

echo "Fetching Monitoring Server IP"
SERVER_IP=$(az vm show -n ${THIS_VM_NAME} -g ${RSC_GRP_NAME} --query privateIps -o tsv)
echo "$SERVER_IP

It would appear that this isnt working as when I echo the variable, it comes back empty.

+ THIS_VM_NAME=XXXX-XX-XX-XX-XX
+ echo 'Fetching Monitoring Server IP'
Fetching Monitoring Server IP
++ az vm show -n XXXX-XX-XX-XX-XX3 -g XXXX-XX-XX-XX-XX --query privateIps -o tsv
+ SERVER_IP=
+ echo ''

I will appreciate any pointers on this

Body:
A solution to my similar problem in Azure Cloud Shell was putting a dollar sign before your SERVER_IP variable if Powershell in chosen.

$SERVER_IP=$(az vm show --name vmname --resource-group rgname --show-details --query [publicIps] --output tsv)


问:
custom field in the IPN of paypal adaptive payment
I have implemented  Adaptive Payment in my website. First It was Standard Payment so in that i was passing a custom parameter in the form and i was getting it in IPN. But i am unable to find how to pass this parameter in  Adaptive Payment.

Thanks

答:
[Edit]

As per @jackvsworld suggests in PayPal Adaptive use parameter as ipnNotificationUrl.

I did this by passing into GET parameters of notify_url

For e.g. http://www.mywebsite.com/index.php?param_1=value&param_2=value


问:
COUNTIFS for Last 10 Matching Entries
Spreadsheet

Tab Ladder - Col J has a COUNTIFS formula that calculates % of matching criteria within the last 24hrs.  I would like to limit the calculation to the last 10 matching entries within the 24hr window.

I have a stub formula in J35 outlining how I would like it structured.  I have done a lot of searching, and while I have found a few examples of "Last x rows" - I haven't been able to translate those concepts to my specific needs.

Thank you in advance for your help!

Title: COUNTIFS for Last 10 Matching Entries

Body:
instead of your:

=COUNTIFS($A$18:$A, ">"&Dates!$C$4+TIME(Dates!$C$3,0,0)-1,
          $D$18:$D, $D35,
          $H$18:$H, $H35,
          $Y$18:$Y, "")

use:

=COUNTA(IFERROR(QUERY(FILTER(ROW($A$18:$A),
 $A$18:$A>Dates!$C$4+TIME(Dates!$C$3,0,0)-1,
 $D$18:$D=$D35,
 $H$18:$H=$H35,
 $Y$18:$Y=""), "limit 10")))


问:
Postgis: How do I select every second point from LINESTRING?
In DBeaver I have a table containing some GPS coordinates stored as Postgis LINESTRING format.
My questions is: If I have, say, this info:

```<code>LINESTRING(20 20, 30 30, 40 40, 50 50, 60 60, 70 70)
</code>```

which built-in ST function can I use to get every N-th element in that LINESTRING? For example, if I choose 2, I would get:

```<code>LINESTRING(20 20, 40 40, 60 60)
</code>```

, if 3:

```<code>LINESTRING(20 20, 50 50)
</code>```

and so on.

I've tried with ST_SIMPLIFY and ST_POINTN, but that's now exactly what I need because I still want it to stay a LINESTRING but just with less points (lower resolution).

Any ideas?

Thanks :-)

答:
ST_Simplify should return a linestring unless the simplification results in an invalid geometry for a lingstring, e.i., less than 2 vertex.   If you always want to return a linestring consider  ST_SimplifyPreserveTopology .  It ensures that at least two vertices are returned in a linestring.

https://postgis.net/docs/ST_SimplifyPreserveTopology.html

Body:
In DBeaver I have a table containing some GPS coordinates stored as Postgis LINESTRING format.
My questions is: If I have, say, this info:

LINESTRING(20 20, 30 30, 40 40, 50 50, 60 60, 70 70)

which built-in ST function can I use to get every N-th element in that LINESTRING? For example, if I choose 2, I would get:

LINESTRING(20 20, 40 40, 60 60)

, if 3:

LINESTRING(20 20, 50 50)

and so on.

I've tried with ST_SIMPLIFY and ST_POINTN, but that's now exactly what I need because I still want it to stay a LINESTRING but just with less points (lower resolution).

Any ideas?

Thanks :-)


问:
Remotely execute Software Center Package using PowerShell
I have a specific use case where I need to remotely execute the Windows 10 version 1809 OS upgrade package which is published in Software Center under the Operating Systems tab on a Windows 10 v1709 PC. I have a PowerShell one-liner that will do it remotely when the PC is logged in with an admin account (the same account that the PC is logged in with) as shown below:

```<code>Invoke-Command -ComputerName Computer001 {(New-Object -ComObject "UIResource.UIResourceMgr").ExecuteProgram("*", "OS_UpGrade", $true)}
</code>```

That works perfectly when the target PC is logged in with the same account that I have used to run PowerShell terminal with. But when the PC (Computer001) is logged off, and I run the same command, I get this error:

```<code>"Error HRESULT E_FAIL has been returned from a call to a COM component.
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
+ PSComputerName        : Computer001"
</code>```

I am guessing that the ComObject cannot be called when the PC is logged off, is that correct and is there any way around that?

Any guidance would be greatly appreciated.

答:
I took a deeper look at the documentation here.

The issue is specifically the COM object you are calling (as you expected).

The SDK for SCCM specifically mentions this COM object is the UI for CM. UIResource.UIResourceMgr. It also notes in the SDK that this particular object can be difficult to call because it relies on user context.

I'm afraid you are going to have to find an execution that does not rely on calling the UI Resource.

It may be easier to run this via PSExec than a PowerShell script invoking SCCM as I presume you cannot use SCCM itself to invoke the installation remotely.

Body:
I have a specific use case where I need to remotely execute the Windows 10 version 1809 OS upgrade package which is published in Software Center under the Operating Systems tab on a Windows 10 v1709 PC. I have a PowerShell one-liner that will do it remotely when the PC is logged in with an admin account (the same account that the PC is logged in with) as shown below:

Invoke-Command -ComputerName Computer001 {(New-Object -ComObject "UIResource.UIResourceMgr").ExecuteProgram("*", "OS_UpGrade", $true)}

That works perfectly when the target PC is logged in with the same account that I have used to run PowerShell terminal with. But when the PC (Computer001) is logged off, and I run the same command, I get this error:

"Error HRESULT E_FAIL has been returned from a call to a COM component.
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
+ PSComputerName        : Computer001"

I am guessing that the ComObject cannot be called when the PC is logged off, is that correct and is there any way around that?

Any guidance would be greatly appreciated.


问:
How to delete data/rows from multiple tables in SQL Server based on some condition
I have a DB that has around 500 tables. I created two table variables to help me with deleting some data:

To store ProductID values (hundreds) from MainTable which are referenced inside 400 other tables in the same DB.

To store the names of all tables that contain ProductID column (referencing the MainTable table), so I can do "foreach" through that list.

Now, how do I tell SQL to delete all data from all the tables in the list that have ProductID from the list?

Now I need to delete all the records from MainTable, but first of course I need to delete all the data from all other tables that is referencing those ProductID values.

Is there a way to create a short query something like:

DELETE *
FROM A_LIST_OF_ALL_TABLES_THAT_CONTAIN_PRODUCTID_COLUMN
WHERE ProductID IN A_LIST_OF_ALL_PRODUCTIDs
```

答:
What i did in the past is to write a Query that generates the 400 Delete-Statements in a script, something like:

```<code>SELECT 'DELETE FROM ' !! TABLE_NAME !! ' WHERE PRODUCT_ID IN (SELECT PRODUCT_ID FROM PRODUCT_ID_TABLE);' FROM TABLE_WITH_TABLE_NAMES
</code>```

and then executed the script.

Body:
What i did in the past is to write a Query that generates the 400 Delete-Statements in a script, something like:

SELECT 'DELETE FROM ' !! TABLE_NAME !! ' WHERE PRODUCT_ID IN (SELECT PRODUCT_ID FROM PRODUCT_ID_TABLE);' FROM TABLE_WITH_TABLE_NAMES

and then executed the script.


问:
Navbar can't be shown
In my project after login, the Navbar has to change.

class App extends React.Component {
  render(){
        return(
          <BrowserRouter>

              {firebase.auth().onAuthStateChanged(user =>{
                if(user){
                  return(
                    <UserNavBar/>
                  )
                }else{
                  return(
                    <CommonNavBar/>
                  )
                }
              })}
              <Route path="/Home" component={Home}/>
              <Route path="/Photos" component={Photos}/>
              <Route path="/RegisterPage" component={RegisterPage}/>
              <Route path="/LoginPage" component={LoginPage}/>
              <Route path="/Account" component={Account}/>

          </BrowserRouter>
        )
    }
}

export default App```

But nothing is returned, I tried to debug it many times:

The system detects that the user is login

If I console log after the if it's work

答:
Make sure whenever you are doing Async operations in a component which is in your case a class component, do the same in componetDidMount(). then change the state of your component by using setState.

you can see the lifecycle of the react here: https://reactjs.org/docs/state-and-lifecycle.html

for eg:

```<code>class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      user: null
    }
  }
  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => user && this.setState({user}) )
  }
  render(){
    const { user } = this.state;
    return(
      <BrowserRouter>
        <div className="App">
          {user ? <UserNavBar/> : <CommonNavBar/>}
          <Route path="/Home" component={Home}/>
          <Route path="/Photos" component={Photos}/>
          <Route path="/RegisterPage" component={RegisterPage}/>
          <Route path="/LoginPage" component={LoginPage}/>
          <Route path="/Account" component={Account}/>
        </div>
      </BrowserRouter>
    )}
}

export default App

</code>```

or you can use hooks instead of class component.

Title: Navbar can't be shown

Body:
In my project after login, the Navbar has to change.

class App extends React.Component {
  render(){
        return(
          <BrowserRouter>

              {firebase.auth().onAuthStateChanged(user =>{
                if(user){
                  return(
                    <UserNavBar/>
                  )
                }else{
                  return(
                    <CommonNavBar/>
                  )
                }
              })}
              <Route path="/Home" component={Home}/>
              <Route path="/Photos" component={Photos}/>
              <Route path="/RegisterPage" component={RegisterPage}/>
              <Route path="/LoginPage" component={LoginPage}/>
              <Route path="/Account" component={Account}/>

          </BrowserRouter>
        )
    }
}

export default App

But nothing is returned, I tried to debug it many times:

The system detects that the user is login

If I console log after the if it's work

Body:
Make sure whenever you are doing Async operations in a component which is in your case a class component, do the same in componetDidMount(). then change the state of your component by using setState.

you can see the lifecycle of the react here: https://reactjs.org/docs/state-and-lifecycle.html

for eg:

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      user: null
    }
  }
  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => user && this.setState({user}) )
  }
  render(){
    const { user } = this.state;
    return(
      <BrowserRouter>
        <div className="App">
          {user ? <UserNavBar/> : <CommonNavBar/>}
          <Route path="/Home" component={Home}/>
          <Route path="/Photos" component={Photos}/>
          <Route path="/RegisterPage" component={RegisterPage}/>
          <Route path="/LoginPage" component={LoginPage}/>
          <Route path="/Account" component={Account}/>
        </div>
      </BrowserRouter>
    )}
}

export default App

or you can use hooks instead of class component.


问:
OpenOffice Calc can not read a simple CSV file. Why?
I have a Web site (PHP) that generates a CSV file (text/csv) with the following content:

```
ID;E-Mail_User;Name;Applikation;Rolle;Auftragsdatum;Administrator
522;user@domain;WXDUILAS;ABCD;XYZ;2009-03-04 05:00:09;user@domain
```

When I select OpenOffice to show the CSV file only an empty spread sheet is shown. No error is displayed. When I try to open the file with oocalc test.csv the same happens. I have tried different versions of OpenOffice.

What is wrong with the file? How can I get an error message out of OpenOffice?

Update:
It does not have anything to do with the use of semicolons. I have reduced the file to 4 charaters. A file with the contents ID;A opens the CSV import dialog. But a ID;E opens an empty sheet. Why?

Update 2:
The pattern id;E also works. ID;E must be some kind of magic code. Does anybody know the meaning?

答:
CSV means C omma S eparated V alues, which is not what your document contains.

Those are semicolons.

If possible, change the PHP code to generate this instead (which is actually CSV):

```<code>ID,E-Mail_User,Name,Applikation,Rolle,Auftragsdatum,Administrator
522,user@domain,WXDUILAS,ABCD,XYZ,2009-03-04 05:00:09,user@domain
</code>```

...or specify ; as the delimiter using the Text Import dialog.

Body:
I have a Web site (PHP) that generates a CSV file (text/csv) with the following content:

ID;E-Mail_User;Name;Applikation;Rolle;Auftragsdatum;Administrator
522;user@domain;WXDUILAS;ABCD;XYZ;2009-03-04 05:00:09;user@domain

When I select OpenOffice to show the CSV file only an empty spread sheet is shown. No error is displayed. When I try to open the file with oocalc test.csv the same happens. I have tried different versions of OpenOffice.

What is wrong with the file? How can I get an error message out of OpenOffice?

Update:
It does not have anything to do with the use of semicolons. I have reduced the file to 4 charaters. A file with the contents ID;A opens the CSV import dialog. But a ID;E opens an empty sheet. Why?

Update 2:
The pattern id;E also works. ID;E must be some kind of magic code. Does anybody know the meaning?

Body:
CSV means C omma S eparated V alues, which is not what your document contains.

Those are semicolons.

If possible, change the PHP code to generate this instead (which is actually CSV):

ID,E-Mail_User,Name,Applikation,Rolle,Auftragsdatum,Administrator
522,user@domain,WXDUILAS,ABCD,XYZ,2009-03-04 05:00:09,user@domain

...or specify ; as the delimiter using the Text Import dialog.


问:
Flat List - ScrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed
```<code>setTimeout(() => { this.myFlatList.scrollToIndex({animated:true , index: 100}) }, 100);
</code>```

If i use scrolltoindex in flat list return to me this error;

scrollToIndex should be used in conjunction with getItemLayout or
  onScrollToIndexFailed

I tried to use  getItemLayout but my flatlist items have different height, how can i fix this?

```<code>getItemLayout={(data, index) => (
                {length: 40, offset: 40 * index, index}
              )}
</code>```

答:
I had a similar error with a horizontal list showing images where the selected image should be shown in a carousel when pressed.

I solved it by setting the selected index on the FlatList by using initialScrollIndex. I also used onScrollToIndexFailed to scroll to the correct image for the times when initialScrollIndex failed to show the correct image.

This is done by setting a timeout for 500ms and then scroll to the selected image.

Complete example (with only the props regarding this error):

```<code>const flatList = useRef<FlatList>(null);

...

<FlatList
  ref={flatList}
  initialScrollIndex={props.activeIndex}
  onScrollToIndexFailed={info => {
    const wait = new Promise(resolve => setTimeout(resolve, 500));
    wait.then(() => {
      flatList.current?.scrollToIndex({ index: info.index, animated: true });
    });
  }}
/>
</code>```

Body:
setTimeout(() => { this.myFlatList.scrollToIndex({animated:true , index: 100}) }, 100);

If i use scrolltoindex in flat list return to me this error;

scrollToIndex should be used in conjunction with getItemLayout or
  onScrollToIndexFailed

I tried to use  getItemLayout but my flatlist items have different height, how can i fix this?

getItemLayout={(data, index) => (
                {length: 40, offset: 40 * index, index}
              )}

Body:
I had a similar error with a horizontal list showing images where the selected image should be shown in a carousel when pressed.

I solved it by setting the selected index on the FlatList by using initialScrollIndex. I also used onScrollToIndexFailed to scroll to the correct image for the times when initialScrollIndex failed to show the correct image.

This is done by setting a timeout for 500ms and then scroll to the selected image.

Complete example (with only the props regarding this error):

const flatList = useRef<FlatList>(null);

...

<FlatList
  ref={flatList}
  initialScrollIndex={props.activeIndex}
  onScrollToIndexFailed={info => {
    const wait = new Promise(resolve => setTimeout(resolve, 500));
    wait.then(() => {
      flatList.current?.scrollToIndex({ index: info.index, animated: true });
    });
  }}
/>


问:
Assign signer to specific signature form field
I'm evaluating DocuSign esignature API (c# SDK) for an e-signature solution.

Our scenario is easy:

single PDF

multiple signers

each signer has its own signature form field defined in the PDF

Is there a way to map specific signature form field inside PDF to specific signer?

What we already tried:

Anchor text is working but it is cumbersome for our clients to position anchor text, changed its color so it is invisible. Also it is error-prone

TransformPdfFields somewhat working but as I understand it is all or nothing it transforms all form fields and all signature fields are mapped to single signer (am I wrong here?)

Thanks.

答:
With DocuSign, each field (SignHere fields, text input fields, etc) is owned by a specific signer or other recipient type. Fields are called tabs in the API.

At a schematic level, the object hierarchy is:

There are multiple ways to map signHere tabs to different signers and locations in your documents:

Use a template. You or your business person can create a template using the DocuSign web tool. Then your app can use the template id to create and send an envelope.

The different signers are referred to as roles in the template. Eg customer signer 1, internal signer etc. Your app assigns specific names / emails to the roles when it creates the envelope.

Assign the tabs (fields) to signers using the API. The tabs can be positioned using absolute locations or via anchor strings.

Use an HTML document as your source documents. You can specify the tab locations in the HTML. See docs.

Use a PDF Form as your source document. If you name the form's fields consistently then you can use the DocuSign composite templates feature to have the form's fields belong to different recipients/signers. I do not recommend this approach if you have control over the source documents. But if you are give PDF Forms as your source documents, you can make use of them.


问:
ExitInstance not called in MFC app
Until now, I never really needed the Winapp ExitInstance() of a large MFC (Single Document Interface if it matters) app I'm working on. But now I do, mainly to cleanup memory alocations, unload some DLLs, etc. Well I soon learned by the obvious memory leaks and such that ExitInstance was not being called. Have I missed something obvious? Do I need to manually add something to the message map to make sure my ExitInstance override is called?

I guess i can do my cleanup elsewhere, but it's the best place if I can get it to run. Interestingly, I found quite a few instances of this by typing strings like "ExitInstance never called" and such into Google, and in no case were any real answers offered. The app normally closes when someone clicks the close box or the "Exit" from the File menu, and the OnClose() of the mainframe window certainly does always get called. I even tried forcing things by putting AfxGetMainWnd()->DestroyWindow(); in that mainframe OnClose() event, but still I can't get the ExitInstance() to actually run. Maybe it's just a big dummy function? Or maybe I'M just a big dummy? :-)

答:
I had a similar problem to you...mine was caused by mixing Unicode and MBCS built code....maybe that was your underlying cause?

I had to convert an MBCS application to Unicode, but it was impossible to convert the whole project, so I had to mix Unicode compiled (the application) and MBCS compiled code (the DLLs).

Some of the MBCS DLLs were MFC extension DLLs, others were regular DLLs.

One of the MFC extension DLLs contained resources (bitmap image list, and common dialogs).

I didn't convert the DLL to UNICODE because it had a lot of dependent DLLs which would also have had to be converted, and in addition I didn't need the controls in the common dialogs to support Unicode text.

So I kept the DLL as MBCS, and used AfxSetResourceHandle prior to using any class in the MBCS DLL that used resources.....this was to make the resources get pulled from the DLL directly, instead of through the MFC resource chain, because MFC couldn't find the non-unicode resources otherwise.

I guess MFC doesn't like it when you have a mix of Unicode and non-unicode compiled code containing resources.....lookups in the resource chain fail (I guess has something to do with the conversion of resource IDs to an ID string i.e. via MAKEINTRESOURCE).

I made the main application UNICODE, and made sure the C++ headers of classes in the MBCS DLLs used CStringA in the function prototypes, or accepted wide strings and did the conversion internally.

What I found was my application wouldn't exit properly...it would stay in the MFC CWinThread::PumpMessage/AfxInternalPumpMessage() call, and ExitInstance would never be called.

To solve it, in my CMainFrame::OnDestroy() I put the following as the last 2 statements:

```<code>void CMainFrame::OnDestroy()
{
    ....

    CFrameWnd::OnDestroy();

    AfxPostQuitMessage(0);
}
</code>```

Title: ExitInstance not called in MFC app

Body:
I had a similar problem to you...mine was caused by mixing Unicode and MBCS built code....maybe that was your underlying cause?

I had to convert an MBCS application to Unicode, but it was impossible to convert the whole project, so I had to mix Unicode compiled (the application) and MBCS compiled code (the DLLs).

Some of the MBCS DLLs were MFC extension DLLs, others were regular DLLs.

One of the MFC extension DLLs contained resources (bitmap image list, and common dialogs).

I didn't convert the DLL to UNICODE because it had a lot of dependent DLLs which would also have had to be converted, and in addition I didn't need the controls in the common dialogs to support Unicode text.

So I kept the DLL as MBCS, and used AfxSetResourceHandle prior to using any class in the MBCS DLL that used resources.....this was to make the resources get pulled from the DLL directly, instead of through the MFC resource chain, because MFC couldn't find the non-unicode resources otherwise.

I guess MFC doesn't like it when you have a mix of Unicode and non-unicode compiled code containing resources.....lookups in the resource chain fail (I guess has something to do with the conversion of resource IDs to an ID string i.e. via MAKEINTRESOURCE).

I made the main application UNICODE, and made sure the C++ headers of classes in the MBCS DLLs used CStringA in the function prototypes, or accepted wide strings and did the conversion internally.

What I found was my application wouldn't exit properly...it would stay in the MFC CWinThread::PumpMessage/AfxInternalPumpMessage() call, and ExitInstance would never be called.

To solve it, in my CMainFrame::OnDestroy() I put the following as the last 2 statements:

void CMainFrame::OnDestroy()
{
    ....

    CFrameWnd::OnDestroy();

    AfxPostQuitMessage(0);
}


问:
What is the problem in this recursive javascript function? [JS]
Hi to all I am trying to make a program in order to output when a number is Even using recursive calls. Can anybody please say me why it doesn't work as I expected?.</p>

```<code>const isEven = num => {
  if (num === 0) return true;
  else if (num === 1) return false;
  //console.log(num);
  isEven(num-2);
}

isEven(16); // Epected Log: 0 but instead it returns undefined
</code>```

答:
Because for arguments different than 0 or 1 there is no return value. The last line:

```<code>  isEven(num-2);
</code>```

should be

```<code>  return isEven(num-2);
</code>```

Body:
Hi to all I am trying to make a program in order to output when a number is Even using recursive calls. Can anybody please say me why it doesn't work as I expected?.

const isEven = num => {
  if (num === 0) return true;
  else if (num === 1) return false;
  //console.log(num);
  isEven(num-2);
}

isEven(16); // Epected Log: 0 but instead it returns undefined

Body:
Because for arguments different than 0 or 1 there is no return value. The last line:

  isEven(num-2);

should be

  return isEven(num-2);


答:
You are not returning a value.

Change:

```<code>isEven(num-2);
</code>```

To:

```<code>return isEven(num-2);
</code>```

Title: What is the problem in this recursive javascript function? [JS]

Body:
You are not returning a value.

Change:

isEven(num-2);

To:

return isEven(num-2);


问:
How to count function calls for unittesting?
I use my own small C# unittesting framework to test my code.

Sometimes I need the functionality to count how often a function of a fake object is called. Like this:

```<code>IDatabase fakeDb = new FakeDatabase();
IResult result = new Foo().ToTest(fakeDb);

//Some other tests

UTest.Equal(fakeDb.FakeCloseCalled(), 1);
</code>```

So at the moment my FakeDatabase-class looks like this:

```<code>class FakeDatabase : IDatabase
{
    //All the other code

    public int FakeCloseCalled
    {
        get;
        private set;
    }

    public void Close()
    {
        FakeCloseCalled++;
    }
}
</code>```

So, everytime I want to know how often a function of my fake objects was called I have to create a property for this in my FakeClass.

So I wonder if there is a more "generic" way to do this. e.g. profilers and some unittest-frameworks seem to be able to count the calls to functions.

So is there a more generic way to count the calls to Close without creating a property every time?

答:
You could use reflection to instantiate an instance of the IDatabase, and replace the objects methods with code that tracks thet calls using various methods described here:

I believe this is how Moq does it. Only reinvent when you want to learn.

Body:
I use my own small C# unittesting framework to test my code.

Sometimes I need the functionality to count how often a function of a fake object is called. Like this:

IDatabase fakeDb = new FakeDatabase();
IResult result = new Foo().ToTest(fakeDb);

//Some other tests

UTest.Equal(fakeDb.FakeCloseCalled(), 1);

So at the moment my FakeDatabase-class looks like this:

class FakeDatabase : IDatabase
{
    //All the other code

    public int FakeCloseCalled
    {
        get;
        private set;
    }

    public void Close()
    {
        FakeCloseCalled++;
    }
}

So, everytime I want to know how often a function of my fake objects was called I have to create a property for this in my FakeClass.

So I wonder if there is a more "generic" way to do this. e.g. profilers and some unittest-frameworks seem to be able to count the calls to functions.

So is there a more generic way to count the calls to Close without creating a property every time?


问:
can we use multiple plugins of flutter from one Repo?
I am stuck at this point where I have multiple plugins that I have implemented for my new flutter App.
But I want to place all these plugins in one repo and refer them as separate plugins

My plugins are

plugin_custom1

custom_plugin2

My repo is having the name flutter_plugins

If Link to my Repo is similar to the below one

https://maja.azure.com/ramraj/flutter_plugins

All the plugin folders are placed in this repo

I've tried to point to these packages similar to the following way in my Pubspec.yaml

```<code>plugin_custom1:
    git:
      url: https://maja.azure.com/ramraj/flutter_pluginspath=%2Fplugin_custom1
</code>```

Then I am facing the following error when getting packages

```<code>(OS Error: The filename, directory name, or volume label syntax is incorrect.
</code>```

Thanks in advance

答:
I have found an Answer

```<code>plugin_custom1:
    git:
      url: https://maja.azure.com/ramraj/flutter_plugins
      path:plugin_custom1
</code>```

Kindly refer to the following documentation of Flutter
https://flutter.dev/docs/development/packages-and-plugins/using-packages#dependencies-on-unpublished-packages

Body:
I am stuck at this point where I have multiple plugins that I have implemented for my new flutter App.
But I want to place all these plugins in one repo and refer them as separate plugins

My plugins are

plugin_custom1

custom_plugin2

My repo is having the name flutter_plugins

If Link to my Repo is similar to the below one

https://maja.azure.com/ramraj/flutter_plugins

All the plugin folders are placed in this repo

I've tried to point to these packages similar to the following way in my Pubspec.yaml

plugin_custom1:
    git:
      url: https://maja.azure.com/ramraj/flutter_pluginspath=%2Fplugin_custom1

Then I am facing the following error when getting packages

(OS Error: The filename, directory name, or volume label syntax is incorrect.

Thanks in advance

Body:
I have found an Answer

plugin_custom1:
    git:
      url: https://maja.azure.com/ramraj/flutter_plugins
      path:plugin_custom1

Kindly refer to the following documentation of Flutter
https://flutter.dev/docs/development/packages-and-plugins/using-packages#dependencies-on-unpublished-packages