问:
Populating a textarea in a datatable with server_processing.php
I have a data table and i want a column on it to be a textarea where edits can be made, but i am finding it difficult to populate this textarea. I was able to activate the button to submit as it is not the first time i am doing it, but i feel populating the textarea wouldn't be far from it though. i would be grateful if i can get any help:

Here is my code:

```<code>$(document).ready(function(){
        var table = $('#admin_table').DataTable({
            //"order": [[ 2, "desc" ]],
            "processing": true,
            "serverSide": true,
            "ajax": $.fn.dataTable.pipeline({
                url: 'server_processing.php',
                pages: 5 // number of pages to cache
            }),

           "columnDefs": [ {
                "targets": 9,
                "data": null,
                "defaultContent": "<div class='w3-btn-group w3-vertical w3-center'><a id='edit_fact' class='w3-btn w3-padding w3-slim w3-small w3-black w3-text-white w3-ripple w3-card-8 w3-hover-orange w3-hover-text-black' title='Edit Fact'><span class='glyphicon glyphicon-pencil w3-center'></span></a> <a id='delete_fact' class='w3-btn w3-padding w3-slim w3-small w3-white w3-text-blue w3-ripple w3-card-8 w3-hover-red w3-hover-text-black' title='Delete Fact'><span class='glyphicon glyphicon-trash w3-center'></span></a></div>"
            },
                    {
                "targets": 3,
                "data": true,
                "defaultContent": "<textarea name='diagnosis' id='diagnosis' ></textarea>"
                    }
        ]

        });

         $('#admin_table tbody').on('click', '#edit_fact', function () {
            var data = table.row( $(this).parents('tr') ).data();
//Where i submit my edits
            });

// Populating the text area
            var data = table.row( $('#admin_table).parents('tr') ).data();
            $('#diagnosis').val(data[3]);

    });
</code>```

what my table looks like:
My datatable

答:
Oh yes i manage to get it to work using render

Here is the code:

```<code>var table = $('#admin_table').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": $.fn.dataTable.pipeline({
            url: 'scripts/server_processing.php',
            pages: 5 // number of pages to cache
        }),

       "columnDefs": [ {
            "targets": 9,
            "data": null,
            "defaultContent": "<div class='w3-btn-group w3-vertical w3-center'><a id='edit_fact' class='w3-btn w3-padding w3-slim w3-small w3-black w3-text-white w3-ripple w3-card-8 w3-hover-orange w3-hover-text-black' title='Edit Fact'><span class='glyphicon glyphicon-pencil w3-center'></span></a> <a id='delete_fact' class='w3-btn w3-padding w3-slim w3-small w3-white w3-text-blue w3-ripple w3-card-8 w3-hover-red w3-hover-text-black' title='Delete Fact'><span class='glyphicon glyphicon-trash w3-center'></span></a></div>"
        },
        {
            "targets": 3,
            "render": function ( data, type, row ) {
                    return "<textarea name='diagnosis' id='diagnosis' >"+data+"</textarea>";
                }
        }
    ]

    });
</code>```

Body:
I have a data table and i want a column on it to be a textarea where edits can be made, but i am finding it difficult to populate this textarea. I was able to activate the button to submit as it is not the first time i am doing it, but i feel populating the textarea wouldn't be far from it though. i would be grateful if i can get any help:

Here is my code:

$(document).ready(function(){
        var table = $('#admin_table').DataTable({
            //"order": [[ 2, "desc" ]],
            "processing": true,
            "serverSide": true,
            "ajax": $.fn.dataTable.pipeline({
                url: 'server_processing.php',
                pages: 5 // number of pages to cache
            }),

           "columnDefs": [ {
                "targets": 9,
                "data": null,
                "defaultContent": "

"
            },
                    {
                "targets": 3,
                "data": true,
                "defaultContent": "<textarea name='diagnosis' id='diagnosis' ></textarea>"
                    }
        ]

        });

         $('#admin_table tbody').on('click', '#edit_fact', function () {
            var data = table.row( $(this).parents('tr') ).data();
//Where i submit my edits
            });

// Populating the text area
            var data = table.row( $('#admin_table).parents('tr') ).data();
            $('#diagnosis').val(data[3]);

    });

what my table looks like:
My datatable

Body:
Oh yes i manage to get it to work using render

Here is the code:

var table = $('#admin_table').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": $.fn.dataTable.pipeline({
            url: 'scripts/server_processing.php',
            pages: 5 // number of pages to cache
        }),

       "columnDefs": [ {
            "targets": 9,
            "data": null,
            "defaultContent": "<div class='w3-btn-group w3-vertical w3-center'><a id='edit_fact' class='w3-btn w3-padding w3-slim w3-small w3-black w3-text-white w3-ripple w3-card-8 w3-hover-orange w3-hover-text-black' title='Edit Fact'><span class='glyphicon glyphicon-pencil w3-center'></span></a> <a id='delete_fact' class='w3-btn w3-padding w3-slim w3-small w3-white w3-text-blue w3-ripple w3-card-8 w3-hover-red w3-hover-text-black' title='Delete Fact'><span class='glyphicon glyphicon-trash w3-center'></span></a></div>"
        },
        {
            "targets": 3,
            "render": function ( data, type, row ) {
                    return "<textarea name='diagnosis' id='diagnosis' >"+data+"</textarea>";
                }
        }
    ]

    });


来源: stackexchange

问:
jQuery DataTables: Can I have 3 states for Sort : ASC, DESC and NO_SORT?
jQuery Datatable's sorting order on clicking column header toggles only between asc(Down Arrow) and desc(Up Arrow). i.e.,

```<code>1st-click ascending
2nd-click descending
3rd-click asc
4th-click desc
   ||   ||
   ||   ||
   ||   ||
   ||   ||
odd-click asc
even-click desc.
</code>```

I want to induce something like this :

```<code>1st-click ascending
2nd-click descending
3rd-click no-sorting
4th-click asc
5th-click desc
6th-click no-sort
   ||   ||
   ||   ||
   ||   ||
   ||   ||
(n%3==1)-click asc
(n%3==2)-click desc
(n%3==0)-click no-sort.
</code>```

Is there a way to change this behavior in jQuery dataTables? Please help!
Thanks in advance.

答:
Solved the issued by maintaining the state of the columns an array, intercepting and stopping the default behavior of the order event and then manually doing :</p>

```<code>var dir = 'asc' for ascending
var dir  ='desc' for descending
var dir = '' for no-sort

$("#table-id").dataTable.order([colIdx, dir]).draw();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
jQuery Datatable's sorting order on clicking column header toggles only between asc(Down Arrow) and desc(Up Arrow). i.e.,

1st-click ascending
2nd-click descending
3rd-click asc
4th-click desc
   ||   ||
   ||   ||
   ||   ||
   ||   ||
odd-click asc
even-click desc.

I want to induce something like this :

1st-click ascending
2nd-click descending
3rd-click no-sorting
4th-click asc
5th-click desc
6th-click no-sort
   ||   ||
   ||   ||
   ||   ||
   ||   ||
(n%3==1)-click asc
(n%3==2)-click desc
(n%3==0)-click no-sort.

Is there a way to change this behavior in jQuery dataTables? Please help!
Thanks in advance.

Body:
Solved the issued by maintaining the state of the columns an array, intercepting and stopping the default behavior of the order event and then manually doing :

var dir = 'asc' for ascending
var dir  ='desc' for descending
var dir = '' for no-sort

$("#table-id").dataTable.order([colIdx, dir]).draw();


问:
Is it possible to require at least one field from a set of defined fields?
Given a definition like this:

```<code>const querySchema = joi.object({
  one: joi.string().min(1).max(255),
  two: joi.string().min(1).max(255),
  three: joi.string().min(1).max(255),
});
</code>```

Is there a way to require at least one of those fields? I don't care which one.

Note: the solution provided for this SO question doesn't serve me as I have 7 fields and they may grow, so doing all the possible combinations is a no-go.

Couldn't find any methods in Joi API Reference that may be useful for this use case.

Any help is greatly appreciated.

答:
Found another way to do it besides the one suggested by @Ankh, was in documentation but I couldn't find it before:

```<code>const schema = joi.object({
   a: joi.number(),
   b: joi.number(),
}).or('a', 'b');
</code>```

This method is good if one needs to require a specific set of keys, while @Ankh's is better when the requirement is exaclty as I this question title and you have many keys, so I'm choosing his answer over mine as the right one.

Just wanted to leave here another way to do it.

Body:
Given a definition like this:

const querySchema = joi.object({
  one: joi.string().min(1).max(255),
  two: joi.string().min(1).max(255),
  three: joi.string().min(1).max(255),
});

Is there a way to require at least one of those fields? I don't care which one.

Note: the solution provided for this SO question doesn't serve me as I have 7 fields and they may grow, so doing all the possible combinations is a no-go.

Couldn't find any methods in Joi API Reference that may be useful for this use case.

Any help is greatly appreciated.

Body:
Found another way to do it besides the one suggested by @Ankh, was in documentation but I couldn't find it before:

const schema = joi.object({
   a: joi.number(),
   b: joi.number(),
}).or('a', 'b');

This method is good if one needs to require a specific set of keys, while @Ankh's is better when the requirement is exaclty as I this question title and you have many keys, so I'm choosing his answer over mine as the right one.

Just wanted to leave here another way to do it.

ContentLicense: CC BY-SA 4.0


问:
printing with java in linux
Does anyone know any good tutorial or howto how to print with java application in linux? In search but i can not find any good tutorial.

Thx

答: If the printer is attached and working for your Linux box, a Java application will be able to print too. However, there are few cases, sometimes, when you don't get desired results. For that you must refer to the official guide.</p>

ContentLicense: CC BY-SA 2.5

Title: printing with java in linux


问:
Rotate Three.js camera around center using mouse
I'm trying to rotate the camera around the center point (0, 0, 0) using the mouse but if I rotate to the right or left 180deg, then the try to rotate up or down, it doesn't rotate vertically at all.

I'm trying to use latitude/longitude coordinates then convert it to cartesian like:

```<code>this.camera.position.x = Math.sin(this.lat) * this.alt;
this.camera.position.z = Math.cos(this.lat) * Math.cos(this.lng) * this.alt;
this.camera.position.y = Math.cos(this.lat) * Math.sin(this.lng) * this.alt;
this.camera.lookAt(new THREE.Vector3(0, 0, 0));
</code>```

A minimal example is here: https://jsfiddle.net/qsor9w27/2/

答:
I think the simplest would be using OrbitControls or TrackballControls

See this example which is using OrbitControls.

Body:
I'm trying to rotate the camera around the center point (0, 0, 0) using the mouse but if I rotate to the right or left 180deg, then the try to rotate up or down, it doesn't rotate vertically at all.

I'm trying to use latitude/longitude coordinates then convert it to cartesian like:

this.camera.position.x = Math.sin(this.lat) * this.alt;
this.camera.position.z = Math.cos(this.lat) * Math.cos(this.lng) * this.alt;
this.camera.position.y = Math.cos(this.lat) * Math.sin(this.lng) * this.alt;
this.camera.lookAt(new THREE.Vector3(0, 0, 0));

A minimal example is here: https://jsfiddle.net/qsor9w27/2/


问:
WSS - Error in connection establishment: net::ERR_CONNECTION_CLOSED
Please do not mark as duplicate since all of the other questions on SO are not quite like this one, and all solutions have been attempted and are irrelevant.

I am working on Windows trying to create a BinaryServer with node.js and allow clients to connect to it over HTTPS, for audio streaming purposes.

Node JS code:

```<code>var binaryServer = require('binaryjs').BinaryServer;
var https = require('https');
var http = require('http');
var fs = require('fs');

var options = {
    key: fs.readFileSync('../cert/example.com.key'),
    cert: fs.readFileSync('../cert/example.com.crt')
};
var httpsserver = https.createServer(options).listen(9001);
var server = binaryServer({ server: httpsserver, port: 9001 });

server.on('connection', function(client) {
   .... // stuff
}
</code>```

Client site JS code:

```<code>client = new BinaryClient('https://example.com:9001');
</code>```

When browsing with Chrome to my site at https://example.com/page.aspx I get the following console message:

Error in connection establishment: net::ERR_CONNECTION_CLOSED

I am suspecting it has something to do with the certificate and the key.

The example.com.key is a .key file that I created using OpenSSL. From that key, I created a .CSR file, which I uploaded to GoDaddy, and got the  example.com.crt file.

What am I doing wrong?

I am struggling with this for 2 weeks, any help would be highly appreciated.

答: Issue resolved - by setting different ports to the httpsserver and the server binary server.

Body:
Please do not mark as duplicate since all of the other questions on SO are not quite like this one, and all solutions have been attempted and are irrelevant.

I am working on Windows trying to create a BinaryServer with node.js and allow clients to connect to it over HTTPS, for audio streaming purposes.

Node JS code:

var binaryServer = require('binaryjs').BinaryServer;
var https = require('https');
var http = require('http');
var fs = require('fs');

var options = {
    key: fs.readFileSync('../cert/example.com.key'),
    cert: fs.readFileSync('../cert/example.com.crt')
};
var httpsserver = https.createServer(options).listen(9001);
var server = binaryServer({ server: httpsserver, port: 9001 });

server.on('connection', function(client) {
   .... // stuff
}

Client site JS code:

client = new BinaryClient('https://example.com:9001');

When browsing with Chrome to my site at https://example.com/page.aspx I get the following console message:

Error in connection establishment: net::ERR_CONNECTION_CLOSED

I am suspecting it has something to do with the certificate and the key.

The example.com.key is a .key file that I created using OpenSSL. From that key, I created a .CSR file, which I uploaded to GoDaddy, and got the  example.com.crt file.

What am I doing wrong?

I am struggling with this for 2 weeks, any help would be highly appreciated.


问:
How to select the last inserted records by date, time, minutes and seconds
I have 4 records with the same CID# 201. I'm trying to get the last updated records by the second.  The issue it is returning all 4 of the records. I would like to return the last updated records by CID# 201. Here is my code.

```<code> SELECT CID, to_char( max( UPDATED_DATE ), 'yyyy-mm-dd hh24:mi:ss' )
 FROM mytable
 WHERE CID = 201;
</code>```

This is the return records. NOT DESIRED

```<code>**`CID#`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:29:36`
 `201` | `03/30/2017 7:29:36`
</code>```

This is what I want returned. YES DESIRED

```<code>**`CID`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`
</code>```

What am I missing here?

答:
You can use this as well.</p>

```<code>select * from your_table
where UPDATED_DATE in
    (select max(UPDATED_DATE)
    from your_table
    where CID=201
    )
</code>```

Body:
I have 4 records with the same CID# 201. I'm trying to get the last updated records by the second.  The issue it is returning all 4 of the records. I would like to return the last updated records by CID# 201. Here is my code.

 SELECT CID, to_char( max( UPDATED_DATE ), 'yyyy-mm-dd hh24:mi:ss' )
 FROM mytable
 WHERE CID = 201;

This is the return records. NOT DESIRED

**`CID#`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:29:36`
 `201` | `03/30/2017 7:29:36`

This is what I want returned. YES DESIRED

**`CID`|   `UPDATED_DATE`**
 `201` | `03/30/2017 7:30:22`
 `201` | `03/30/2017 7:30:22`

What am I missing here?

Body:
You can use this as well.

select * from your_table
where UPDATED_DATE in
    (select max(UPDATED_DATE)
    from your_table
    where CID=201
    )


问:
html check if input is greater than other input after submit
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>```

Do I need jquery? I want to do this check before checking the submt button.

答:
<form onsubmit="return validate();">
    <input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

    <input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

    <button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>

</form>

```

Body:
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>

Do I need jquery? I want to do this check before checking the submt button.

Body:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form onsubmit="return validate();">
    <input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

    <input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

    <button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>

</form>

<script>
function validate() {
if ($("#min_value").val() > $("#max_value").val()) {

    alert("min_value field > max_value");
} else {
    alert("max_value field > min_value");
}
}
</script>


问:
Add filter for every query over certain entity in EF
I would like to add a filter to every query fired on my User entity to filter on IsSystemUser == false.

I had see examples using IDbCommandTreeInterceptor and IDbCommandInterceptor, and there is also a chance to override method Executing(DbCommand command, IEnumerable<DbContext> interceptionContext) on the DbContext child class, but it's unclear to me how to achieve this.

What is the easier approach to add a filter to every query fired over Users entity to filter data based on my IsSystemUser property?

答:
A straightforward solution would be to add a filtered IQueryable property to your DbContext, something like:</p>

```<code>public DbSet<User> Users { get; set; }

public IQueryable<User> FilteredUsers
{
    get
    {
        return Users.Where(u => !u.IsSystemUser);
    }
}
</code>```

Body:
A straightforward solution would be to add a filtered IQueryable property to your DbContext, something like:

public DbSet<User> Users { get; set; }

public IQueryable<User> FilteredUsers
{
    get
    {
        return Users.Where(u => !u.IsSystemUser);
    }
}


问:
Easily declaring java lambdas of intersectional types
Let's say I have a method like the following:

```<code>public <T extends Supplier<Collection<String>> & Serializable> void doSomething(T supplier){
    new ArrayList<String>().stream().collect(Collectors.toCollection(supplier));
}
</code>```

Why is it that

```<code>doSomething(() -> new ArrayList<>());
</code>```

causes a problem, but

```<code>doSomething((Supplier<Collection<String>> & Serializable)() -> new ArrayList<>());
</code>```

is fine? The lambda itself is exactly the same in both cases, and in the second one it works. That means that the JVM is capable of creating serialisable lambdas, however is the compiler not able to recognise that this is possible?

Edit: changed the first call to what I intended.

答:
From the JLS 15.16. Cast Expressions:

Casts can be used to explicitly "tag" a lambda expression or a method reference expression with a particular target type. To provide an appropriate degree of flexibility, the target type may be a list of types denoting an intersection type, provided the intersection induces a functional interface (§9.8).

and no comment why it isn't inferred automatically. My guess: it could be possible, but wasn't yet implemented. Also interesting what Eugene stated in the comments. May that mean that something similar is coming in Java 9?

Body:
Let's say I have a method like the following:

public <T extends Supplier<Collection<String>> & Serializable> void doSomething(T supplier){
    new ArrayList<String>().stream().collect(Collectors.toCollection(supplier));
}

Why is it that

doSomething(() -> new ArrayList<>());

causes a problem, but

doSomething((Supplier<Collection<String>> & Serializable)() -> new ArrayList<>());

is fine? The lambda itself is exactly the same in both cases, and in the second one it works. That means that the JVM is capable of creating serialisable lambdas, however is the compiler not able to recognise that this is possible?

Edit: changed the first call to what I intended.


问:
DOT Language Parser
Does anyone know of a DOT Language (or other GraphViz-ish format)  Parser for .NET?
I have been experimenting with QuickGraph, but it seems to only support serialization, and not parsing from a stream/string/file. </p>

答:
The SPGraphviz project handles graph descriptions in DOT:

SPGraphviz - create your own visualization graphs without programming in Sharepoint. Just define graph on DOT language in simple text file, upload it into document library and specify URL in SPGraphvizWebPart - it will make graphical representation of your graph

The documentation implies that the project uses a wrapper around the C language graphviz, and points to 2 such wrappers:

SPGraphvizWebPart uses Graphviz open source library for rendering graphs defined on DOT language. Many objects in real life can be presented as a graph mathematical abstraction. E.g. organization structure, portal hierarchy, version history of the files, etc. - all these can be displayed as a graph (number of nodes with relations between them). Using DOT language you can create textual definition of a graph (nodes, relations, visual effects like color, shape, etc) in simple text file and pass this file into Graphviz library. It will make graphical representation of the graph using selected layout and image type.

Graphviz - is library written on C. SPGraphviz uses managed wrapper for using functions from Graphviz library. There are several implementations of managed wrapper for Graphviz:

WinGraphviz by ood Tsen

Rendering an in-memory Graphviz image with C# by David Brown

Title: DOT Language Parser


问:
Wildcard to match files with two "dots"
This does not work:

```<code>del "folder\*.dll.config"
</code>```

However, it does work without specifying a folder

```<code>cd folder
del "*.dll.config"
</code>```

Why?

PS. Also, any workarounds? (beside the one mentioned - changing current dir and then going back)

EDIT: I'm an idiot I had a typo in my code, voting to close my own question now.

答:
You can use thepushd and popd commands like:

```<code> pushd folder
 del "*.dll.config"
 popd
</code>```

This way you move to the desire location, erase all .dll.config files and return to the previous location.

Title: Wildcard to match files with two "dots"

Body:
This does not work:

del "folder\*.dll.config"

However, it does work without specifying a folder

cd folder
del "*.dll.config"

Why?

PS. Also, any workarounds? (beside the one mentioned - changing current dir and then going back)

EDIT: I'm an idiot I had a typo in my code, voting to close my own question now.

Body:
You can use thepushd and popd commands like:

 pushd folder
 del "*.dll.config"
 popd

This way you move to the desire location, erase all .dll.config files and return to the previous location.


问:
MVC 4 client side validation not working
Can anyone tell me why client side validation is not working in my MVC 4 application.

_layout.schtml

```<code>@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</code>```

In my web.config I have:

```<code><appSettings>
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
</code>```

In my login.cshtml page I have:

```<code>@using (Html.BeginForm())
{
    <div class="formscontent">

        <ol>
            <li>
                @Html.LabelFor(x => x.AgreementNumber)
                <br />
                @Html.TextBoxFor(x => x.AgreementNumber, new { size = "30" })
                <br />
                @Html.ValidationMessageFor(m => m.AgreementNumber)
                <br />
                <br />
            </li>
            <li>
                @Html.LabelFor(x => x.UserName)
                <br />
                @Html.TextBoxFor(x => x.UserName, new { size = "30" })
                <br />
                @Html.ValidationMessageFor(m => m.UserName)
                <br />
                <br />
            </li>
            <li>
                @Html.LabelFor(x => x.Password)
                <br />
                @Html.PasswordFor(x => x.Password, new { size = "30" })
                <br />
                @Html.ValidationMessageFor(m => m.Password)
                <br />
                <br />
            </li>
        </ol>

    </div>

    <ol>
        <li>
            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
        </li>
    </ol>

    <br />

    <input class="mainbutton" type="submit" value="@Model.Localisation.TranslateHtmlString("LogonBtn")" /><br />
    <div style="text-align: left; padding: 0 5px 5px 10px;">
        Forgot login-info? clik <a class="link" href="@Url.Action("Index", "Credentials")">here.</a>
    </div>

}
</code>```

In the bottom of login page:

```<code>@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
}
</code>```

JavaScript is enabled in my browser. In the MVC 4 template project from Visual Studio client validation works fine.

Running the application, on login page when viewing page source, I see this rendered:

```<code><label for="AgreementNumber">number</label>
<br />
<input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" />
<br />
<span class="field-validation-valid" data-valmsg-for="AgreementNumber" data-valmsg-  replace="true"></span>
</code>```

and in this in the bottom:

```<code><script src="/BMWebsite/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/BMWebsite/Scripts/jquery.validate.inline.js"></script>
<script src="/BMWebsite/Scripts/jquery.validate.js"></script>
<script src="/BMWebsite/Scripts/jquery.validate.unobtrusive.js"></script>
</code>```

My model properties are annotated:

```<code>public class LogonModel : ModelBase
{
    [MyRequired("AgreementNumberRequiredProperty")]
    [MyDisplay("AgreementNumberLabel")]
    public string AgreementNumber { get; set; }

    [MyRequired("UserNameRequiredProperty")]
    [MyDisplay("UserNameLabel")]
    public string UserName { get; set; }

    [MyRequired("PasswordRequiredProperty")]
    [DataType(DataType.Password)]
    [MyDisplay("PasswordLabel")]
    public string Password { get; set; }

    [MyDisplay("RememberMeCheckBox")]
    public bool RememberMe { get; set; }
}
</code>```

MyRequired is a class derived from the regular RequiredAttribute. The reason is that my error messages are localised by overriding the FormatErrorMessage(string name) method of the RequiredAttribute class. And it works fine - My labels and error messages are localized.

MyRequired.cs

```<code>public class MyRequiredAttribute : RequiredAttribute
{
    private readonly string _errorMessagekey;

    public MyRequiredAttribute(string errorMessage)
    {
        _errorMessagekey = errorMessage;
    }

    public override string FormatErrorMessage(string name)
    {
        var translation = HttpContext.Current.Session["translation"] as LocalisationHelper;

        return translation != null ? translation.Translate(_errorMessagekey) : ErrorMessage;
    }
}
</code>```

I put a breakpoint in the POST version of my login action method, and it is being hit. The form is posted to server where server side validation happens. Client side validation doesn't happen.

What am I missing?

Thank you.

答: I created this html <form action="/StudentInfo/Edit/2" method="post" novalidate="novalidate"> where the novalidate="novalidate" was preventing the client-side jQuery from executing, when I removed novalidate="novalidate", client-side jQuery was enabled and stared working.

Body:
Can anyone tell me why client side validation is not working in my MVC 4 application.

_layout.schtml

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

In my web.config I have:

<appSettings>
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

In my login.cshtml page I have:

@using (Html.BeginForm())
{

                @Html.LabelFor(x => x.AgreementNumber)

                @Html.TextBoxFor(x => x.AgreementNumber, new { size = "30" })

                @Html.ValidationMessageFor(m => m.AgreementNumber)

                @Html.LabelFor(x => x.UserName)

                @Html.TextBoxFor(x => x.UserName, new { size = "30" })

                @Html.ValidationMessageFor(m => m.UserName)

                @Html.LabelFor(x => x.Password)

                @Html.PasswordFor(x => x.Password, new { size = "30" })

                @Html.ValidationMessageFor(m => m.Password)

            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })

    <input class="mainbutton" type="submit" value="@Model.Localisation.TranslateHtmlString("LogonBtn")" />

        Forgot login-info? clik here.

}

In the bottom of login page:

@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
}

JavaScript is enabled in my browser. In the MVC 4 template project from Visual Studio client validation works fine.

Running the application, on login page when viewing page source, I see this rendered:

number

<input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" />

and in this in the bottom:

My model properties are annotated:

public class LogonModel : ModelBase
{
    [MyRequired("AgreementNumberRequiredProperty")]
    [MyDisplay("AgreementNumberLabel")]
    public string AgreementNumber { get; set; }

    [MyRequired("UserNameRequiredProperty")]
    [MyDisplay("UserNameLabel")]
    public string UserName { get; set; }

    [MyRequired("PasswordRequiredProperty")]
    [DataType(DataType.Password)]
    [MyDisplay("PasswordLabel")]
    public string Password { get; set; }

    [MyDisplay("RememberMeCheckBox")]
    public bool RememberMe { get; set; }
}

MyRequired is a class derived from the regular RequiredAttribute. The reason is that my error messages are localised by overriding the FormatErrorMessage(string name) method of the RequiredAttribute class. And it works fine - My labels and error messages are localized.

MyRequired.cs

public class MyRequiredAttribute : RequiredAttribute
{
    private readonly string _errorMessagekey;

    public MyRequiredAttribute(string errorMessage)
    {
        _errorMessagekey = errorMessage;
    }

    public override string FormatErrorMessage(string name)
    {
        var translation = HttpContext.Current.Session["translation"] as LocalisationHelper;

        return translation != null ? translation.Translate(_errorMessagekey) : ErrorMessage;
    }
}

I put a breakpoint in the POST version of my login action method, and it is being hit. The form is posted to server where server side validation happens. Client side validation doesn't happen.

What am I missing?

Thank you.


问:
Node JS - How to use URL query strings?
How can you use URL query strings in NodeJS like PHP's $_GET["query"] command?

http://php.net/manual/en/reserved.variables.get.php

Say for example you wanted to extend the code below to use a ?option=1 on the /page001 part.

So visiting ServerURL/page001?option=1 would write "Page1: Option 001 Selected".

And ServerURL/page001?option=2 would write "Page1: Option 002 Selected" etc.

```<code>var http = require('http');
var fs = require("fs");
var location = require('location-href');

var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();

////////////////////

var http=require('http');
var url=require('url');

var server=http.createServer(function(req,res){
    var pathname=url.parse(req.url).pathname;
    switch(pathname){
        case '/page001':
            res.end('<div id="page001"><h2>Page 001</h2><div>Page 001 Content</div></div>');
            console.log("Page 001 Loaded");
        break;
        case '/page002':
            res.end('<div id="page002"><h2>Page 002</h2><div>Page 002 Content</div></div>');
            console.log("Page 002 Loaded");
        break;
        default:
            res.end('<div id="default"><h2>Default</h2><div>This is the default page</div></div>');
            console.log("Default page was loaded");
        break;
    }

}).listen(8080);

console.log("Running on Port 8080");
</code>```

答:
You'll have to parse the .search property of the URL that you parsed. There's plenty of examples on how to parse a query string on this site.

```<code>var reqUrl = url.parse(req.url),
    search = reqUrl.search,
    pathname = reqUrl.pathname;
</code>```

Title: Node JS - How to use URL query strings?

Body:
How can you use URL query strings in NodeJS like PHP's $_GET["query"] command?

http://php.net/manual/en/reserved.variables.get.php

Say for example you wanted to extend the code below to use a ?option=1 on the /page001 part.

So visiting ServerURL/page001?option=1 would write "Page1: Option 001 Selected".

And ServerURL/page001?option=2 would write "Page1: Option 002 Selected" etc.

var http = require('http');
var fs = require("fs");
var location = require('location-href');

var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();

////////////////////

var http=require('http');
var url=require('url');

var server=http.createServer(function(req,res){
    var pathname=url.parse(req.url).pathname;
    switch(pathname){
        case '/page001':
            res.end('

Page 001

Page 001 Content

');
            console.log("Page 001 Loaded");
        break;
        case '/page002':
            res.end('

Page 002

Page 002 Content

');
            console.log("Page 002 Loaded");
        break;
        default:
            res.end('

Default

This is the default page

');
            console.log("Default page was loaded");
        break;
    }

}).listen(8080);

console.log("Running on Port 8080");

Body:
You'll have to parse the .search property of the URL that you parsed. There's plenty of examples on how to parse a query string on this site.

var reqUrl = url.parse(req.url),
    search = reqUrl.search,
    pathname = reqUrl.pathname;


问:
c++ - having trouble in random numbers
This program generates random numbers and lets the user guess it.
I'm using Geany as IDE and it highlights this as an error:
Error message: error: 'rand' was not declared in this scope

```<code>the_number = rand() % 101 + 1;
</code>```

Code (not working):

```<code>#include <iostream>
using namespace std;
int main()

{
using namespace std;

int the_number;
int guess;
int tries=8;

the_number = rand() % 101 + 1;

cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;

for (tries = 8; tries++;)
{
    if (guess == 8)
    {
        cout << "You guessed it!";
        cout << "And it only took you: "<< tries;
    }
    else if (guess < the_number)
    {
        cout << "Higher";
        tries++;
    }

    else if (guess > the_number)
    {
        cout << "Lower";
        tries++;
    }

    else
         cout << "That's not even in range!";
    return 0;
   }
}
</code>```

答:
You are missing the include for cstdlib. Here is a minimal working example:</p>

```<code>#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    // your code goes here
    std::cout<<rand()<<std::endl;
    return 0;
}
</code>```

Title: c++ - having trouble in random numbers

Body:
This program generates random numbers and lets the user guess it.
I'm using Geany as IDE and it highlights this as an error:
Error message: error: 'rand' was not declared in this scope

the_number = rand() % 101 + 1;

Code (not working):

#include <iostream>
using namespace std;
int main()

{
using namespace std;

int the_number;
int guess;
int tries=8;

the_number = rand() % 101 + 1;

cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;

for (tries = 8; tries++;)
{
    if (guess == 8)
    {
        cout << "You guessed it!";
        cout << "And it only took you: "<< tries;
    }
    else if (guess < the_number)
    {
        cout << "Higher";
        tries++;
    }

    else if (guess > the_number)
    {
        cout << "Lower";
        tries++;
    }

    else
         cout << "That's not even in range!";
    return 0;
   }
}

Body:
You are missing the include for cstdlib. Here is a minimal working example:

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    // your code goes here
    std::cout<<rand()<<std::endl;
    return 0;
}


问:
Extract 'p' data from 'div' with Class of div = ""
I am trying to extract the data in the div with "" as className followed by p tag.
My html looks like this

```<code><div class=""><p>I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.</p><p>I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.</p></div></div>
</code>```

I am using Beautifulsoup and my code to extarct this data is :

```<code>reviewAllList = [row.text for row in soup.find_all('div',attrs={"class" : ""})]
</code>```

However, I am not able to extarct the correct data from the same. Is it that I am missing something? I am using Python 3.5.

答:
I assume you just want to get the text from the paragraphs.

You could do something like:

```<code>mydiv = soup.find("div", { "class" : "" })
for p in mydiv.find_all('p'):
    text_list.append(p.get_text())
</code>```

or

```<code>mydiv = soup.find("div", { "class" : "" })
text = mydiv.find('p').get_text()
</code>```

Can not test right now, but from my experience with BS this should work fine.

Edit: tested and corrected it.

Body:
I am trying to extract the data in the div with "" as className followed by p tag.
My html looks like this

I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.

I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.

I am using Beautifulsoup and my code to extarct this data is :

reviewAllList = [row.text for row in soup.find_all('div',attrs={"class" : ""})]

However, I am not able to extarct the correct data from the same. Is it that I am missing something? I am using Python 3.5.

Body:
I assume you just want to get the text from the paragraphs.

You could do something like:

mydiv = soup.find("div", { "class" : "" })
for p in mydiv.find_all('p'):
    text_list.append(p.get_text())

or

mydiv = soup.find("div", { "class" : "" })
text = mydiv.find('p').get_text()

Can not test right now, but from my experience with BS this should work fine.

Edit: tested and corrected it.


问:
Nuget Package restore with git submodule
i have a project where i include 2 submodules from git. Both projects have "nuget package restore" enabled, the parent project too.
The package folder in the two included submodules is not checked in, does not exist in checked out projects.
When building the parent project Nuget tries to restore the packages in the subfolders but into the wrong package folder!

```<code>"C:\Dev\git\oasisdb\odb_oasis_repository\ODB_OASIS_Repository\.nuget\NuGet.exe" install "C:\Dev\git\oasisdb\odb_oasis_repository\odb_oasis_rvm\ODB_OASIS_RVM_EF\ODB_OASIS_RVM_EF\packages.config" -source ""  -NonInteractive -RequireConsent -solutionDir "C:\Dev\git\oasisdb\odb_oasis_repository\ODB_OASIS_Repository\ "
</code>```

Why does nuget not restore in the solution dir of the submodule?

Thanks

答:
If you're using VS2015 Update 1 or later, you can convert your project to use project.json to fix this.

In short:

Run Uninstall-Package <package name> -Force -RemoveDependencies for all your packages. You may wanna copy-paste your packages.config in notepad before you do this.

Delete packages.config from the project, save the project, unload

Edit the project file and remove:

Any referenced .props files at the top related to nuget

Any <Reference> elements that reference a package

The .targets files at the bottom that reference nuget - usually starts with: <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

If your packages contain Roslyn analyzers, make sure to remove them too.

Save the file and relod the project

Add project.json with:

```<code>{
  "dependencies": {
  },
  "frameworks": {
    ".NETFramework,Version=v4.6.1": {}
  },
  "runtimes": {
    "win": {}
  }
}
</code>```

Finally add your packages again, either by hand under dependencies or using Install-Package or with the nuget UI in VS.

I've also had to remove any Microsoft.Bcl.* packages from my projects because they explicitly look for a packages.config file.

EDIT: this (removing the Microsoft.Bcl.* packages will give you a compile-time error, even though the project will build fine, because the .targets file Microsoft.Bcl.Build adds will still look for packages.config.

To suppress this, edit your project file and add:

```<code><SkipValidatePackageReferences>true</SkipValidatePackageReferences>
</code>```

This needs to go to the first <PropertyGroup> that doesn't have a Condition attribute set. If there isn't one, just add another at the top, like:

```<code><PropertyGroup>
    <SkipValidatePackageReferences>true</SkipValidatePackageReferences>
</PropertyGroup>
</code>```

Body:
i have a project where i include 2 submodules from git. Both projects have "nuget package restore" enabled, the parent project too.
The package folder in the two included submodules is not checked in, does not exist in checked out projects.
When building the parent project Nuget tries to restore the packages in the subfolders but into the wrong package folder!

"C:\Dev\git\oasisdb\odb_oasis_repository\ODB_OASIS_Repository\.nuget\NuGet.exe" install "C:\Dev\git\oasisdb\odb_oasis_repository\odb_oasis_rvm\ODB_OASIS_RVM_EF\ODB_OASIS_RVM_EF\packages.config" -source ""  -NonInteractive -RequireConsent -solutionDir "C:\Dev\git\oasisdb\odb_oasis_repository\ODB_OASIS_Repository\ "

Why does nuget not restore in the solution dir of the submodule?

Thanks

Body:
If you're using VS2015 Update 1 or later, you can convert your project to use project.json to fix this.

In short:

Run Uninstall-Package <package name> -Force -RemoveDependencies for all your packages. You may wanna copy-paste your packages.config in notepad before you do this.

Delete packages.config from the project, save the project, unload

Edit the project file and remove:

Any referenced .props files at the top related to nuget

Any <Reference> elements that reference a package

The .targets files at the bottom that reference nuget - usually starts with: <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

If your packages contain Roslyn analyzers, make sure to remove them too.

Save the file and relod the project

Add project.json with:

{
  "dependencies": {
  },
  "frameworks": {
    ".NETFramework,Version=v4.6.1": {}
  },
  "runtimes": {
    "win": {}
  }
}

Finally add your packages again, either by hand under dependencies or using Install-Package or with the nuget UI in VS.

I've also had to remove any Microsoft.Bcl.* packages from my projects because they explicitly look for a packages.config file.

EDIT: this (removing the Microsoft.Bcl.* packages will give you a compile-time error, even though the project will build fine, because the .targets file Microsoft.Bcl.Build adds will still look for packages.config.

To suppress this, edit your project file and add:

<SkipValidatePackageReferences>true</SkipValidatePackageReferences>

This needs to go to the first <PropertyGroup> that doesn't have a Condition attribute set. If there isn't one, just add another at the top, like:

<PropertyGroup>
    <SkipValidatePackageReferences>true</SkipValidatePackageReferences>
</PropertyGroup>


问:
Powershell Script That uploads files to Azure File Storage
So I have a Azure file storage which you can map a collective drive too.
At the moment it's chosen as the X drive but I'm in a little problem becuase sometimes I lose connection to the drive because it goes IDLE.

I followed this guide that provided me how to set evrything up (" https://ppolyzos.com/2016/09/09/map-network-drive-to-azure-storage-account-file-storage/")

I wanted to move some files to that specific folder through a timed schedule with the following script.

```<code>With CreateObject("Scripting.FileSystemObject")
    .MoveFile "YourFolder\*.*", "X:\AzureFolder"
End With
</code>```

The above vbscript worked like a charm but as I mentioned the azure file storage actually goes IDLE and the job failes.

So my plan now was to actually create a powershell script that has the authentication values set as hard variables and then just move the files as the above vbscript does.
Does anyone know if there are some open source code where someone has done something similar?

I did finde some script on the net ( " https://gallery.technet.microsoft.com/scriptcenter/Recursively-upload-a-bfb615fe " )
But they dont seem to work.

Would be pleased if someone can point me in the right direction or provide with a helpfull guide.

Thanks!

答:
The following lines uploads local files into azure blob storage

```<code>$ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName ` -StorageAccountKey $StorageAccountKey
$ContainerName = "webimages"
New-AzureStorageContainer -Name $ContainerName -Context $ctx -Permission Blob
$localFileDirectory = "X:\Temp\AzureFilesToUpload\"
$files = Get-ChildItem -Path $localFileDirectory -Recurse -File
foreach($file in $files)
{
    $localFile = $localFileDirectory+$file
    Set-AzureStorageBlobContent -File $localFile -Container $ContainerName `-Blob $BlobName -Context $ctx
}
Get-AzureStorageBlob -Container $ContainerName -Context $ctx | Select Name
</code>```

Below lines uploads local files into azure files section of storage account instead of blob

```<code>$ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName ` -StorageAccountKey $StorageAccountKey
$s = New-AzureStorageShare $filesharename –Context $ctx # to create new file share
$localFileDirectory = "X:\Temp\AzureFilesToUpload\"
$files = Get-ChildItem -Path $localFileDirectory -Recurse -File
foreach($file in $files)
{
    $localFile = $localFileDirectory+$file
    Set-AzureStorageFileContent –Share $s –Source $localFile
}
  # if you don’t want them in the root folder of the share, but in a subfolder?
New-AzureStorageDirectory –Share $s –Path $foldername
foreach($file in $files)
{
    $localFile = $localFileDirectory+$file
    Set-AzureStorageFileContent –Share $s –Source $localFile –Path $foldername
}
</code>```

Body:
So I have a Azure file storage which you can map a collective drive too.
At the moment it's chosen as the X drive but I'm in a little problem becuase sometimes I lose connection to the drive because it goes IDLE.

I followed this guide that provided me how to set evrything up (" https://ppolyzos.com/2016/09/09/map-network-drive-to-azure-storage-account-file-storage/")

I wanted to move some files to that specific folder through a timed schedule with the following script.

With CreateObject("Scripting.FileSystemObject")
    .MoveFile "YourFolder\*.*", "X:\AzureFolder"
End With

The above vbscript worked like a charm but as I mentioned the azure file storage actually goes IDLE and the job failes.

So my plan now was to actually create a powershell script that has the authentication values set as hard variables and then just move the files as the above vbscript does.
Does anyone know if there are some open source code where someone has done something similar?

I did finde some script on the net ( " https://gallery.technet.microsoft.com/scriptcenter/Recursively-upload-a-bfb615fe " )
But they dont seem to work.

Would be pleased if someone can point me in the right direction or provide with a helpfull guide.

Thanks!

Body:
The following lines uploads local files into azure blob storage

$ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName ` -StorageAccountKey $StorageAccountKey
$ContainerName = "webimages"
New-AzureStorageContainer -Name $ContainerName -Context $ctx -Permission Blob
$localFileDirectory = "X:\Temp\AzureFilesToUpload\"
$files = Get-ChildItem -Path $localFileDirectory -Recurse -File
foreach($file in $files)
{
    $localFile = $localFileDirectory+$file
    Set-AzureStorageBlobContent -File $localFile -Container $ContainerName `-Blob $BlobName -Context $ctx
}
Get-AzureStorageBlob -Container $ContainerName -Context $ctx | Select Name

Below lines uploads local files into azure files section of storage account instead of blob

$ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName ` -StorageAccountKey $StorageAccountKey
$s = New-AzureStorageShare $filesharename –Context $ctx # to create new file share
$localFileDirectory = "X:\Temp\AzureFilesToUpload\"
$files = Get-ChildItem -Path $localFileDirectory -Recurse -File
foreach($file in $files)
{
    $localFile = $localFileDirectory+$file
    Set-AzureStorageFileContent –Share $s –Source $localFile
}
  # if you don’t want them in the root folder of the share, but in a subfolder?
New-AzureStorageDirectory –Share $s –Path $foldername
foreach($file in $files)
{
    $localFile = $localFileDirectory+$file
    Set-AzureStorageFileContent –Share $s –Source $localFile –Path $foldername
}


问:
How to open window or whatever while my method is doing something in background WPF
as much as we know,
programs are executing line by line, and now I am facing issue, I have a method which is taking few seconds to execute,
I thought I could solve it by threads but I will speak about it later, now what I would like to do is next:

How could I open a window with message like "Still executing..." when that method start execution and when method is done window could close himself,
I need that because I Would like to avoid UI freezing because that long method is not in another task/thread.

Here is how it looks like:

```<code>if (e.Key == Key.Delete)
{
    //Could I show window here like like "Loading please wait.."
    ExecuteLongMethod();
    //When this is done close this method
}
</code>```

Thanks guys,
Cheers

答:
Use the await-pattern

```<code>    public void YourMethod()
    {

        if (e.Key == Key.Delete)
        {
            //Could I show window here like like "Loading please wait.."
            FireAndForget();
            //When this is done close this method
        }
    }

    public async void FireAndForget()
    {

        await Task.Run(() => { ExecuteLongMethod(); });

    }
</code>```

Fire and forget is an antipattern so, but sometimes u face problems where you cant await forever - like in Commands.

If you want to wait for a Result or till its finished go like this

```<code>public async void YourMethodAsync()
{

    if (e.Key == Key.Delete)
    {
        //Could I show window here like like "Loading please wait.."
        await CorrectWayAsync();
        //When this is done close this method
    }
}

public async Task CorrectWayAsync()
{
    await Task.Run(() => { ExecuteLongMethod(); });
}
</code>```

Body:
as much as we know,
programs are executing line by line, and now I am facing issue, I have a method which is taking few seconds to execute,
I thought I could solve it by threads but I will speak about it later, now what I would like to do is next:

How could I open a window with message like "Still executing..." when that method start execution and when method is done window could close himself,
I need that because I Would like to avoid UI freezing because that long method is not in another task/thread.

Here is how it looks like:

if (e.Key == Key.Delete)
{
    //Could I show window here like like "Loading please wait.."
    ExecuteLongMethod();
    //When this is done close this method
}

Thanks guys,
Cheers

Body:
Use the await-pattern

    public void YourMethod()
    {

        if (e.Key == Key.Delete)
        {
            //Could I show window here like like "Loading please wait.."
            FireAndForget();
            //When this is done close this method
        }
    }

    public async void FireAndForget()
    {

        await Task.Run(() => { ExecuteLongMethod(); });

    }

Fire and forget is an antipattern so, but sometimes u face problems where you cant await forever - like in Commands.

If you want to wait for a Result or till its finished go like this

public async void YourMethodAsync()
{

    if (e.Key == Key.Delete)
    {
        //Could I show window here like like "Loading please wait.."
        await CorrectWayAsync();
        //When this is done close this method
    }
}

public async Task CorrectWayAsync()
{
    await Task.Run(() => { ExecuteLongMethod(); });
}


问:
UIDatePicker Shows Empty Picker view
UIDatePicker Shows Empty Picker View. It's working perfect, I mean It is scrolling, It is setting date to respective textfield but in picker view it is not displaying date. I have attached a screenshot.

Code for DatePiker,

```<code> datePicker = [[UIDatePicker alloc]init];
 datePicker.datePickerMode = UIDatePickerModeDateAndTime;
 [datePicker setDate:[NSDate date]];

 _txtDue.inputView = datePicker;
</code>```

Any help will be appreciated!

答:
Finally I figure out it. It was a issue of one third party library called UIHidingView!! It was added by someone in this project. This library's description from github states that,

UIHidingView is an iOS class that displays UIView element on top UITableView which is hiding when Table View is scrolling

Now UIDatePicker internally used tableview in it so, it was hiding it's components!

PS : take care when using third party libraries!!

Title: UIDatePicker Shows Empty Picker view

Body:
UIDatePicker Shows Empty Picker View. It's working perfect, I mean It is scrolling, It is setting date to respective textfield but in picker view it is not displaying date. I have attached a screenshot.

Code for DatePiker,

 datePicker = [[UIDatePicker alloc]init];
 datePicker.datePickerMode = UIDatePickerModeDateAndTime;
 [datePicker setDate:[NSDate date]];

 _txtDue.inputView = datePicker;

Any help will be appreciated!


问:
Container of pointers to template class
I'm trying to make a class (ParametersHolder) that can contain different named parameters (Parameter<T>). The ParametersHolder has an std::unordered_map container holding my parameters. To make this work, I had to derive Parameter<T> from an empty ParameterBase class and I dynamically cast ParameterBase to Parameter<T> when I want to get a parameter with the right type. Here is the code:

ParametersHolder.hpp

```<code>...
#include "Parameter.hpp"

class ParametersHolder {

  std::unordered_map<std::string, std::shared_ptr<ParameterBase>> parameters;

  public:

    bool paramExists(std::string name) {
      return parameters.find(name) != parameters.end();
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getOrCreate(std::string name, int dims = 1) {
      if (paramExists(name)) {
        return getParam<T>(name);
      }
      return create<T>(name, dims);
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> create(std::string name, int dims = 1) {
      if (paramExists(name)) throw std::runtime_error("Trying to create parameter '" + name + "' but it already exists");
      auto param = std::make_shared<Parameter<T>>(dims);
      parameters[name] = param;
      return param;
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getParam(std::string name) {
      if (!paramExists(name)) throw std::runtime_error("Parameter '" + name + "' doesn't exist");
      auto param = std::dynamic_pointer_cast<Parameter<T>>(parameters[name]);
      if (param == nullptr) throw std::runtime_error("Parameter '" + name + "' is not a(n) " + boost::typeindex::type_id<T>().pretty_name());
      return param;
    }

};
</code>```

Parameter.hpp

```<code>class ParameterBase {
  public:
    virtual ~ParameterBase() {}
};

template<typename T>
class Parameter : public ParameterBase {

  std::vector<T> data;

  public:

    explicit Parameter(int dim = 1) : data(dim) {}

    T getValue(int dim = 1) {
      dimCheck(dim);
      return data[dim - 1];
    }

    void setValue(T value, int dim = 1) {
      dimCheck(dim);
      data[dim - 1] = value;
    }

  private:
    void dimCheck(int dim) {
      if (dim > data.size()) {
        auto errorMsg = "Trying to access dimension " + std::to_string(dim)
          + " but parameter has only " + std::to_string(data.size()) + " dimensions";

        throw std::runtime_error(errorMsg);
      }
    }
};
</code>```

To use this code I can do that:

```<code>auto paramsHolder = std::make_shared<ParametersHolder>();
auto filename = paramsHolder->create<std::string>("filename");
filename->setValue("untitled.txt");

...

auto param = paramsHolder->getParam<std::string>("filename");
std::cout << param->getValue() << std::endl;
</code>```

This works fine but having an empty ParameterBase feels odd. Is there another way to achieve that? I read about boost::any, but I'm not sure this is the right use case. And if it is, I don't know what the type signature of the unordered_map should be among these:

```<code>std::unordered_map<std::string, std::shared_ptr<Parameter<boost::any>>>
std::unordered_map<std::string, std::shared_ptr<boost::any>>
std::unordered_map<std::string, boost::any>
</code>```

答:
You can get rid of it by using shared_ptr<void>, static_pointer_cast and a static family identifier for the types, so that you know when the T used to create the pointer and the one used to get it differ.

A working example based on your own code is much better in this case:

```<code>#include <vector>
#include <unordered_map>
#include <memory>
#include <string>
#include <iostream>
#include <utility>

template<typename T>
class Parameter {
  std::vector<T> data;

  public:

    explicit Parameter(int dim = 1) : data(dim) {}

    T getValue(int dim = 1) {
      dimCheck(dim);
      return data[dim - 1];
    }

    void setValue(T value, int dim = 1) {
      dimCheck(dim);
      data[dim - 1] = value;
    }

  private:
    void dimCheck(int dim) {
      if (dim > data.size()) {
        auto errorMsg = "Trying to access dimension " + std::to_string(dim)
          + " but parameter has only " + std::to_string(data.size()) + " dimensions";

        throw std::runtime_error(errorMsg);
      }
    }
};

class ParametersHolder {
  std::unordered_map<std::string, std::pair<std::size_t, std::shared_ptr<void>>> parameters;

  std::size_t next() {
      static std::size_t value = 0;
      return value++;
  }

  template<typename>
  std::size_t type() {
      static std::size_t value = next();
      return value;
  }

public:

    bool paramExists(std::string name) {
      return parameters.find(name) != parameters.end();
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getOrCreate(std::string name, int dims = 1) {
      if (paramExists(name)) {
        return getParam<T>(name);
      }
      return create<T>(name, dims);
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> create(std::string name, int dims = 1) {
      if (paramExists(name)) throw std::runtime_error("Trying to create parameter '" + name + "' but it already exists");
      auto param = std::make_shared<Parameter<T>>(dims);
      parameters[name] = { type<T>(), param };
      return param;
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getParam(std::string name) {
      if (!paramExists(name)) throw std::runtime_error("Parameter '" + name + "' doesn't exist");
      if (parameters[name].first != type<T>()) throw std::runtime_error("Parameter '" + name + "' is not a(n) " + std::to_string(type<T>()));
      auto param = std::static_pointer_cast<Parameter<T>>(parameters[name].second);
      return param;
    }
};

int main() {
     auto paramsHolder = std::make_shared<ParametersHolder>();
     auto filename = paramsHolder->create<std::string>("filename");
     filename->setValue("untitled.txt");

     auto param = paramsHolder->getParam<std::string>("filename");
     std::cout << param->getValue() << std::endl;
}
</code>```

See it on Coliru.

Title: Container of pointers to template class

Body:
I'm trying to make a class (ParametersHolder) that can contain different named parameters (Parameter<T>). The ParametersHolder has an std::unordered_map container holding my parameters. To make this work, I had to derive Parameter<T> from an empty ParameterBase class and I dynamically cast ParameterBase to Parameter<T> when I want to get a parameter with the right type. Here is the code:

ParametersHolder.hpp

...
#include "Parameter.hpp"

class ParametersHolder {

  std::unordered_map<std::string, std::shared_ptr<ParameterBase>> parameters;

  public:

    bool paramExists(std::string name) {
      return parameters.find(name) != parameters.end();
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getOrCreate(std::string name, int dims = 1) {
      if (paramExists(name)) {
        return getParam<T>(name);
      }
      return create<T>(name, dims);
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> create(std::string name, int dims = 1) {
      if (paramExists(name)) throw std::runtime_error("Trying to create parameter '" + name + "' but it already exists");
      auto param = std::make_shared<Parameter<T>>(dims);
      parameters[name] = param;
      return param;
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getParam(std::string name) {
      if (!paramExists(name)) throw std::runtime_error("Parameter '" + name + "' doesn't exist");
      auto param = std::dynamic_pointer_cast<Parameter<T>>(parameters[name]);
      if (param == nullptr) throw std::runtime_error("Parameter '" + name + "' is not a(n) " + boost::typeindex::type_id<T>().pretty_name());
      return param;
    }

};

Parameter.hpp

class ParameterBase {
  public:
    virtual ~ParameterBase() {}
};

template<typename T>
class Parameter : public ParameterBase {

  std::vector<T> data;

  public:

    explicit Parameter(int dim = 1) : data(dim) {}

    T getValue(int dim = 1) {
      dimCheck(dim);
      return data[dim - 1];
    }

    void setValue(T value, int dim = 1) {
      dimCheck(dim);
      data[dim - 1] = value;
    }

  private:
    void dimCheck(int dim) {
      if (dim > data.size()) {
        auto errorMsg = "Trying to access dimension " + std::to_string(dim)
          + " but parameter has only " + std::to_string(data.size()) + " dimensions";

        throw std::runtime_error(errorMsg);
      }
    }
};

To use this code I can do that:

auto paramsHolder = std::make_shared<ParametersHolder>();
auto filename = paramsHolder->create<std::string>("filename");
filename->setValue("untitled.txt");

...

auto param = paramsHolder->getParam<std::string>("filename");
std::cout << param->getValue() << std::endl;

This works fine but having an empty ParameterBase feels odd. Is there another way to achieve that? I read about boost::any, but I'm not sure this is the right use case. And if it is, I don't know what the type signature of the unordered_map should be among these:

std::unordered_map<std::string, std::shared_ptr<Parameter<boost::any>>>
std::unordered_map<std::string, std::shared_ptr<boost::any>>
std::unordered_map<std::string, boost::any>

Body:
You can get rid of it by using shared_ptr<void>, static_pointer_cast and a static family identifier for the types, so that you know when the T used to create the pointer and the one used to get it differ.

A working example based on your own code is much better in this case:

#include <vector>
#include <unordered_map>
#include <memory>
#include <string>
#include <iostream>
#include <utility>

template<typename T>
class Parameter {
  std::vector<T> data;

  public:

    explicit Parameter(int dim = 1) : data(dim) {}

    T getValue(int dim = 1) {
      dimCheck(dim);
      return data[dim - 1];
    }

    void setValue(T value, int dim = 1) {
      dimCheck(dim);
      data[dim - 1] = value;
    }

  private:
    void dimCheck(int dim) {
      if (dim > data.size()) {
        auto errorMsg = "Trying to access dimension " + std::to_string(dim)
          + " but parameter has only " + std::to_string(data.size()) + " dimensions";

        throw std::runtime_error(errorMsg);
      }
    }
};

class ParametersHolder {
  std::unordered_map<std::string, std::pair<std::size_t, std::shared_ptr<void>>> parameters;

  std::size_t next() {
      static std::size_t value = 0;
      return value++;
  }

  template<typename>
  std::size_t type() {
      static std::size_t value = next();
      return value;
  }

public:

    bool paramExists(std::string name) {
      return parameters.find(name) != parameters.end();
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getOrCreate(std::string name, int dims = 1) {
      if (paramExists(name)) {
        return getParam<T>(name);
      }
      return create<T>(name, dims);
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> create(std::string name, int dims = 1) {
      if (paramExists(name)) throw std::runtime_error("Trying to create parameter '" + name + "' but it already exists");
      auto param = std::make_shared<Parameter<T>>(dims);
      parameters[name] = { type<T>(), param };
      return param;
    }

    template<typename T>
    std::shared_ptr<Parameter<T>> getParam(std::string name) {
      if (!paramExists(name)) throw std::runtime_error("Parameter '" + name + "' doesn't exist");
      if (parameters[name].first != type<T>()) throw std::runtime_error("Parameter '" + name + "' is not a(n) " + std::to_string(type<T>()));
      auto param = std::static_pointer_cast<Parameter<T>>(parameters[name].second);
      return param;
    }
};

int main() {
     auto paramsHolder = std::make_shared<ParametersHolder>();
     auto filename = paramsHolder->create<std::string>("filename");
     filename->setValue("untitled.txt");

     auto param = paramsHolder->getParam<std::string>("filename");
     std::cout << param->getValue() << std::endl;
}

See it on Coliru.


问:
How to upload a word file from Windows Explorer using Protractor testing?
I am trying to upload a word file from Windows Explorer using Protractor.

After I click the "Upload" button, the file explorer window pops up to choose a file, after open - the file name will be auto populated in the text box field. I can't enter the name of the file directly because it's a non-editable field:

```<code><div class="form-control uneditable-input">
  <i class="glyphicon glyphicon-file ng-hide" ng-show="file != null"/>
  <span class="fileinput-filename ng-binding"/>
</div>
</code>```

How can I upload my file?

答:
You can pass the relativePath as "../../directory/sample.doc":

```<code>var absolutePath = require('path').resolve(__dirname, relativePath);
element(by.css("i span")).sendKeys(absolutePath);
browser.waitForAngular();
</code>```

This would help you.

Body:
I am trying to upload a word file from Windows Explorer using Protractor.

After I click the "Upload" button, the file explorer window pops up to choose a file, after open - the file name will be auto populated in the text box field. I can't enter the name of the file directly because it's a non-editable field:

How can I upload my file?

Body:
You can pass the relativePath as "../../directory/sample.doc":

var absolutePath = require('path').resolve(__dirname, relativePath);
element(by.css("i span")).sendKeys(absolutePath);
browser.waitForAngular();

This would help you.


问:
What does the second parameter in AddHeaderView in the class ListView do?
Below is the documentation of the method, I dont understand what does the Object data do?

What is it for?

```<code>public void addHeaderView (View v, Object data, boolean isSelectable)
</code>```

Add a fixed view to appear at the top of the list. If addHeaderView is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.
NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.

Parameters:

```<code>   v:           The view to add.
   data:         Data to associate with this view.
   isSelectable: whether the item is selectable.
</code>```

答: It's the data returned from Adapter's getItem method.</p>

Body:
Below is the documentation of the method, I dont understand what does the Object data do?

What is it for?

public void addHeaderView (View v, Object data, boolean isSelectable)

Add a fixed view to appear at the top of the list. If addHeaderView is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.
NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.

Parameters:

   v:           The view to add.
   data:         Data to associate with this view.
   isSelectable: whether the item is selectable.


问:
using c# linq to populate/load a list one time to enhance performance
I'm working on an ASP.NET MVC 4.5 application. I need to populate a list in a dropdown. I t works fine, anyhow, when I click the field there is allways a server request.

I'd like to store the values after the initial load on the client side to speed up the application.

I'm using a ViewModel to populate the list in my Razor View.

Do you know how to achieve an initial load of the this?

Here is my DataSource Controller:

```<code>public JsonResult GetBusinessLineList(string id = null, string query = null)
{

    return
        Json(Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList(),
            JsonRequestBehavior.AllowGet);
}
</code>```

The Razor View:

```<code><div class="form-group">
    @Html.LabelFor(model => model.BusinessLineIdList, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.Select2AjaxFor(model => model.BusinessLineIdList, @Url.Action("GetBusinessLineList", "DataSource"),
               new { @class = "form-control"))

    </div>
</div>
</code>```

Many thanks and kind regards!

答:
You need some caching stratergies here is simple cache helper class

```<code>using System.Runtime.Caching;

public class cacheservice: ICacheservice
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}
</code>```

Usage:

```<code>cacheservice.GetOrSet("CACHEKEY", (delegate method if cache is empty));
</code>```

Cache provider will check if there's anything by the name of "CACHEKEY" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

Example:

```<code>var Data=cacheService.GetOrSet("CACHEKEY", ()=>SomeRepository.GetData());
</code>```

In your case it would be like

```<code>var Data=cacheService.GetOrSet("CACHEKEY", Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList());
</code>```

You can customize according to your needs as well

Using these caching strategies it will first time load data and store in cache in second time it will get value from cache instead of round trip to database.

Body:
I'm working on an ASP.NET MVC 4.5 application. I need to populate a list in a dropdown. I t works fine, anyhow, when I click the field there is allways a server request.

I'd like to store the values after the initial load on the client side to speed up the application.

I'm using a ViewModel to populate the list in my Razor View.

Do you know how to achieve an initial load of the this?

Here is my DataSource Controller:

public JsonResult GetBusinessLineList(string id = null, string query = null)
{

    return
        Json(Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList(),
            JsonRequestBehavior.AllowGet);
}

The Razor View:

    @Html.LabelFor(model => model.BusinessLineIdList, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.Select2AjaxFor(model => model.BusinessLineIdList, @Url.Action("GetBusinessLineList", "DataSource"),
               new { @class = "form-control"))

Many thanks and kind regards!

Body:
You need some caching stratergies here is simple cache helper class

using System.Runtime.Caching;

public class cacheservice: ICacheservice
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}

Usage:

cacheservice.GetOrSet("CACHEKEY", (delegate method if cache is empty));

Cache provider will check if there's anything by the name of "CACHEKEY" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

Example:

var Data=cacheService.GetOrSet("CACHEKEY", ()=>SomeRepository.GetData());

In your case it would be like

var Data=cacheService.GetOrSet("CACHEKEY", Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList());

You can customize according to your needs as well

Using these caching strategies it will first time load data and store in cache in second time it will get value from cache instead of round trip to database.


问:
Fitting to histogram in Matlab
I have used below code to fit to my data's histogram:

```<code>histfit(data,40,'exponential')
</code>```

The questions I can not answer are:

1- How can I find fit parameters of exponential fit?

2- How can I fit a power law to the histogram of data?

Any answer to these questions is highly appreciated.

I have a dataset and I want to fit a power law distribution to histogram of data.

答:
The function which does the heavy lifting inside histfit() is fitdist().

This is the function which calculates the Distribution Parameters.

So you should do the following:

pd = fitdist(data, 'exponential');

To get the parameters of the Exponential Distribution.

Those are the distribution supported in fitdist():

Title: Fitting to histogram in Matlab

Body:
I have used below code to fit to my data's histogram:

histfit(data,40,'exponential')

The questions I can not answer are:

1- How can I find fit parameters of exponential fit?

2- How can I fit a power law to the histogram of data?

Any answer to these questions is highly appreciated.

I have a dataset and I want to fit a power law distribution to histogram of data.


问:
Is there a decent HTML Junit report plugin for Maven?
I find the surefire-report plug-in very unsuitable to my working style. I clean the project all the time and I don't want to spend 5 min to rebuild the whole site every time I want to look at the test report in my browser.

If I type mvn surefire-report:report-only, the generated report is too ugly and barely readable.

What I'm looking for is something like ant's JUnitReport task. Is there one available out there already?

答:
Run the below command

```<code>mvn clean install surefire-report:report
</code>```

You can find the report in the below location

```<code>{basedir}/target/site/surefire-report.html
</code>```

For more details refer the below link

http://maven.apache.org/surefire/maven-surefire-report-plugin/usage.html

Body:
Run the below command

mvn clean install surefire-report:report

You can find the report in the below location

{basedir}/target/site/surefire-report.html

For more details refer the below link

http://maven.apache.org/surefire/maven-surefire-report-plugin/usage.html


问:
.NET encoding issue of mail attachment (.csv)
I use following code to send a attachment (.csv) with Chinese characters. However, MS excel fails to disply the characters properly, it displays something like "¨å¯¹æ–°ç". Is it because I didn't set some property when sending the mail?

Thanks for any advise.

```<code>                byte[] attachBytes = Encoding.UTF8.GetBytes(attachText);
                ms.Write(attachBytes, 0, attachBytes.Length);
                // Set the position to the beginning of the stream.
                ms.Position = 0;
                ContentType ct = new ContentType(MediaTypeNames.Text.Plain);

                Attachment attactment = new Attachment(ms, attachFileName);
                message.Attachments.Add(attactment);
</code>```

答:
i think you need an extra encoding setup for the mail body object, something like this:</p>

```<code>message.BodyEncoding = UTF8
</code>```

Body:
I use following code to send a attachment (.csv) with Chinese characters. However, MS excel fails to disply the characters properly, it displays something like "¨å¯¹æ–°ç". Is it because I didn't set some property when sending the mail?

Thanks for any advise.

                byte[] attachBytes = Encoding.UTF8.GetBytes(attachText);
                ms.Write(attachBytes, 0, attachBytes.Length);
                // Set the position to the beginning of the stream.
                ms.Position = 0;
                ContentType ct = new ContentType(MediaTypeNames.Text.Plain);

                Attachment attactment = new Attachment(ms, attachFileName);
                message.Attachments.Add(attactment);

Body:
i think you need an extra encoding setup for the mail body object, something like this:

message.BodyEncoding = UTF8


问:
How to map a user to a domain other than Federated in OpenStack federation?
I am trying to understand direct mapping on OpenStack. I want to map a user to a domain other than Federated domain. But I always get user mapped to Federated domain. Here follows the link for direct mapping that I am using:

https://specs.openstack.org/openstack/keystone-specs/specs/kilo/federated-direct-user-mapping.html

Here follows the rule for mapping that I am using:

```<code>[
  {
    "local": [
      {
        "user": {
          "name": "{0}",
          "domain": {"name": "Default"}
        }
      },
      {
        "group": {
          "id": "GROUP_ID"
        }
      }
    ],
    "remote": [
      {
        "type": "HTTP_OIDC_SUB"
      }
    ]
  }
]
</code>```

I have configured OpenID connect Idp for federation.

Could someone help me how I can do direct mapping to map a federated user to a domain other than Federated ?

答:
the only way I've been able to get it to not be in the 'Federate' domain, is to force the user to be of type local, but then they need to exist in the backend (SQL/LDAP).

```<code>[
  {
    "local": [
      {
        "user": {
          "name": "{0}",
          "type": "local",
          "domain": {"name": "Default"}
        }
      },
      {
        "group": {
          "id": "GROUP_ID"
        }
      }
    ],
    "remote": [
      {
        "type": "HTTP_OIDC_SUB"
      }
    ]
  }
]
</code>```

The following bit of code in keystone is the culprit for doing this:

```<code>   if user_type is None:
        user_type = user['type'] = UserType.EPHEMERAL

    if user_type == UserType.EPHEMERAL:
        user['domain'] = {
            'id': CONF.federation.federated_domain_name
        }
</code>```

It Basically overrides the domain to a pre-configured domain if your user doesn't have a type, or is ephemeral.

Body:
I am trying to understand direct mapping on OpenStack. I want to map a user to a domain other than Federated domain. But I always get user mapped to Federated domain. Here follows the link for direct mapping that I am using:

https://specs.openstack.org/openstack/keystone-specs/specs/kilo/federated-direct-user-mapping.html

Here follows the rule for mapping that I am using:

[
  {
    "local": [
      {
        "user": {
          "name": "{0}",
          "domain": {"name": "Default"}
        }
      },
      {
        "group": {
          "id": "GROUP_ID"
        }
      }
    ],
    "remote": [
      {
        "type": "HTTP_OIDC_SUB"
      }
    ]
  }
]

I have configured OpenID connect Idp for federation.

Could someone help me how I can do direct mapping to map a federated user to a domain other than Federated ?

Body:
the only way I've been able to get it to not be in the 'Federate' domain, is to force the user to be of type local, but then they need to exist in the backend (SQL/LDAP).

[
  {
    "local": [
      {
        "user": {
          "name": "{0}",
          "type": "local",
          "domain": {"name": "Default"}
        }
      },
      {
        "group": {
          "id": "GROUP_ID"
        }
      }
    ],
    "remote": [
      {
        "type": "HTTP_OIDC_SUB"
      }
    ]
  }
]

The following bit of code in keystone is the culprit for doing this:

   if user_type is None:
        user_type = user['type'] = UserType.EPHEMERAL

    if user_type == UserType.EPHEMERAL:
        user['domain'] = {
            'id': CONF.federation.federated_domain_name
        }

It Basically overrides the domain to a pre-configured domain if your user doesn't have a type, or is ephemeral.


问:
How do you decrease navbar height in Bootstrap 4?
Below is my code for bootstrap 4

```<code> <nav class="navbar navbar-collapse navbar-toggleable-md navbar-light bg-faded ">
    <div class="collapse navbar-collapse" id="navbarText">
      <ul class="navbar-nav mr-auto">

        <li class="nav-item">

          <a class="nav-link " >
            <span  class="icon icon18 icon-upload"></span>
            Input Data From Prior Month
            </a>
        </li>
        <li class="nav-item">
          <a class="nav-link " >
            <span  class="icon icon18 icon-excel-file"></span>
            Export to Excel
          </a>
        </li>
      </ul>
      <span class="navbar-text color-blue">
        *Data Automatically pulled from sources
      </span>
    </div>
   </nav>
</code>```

there are various examples given for bootstrap 3 here
How do you decrease navbar height in Bootstrap 3?
but none of them seem to work for bootstrap 4, can anyone help with this one?

答:
Decreasing the Navbar height is easier in Bootstrap 4 using the spacing utils. The height of the navbar comes from padding in the Navbar contents.

Just use py-0 in the nav-link and navbar-text..

```<code><nav class="navbar navbar-collapse navbar-toggleable-md navbar-light bg-faded ">
    <div class="collapse navbar-collapse" id="navbarText">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link py-0">
                    <span class="icon icon18 icon-upload"></span> Input Data From Prior Month
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link py-0">
                    <span class="icon icon18 icon-excel-file"></span> Export to Excel
                </a>
            </li>
        </ul>
        <span class="navbar-text py-0 color-blue">
        *Data Automatically pulled from sources
      </span>
    </div>
</nav>
</code>```

The py-0 class sets padding-top:0;padding-bottom:0 on the items.

Bootstrap 4 Navbar Shrink Height

Body:
Below is my code for bootstrap 4

            Input Data From Prior Month

            Export to Excel

        *Data Automatically pulled from sources

there are various examples given for bootstrap 3 here
How do you decrease navbar height in Bootstrap 3?
but none of them seem to work for bootstrap 4, can anyone help with this one?

Body:
Decreasing the Navbar height is easier in Bootstrap 4 using the spacing utils. The height of the navbar comes from padding in the Navbar contents.

Just use py-0 in the nav-link and navbar-text..

<nav class="navbar navbar-collapse navbar-toggleable-md navbar-light bg-faded ">
    <div class="collapse navbar-collapse" id="navbarText">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link py-0">
                    <span class="icon icon18 icon-upload"></span> Input Data From Prior Month
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link py-0">
                    <span class="icon icon18 icon-excel-file"></span> Export to Excel
                </a>
            </li>
        </ul>
        <span class="navbar-text py-0 color-blue">
        *Data Automatically pulled from sources
      </span>
    </div>
</nav>

The py-0 class sets padding-top:0;padding-bottom:0 on the items.

Bootstrap 4 Navbar Shrink Height


问:
a member of a non managed class cannot have a ref class type or interface class type
i am trying to implement a gui to a small c++ project, now i am trying to use my unmanaged c++ code in c++/cli in order to use windows forms. after the transform i cannot use the normal sqlite so i am trying to move to the managed sqlite version and i get the error code:
"a member of a non managed class cannot have a ref class type or interface class type" when trying to include a SQLiteConnection in the members of the class.</p>

```<code>#pragma once
#include <list>
#include "CAlbum.h"
#include "CUser.h"
#include "CDataAccess.h"
using namespace System::Data::SQLite;

class CDatabaseAccess : public CDataAccess
{
private:
    albums _albums;
    users _users;
    SQLiteConnection _sqldb;
    int _lastId;
    CPicture _topTaggedPicture;

    albums _albumsOfUser;
    pictures _picturesOfUser;

    bool fileExistsOnDisk(const string& filename);
    bool initDatabase();

public:
    CDatabaseAccess();
    ~CDatabaseAccess();

    bool open() override;
    void close() override;
    void clear() override;

    // album related
    const albums& getAlbums() override;
    const albums& getAlbumsOfUser(int userId) override;
    void insertAlbum(CAlbum& album) override;
    void deleteAlbum(string albumName) override;
    bool albumExists(string albumName) override;
    CAlbum* openAlbum(string albumName) override;
    void closeAlbum(CAlbum *pAlbum) override;

    // picture related
    void addPictureToAlbum(int albumId, CPicture& picture) override;
    void removePictureFromAlbum(int albumId, int pictureId) override;
    void tagUserInPicture(CPicture& picture, int userId) override;
    void untagUserInPicture(CPicture& picture, int userId) override;
    bool isUserTaggedInPicture(const CPicture& picture, int userId) override;

    // user related
    const users& getUsers() override;
    void addUser(CUser& user) override;
    void deleteUser(string userName) override;
    bool userExists(string userName) override;
    bool userExists(int userId) override;
    CUser* getUser(int userId) override;

    // user statistics
    int countAlbumsOwnedOfUser(int userId) override;
    int countAlbumsTaggedOfUser(int userId) override;
    int countTagsOfUser(int userId) override;
    float averageTagsPerAlbumOfUser(int userId) override;

    // queries
    const CUser* getTopTaggedUser() override;
    const CPicture* getTopTaggedPicture() override;
    const pictures& getTaggedPicturesOfUser(int userId) override;

    // sql related
    void setLastId(char* lastId);
    void resetLastId();
};
</code>```

答:
I don't know of any reasonable way to access (not to say create) managed objects from native c++ code.

But that is not the point. You said you have a c++ program for which you want just a c++/CLI (.Net) GUI. As @AlgirdasPreidžius said you need to decide where to put functionality: in native or managed code, but not mix.

In your case, you need to make clear what is core code and what GUI, and try not to mix. The core have to be agnostic (not use!) about the GUI. And the GUI have to acces the core in a very controled form. In this case is convenient to just have pointers to native classes from your core inserted in your managed clases. It "just works". You have to decide if the SQLite belong to the core or to the GUI. The only trick I see here is to acces the data base differently in the GUI and the core: with a "managed" conection from System::Data::SQLite used in GUI and a native sqlite conection for the native core code. Or, if the managed version can generate a native handle you may pass it to the core code, or create a managed version that take a native conection (if System::Data::SQLite have that posibility).

see: Sqlite3DatabaseHandle definition, the SQLiteConnection::Handle, and how it is used to open a conection and how it compare with native use.

That said, I had a similar problem (has a c++ program for which want just a c++/CLI (.Net) GUI.) , and it worked good... in my machine. All other machine where I wanted to run my program were protected, I have no admin rigth there and it was always a compatibility .Net version problem which I can't solve. For my needs it was a better solution to switch to Nana C++ GUI. My core code was already GUI agnostic, so the GUI change was not very difficult. Now everything is native code and with static linking the program is an small portable ejecutable than run aeasly in any of my windows machines as a simple user.

Body:
i am trying to implement a gui to a small c++ project, now i am trying to use my unmanaged c++ code in c++/cli in order to use windows forms. after the transform i cannot use the normal sqlite so i am trying to move to the managed sqlite version and i get the error code:
"a member of a non managed class cannot have a ref class type or interface class type" when trying to include a SQLiteConnection in the members of the class.

#pragma once
#include <list>
#include "CAlbum.h"
#include "CUser.h"
#include "CDataAccess.h"
using namespace System::Data::SQLite;

class CDatabaseAccess : public CDataAccess
{
private:
    albums _albums;
    users _users;
    SQLiteConnection _sqldb;
    int _lastId;
    CPicture _topTaggedPicture;

    albums _albumsOfUser;
    pictures _picturesOfUser;

    bool fileExistsOnDisk(const string& filename);
    bool initDatabase();

public:
    CDatabaseAccess();
    ~CDatabaseAccess();

    bool open() override;
    void close() override;
    void clear() override;

    // album related
    const albums& getAlbums() override;
    const albums& getAlbumsOfUser(int userId) override;
    void insertAlbum(CAlbum& album) override;
    void deleteAlbum(string albumName) override;
    bool albumExists(string albumName) override;
    CAlbum* openAlbum(string albumName) override;
    void closeAlbum(CAlbum *pAlbum) override;

    // picture related
    void addPictureToAlbum(int albumId, CPicture& picture) override;
    void removePictureFromAlbum(int albumId, int pictureId) override;
    void tagUserInPicture(CPicture& picture, int userId) override;
    void untagUserInPicture(CPicture& picture, int userId) override;
    bool isUserTaggedInPicture(const CPicture& picture, int userId) override;

    // user related
    const users& getUsers() override;
    void addUser(CUser& user) override;
    void deleteUser(string userName) override;
    bool userExists(string userName) override;
    bool userExists(int userId) override;
    CUser* getUser(int userId) override;

    // user statistics
    int countAlbumsOwnedOfUser(int userId) override;
    int countAlbumsTaggedOfUser(int userId) override;
    int countTagsOfUser(int userId) override;
    float averageTagsPerAlbumOfUser(int userId) override;

    // queries
    const CUser* getTopTaggedUser() override;
    const CPicture* getTopTaggedPicture() override;
    const pictures& getTaggedPicturesOfUser(int userId) override;

    // sql related
    void setLastId(char* lastId);
    void resetLastId();
};


问:
Searching from File title as well as file content in media library
I managed to Search the contents of text files using custom search as described in the link below: https://docs.kentico.com/k8/custom-development/miscellaneous-custom-development-tasks/smart-search-api/creating-custom-smart-search-indexes

But it is not able to search in the filename. For example, if my search text is "Roman", the file "RomanRaj.txt" should show up in the results. Please help.

答: Try to add file name to your search index by index content customization. See the documentation on this topic.</p>


问:
how to make phone number clickable in classifield wordpress
I tried everything to make the phone number clickable but for some reason it didn't work

```<code>    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>
    <li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><?php echo $post_phone; ?></li>
</code>```

I added this and it still didn't work :

```<code><a href="tel:$post_phone"> $post_phone</a>
</code>```

and this

```<code><li><span><?php esc_html_e( 'Phone', 'classiera' ); ?></span><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?></a></li>
                        <?php }?>
</code>```

Thank you so much for your help

答:
If it is not working for  you in PHP write it in HTML

```<code>    <a href="tel:003531234567">Call me</a>
</code>```

If that doesnt work it is probably something to do with the phone nummber, make sure it is set up for international calling.

Body:
I tried everything to make the phone number clickable but for some reason it didn't work

    <?php global $redux_demo;?>
<?php $phoneon= $redux_demo['phoneon']; ?>
<?php if($phoneon == 1){?>
    <?php $post_phone = get_post_meta($post->ID, 'post_phone', true);  ?>
    <?php if(!empty($post_phone)) {?>

<?php esc_html_e( 'Phone', 'classiera' ); ?><?php echo $post_phone; ?>

I added this and it still didn't work :

 $post_phone

and this

<?php esc_html_e( 'Phone', 'classiera' ); ?><a href="callto://<?php echo $post_phone; ?>"><?php echo $post_phone; ?>

                        <?php }?>

Thank you so much for your help

Body:
If it is not working for  you in PHP write it in HTML

    <a href="tel:003531234567">Call me</a>

If that doesnt work it is probably something to do with the phone nummber, make sure it is set up for international calling.