问:
Dates are not converted in Unix Timestamp from C#
I have a method in which I call a method that performs a query returning an IEnumerable of objects, than I perform a group by Linq on this IEnumerable, and elaborate the result of the grouping to insert it in a JQGrid. The problem I'm having is that when the JQgrid is passed to the js file, the dates are not in the format /Date(milliseconds)/, but are formatted as a string, and I cannot localize them in the grid.
This is the call to method that performs the query, returning the IEnumerable object:

```<code>IEnumerable documentList = ObjBase.getAll(string.IsNullOrEmpty(columnList) ? null : columnList.Split(';'), sidx, sord, sqlWhere, out totalRows, userid: userId, siteId: siteId);
</code>```

This is the Group By Linq operation on these IEnumerable:

```<code>    var documentContact = documentList.GroupBy(c => new
    {
        c.CODE_CUSTOMERID,
        c.DESC_CONTACT_NUMBER,
        c.CODE_CUSTOMERTYPEID,
        c.CODE_CONTRACT_ID,
        c.DESC_CONTRACT_NUMBER,
        c.DESC_CONTRACT_STATES,
    })
    .Select(gcs => new DocumentContact()
    {
        CODE_CUSTOMER_ID = gcs.Key.CODE_CUSTOMERID,
        DESC_CONTACT_NUMBER = gcs.Key.DESC_CONTACT_NUMBER,
        CODE_CUSTOMERTYPEID = gcs.Key.CODE_CUSTOMERTYPEID,
        CODE_CONTRACT_ID = gcs.Key.CODE_CONTRACT_ID,
        DESC_CONTRACT_NUMBER = gcs.Key.DESC_CONTRACT_NUMBER,
        DESC_CONTRACT_STATES = gcs.Key.DESC_CONTRACT_STATES,
        CODE_SITEID = siteId,
        Documents = gcs.ToList(),
    });
</code>```

This is the class of objects that I have after the group by Linq:

```<code>public class DocumentContact : ObjBase
{
    public long? CODE_CUSTOMER_ID { get; set; }
    public long? CODE_CUSTOMERTYPEID { get; set; }
    public long? CODE_CONTRACT_ID { get; set; }
    public long CODE_SITEID { get; set; }
    public string DESC_CONTACT_NUMBER { get; set; }
    public string DESC_CONTRACT_NUMBER { get; set; }
    public string DESC_CONTRACT_STATES { get; set; }
    public List<DocumentModel> Documents { get; set; }
}
</code>```

This is the DocumentModel class:

```<code>public class DocumentModel : ObjBase
{
    private long _id;
    private string _documentModel;
    private long? _documentModelTypeId;
    private long? _documentModelIssuingEntityId;
    private string _documentModelFilename;
    private string _documentModelPath;
    private DateTime? _documentModelStart;
    private DateTime? _documentModelEnd;
    private string _documentModelVersion;
    private long _contractId;
    private string _contractNumber;
    private long _contractTypeId;
    private long _contractStateId;
    private string _contractState;
    private long _documentModelStateId;
    private string _documentModelValoId;
    private DateTime? _documentModelUploadDate;
    private byte[] _documentModelContent;
    private long _documentModelFilter;
    private bool _flagDeleted;
    private long _userId;
    private int _orderDocumentModel = 0;
    private string _placeOfIssue;
    private string _issuingEntity;
    private DateTime? _releaseDate;
    private int? _idOpInsert;
    private int? _idOpId;
    private long? _customerId;
    private long? _customerTypeId;
    private string _customerNumber;
    private DateTime? _documentModelInvalidated;
    private bool _flagValidating;
    private string _fileRemotePath;
    private long? _folderId;
    private string _folderName;
    protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
}
</code>```

What am I missing, or what can I do to localize correctly the dates, considering te the application is multilingual and the date formats are different for the various languages? Thanks

答:
This is the jqGrid setup: </p>

```<code>function initializeGridDocument(div_content, gridSelector, div_pager, div_empty) {

var gridId = gridSelector;
var pager_top = gridSelector + '_toppager';
var vl = loadCookieGroup();
jQuery(gridSelector).jqGrid("GridUnload");
jQuery(gridSelector).jqGrid({
    loadui: "block",
    mtype: 'POST',
    ajaxGridOptions: {
        contentType: 'application/json; charset=utf-8'
    },
    ajaxEditOptions: {
        contentType: 'application/json; charset=utf-8',
        datatype: "json"
    },
    ajaxRowOptions: {
        contentType: 'application/json; charset=utf-8'
    },
    datatype: "json",
    serializeGridData: function (postData) {
        if (postData.searchField === undefined) postData.searchField = null;
        if (postData.searchString === undefined) postData.searchString = null;
        if (postData.searchOper === undefined) postData.searchOper = null;
        if (postData.columnList === undefined) {
            postData.columnList = $.map($(gridSelector).jqGrid('getGridParam', 'colModel'), function (value, index) {
                if (value.fetched)
                    return value.index;
            }).join(';');
        }
        if ((postData.searchField != undefined) && (postData.searchField != "")) {
            if (postData.searchField.indexOf('DATE_') > -1) {
                if (postData.searchString.match(/Z$/) == null)
                    postData.searchString = mLoc2UTC(postData.searchString, 'L').toISOString();
            }
        }
        postData = $.extend(postData, {
            _search: true,
            userId: $('#hfCODE_USERID').val(),
            siteId: $('#ddl_site_Options').val(),
            stateId: $('#ddl_documentmodelState').val(),
            folderId: $('#chnfolder').val()
        });

        return JSON.stringify(postData);
    },
    url: 'GestioneDocument.aspx/getDocumentList',
    editurl: '',
    colNames: ['', '', '', '', '', '', t('label.customerprovider.contactnumber'), t('label.contractnumber'), t('label.contractsate'), t('label.actions')],//, t('label.documentid'), t('label.type'), t('label.documentstate'), '', t('label.folder'), t('label.filename'), t('label.uploaddate'), t('label.customerprovider.datedocumentmodelstart'), t('label.customerprovider.datedocumentmodelend'), '', t('label.actions')],
    colModel: [
    {
        name: 'CODE_CUSTOMER_ID',
        index: 'CODE_CUSTOMERID',
        jsonmap: 'OGGETTO.CODE_CUSTOMER_ID',
        sortable: false,
        hidden: true
    },
    {
        name: 'CODE_SITEID',
        index: 'CODE_SITEID',
        jsonmap: 'OGGETTO.CODE_SITEID',
        sortable: false,
        hidden: true
    },
    {
        name: 'CODE_CUSTOMERTYPEID',
        index: 'CODE_CUSTOMERTYPEID',
        jsonmap: 'OGGETTO.CODE_CUSTOMERTYPEID',
        sortable: false,
        hidden: true
        },

    {
        name: 'CODE_CONTRACT_ID',
        index: 'CODE_CONTRACT_ID',
        jsonmap: 'OGGETTO.CODE_CONTRACT_ID',
        sortable: false,
        hidden: true
    },
    {
        name: 'imgInfoRequester', label: '', jsonmap: 'OGGETTO.CODE_CUSTOMER_ID', width: 18, fixed: true, align: 'center', search: false, sortable: false,
        formatter: function (cellvalue, options, rowObject) {
            if (rowObject.OGGETTO.CODE_CUSTOMER_ID) {
                switch (rowObject.OGGETTO.CODE_CUSTOMERTYPEID)
                {
                    case 1:
                        return FormatterAccountGridSales(rowObject.OGGETTO.CODE_CUSTOMER_ID, options, rowObject);
                        break;
                    case 2:
                        return FormatterContactGridSales(rowObject.OGGETTO.CODE_CUSTOMER_ID, options, rowObject);
                        break;
                }
            }
        }
    },

    {
        name: 'imgInfor', label: '', jsonmap: 'OGGETTO.CODE_CONTRACT_ID', width: 18, fixed: true, align: 'center', search: false, sortable: false,
        formatter: function (cellvalue, options, rowObject) {
            if (rowObject.OGGETTO.CODE_CONTRACT_ID)
                return FormatterContractInfos(cellvalue, options, rowObject);
            return "";
        }
    },

    {
        name: 'DESC_CONTACT_NUMBER', label: t('label.customerprovider.contactnumber'), index: 'DESC_CONTACT_NUMBER',
        jsonmap: 'OGGETTO.DESC_CONTACT_NUMBER', sortable: true, width: 125, align: 'left', search: true, group: true, searchoptions: { sopt: ['eq', 'ne', 'cn'] }
    },
    { name: 'DESC_CONTRACT_NUMBER', label: t('label.contractnumber'), index: 'DESC_CONTRACT_NUMBER',
        jsonmap: 'OGGETTO.DESC_CONTRACT_NUMBER', sortable: true, width: 125, align: 'left', search: true, group: true, searchoptions: { sopt: ['eq', 'ne', 'cn'] }
    },
    {
        name: 'DESC_CONTRACT_STATES', label: t('label.contractsate'), index: 'DESC_CONTRACT_STATES',
        jsonmap: 'OGGETTO.DESC_CONTRACT_STATES', sortable: true, width: 125, align: 'left', search: false, group: true, formatter: 'formatTranslate'
    },

    {
        name: 'CODE_CUSTOMER_ID',
        jsonmap: 'OGGETTO.CODE_CUSTOMER_ID',
        formatter: function (cellvalue, options, rowObject) {
            $.extend(options, {
                idGridReload: gridSelector,
            });

            $.extend(rowObject.OGGETTO, {
                CODE_SITEID: $('#ddl_site_Options').val(),
            });
            return FormatterVerificationAction(cellvalue, options, rowObject);
        },
        sortable: false, search: false,
        width: 450
    }
    ],
    pager: $(div_pager),
    //sortname: "CODE_DOCUMENT_MODEL_ID",
    sortname: "DESC_CONTACT_NUMBER",
    sortable: true,
    sortorder: 'desc',
    shrinkToFit: true,
    rowNum: 25,
    rowList: [25, 50, 100, 200, 500],
    height: 500,
    viewrecords: true,
    caption: t('label.documents'),
    imgpath: '../JS/jqGrid/themes/basic/images',
    autowidth: true,
    forceFit: true,
    grouping: false,
    groupingView: false,
    multiselect: false,
    toppager: true,
    grouping: vl != 'clear' && vl != '',
    groupingView:
    {
        groupField: [vl],
        groupText: ['<b>{0}</b> <font color=\'blue\'>({1})</font>'],
        groupCollapse: false,
        groupOrder: ['asc'],
        groupDataSorted: true
    },
    footerrow: false,
    userDataOnFooter: false,
    autoencode: false,
    subGrid: hasPrivilegeWithoutAlerting('showdocumentincontract', $('#hfUSER_PRIVILEGES').val()),
    recreateFilter: true,
    jsonReader: {
        root: function (obj) {

            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");

            return d.rows;
        },
        repeatitems: false,
        page: function (obj) {
            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");
            return d.page;
        },
        total: function (obj) {
            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");
            return d.total;
        },
        records: function (obj) {
            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");

            return d.records;
        },
        cell: function (obj) {

            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");
            return d.OGGETTO;
        } //'OBJ'
    },
    ondblClickRow: function (rowid, iRow, iCol, e) { },
    beforeRequest: function () {
        var gridid = $(this).attr('id');
        $('#' + gridid + '_toppager_center').remove();
        $('#' + gridid + '_toppager_right').remove();
        return true;
    },
    gridComplete: function () {
        var grid = $(this), recs = grid.jqGrid('getGridParam', 'records');
        if (recs > 0) {
            $('#gbox_' + gridId).show();
            $(div_empty).hide();
        } else {
            $('#gbox_' + gridId).hide();
            $(div_empty).show();
        }

        resizeGrid(gridSelector);

        $(gridSelector + '_toppager_center').remove();
        $(gridSelector + '_toppager_right').remove();

        //NA: Chiudo il pannello della ricerca quando effettuo il Refresh della griglia
        jQuery('.ui-icon-refresh').click(function () {
            var searchIsOpen = $('#fbox_' + gridId).is(':visible');
            if (searchIsOpen) {
                $('#fbox_' + gridId + ' .ui-closer').click();
            }
        });

    },
    afterInsertRow: function (rowid, rowdata, rowelem) {
        var existDocument = rowelem.OGGETTO.Documents && rowelem.OGGETTO.Documents.length > 0 ? true : false;
        var contractUserData = {
            documentModelList: rowelem.OGGETTO.Documents
        };
        var userData = $(this).jqGrid('getGridParam', 'userData');
        if (!userData)
            userData = [];
        userData[rowid] = contractUserData;
        $(this).jqGrid('setGridParam', 'userData', userData);
        if (!existDocument) {
            $('#' + rowid).children("td.sgcollapsed").unbind().html("").removeClass("ui-sgcollapsed sgcollapsed");
        }
    },
    subGridRowExpanded: function (subgridId, rowid) {
        var dati = $(this).jqGrid('getGridParam', 'userData');
        if (dati && dati[rowid]) {
            recursiveDateConvert(dati, { onlyDateSet: ['DATE_DOCUMENT_MODEL_START', 'DATE_DOCUMENT_MODEL_END'] });
            var subgridTableId = subgridId + "_t";
            $("#" + subgridId).html("<table id='" + subgridTableId + "'></table>");
            $("#" + subgridTableId).jqGrid({
                datatype: "local",
                autowidth: true,
                shrinktofit: true,
                data: dati[rowid].documentModelList,
                colNames: ['', '', '', t('label.documentid'), t('label.type'), t('label.contractsate'), '', t('label.folder'), t('label.filename'), t('label.uploaddate'), t('label.customerprovider.datedocumentmodelstart'), t('label.customerprovider.datedocumentmodelend'), t('label.actions'), t('label.validate')],
                colModel: [{
                    name: 'CODE_DOCUMENT_MODEL_ID',
                    index: 'CODE_DOCUMENT_MODEL_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_ID',
                    sortable: false,
                    hidden: true
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_STATE_ID',
                    index: 'CODE_DOCUMENT_MODEL_STATE_ID',
                   // jsonmap: 'CODE_DOCUMENT_MODEL_STATE_ID',
                    sortable: false,
                    hidden: true
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_ID',
                    index: 'CODE_DOCUMENT_MODEL_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_ID',
                    sortable: false,
                    formatter: function (cellvalue, options, rowObject) {
                        return FormatterDocumentStateImg(cellvalue, options, rowObject);
                    },
                    width: 15,
                    fixed: true
                },
                {
                    name: 'VALO_DOCUMENT_MODEL_ID',
                    index: 'VALO_DOCUMENT_MODEL_ID',
                    //jsonmap: 'VALO_DOCUMENT_MODEL_ID',
                    sortable: true, group: true, label: t('label.documentid'), search: true, searchoptions: { sopt: ['eq', 'ne', 'cn'] }
                },
                {
                    name: 'documentModelType.DESC_DOCUMENT_MODEL_TYPE',
                    index: 'DESC_DOCUMENT_MODEL_TYPE',
                    //jsonmap: 'documentModelType.DESC_DOCUMENT_MODEL_TYPE',
                    sortable: true,
                    formatter: 'formatTranslate', search: false, group: true, label: t('label.type')
                },
                {
                    name: 'documentModelState.DESC_DOCUMENT_MODEL_STATE',
                    index: 'DESC_DOCUMENT_MODEL_STATE',
                    //jsonmap: 'documentModelState.DESC_DOCUMENT_MODEL_STATE', label: t('label.documentstate'),
                    formatter: 'formatTranslate', search: false,
                    stype: 'select', searchoptions: {
                        sopt: ['eq'],
                        value: "-1:All;1:Active;0:Inactive",

                    },
                    sortable: true, group: true
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_FOLDER_ID',
                    index: 'CODE_DOCUMENT_MODEL_FOLDER_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_FOLDER_ID',
                    sortable: false,
                    hidden: true
                },
                {
                    name: 'DocumentModelFolderName',
                    index: 'DocumentModelFolderName',
                    //jsonmap: 'DocumentModelFolderName', label: t('label.folder'),
                    formatter: function (cellvalue, options, rowObject) {
                        $.extend(options, {
                            idGridReload: gridSelector,
                        });

                        $.extend(rowObject.OGGETTO, {
                            CODE_SITEID: $('#ddl_site_Options').val(),
                        });
                        if (hasPrivilegeWithoutAlerting('updatefolderdocument', $('#hfUSER_PRIVILEGES').val())) {
                            return FormatterDocumentFolder(cellvalue, options, rowObject);
                        }
                        else
                            return (cellvalue !== "") ? cellvalue : t('label.notassignedto');
                    },
                    search: false,
                    stype: 'select', searchoptions: {
                        sopt: ['eq'],
                        value: "-1:All;1:Active;0:Inactive",

                    },
                    sortable: true, group: true
                },

                {
                    name: 'DESC_DOCUMENT_MODEL_FILENAME',
                    index: 'DESC_DOCUMENT_MODEL_FILENAME',
                    //jsonmap: 'DESC_DOCUMENT_MODEL_FILENAME',
                    sortable: true,
                    hidden: true, search: false
                },
                {
                    name: 'DATE_DOCUMENT_MODEL_UPLOAD',
                    index: 'DATE_DOCUMENT_MODEL_UPLOAD',
                    //jsonmap: 'DATE_DOCUMENT_MODEL_UPLOAD',
                    formatter: function (cellvalue, options, rowObject) { if (cellvalue != null) return dateUTCToUserTimeZoneLocale(cellvalue); else return ''; },
                    sortable: true, search: false, stype: 'text', searchoptions: {
                        sopt: ['lt', 'le', 'gt', 'ge'],
                        dataInit: function (elem) {
                            $(elem).datepicker({
                                duration: '',
                                constrainInput: true,
                                changeYear: true,
                                changeMonth: true
                            });

                        }
                    },
                    width: 200
                },
                {
                    name: 'DATE_DOCUMENT_MODEL_START',
                    index: 'DATE_DOCUMENT_MODEL_START',
                    //jsonmap: 'DATE_DOCUMENT_MODEL_START',
                    formatter: function (cellvalue, options, rowObject) { if (cellvalue != null) return moment.utc(dotnetDateToJSDate(cellvalue)).format('L'); else return ''; },
                    sortable: true, search: false,
                    width: 200
                },
                {
                    name: 'DATE_DOCUMENT_MODEL_END',
                    index: 'DATE_DOCUMENT_MODEL_END',
                    //jsonmap: 'DATE_DOCUMENT_MODEL_END',
                    formatter: function (cellvalue, options, rowObject) { if (cellvalue != null) return moment.utc(dotnetDateToJSDate(cellvalue)).format('L'); else return ''; },
                    sortable: true, search: false,
                    width: 200
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_ID',
                    formatter: function (cellvalue, options, rowObject) {
                        $.extend(options, {
                            idGridReload: gridSelector,
                        });

                        $.extend(rowObject.OGGETTO, {
                            CODE_SITEID: $('#ddl_site_Options').val(),
                        });
                        return FormatterDocumentAction(cellvalue, options, rowObject);
                    },
                    sortable: false, search: false,
                    width: 450
                },
                {
                    name: 'FLAG_VALIDATING',
                    index: 'FLAG_VALIDATING',
                    //jsonmap: 'FLAG_VALIDATING',
                    sortable: true,
                    hidden: true
                }],
                height: "100%",
                rowNum: 11,
                sortname: "name",
                idPrefix: "s_" + rowid + "_",
                beforeSelectRow: function (rowID, e) {
                    return false;
                }
            });
        }
    }
});

jQuery(gridSelector).jqGrid('navGrid', div_pager, { edit: false, add: false, del: false, search: true, refresh: true }, {}, {}, {}, { recreateFilter: true }, {}, {});
jQuery(gridSelector).jqGrid('navGrid',
    pager_top,
    {
        edit: false,
        add: false,
        del: false,
        search: true
    },
    {//search
        recreateFilter: true,
        beforeShowSearch: function(form) {
            $('.ui-reset', form).click(function() {
                //NA: Effettuo il Reset della ricerca azzerando i campi
                var gridSearchIsOpen = $('#fbox_gridDocument').is(':visible');
                if (gridSearchIsOpen) {
                    $('#fbox_gridCocument .ui-closer').click();
                    $('#search_gridDocument_top').click();
                }
            });
        }

    });

$(gridSelector).jqGrid('navButtonAdd', gridSelector + '_toppager', {
    caption: t('label.documentstate'), buttonicon: "ui-icon-document", title: t('label.documentstate'), cursor: 'pointer',
    onClickButton: function () {

        $('#dialogDocumentModelStates').dialog({
            bgiframe: true,
            autoOpen: true,
            width: 800,
            height: 400,
            modal: true,
            resizable: false,
            position: "top",
            zIndex: 3000,
            open: function () {
                loadGridDMS();
                updateElementI18N('dialogDocumentModelStates');
            },
            close: function () { },
            buttons: {
                'button.close': function () {
                    $(this).dialog('close');
                }
            }
        });
    }
});
</code>```

<p>}</p>

Body:
I have a method in which I call a method that performs a query returning an IEnumerable of objects, than I perform a group by Linq on this IEnumerable, and elaborate the result of the grouping to insert it in a JQGrid. The problem I'm having is that when the JQgrid is passed to the js file, the dates are not in the format /Date(milliseconds)/, but are formatted as a string, and I cannot localize them in the grid.
This is the call to method that performs the query, returning the IEnumerable object:

IEnumerable documentList = ObjBase.getAll(string.IsNullOrEmpty(columnList) ? null : columnList.Split(';'), sidx, sord, sqlWhere, out totalRows, userid: userId, siteId: siteId);

This is the Group By Linq operation on these IEnumerable:

    var documentContact = documentList.GroupBy(c => new
    {
        c.CODE_CUSTOMERID,
        c.DESC_CONTACT_NUMBER,
        c.CODE_CUSTOMERTYPEID,
        c.CODE_CONTRACT_ID,
        c.DESC_CONTRACT_NUMBER,
        c.DESC_CONTRACT_STATES,
    })
    .Select(gcs => new DocumentContact()
    {
        CODE_CUSTOMER_ID = gcs.Key.CODE_CUSTOMERID,
        DESC_CONTACT_NUMBER = gcs.Key.DESC_CONTACT_NUMBER,
        CODE_CUSTOMERTYPEID = gcs.Key.CODE_CUSTOMERTYPEID,
        CODE_CONTRACT_ID = gcs.Key.CODE_CONTRACT_ID,
        DESC_CONTRACT_NUMBER = gcs.Key.DESC_CONTRACT_NUMBER,
        DESC_CONTRACT_STATES = gcs.Key.DESC_CONTRACT_STATES,
        CODE_SITEID = siteId,
        Documents = gcs.ToList(),
    });

This is the class of objects that I have after the group by Linq:

public class DocumentContact : ObjBase
{
    public long? CODE_CUSTOMER_ID { get; set; }
    public long? CODE_CUSTOMERTYPEID { get; set; }
    public long? CODE_CONTRACT_ID { get; set; }
    public long CODE_SITEID { get; set; }
    public string DESC_CONTACT_NUMBER { get; set; }
    public string DESC_CONTRACT_NUMBER { get; set; }
    public string DESC_CONTRACT_STATES { get; set; }
    public List<DocumentModel> Documents { get; set; }
}

This is the DocumentModel class:

public class DocumentModel : ObjBase
{
    private long _id;
    private string _documentModel;
    private long? _documentModelTypeId;
    private long? _documentModelIssuingEntityId;
    private string _documentModelFilename;
    private string _documentModelPath;
    private DateTime? _documentModelStart;
    private DateTime? _documentModelEnd;
    private string _documentModelVersion;
    private long _contractId;
    private string _contractNumber;
    private long _contractTypeId;
    private long _contractStateId;
    private string _contractState;
    private long _documentModelStateId;
    private string _documentModelValoId;
    private DateTime? _documentModelUploadDate;
    private byte[] _documentModelContent;
    private long _documentModelFilter;
    private bool _flagDeleted;
    private long _userId;
    private int _orderDocumentModel = 0;
    private string _placeOfIssue;
    private string _issuingEntity;
    private DateTime? _releaseDate;
    private int? _idOpInsert;
    private int? _idOpId;
    private long? _customerId;
    private long? _customerTypeId;
    private string _customerNumber;
    private DateTime? _documentModelInvalidated;
    private bool _flagValidating;
    private string _fileRemotePath;
    private long? _folderId;
    private string _folderName;
    protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
}

What am I missing, or what can I do to localize correctly the dates, considering te the application is multilingual and the date formats are different for the various languages? Thanks

Body:
This is the jqGrid setup:

function initializeGridDocument(div_content, gridSelector, div_pager, div_empty) {

var gridId = gridSelector;
var pager_top = gridSelector + '_toppager';
var vl = loadCookieGroup();
jQuery(gridSelector).jqGrid("GridUnload");
jQuery(gridSelector).jqGrid({
    loadui: "block",
    mtype: 'POST',
    ajaxGridOptions: {
        contentType: 'application/json; charset=utf-8'
    },
    ajaxEditOptions: {
        contentType: 'application/json; charset=utf-8',
        datatype: "json"
    },
    ajaxRowOptions: {
        contentType: 'application/json; charset=utf-8'
    },
    datatype: "json",
    serializeGridData: function (postData) {
        if (postData.searchField === undefined) postData.searchField = null;
        if (postData.searchString === undefined) postData.searchString = null;
        if (postData.searchOper === undefined) postData.searchOper = null;
        if (postData.columnList === undefined) {
            postData.columnList = $.map($(gridSelector).jqGrid('getGridParam', 'colModel'), function (value, index) {
                if (value.fetched)
                    return value.index;
            }).join(';');
        }
        if ((postData.searchField != undefined) && (postData.searchField != "")) {
            if (postData.searchField.indexOf('DATE_') > -1) {
                if (postData.searchString.match(/Z$/) == null)
                    postData.searchString = mLoc2UTC(postData.searchString, 'L').toISOString();
            }
        }
        postData = $.extend(postData, {
            _search: true,
            userId: $('#hfCODE_USERID').val(),
            siteId: $('#ddl_site_Options').val(),
            stateId: $('#ddl_documentmodelState').val(),
            folderId: $('#chnfolder').val()
        });

        return JSON.stringify(postData);
    },
    url: 'GestioneDocument.aspx/getDocumentList',
    editurl: '',
    colNames: ['', '', '', '', '', '', t('label.customerprovider.contactnumber'), t('label.contractnumber'), t('label.contractsate'), t('label.actions')],//, t('label.documentid'), t('label.type'), t('label.documentstate'), '', t('label.folder'), t('label.filename'), t('label.uploaddate'), t('label.customerprovider.datedocumentmodelstart'), t('label.customerprovider.datedocumentmodelend'), '', t('label.actions')],
    colModel: [
    {
        name: 'CODE_CUSTOMER_ID',
        index: 'CODE_CUSTOMERID',
        jsonmap: 'OGGETTO.CODE_CUSTOMER_ID',
        sortable: false,
        hidden: true
    },
    {
        name: 'CODE_SITEID',
        index: 'CODE_SITEID',
        jsonmap: 'OGGETTO.CODE_SITEID',
        sortable: false,
        hidden: true
    },
    {
        name: 'CODE_CUSTOMERTYPEID',
        index: 'CODE_CUSTOMERTYPEID',
        jsonmap: 'OGGETTO.CODE_CUSTOMERTYPEID',
        sortable: false,
        hidden: true
        },

    {
        name: 'CODE_CONTRACT_ID',
        index: 'CODE_CONTRACT_ID',
        jsonmap: 'OGGETTO.CODE_CONTRACT_ID',
        sortable: false,
        hidden: true
    },
    {
        name: 'imgInfoRequester', label: '', jsonmap: 'OGGETTO.CODE_CUSTOMER_ID', width: 18, fixed: true, align: 'center', search: false, sortable: false,
        formatter: function (cellvalue, options, rowObject) {
            if (rowObject.OGGETTO.CODE_CUSTOMER_ID) {
                switch (rowObject.OGGETTO.CODE_CUSTOMERTYPEID)
                {
                    case 1:
                        return FormatterAccountGridSales(rowObject.OGGETTO.CODE_CUSTOMER_ID, options, rowObject);
                        break;
                    case 2:
                        return FormatterContactGridSales(rowObject.OGGETTO.CODE_CUSTOMER_ID, options, rowObject);
                        break;
                }
            }
        }
    },

    {
        name: 'imgInfor', label: '', jsonmap: 'OGGETTO.CODE_CONTRACT_ID', width: 18, fixed: true, align: 'center', search: false, sortable: false,
        formatter: function (cellvalue, options, rowObject) {
            if (rowObject.OGGETTO.CODE_CONTRACT_ID)
                return FormatterContractInfos(cellvalue, options, rowObject);
            return "";
        }
    },

    {
        name: 'DESC_CONTACT_NUMBER', label: t('label.customerprovider.contactnumber'), index: 'DESC_CONTACT_NUMBER',
        jsonmap: 'OGGETTO.DESC_CONTACT_NUMBER', sortable: true, width: 125, align: 'left', search: true, group: true, searchoptions: { sopt: ['eq', 'ne', 'cn'] }
    },
    { name: 'DESC_CONTRACT_NUMBER', label: t('label.contractnumber'), index: 'DESC_CONTRACT_NUMBER',
        jsonmap: 'OGGETTO.DESC_CONTRACT_NUMBER', sortable: true, width: 125, align: 'left', search: true, group: true, searchoptions: { sopt: ['eq', 'ne', 'cn'] }
    },
    {
        name: 'DESC_CONTRACT_STATES', label: t('label.contractsate'), index: 'DESC_CONTRACT_STATES',
        jsonmap: 'OGGETTO.DESC_CONTRACT_STATES', sortable: true, width: 125, align: 'left', search: false, group: true, formatter: 'formatTranslate'
    },

    {
        name: 'CODE_CUSTOMER_ID',
        jsonmap: 'OGGETTO.CODE_CUSTOMER_ID',
        formatter: function (cellvalue, options, rowObject) {
            $.extend(options, {
                idGridReload: gridSelector,
            });

            $.extend(rowObject.OGGETTO, {
                CODE_SITEID: $('#ddl_site_Options').val(),
            });
            return FormatterVerificationAction(cellvalue, options, rowObject);
        },
        sortable: false, search: false,
        width: 450
    }
    ],
    pager: $(div_pager),
    //sortname: "CODE_DOCUMENT_MODEL_ID",
    sortname: "DESC_CONTACT_NUMBER",
    sortable: true,
    sortorder: 'desc',
    shrinkToFit: true,
    rowNum: 25,
    rowList: [25, 50, 100, 200, 500],
    height: 500,
    viewrecords: true,
    caption: t('label.documents'),
    imgpath: '../JS/jqGrid/themes/basic/images',
    autowidth: true,
    forceFit: true,
    grouping: false,
    groupingView: false,
    multiselect: false,
    toppager: true,
    grouping: vl != 'clear' && vl != '',
    groupingView:
    {
        groupField: [vl],
        groupText: ['<b>{0}</b>&nbsp;<font color=\'blue\'>({1})</font>'],
        groupCollapse: false,
        groupOrder: ['asc'],
        groupDataSorted: true
    },
    footerrow: false,
    userDataOnFooter: false,
    autoencode: false,
    subGrid: hasPrivilegeWithoutAlerting('showdocumentincontract', $('#hfUSER_PRIVILEGES').val()),
    recreateFilter: true,
    jsonReader: {
        root: function (obj) {

            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");

            return d.rows;
        },
        repeatitems: false,
        page: function (obj) {
            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");
            return d.page;
        },
        total: function (obj) {
            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");
            return d.total;
        },
        records: function (obj) {
            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");

            return d.records;
        },
        cell: function (obj) {

            if (obj.d != undefined) obj = obj.d;
            var d = null;
            if (typeof (obj) == "object")
                d = obj;
            else
                d = eval("(" + obj + ")");
            return d.OGGETTO;
        } //'OBJ'
    },
    ondblClickRow: function (rowid, iRow, iCol, e) { },
    beforeRequest: function () {
        var gridid = $(this).attr('id');
        $('#' + gridid + '_toppager_center').remove();
        $('#' + gridid + '_toppager_right').remove();
        return true;
    },
    gridComplete: function () {
        var grid = $(this), recs = grid.jqGrid('getGridParam', 'records');
        if (recs > 0) {
            $('#gbox_' + gridId).show();
            $(div_empty).hide();
        } else {
            $('#gbox_' + gridId).hide();
            $(div_empty).show();
        }

        resizeGrid(gridSelector);

        $(gridSelector + '_toppager_center').remove();
        $(gridSelector + '_toppager_right').remove();

        //NA: Chiudo il pannello della ricerca quando effettuo il Refresh della griglia
        jQuery('.ui-icon-refresh').click(function () {
            var searchIsOpen = $('#fbox_' + gridId).is(':visible');
            if (searchIsOpen) {
                $('#fbox_' + gridId + ' .ui-closer').click();
            }
        });

    },
    afterInsertRow: function (rowid, rowdata, rowelem) {
        var existDocument = rowelem.OGGETTO.Documents && rowelem.OGGETTO.Documents.length > 0 ? true : false;
        var contractUserData = {
            documentModelList: rowelem.OGGETTO.Documents
        };
        var userData = $(this).jqGrid('getGridParam', 'userData');
        if (!userData)
            userData = [];
        userData[rowid] = contractUserData;
        $(this).jqGrid('setGridParam', 'userData', userData);
        if (!existDocument) {
            $('#' + rowid).children("td.sgcollapsed").unbind().html("").removeClass("ui-sgcollapsed sgcollapsed");
        }
    },
    subGridRowExpanded: function (subgridId, rowid) {
        var dati = $(this).jqGrid('getGridParam', 'userData');
        if (dati && dati[rowid]) {
            recursiveDateConvert(dati, { onlyDateSet: ['DATE_DOCUMENT_MODEL_START', 'DATE_DOCUMENT_MODEL_END'] });
            var subgridTableId = subgridId + "_t";
            $("#" + subgridId).html("<table id='" + subgridTableId + "'></table>");
            $("#" + subgridTableId).jqGrid({
                datatype: "local",
                autowidth: true,
                shrinktofit: true,
                data: dati[rowid].documentModelList,
                colNames: ['', '', '', t('label.documentid'), t('label.type'), t('label.contractsate'), '', t('label.folder'), t('label.filename'), t('label.uploaddate'), t('label.customerprovider.datedocumentmodelstart'), t('label.customerprovider.datedocumentmodelend'), t('label.actions'), t('label.validate')],
                colModel: [{
                    name: 'CODE_DOCUMENT_MODEL_ID',
                    index: 'CODE_DOCUMENT_MODEL_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_ID',
                    sortable: false,
                    hidden: true
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_STATE_ID',
                    index: 'CODE_DOCUMENT_MODEL_STATE_ID',
                   // jsonmap: 'CODE_DOCUMENT_MODEL_STATE_ID',
                    sortable: false,
                    hidden: true
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_ID',
                    index: 'CODE_DOCUMENT_MODEL_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_ID',
                    sortable: false,
                    formatter: function (cellvalue, options, rowObject) {
                        return FormatterDocumentStateImg(cellvalue, options, rowObject);
                    },
                    width: 15,
                    fixed: true
                },
                {
                    name: 'VALO_DOCUMENT_MODEL_ID',
                    index: 'VALO_DOCUMENT_MODEL_ID',
                    //jsonmap: 'VALO_DOCUMENT_MODEL_ID',
                    sortable: true, group: true, label: t('label.documentid'), search: true, searchoptions: { sopt: ['eq', 'ne', 'cn'] }
                },
                {
                    name: 'documentModelType.DESC_DOCUMENT_MODEL_TYPE',
                    index: 'DESC_DOCUMENT_MODEL_TYPE',
                    //jsonmap: 'documentModelType.DESC_DOCUMENT_MODEL_TYPE',
                    sortable: true,
                    formatter: 'formatTranslate', search: false, group: true, label: t('label.type')
                },
                {
                    name: 'documentModelState.DESC_DOCUMENT_MODEL_STATE',
                    index: 'DESC_DOCUMENT_MODEL_STATE',
                    //jsonmap: 'documentModelState.DESC_DOCUMENT_MODEL_STATE', label: t('label.documentstate'),
                    formatter: 'formatTranslate', search: false,
                    stype: 'select', searchoptions: {
                        sopt: ['eq'],
                        value: "-1:All;1:Active;0:Inactive",

                    },
                    sortable: true, group: true
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_FOLDER_ID',
                    index: 'CODE_DOCUMENT_MODEL_FOLDER_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_FOLDER_ID',
                    sortable: false,
                    hidden: true
                },
                {
                    name: 'DocumentModelFolderName',
                    index: 'DocumentModelFolderName',
                    //jsonmap: 'DocumentModelFolderName', label: t('label.folder'),
                    formatter: function (cellvalue, options, rowObject) {
                        $.extend(options, {
                            idGridReload: gridSelector,
                        });

                        $.extend(rowObject.OGGETTO, {
                            CODE_SITEID: $('#ddl_site_Options').val(),
                        });
                        if (hasPrivilegeWithoutAlerting('updatefolderdocument', $('#hfUSER_PRIVILEGES').val())) {
                            return FormatterDocumentFolder(cellvalue, options, rowObject);
                        }
                        else
                            return (cellvalue !== "") ? cellvalue : t('label.notassignedto');
                    },
                    search: false,
                    stype: 'select', searchoptions: {
                        sopt: ['eq'],
                        value: "-1:All;1:Active;0:Inactive",

                    },
                    sortable: true, group: true
                },

                {
                    name: 'DESC_DOCUMENT_MODEL_FILENAME',
                    index: 'DESC_DOCUMENT_MODEL_FILENAME',
                    //jsonmap: 'DESC_DOCUMENT_MODEL_FILENAME',
                    sortable: true,
                    hidden: true, search: false
                },
                {
                    name: 'DATE_DOCUMENT_MODEL_UPLOAD',
                    index: 'DATE_DOCUMENT_MODEL_UPLOAD',
                    //jsonmap: 'DATE_DOCUMENT_MODEL_UPLOAD',
                    formatter: function (cellvalue, options, rowObject) { if (cellvalue != null) return dateUTCToUserTimeZoneLocale(cellvalue); else return ''; },
                    sortable: true, search: false, stype: 'text', searchoptions: {
                        sopt: ['lt', 'le', 'gt', 'ge'],
                        dataInit: function (elem) {
                            $(elem).datepicker({
                                duration: '',
                                constrainInput: true,
                                changeYear: true,
                                changeMonth: true
                            });

                        }
                    },
                    width: 200
                },
                {
                    name: 'DATE_DOCUMENT_MODEL_START',
                    index: 'DATE_DOCUMENT_MODEL_START',
                    //jsonmap: 'DATE_DOCUMENT_MODEL_START',
                    formatter: function (cellvalue, options, rowObject) { if (cellvalue != null) return moment.utc(dotnetDateToJSDate(cellvalue)).format('L'); else return ''; },
                    sortable: true, search: false,
                    width: 200
                },
                {
                    name: 'DATE_DOCUMENT_MODEL_END',
                    index: 'DATE_DOCUMENT_MODEL_END',
                    //jsonmap: 'DATE_DOCUMENT_MODEL_END',
                    formatter: function (cellvalue, options, rowObject) { if (cellvalue != null) return moment.utc(dotnetDateToJSDate(cellvalue)).format('L'); else return ''; },
                    sortable: true, search: false,
                    width: 200
                },
                {
                    name: 'CODE_DOCUMENT_MODEL_ID',
                    //jsonmap: 'CODE_DOCUMENT_MODEL_ID',
                    formatter: function (cellvalue, options, rowObject) {
                        $.extend(options, {
                            idGridReload: gridSelector,
                        });

                        $.extend(rowObject.OGGETTO, {
                            CODE_SITEID: $('#ddl_site_Options').val(),
                        });
                        return FormatterDocumentAction(cellvalue, options, rowObject);
                    },
                    sortable: false, search: false,
                    width: 450
                },
                {
                    name: 'FLAG_VALIDATING',
                    index: 'FLAG_VALIDATING',
                    //jsonmap: 'FLAG_VALIDATING',
                    sortable: true,
                    hidden: true
                }],
                height: "100%",
                rowNum: 11,
                sortname: "name",
                idPrefix: "s_" + rowid + "_",
                beforeSelectRow: function (rowID, e) {
                    return false;
                }
            });
        }
    }
});

jQuery(gridSelector).jqGrid('navGrid', div_pager, { edit: false, add: false, del: false, search: true, refresh: true }, {}, {}, {}, { recreateFilter: true }, {}, {});
jQuery(gridSelector).jqGrid('navGrid',
    pager_top,
    {
        edit: false,
        add: false,
        del: false,
        search: true
    },
    {//search
        recreateFilter: true,
        beforeShowSearch: function(form) {
            $('.ui-reset', form).click(function() {
                //NA: Effettuo il Reset della ricerca azzerando i campi
                var gridSearchIsOpen = $('#fbox_gridDocument').is(':visible');
                if (gridSearchIsOpen) {
                    $('#fbox_gridCocument .ui-closer').click();
                    $('#search_gridDocument_top').click();
                }
            });
        }

    });

$(gridSelector).jqGrid('navButtonAdd', gridSelector + '_toppager', {
    caption: t('label.documentstate'), buttonicon: "ui-icon-document", title: t('label.documentstate'), cursor: 'pointer',
    onClickButton: function () {

        $('#dialogDocumentModelStates').dialog({
            bgiframe: true,
            autoOpen: true,
            width: 800,
            height: 400,
            modal: true,
            resizable: false,
            position: "top",
            zIndex: 3000,
            open: function () {
                loadGridDMS();
                updateElementI18N('dialogDocumentModelStates');
            },
            close: function () { },
            buttons: {
                'button.close': function () {
                    $(this).dialog('close');
                }
            }
        });
    }
});

}


来源: stackexchange

问:
Err: cannot use c.Param("id") (type string) as type int in argument to services.GetCharactersID
Following code has the err:

Error:

controllers/controllers.go:80:53: cannot use c.Param(id) (type string) as type int in argument to services.GetCharactersID controllers/controllers.go:80:54: undefined: id)

```<code>func GetCharactersID (c *gin.Context) {
    characters, err := services.GetCharactersID(c.Param("id"))
    if err!=nil {
        response:= domain.Response{Mensaje:err.Error()}
        c.JSON(http.StatusInternalServerError,response)
        return
    }
    c.JSON (http.StatusOK,characters)
}
//Services

func GetCharactersID (id int) (domain.Characters,error) {
    var err error
    characterss,err := GetCharactersID(id)
    s := strconv.Itoa(id)
    ts := "my_hashjavi"
    hash := GetHashString(ts+private_key+public_key)
    var url string = "https://gateway.marvel.com:443/v1/public"
    url += "/characters" + "/"
    url+= s + "?"
    url += "ts="+ts
    url += "&apikey="+ public_key
    url += "&hash="+ hash
    resp,err1 := http.Get(url)
    Data, err2 := ioutil.ReadAll(resp.Body)

    if err1 != nil || err2 != nil {
        err= errors.New("Error al obtener los personajes")
        return characterss,err
    }
    json.Unmarshal(Data,&characterss)
    return characterss , nil

}
</code>```

答:
I dont have your full code, but I refactor it and apply your fix about id is not a int</p>

```<code>func GetCharactersID(c *gin.Context) {
    characters, err := services.GetCharactersID(c.Param("id"))
    if err != nil {
        response := domain.Response{Mensaje: err.Error()}
        c.JSON(http.StatusInternalServerError, response)
        return
    }
    c.JSON(http.StatusOK, characters)
}

func GetCharactersID(sID string) (domain.Characters, error) {
    base := "https://gateway.marvel.com:443/v1/public"
    ts := "my_hashjavi"
    id, err := strconv.Atoi(sID)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    characterss, err := GetCharactersID(sID)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    hash := GetHashString(ts + private_key + public_key)
    url := fmt.Sprint("%s/characters/%d?ts=%s&apikey=%s&hash=%s",
        base, sID, ts, public_key, hash)

    resp, err := http.Get(url)
    if err != nil
        return characterss, errors.New("xxx...")
    }

    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    err = json.Unmarshal(data, &characterss)
    if err != nil {
        return characterss, err
    }

    return characterss, errors.New("xxx...")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Following code has the err:

Error:

controllers/controllers.go:80:53: cannot use c.Param(id) (type string) as type int in argument to services.GetCharactersID controllers/controllers.go:80:54: undefined: id)

func GetCharactersID (c *gin.Context) {
    characters, err := services.GetCharactersID(c.Param("id"))
    if err!=nil {
        response:= domain.Response{Mensaje:err.Error()}
        c.JSON(http.StatusInternalServerError,response)
        return
    }
    c.JSON (http.StatusOK,characters)
}
//Services

func GetCharactersID (id int) (domain.Characters,error) {
    var err error
    characterss,err := GetCharactersID(id)
    s := strconv.Itoa(id)
    ts := "my_hashjavi"
    hash := GetHashString(ts+private_key+public_key)
    var url string = "https://gateway.marvel.com:443/v1/public"
    url += "/characters" + "/"
    url+= s + "?"
    url += "ts="+ts
    url += "&apikey="+ public_key
    url += "&hash="+ hash
    resp,err1 := http.Get(url)
    Data, err2 := ioutil.ReadAll(resp.Body)

    if err1 != nil || err2 != nil {
        err= errors.New("Error al obtener los personajes")
        return characterss,err
    }
    json.Unmarshal(Data,&characterss)
    return characterss , nil

}

Body:
I dont have your full code, but I refactor it and apply your fix about id is not a int

func GetCharactersID(c *gin.Context) {
    characters, err := services.GetCharactersID(c.Param("id"))
    if err != nil {
        response := domain.Response{Mensaje: err.Error()}
        c.JSON(http.StatusInternalServerError, response)
        return
    }
    c.JSON(http.StatusOK, characters)
}

func GetCharactersID(sID string) (domain.Characters, error) {
    base := "https://gateway.marvel.com:443/v1/public"
    ts := "my_hashjavi"
    id, err := strconv.Atoi(sID)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    characterss, err := GetCharactersID(sID)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    hash := GetHashString(ts + private_key + public_key)
    url := fmt.Sprint("%s/characters/%d?ts=%s&apikey=%s&hash=%s",
        base, sID, ts, public_key, hash)

    resp, err := http.Get(url)
    if err != nil
        return characterss, errors.New("xxx...")
    }

    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    err = json.Unmarshal(data, &characterss)
    if err != nil {
        return characterss, err
    }

    return characterss, errors.New("xxx...")
}


问:
Ansible output extract package version using jq
I have below json output from ansible, I want to parse this file using jq.  I want to match packages name GeoIP and print version number.

How can I use jq to get this version number for matching package name? looking output like this

```<code>"GeoIP","1.5.0"
</code>```

sample ansible output

```<code>{
    "ansible_facts.packages": {
        "GConf2": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GConf2",
                "release": "8.el7",
                "source": "rpm",
                "version": "3.2.6"
            }
        ],
        "GeoIP": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GeoIP",
                "release": "14.el7",
                "source": "rpm",
                "version": "1.5.0"
            }
        ],
        "ImageMagick": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "ImageMagick",
                "release": "18.el7",
                "source": "rpm",
                "version": "6.7.8.9"
            }
        ],
    }
}
</code>```

答:
Q: "How can I use jq to get the version number for matching package name?"

A: Try the script below

```<code>$ cat print-version.sh
#!/bin/sh
cat output.json | jq ".ansible_facts.packages.$1 | .[].version"
</code>```

For example

```<code>$ print-version.sh GeoIP
"1.5.0"
</code>```

Improved version of the script

Quoting the comment: "Using the shell's string interpolation as done here is risky and generally regarded as an "anti-pattern". – peak"

The improved script below does the job

```<code>$ cat print-version.sh
#!/bin/sh
cat output.json | jq ".ansible_facts.packages.$1[].version"
</code>```

output.json

```<code>{
    "ansible_facts": {
        "packages": {
            "GConf2": [
                {
                    "arch": "x86_64",
                    "epoch": null,
                    "name": "GConf2",
                    "release": "8.el7",
                    "source": "rpm",
                    "version": "3.2.6"
                }
            ],
            "GeoIP": [
                {
                    "arch": "x86_64",
                    "epoch": null,
                    "name": "GeoIP",
                    "release": "14.el7",
                    "source": "rpm",
                    "version": "1.5.0"
                }
            ],
            "ImageMagick": [
                {
                    "arch": "x86_64",
                    "epoch": null,
                    "name": "ImageMagick",
                    "release": "18.el7",
                    "source": "rpm",
                    "version": "6.7.8.9"
                }
            ]
        }
    }
}
</code>```

Body:
I have below json output from ansible, I want to parse this file using jq.  I want to match packages name GeoIP and print version number.

How can I use jq to get this version number for matching package name? looking output like this

"GeoIP","1.5.0"

sample ansible output

{
    "ansible_facts.packages": {
        "GConf2": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GConf2",
                "release": "8.el7",
                "source": "rpm",
                "version": "3.2.6"
            }
        ],
        "GeoIP": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "GeoIP",
                "release": "14.el7",
                "source": "rpm",
                "version": "1.5.0"
            }
        ],
        "ImageMagick": [
            {
                "arch": "x86_64",
                "epoch": null,
                "name": "ImageMagick",
                "release": "18.el7",
                "source": "rpm",
                "version": "6.7.8.9"
            }
        ],
    }
}

Body:
Q: "How can I use jq to get the version number for matching package name?"

A: Try the script below

$ cat print-version.sh
#!/bin/sh
cat output.json | jq ".ansible_facts.packages.$1 | .[].version"

For example

$ print-version.sh GeoIP
"1.5.0"

Improved version of the script

Quoting the comment: "Using the shell's string interpolation as done here is risky and generally regarded as an "anti-pattern". – peak"

The improved script below does the job

$ cat print-version.sh
#!/bin/sh
cat output.json | jq ".ansible_facts.packages.$1[].version"

output.json

{
    "ansible_facts": {
        "packages": {
            "GConf2": [
                {
                    "arch": "x86_64",
                    "epoch": null,
                    "name": "GConf2",
                    "release": "8.el7",
                    "source": "rpm",
                    "version": "3.2.6"
                }
            ],
            "GeoIP": [
                {
                    "arch": "x86_64",
                    "epoch": null,
                    "name": "GeoIP",
                    "release": "14.el7",
                    "source": "rpm",
                    "version": "1.5.0"
                }
            ],
            "ImageMagick": [
                {
                    "arch": "x86_64",
                    "epoch": null,
                    "name": "ImageMagick",
                    "release": "18.el7",
                    "source": "rpm",
                    "version": "6.7.8.9"
                }
            ]
        }
    }
}


问:
c# linq: how to retrieve pieces of data from a returned record
So i have the query:

```<code> var query =
                from product in db.LUT_ProductInfos
                where product.flavor == flavor && product.Container == container
                select flavor;
</code>```

which is returning 1 record (it should always return one record). How do i pull individual attribute values from the result? For example, if it returns 1 record with 3 columns like firstName lastName phoneNumber, and i want to do something with each of the values like

```<code>string fName = firstName
string lName = lastName
int pNumber = phoneNumber
</code>```

without getting into data mapping for objects, what is the most direct way to extract those values from the result variable query

答:
```<code>var query =
            from product in db.LUT_ProductInfos
            where product.flavor == flavor && product.Container == container
            select new {product.Foo, product.flavor.Bar, ...};

var row = query.First(); // or Single(), FirstOrDefault(), SingleOrDefault()

string foo = row.Foo;
int bar = row.Bar;
...
</code>```

This has the advantage that only the desired properties are included in the SELECT statement, and there are no hidden additional round-trips (lazy loading).

ContentLicense: CC BY-SA 3.0

Body:
So i have the query:

 var query =
                from product in db.LUT_ProductInfos
                where product.flavor == flavor && product.Container == container
                select flavor;

which is returning 1 record (it should always return one record). How do i pull individual attribute values from the result? For example, if it returns 1 record with 3 columns like firstName lastName phoneNumber, and i want to do something with each of the values like

string fName = firstName
string lName = lastName
int pNumber = phoneNumber

without getting into data mapping for objects, what is the most direct way to extract those values from the result variable query

Body:
var query =
            from product in db.LUT_ProductInfos
            where product.flavor == flavor && product.Container == container
            select new {product.Foo, product.flavor.Bar, ...};

var row = query.First(); // or Single(), FirstOrDefault(), SingleOrDefault()

string foo = row.Foo;
int bar = row.Bar;
...

This has the advantage that only the desired properties are included in the SELECT statement, and there are no hidden additional round-trips (lazy loading).


问:
Putting Debug.log as a GUI element in unity
My program currently displays text in the console.

I want this text to be displayed in the game window.

The data is part of a web request.

Is there a simple way of displaying what appears in the console as a GUI element?

答:
Yes you can simply add a callback to e.g. Application.logMessageReceivedThreaded

Example from the API extended with OnGUI script from this thread

```<code>// Put this on any GameObject in the scene
public class ExampleClass : MonoBehaviour
{
    // Adjust via the Inspector
    public int maxLines = 8;
    private Queue<string> queue = new Queue<string>();
    private string currentText = "";

    void OnEnable()
    {
        Application.logMessageReceivedThreaded += HandleLog;
    }

    void OnDisable()
    {
        Application.logMessageReceivedThreaded -= HandleLog;
    }

    void HandleLog(string logString, string stackTrace, LogType type)
    {
        // Delete oldest message
        if (queue.Count >= maxLines) queue.Dequeue();

        queue.Enqueue(logString);

        var builder = new StringBuilder();
        foreach (string st in queue)
        {
            builder.Append(st).Append("\n");
        }

        currentText = builder.ToString();
    }

    void OnGUI()
    {
        GUI.Label(
           new Rect(
               5,                   // x, left offset
               Screen.height - 150, // y, bottom offset
               300f,                // width
               150f                 // height
           ),
           currentText,             // the display text
           GUI.skin.textArea        // use a multi-line text area
        );
    }
}
</code>```

In general: OnGUI is kind of legacy and you should really only use this for debugging.

But you can basically use the same script also for e.g. a UI.Text component and instead of using OnGUI assign the text to it.

The script would basically look the same but have a

```<code>public Text text;
</code>```

and instead of OnGUI would directly do

```<code>text.text = builder.ToString();
</code>```

Body:
Yes you can simply add a callback to e.g. Application.logMessageReceivedThreaded

Example from the API extended with OnGUI script from this thread

// Put this on any GameObject in the scene
public class ExampleClass : MonoBehaviour
{
    // Adjust via the Inspector
    public int maxLines = 8;
    private Queue<string> queue = new Queue<string>();
    private string currentText = "";

    void OnEnable()
    {
        Application.logMessageReceivedThreaded += HandleLog;
    }

    void OnDisable()
    {
        Application.logMessageReceivedThreaded -= HandleLog;
    }

    void HandleLog(string logString, string stackTrace, LogType type)
    {
        // Delete oldest message
        if (queue.Count >= maxLines) queue.Dequeue();

        queue.Enqueue(logString);

        var builder = new StringBuilder();
        foreach (string st in queue)
        {
            builder.Append(st).Append("\n");
        }

        currentText = builder.ToString();
    }

    void OnGUI()
    {
        GUI.Label(
           new Rect(
               5,                   // x, left offset
               Screen.height - 150, // y, bottom offset
               300f,                // width
               150f                 // height
           ),
           currentText,             // the display text
           GUI.skin.textArea        // use a multi-line text area
        );
    }
}

In general: OnGUI is kind of legacy and you should really only use this for debugging.

But you can basically use the same script also for e.g. a UI.Text component and instead of using OnGUI assign the text to it.

The script would basically look the same but have a

public Text text;

and instead of OnGUI would directly do

text.text = builder.ToString();


问:
Union – useless anachronism or useful old school trick?
I recently came across a great data structures book,"Data Structures Using C" (c) 1991, at a local Library book sale for only $2. As the book's title implies, the book covers data structures using the C programming language.

I got the book knowing it would be out-dated but would probably contain lots of advanced C topics that I wouldn't encounter elsewhere.

Sure enough within 5 minutes I found something I didn't know about C. I came across a section talking about the union keyword and I realized that I had never used it, nor ever seen any code that does. I was grateful for learning something interesting and quickly bought the book.

For those of you not knowledgeable about what a union is, the book uses a good metaphor to explain:

To fully understand the concept of a
  union, it is necessary to examine its
  implementation. A Structure may be
  regarded as a road map to an area of
  memory. It defines how the memory is
  to be interpreted. A union provides
  several different road maps for the
  same area of memory, and it is the
  responsibility of the programmer to
  determine which road map is in current
  use. In practice, the compiler
  allocates sufficient storage to
  contain the largest member of the
  union. It is the road map, however,
  that determines how that storage is to
  be interpreted.

I could easily come up with contrived situations or hacks where I would use a Union. (But I am not interested in contrived situations or hacks...)

Have you used or seen an implementation where using Union solved the problem **more elegantly** than not using a Union?

Added bonus if you include a quick explanation of why using union was better/easier than not using a union.

答:
I think this one is a good example:</p>

```<code>        struct fieldsv4{
            unsigned int ip4 : 8;
            unsigned int ip3 : 8;
            unsigned int ip2 : 8;
            unsigned int ip1 : 8;
        };
        typedef union {
            unsigned int ip32; // Assume this is 32-bits
            struct fieldsv4 part;
        } ipv4;

        ipv4 dir1;
        struct fieldsv4 f1 = {1, 1, 168, 192}; //for little endian depending OS  for big endian do not invert
        dir1.part = f1;
        ipv4 dir2= dir1;
        dir2.part.ip4 = 2;
        printf("%d.%d.%d.%d\n", dir2.part.ip1, dir2.part.ip2, dir2.part.ip3, dir2.part.ip4);
        printf("%d.%d.%d.%d\n", dir1.part.ip1, dir1.part.ip2, dir1.part.ip3, dir1.part.ip4);
        printf("%X\n", dir1.ip32 ^ dir2.ip32);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think this one is a good example:

        struct fieldsv4{
            unsigned int ip4 : 8;
            unsigned int ip3 : 8;
            unsigned int ip2 : 8;
            unsigned int ip1 : 8;
        };
        typedef union {
            unsigned int ip32; // Assume this is 32-bits
            struct fieldsv4 part;
        } ipv4;

        ipv4 dir1;
        struct fieldsv4 f1 = {1, 1, 168, 192}; //for little endian depending OS  for big endian do not invert
        dir1.part = f1;
        ipv4 dir2= dir1;
        dir2.part.ip4 = 2;
        printf("%d.%d.%d.%d\n", dir2.part.ip1, dir2.part.ip2, dir2.part.ip3, dir2.part.ip4);
        printf("%d.%d.%d.%d\n", dir1.part.ip1, dir1.part.ip2, dir1.part.ip3, dir1.part.ip4);
        printf("%X\n", dir1.ip32 ^ dir2.ip32);


问:
Problem On Getting Data From Arduino It outputs end line chracters Python
Greetings how can I remove \r\n and "['']" line?
It is a barometric data logger. My future plans are making a gui and showing the values there.
And my pcb has a bluetooth to how can I add bluetooth support.

Python Code

```<code>import serial
ser = serial.Serial('COM6', baudrate = 9600, timeout=1)
 while 1:
  arduinoData = ser.readline().decode('ascii')
  parsed = arduinoData.split(',')
  print(parsed)
</code>```

Python Output

```<code>enter code here
['']
['26.03', '882.70', '1340.80\r\n']
['']
['26.03', '882.68', '1341.02\r\n']
['']
['26.03', '882.66', '1341.13\r\n']
['']
['26.03', '882.66', '1341.14\r\n']
</code>```

Arduino Code

```<code>#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

Adafruit_BMP280 bme;
#define SEALEVELPRESSURE_HPA (1037.3)

 void setup() {
 Serial.begin(9600);
   bme.begin(0x76);
  }

 void loop() {
  Serial.print(bme.readTemperature());
  Serial.print(",");
  Serial.print(bme.readPressure()/100);
  Serial.print(",");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println("");
  delay(1000);
</code>```

}

答:
Replace

```<code>parsed = arduinoData.split(',')
</code>```

with

```<code>parsed = [datum.strip() for datum in arduinoData.split(',')]
</code>```

which will strip whitespace from both sides of each item. \r and \n count as whitespace, so it'll remove that.

Additionally, it looks like

```<code>Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
</code>```

already outputs a newline - the empty lists you're getting might be from the second newline you get from Serial.println(""). Try removing that line and see if it fixes your issue.

Body:
Greetings how can I remove \r\n and "['']" line?
It is a barometric data logger. My future plans are making a gui and showing the values there.
And my pcb has a bluetooth to how can I add bluetooth support.

Python Code

import serial
ser = serial.Serial('COM6', baudrate = 9600, timeout=1)
 while 1:
  arduinoData = ser.readline().decode('ascii')
  parsed = arduinoData.split(',')
  print(parsed)

Python Output

enter code here
['']
['26.03', '882.70', '1340.80\r\n']
['']
['26.03', '882.68', '1341.02\r\n']
['']
['26.03', '882.66', '1341.13\r\n']
['']
['26.03', '882.66', '1341.14\r\n']

Arduino Code

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

Adafruit_BMP280 bme;
#define SEALEVELPRESSURE_HPA (1037.3)

 void setup() {
 Serial.begin(9600);
   bme.begin(0x76);
  }

 void loop() {
  Serial.print(bme.readTemperature());
  Serial.print(",");
  Serial.print(bme.readPressure()/100);
  Serial.print(",");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println("");
  delay(1000);

}

Body:
Replace

parsed = arduinoData.split(',')

with

parsed = [datum.strip() for datum in arduinoData.split(',')]

which will strip whitespace from both sides of each item. \r and \n count as whitespace, so it'll remove that.

Additionally, it looks like

Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));

already outputs a newline - the empty lists you're getting might be from the second newline you get from Serial.println(""). Try removing that line and see if it fixes your issue.


问:
Can you use the name of a Check-box to access its value?
I am currently working on a Word document with ActiveX check-boxes.

You can use the following line of code to access a check-box :

ActiveDocument.InlineShapes(n).OLEFormat.Object

where n is an integer representing the position of that check-box in the document. Unfortunately for me, if any check-box or option button is added before a check-box, the position of that check-box change, thus a given n can point to a different check-box.

My question : is there a way to replace the n with the name (or something else as long as it cannot be changed by adding a new check-box) of the check-box ?

Thank you in advance.

答:
Unfortunately, ActiveX controls don't take names. The most convenient alternative is to use the Caption (the label text appearing beside the checkbox). You have to take an approach like you do in PowerPoint, where you poll each shape to find the one that meets your criterion:</p>

```<code>Sub GetCheckBoxValue()
    For x = 1 To ActiveDocument.InlineShapes.Count
        If ActiveDocument.InlineShapes(x).OLEFormat.Object.Caption = "ActiveX Label Text" Then
            CheckboxValue = ActiveDocument.InlineShapes(x).OLEFormat.Object.value
        End If
    Next x
End Sub
</code>```

Body:
Unfortunately, ActiveX controls don't take names. The most convenient alternative is to use the Caption (the label text appearing beside the checkbox). You have to take an approach like you do in PowerPoint, where you poll each shape to find the one that meets your criterion:

Sub GetCheckBoxValue()
    For x = 1 To ActiveDocument.InlineShapes.Count
        If ActiveDocument.InlineShapes(x).OLEFormat.Object.Caption = "ActiveX Label Text" Then
            CheckboxValue = ActiveDocument.InlineShapes(x).OLEFormat.Object.value
        End If
    Next x
End Sub


问:
How to pull the key and value of an item with the maximum value out of a python dictionary
The following code creates a dictionary of email addresses and how frequently each email appears.  What is the best way to pull out the key and value for the email with the max frequency?</p>

```<code>fname = input("Enter file:")
try:
    fhand = open(fname)
except:
    print('File cannot be opened:')
    exit()
counts = dict()
for line in fhand:
    if line.startswith('From:'):
         words = line.split(' ', 1)[1]
         words = words.rstrip('\n')

         counts[words] = counts.get(words,0)+1

print(counts)
</code>```

答:
Use collections.Counter instead, which has a most_common method.

```<code>from collections import Counter

# Ignoring file opening code since it's irrelevant...

counts = Counter()
for line in fhand:
    if line.startswith('From:'):
         email_addr = line.rstrip('\n').split(' ', 1)[1]
         counts[email_addr] += 1

print(counts.most_common(1))
</code>```

Or as a comprehension:

```<code>counts = Counter(
    line.rstrip('\n').split(' ', 1)[1]
    for line in fhand
    if line.startswith('From:')
    )
</code>```

Body:
The following code creates a dictionary of email addresses and how frequently each email appears.  What is the best way to pull out the key and value for the email with the max frequency?

fname = input("Enter file:")
try:
    fhand = open(fname)
except:
    print('File cannot be opened:')
    exit()
counts = dict()
for line in fhand:
    if line.startswith('From:'):
         words = line.split(' ', 1)[1]
         words = words.rstrip('\n')

         counts[words] = counts.get(words,0)+1

print(counts)

Body:
Use collections.Counter instead, which has a most_common method.

from collections import Counter

# Ignoring file opening code since it's irrelevant...

counts = Counter()
for line in fhand:
    if line.startswith('From:'):
         email_addr = line.rstrip('\n').split(' ', 1)[1]
         counts[email_addr] += 1

print(counts.most_common(1))

Or as a comprehension:

counts = Counter(
    line.rstrip('\n').split(' ', 1)[1]
    for line in fhand
    if line.startswith('From:')
    )


问:
Python xml2csv xmlutils program need
I have a set of code on a recently installed machine I need to activate. Basically it is a script that convert xml style .dat file into a .csv file by creating a temporary file as an intermediary and converting the text using a convert() function. This appears to use the source code from the pypi.org site.

```<code>from xmlutils.xml2csv import xml2csv
import sys

xml_source = sys.argv[1]
obj_name = sys.argv[2]
filename_temp = xml_source + '.temp'
filename_csv = xml_source.replace('.dat','') + '.csv'

fin = open(xml_source)
fout = open(filename_temp, "wt")
fout.write("<root>")
for line in fin:
    fout.write( line.replace("<?xml version='1.0' encoding='UTF-8'?>", '') )
fout.write("</root>")
fin.close()
fout.close()

converter = xml2csv(filename_temp, filename_csv)
converter.convert(tag=obj_name)
</code>```

Below is a sample of the input in the xml format that gets translated line by line grouped into one record in the .csv file by the  tag. The output will be one line of a .csv file.

```<code>    <?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>GIS</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Sun & Moon Cafe</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>22929 Highway 99</ShippingStreet>
  <ShippingCity>Edmonds</ShippingCity>
  <ShippingState>WA</ShippingState>
  <ShippingPostalCode>98026-8468</ShippingPostalCode>
  <Phone>425-977-2929</Phone>
  <Sic>5812</Sic>
  <NumberOfEmployees>9</NumberOfEmployees>
  <Description>EATING PLACES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>22929 Highway 99</Xerox_Address_1__c>
  <Xerox_City__c>Edmonds</Xerox_City__c>
  <Duns__c>031593575</Duns__c>
  <Legal_Name__c>SUN & MOON CAFE</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>47.791194</Latitude__c>
  <Longitude__c>-122.337749</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SNOHOMISH</Xerox_County__c>
  <Xerox_State__c>WA</Xerox_State__c>
  <Xerox_Zip_4__c>8468</Xerox_Zip_4__c>
  <County__c>SNOHOMISH</County__c>
  <Department__c />
  <Franchise__c />
  <County_Code__c>061</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c />
  <Global_Ultimate_DUNS_Number__c />
  <Headquarters_DUNS_Number__c />
  <Location_Employee_Qty__c>9</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>98026-8468</Xerox_Zip_Code__c>
  <Org_Group_Code__c>0</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>994.5</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>1976.67</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>8468</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>425</Telephone_Area_Code__c>
  <Telephone_Exchange__c>977</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
</code>```

On my previous machine, I was able to enter the path of the python conversion script name, the xml style .dat file name, the Account handle and process accordingly.

Example:

```<code>C:\data\convert_xml_to_csv.py C:\data\csv\2020-02-13-estab-insert.dat Account
</code>```

At first, I got an error message that the program wasn't available, so I eventually found the page to download the latest version of Python (v 3.8.1). I selected the executable x86-64 version of the download. After that, the command just goes to the next line without any action or anything processed. I'm not sure if I have to download anything else off the xmlutils source code page or what action to take next. I may need to be walked through the rest of the process to activate this script on a new machine. It was transferred once before but the creator is no longer with the company. Is anyone able to help me?

Joao,

So I downloaded the latest version of Python (version 3.8.1), identified the path of the .exe install file and added it to the Path in environmental variables. The paths are in screenshots 2 and 3 below:

I then tried to run my script from the Powershell, however, it simply skipped to the next line without creating an output file. So then I tried to run the same script on the Command Prompt and it yielded that the xmlutils module was not found.

So it looks like I may have to download the xmlutils package from the PyPl site. But it doesn't look like there's a clear way for me to do that at this point with running a .tar.gz file.

Update: 2/18/20

I believe I have successfully installed the latest version of the xmlutils python package via the pip command. Once I did that, I tried to convert a file again where it doesn't recognize part of the code. My only guess with this error at this point is that it's an error related to an updated version of these program. Is anyone able to make the necessary tweaks from here based on this information?

Update: 3/5/2020

So after installing the xmlutils and the setuptools package where both are located in the path for Environment Variables, running the script now does in fact create the cloned temporary file this script customary has done. However, it leaves the destination file of the finished output blank for the .csv file. Anyone have any other suggestions in regards to correcting this?

xml2csv python script result - Mar 5th

Conversion error with xmlutils installed

Command Prompt Output

Python Environment check result

Python Path image

Environmental variable path

答:
Per python.org:

If the first line of a script file starts with #!, it is known as a “shebang” line. Linux and other Unix like operating systems have native support for such lines and they are commonly used on such systems to indicate how a script should be executed. This launcher allows the same facilities to be used with Python scripts on Windows and the examples above demonstrate their use.

Source: Python.org:Shebang lines

My suggestion is to add shebang lines (yes, even in Windows) to the beginning of your Python script.  It should run without prefacing the script name with 'python'.

Hope this helps.

Title: Python xml2csv xmlutils program need

Body:
I have a set of code on a recently installed machine I need to activate. Basically it is a script that convert xml style .dat file into a .csv file by creating a temporary file as an intermediary and converting the text using a convert() function. This appears to use the source code from the pypi.org site.

from xmlutils.xml2csv import xml2csv
import sys

xml_source = sys.argv[1]
obj_name = sys.argv[2]
filename_temp = xml_source + '.temp'
filename_csv = xml_source.replace('.dat','') + '.csv'

fin = open(xml_source)
fout = open(filename_temp, "wt")
fout.write("<root>")
for line in fin:
    fout.write( line.replace("<?xml version='1.0' encoding='UTF-8'?>", '') )
fout.write("</root>")
fin.close()
fout.close()

converter = xml2csv(filename_temp, filename_csv)
converter.convert(tag=obj_name)

Below is a sample of the input in the xml format that gets translated line by line grouped into one record in the .csv file by the  tag. The output will be one line of a .csv file.

    <?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Alta Paints & Coatings  Inc</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>136 W 3300 S</ShippingStreet>
  <ShippingCity>Salt Lake City</ShippingCity>
  <ShippingState>UT</ShippingState>
  <ShippingPostalCode>84115-3704</ShippingPostalCode>
  <Phone>801-466-9625</Phone>
  <Sic>5198</Sic>
  <NumberOfEmployees>16</NumberOfEmployees>
  <Description>PAINTS, VARNISHES, AND SUPPLIES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>136 W 3300 S</Xerox_Address_1__c>
  <Xerox_City__c>Salt Lake City</Xerox_City__c>
  <Duns__c>197857873</Duns__c>
  <Legal_Name__c>ALTA PAINTS & COATINGS, INC.</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>40.699928</Latitude__c>
  <Longitude__c>-111.895096</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SALT LAKE</Xerox_County__c>
  <Xerox_State__c>UT</Xerox_State__c>
  <Xerox_Zip_4__c>3704</Xerox_Zip_4__c>
  <County__c>SALT LAKE</County__c>
  <Department__c>1</Department__c>
  <Franchise__c />
  <County_Code__c>035</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c>197857873</Domestic_Ultimate_DUNS_Number__c>
  <Global_Ultimate_DUNS_Number__c>197857873</Global_Ultimate_DUNS_Number__c>
  <Headquarters_DUNS_Number__c>197857873</Headquarters_DUNS_Number__c>
  <Location_Employee_Qty__c>16</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>84115-3704</Xerox_Zip_Code__c>
  <Org_Group_Code__c>1</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>4974.4</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>10152.0</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>3704</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>801</Telephone_Area_Code__c>
  <Telephone_Exchange__c>466</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>GIS</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>
<Account>
  <Name>Sun & Moon Cafe</Name>
  <Type>Non Customer</Type>
  <RecordTypeId>012E0000000PR3uIAG</RecordTypeId>
  <ShippingStreet>22929 Highway 99</ShippingStreet>
  <ShippingCity>Edmonds</ShippingCity>
  <ShippingState>WA</ShippingState>
  <ShippingPostalCode>98026-8468</ShippingPostalCode>
  <Phone>425-977-2929</Phone>
  <Sic>5812</Sic>
  <NumberOfEmployees>9</NumberOfEmployees>
  <Description>EATING PLACES</Description>
  <Sales_Channel__c>NAAO</Sales_Channel__c>
  <Xerox_Address_1__c>22929 Highway 99</Xerox_Address_1__c>
  <Xerox_City__c>Edmonds</Xerox_City__c>
  <Duns__c>031593575</Duns__c>
  <Legal_Name__c>SUN & MOON CAFE</Legal_Name__c>
  <Secondary_Name__c />
  <Latitude__c>47.791194</Latitude__c>
  <Longitude__c>-122.337749</Longitude__c>
  <Map_Status__c>G_GEO_SUCCESS</Map_Status__c>
  <Xerox_County__c>SNOHOMISH</Xerox_County__c>
  <Xerox_State__c>WA</Xerox_State__c>
  <Xerox_Zip_4__c>8468</Xerox_Zip_4__c>
  <County__c>SNOHOMISH</County__c>
  <Department__c />
  <Franchise__c />
  <County_Code__c>061</County_Code__c>
  <Domestic_Ultimate_DUNS_Number__c />
  <Global_Ultimate_DUNS_Number__c />
  <Headquarters_DUNS_Number__c />
  <Location_Employee_Qty__c>9</Location_Employee_Qty__c>
  <Xerox_Zip_Code__c>98026-8468</Xerox_Zip_Code__c>
  <Org_Group_Code__c>0</Org_Group_Code__c>
  <Parent_DUNS__c />
  <Potential_Copy_Dupl_Qty__c>994.5</Potential_Copy_Dupl_Qty__c>
  <Potential_Printing_Sys_Qty__c>1976.67</Potential_Printing_Sys_Qty__c>
  <Telephone_Last_4__c />
  <Subsidiary_Indicator__c>0</Subsidiary_Indicator__c>
  <Trade_Name__c />
  <XNAC_Code__c />
  <XNAC_Division__c />
  <Zip_4__c>8468</Zip_4__c>
  <Customer_Indicator__c>0.0</Customer_Indicator__c>
  <Franchise_Parent__c />
  <Telephone_Area_Code__c>425</Telephone_Area_Code__c>
  <Telephone_Exchange__c>977</Telephone_Exchange__c>
  <Total_Lsr_Prtg_Vol__c>0.0</Total_Lsr_Prtg_Vol__c>
  <Open_Sales_Channel__c>USCO</Open_Sales_Channel__c>
  <Estab_Copy_Volume__c>0.0</Estab_Copy_Volume__c>
</Account><?xml version='1.0' encoding='UTF-8'?>

On my previous machine, I was able to enter the path of the python conversion script name, the xml style .dat file name, the Account handle and process accordingly.

Example:

C:\data\convert_xml_to_csv.py C:\data\csv\2020-02-13-estab-insert.dat Account

At first, I got an error message that the program wasn't available, so I eventually found the page to download the latest version of Python (v 3.8.1). I selected the executable x86-64 version of the download. After that, the command just goes to the next line without any action or anything processed. I'm not sure if I have to download anything else off the xmlutils source code page or what action to take next. I may need to be walked through the rest of the process to activate this script on a new machine. It was transferred once before but the creator is no longer with the company. Is anyone able to help me?

Joao,

So I downloaded the latest version of Python (version 3.8.1), identified the path of the .exe install file and added it to the Path in environmental variables. The paths are in screenshots 2 and 3 below:

I then tried to run my script from the Powershell, however, it simply skipped to the next line without creating an output file. So then I tried to run the same script on the Command Prompt and it yielded that the xmlutils module was not found.

So it looks like I may have to download the xmlutils package from the PyPl site. But it doesn't look like there's a clear way for me to do that at this point with running a .tar.gz file.

Update: 2/18/20

I believe I have successfully installed the latest version of the xmlutils python package via the pip command. Once I did that, I tried to convert a file again where it doesn't recognize part of the code. My only guess with this error at this point is that it's an error related to an updated version of these program. Is anyone able to make the necessary tweaks from here based on this information?

Update: 3/5/2020

So after installing the xmlutils and the setuptools package where both are located in the path for Environment Variables, running the script now does in fact create the cloned temporary file this script customary has done. However, it leaves the destination file of the finished output blank for the .csv file. Anyone have any other suggestions in regards to correcting this?

xml2csv python script result - Mar 5th

Conversion error with xmlutils installed

Command Prompt Output

Python Environment check result

Python Path image

Environmental variable path


问:
Looking for a Reader Writer Lock that works with async/await
I am porting an old application to .NET core.  I need a reader writer lock (many read operations, occasional write operations).  My old code was heavily multithreaded, so the old ReaderWriterLock worked just great.  The new code is Task based, so I'm trying to embrace the async/await pattern.

Which brings me to my need for locking primitives.  The old locking primitives only works when you wait on a single thread.  There's a SemaphoreSlim that's task-aware, but I don't see how this can be used for a Reader Writer lock.

I found this: AsyncReaderWriterLock, but I can't find any examples of usage or anyone who seems to be using it.  I don't want to use Stephen Cleary's library if I can use something from Microsoft.  So, what's the story here?  Is there a .NET multi-tasking primitive that supports reader writer locking?  Is there a reason I should avoid using AsyncReaderWriterLock?  Has anyone seen an example of it working?

答:
I don't want to use Stephen Cleary's library if I can use something from Microsoft.

Me, either.

So, what's the story here?

The VS-Threading library has a bit of history. It was originally part of the VS-SDK and intended for (and only licensed for) VS extensions. That didn't stop people from finding it and distributing it with their own apps, which I recommended against a few times. These days it's spun off into its own project, available on NuGet, and licensed MIT. So I think it's fine to use these days. But that's the history and I think the history is why it hasn't been widely adopted.

Is there a .NET multi-tasking primitive that supports reader writer locking?

Not as a part of the framework (at least, not yet). There's AsyncEx, VS-Threading, and roll-your-own. I'm not sure where VS-Threading exists in terms of Microsoft support - i.e., is it maintained by a particular team? I do see Andrew Arnott and Sam Harwell on recent commits, and they are both geniuses in this area, so I'd say it's in good hands for now. I'm just not sure how official of a Microsoft project it is.

Is there a reason I should avoid using AsyncReaderWriterLock?

Absolutely. I'm generally against reader/writer locks. The reason is that a lot of developers think "some of my code reads, and some of my code writes, and so I need a RWL", when this is not the case. There's additional requirements: the reads must vastly outnumber the writes, and the reads must at least threaten to overwhelm the writes. If those additional requirements aren't met, then a simple lock works just fine. This is especially the case with asynchronous code; it's not common to hold a lock while doing I/O.

Has anyone seen an example of it working?

Actually, I haven't, which is kind of funny. But looking at the source, I'd say call await ReadLockAsync/await WriteLockAsync and then dispose the result value to release the lock. E.g.:

```<code>using (var releaser = await arwl.ReadLockAsync())
{
  ... // code using await
}
</code>```

AsyncEx and the roll-your-own approach have the same usage.

Body:
I don't want to use Stephen Cleary's library if I can use something from Microsoft.

Me, either.

So, what's the story here?

The VS-Threading library has a bit of history. It was originally part of the VS-SDK and intended for (and only licensed for) VS extensions. That didn't stop people from finding it and distributing it with their own apps, which I recommended against a few times. These days it's spun off into its own project, available on NuGet, and licensed MIT. So I think it's fine to use these days. But that's the history and I think the history is why it hasn't been widely adopted.

Is there a .NET multi-tasking primitive that supports reader writer locking?

Not as a part of the framework (at least, not yet). There's AsyncEx, VS-Threading, and roll-your-own. I'm not sure where VS-Threading exists in terms of Microsoft support - i.e., is it maintained by a particular team? I do see Andrew Arnott and Sam Harwell on recent commits, and they are both geniuses in this area, so I'd say it's in good hands for now. I'm just not sure how official of a Microsoft project it is.

Is there a reason I should avoid using AsyncReaderWriterLock?

Absolutely. I'm generally against reader/writer locks. The reason is that a lot of developers think "some of my code reads, and some of my code writes, and so I need a RWL", when this is not the case. There's additional requirements: the reads must vastly outnumber the writes, and the reads must at least threaten to overwhelm the writes. If those additional requirements aren't met, then a simple lock works just fine. This is especially the case with asynchronous code; it's not common to hold a lock while doing I/O.

Has anyone seen an example of it working?

Actually, I haven't, which is kind of funny. But looking at the source, I'd say call await ReadLockAsync/await WriteLockAsync and then dispose the result value to release the lock. E.g.:

using (var releaser = await arwl.ReadLockAsync())
{
  ... // code using await
}

AsyncEx and the roll-your-own approach have the same usage.