问:
Using VBA to unzip file without prompting me once (choose "Yes to All" for any dialog box)
There is an unzipping code I'd like to adjust 4 my needs.

```<code>Sub Unzip()
    Dim FSO As Object
    Dim oApp As Object
    Dim Fname As Variant
    Dim FileNameFolder As Variant
    Dim DefinePath As String

          ' Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
    Fname = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl.zip"

    If Fname = False Then
          'Do nothing
    Else
          'Destination folder
       DefinePath = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_mst\"    ' Change to your path / variable
       If Right(DefinePath, 1) <> "\" Then
           DefinePath = DefinePath & "\"
       End If

       FileNameFolder = DefinePath

        '        Delete all the files in the folder DefPath first if you want.
        '        On Error Resume Next
        '        Kill DefPath & "*.*"
        '        On Error GoTo 0

        'Extract the files into the Destination folder
       Set oApp = CreateObject("Shell.Application")
       oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items

        ' MsgBox "You find the files here: " & FileNameFolder

      On Error Resume Next
      Set FSO = CreateObject("scripting.filesystemobject")
      FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
   End If
End Sub
</code>```

Somewhere here:

```<code>  `Set oApp = CreateObject("Shell.Application")
   oApp.Namespace(FileNameFolder).CopyHere`
</code>```

a dialog box appears asking me if I want to overwrite the file that have the same names - and Yes I do want to overwrite them, but without answering the dialog box - I would like to hardcode it into the code, please.

I've found this page https://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx  but I just don't know how to add this parameter #16 which is "Respond with "Yes to All" for any dialog box that is displayed."
Can U help me with that?

And the last thing:
can You explain oApp.Namespace(Fname).items line for me.
I've really tried to guess it myself, but I thing I'm to short 4 this.

答:
the code that results in no questions or no prompting of any kind is as follows:

```<code> Option Explicit

 Sub Bossa_Unzip()
 Dim FSO As Object
 Dim oApp As Object             ' oApp is the object which has the methods you're using in your code to unzip the zip file:
                               'you need to create that object before you can use it.
 Dim Fname As Variant
 Dim FileNameFolder As Variant     ' previously Dim FileNameFolder As Variant
 Dim DefinePath As String

' Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
 Fname = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl.zip"

 If Fname = False Then
    'Do nothing
 Else
    'Destination folder
     DefinePath = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_mst\"      ' Change to your path / variable
     If Right(DefinePath, 1) <> "\" Then
        DefinePath = DefinePath & "\"
     End If

     FileNameFolder = DefinePath

    '        Delete all the files in the folder DefPath first if you want.
    '        On Error Resume Next
    '        Kill DefPath & "*.*"
    '        On Error GoTo 0

    'Extract the files into the Destination folder
     Set oApp = CreateObject("Shell.Application")            ' you need to create oApp object before you can use it.
               oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items, 16

     'MsgBox "You'll find the files here: " & DefinePath

     On Error Resume Next
     Set FSO = CreateObject("scripting.filesystemobject")
     FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
  End Sub
</code>```

Of course this site helped me a lot - its CpyHere explanation site.

One thing I don't understand is why Fname and FileNumberFolder need to be declared as variant. In my opinion, they should be declared as String. Just look at this screenshot.

But when I declare them that way, the code gives me error.

Just look here, when the variables already have their values (first picture). The FileNameVariable and DefinePath variable have the exact same value, and it looks like a string 4 me. How is that necessary, that I need to declare another variable - FileNameVariable in that case (in 17th line) with the same value, but variant type.
please explain that to me, someone.

Body:
There is an unzipping code I'd like to adjust 4 my needs.

Sub Unzip()
    Dim FSO As Object
    Dim oApp As Object
    Dim Fname As Variant
    Dim FileNameFolder As Variant
    Dim DefinePath As String

          ' Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
    Fname = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl.zip"

    If Fname = False Then
          'Do nothing
    Else
          'Destination folder
       DefinePath = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_mst\"    ' Change to your path / variable
       If Right(DefinePath, 1) <> "\" Then
           DefinePath = DefinePath & "\"
       End If

       FileNameFolder = DefinePath

        '        Delete all the files in the folder DefPath first if you want.
        '        On Error Resume Next
        '        Kill DefPath & "*.*"
        '        On Error GoTo 0

        'Extract the files into the Destination folder
       Set oApp = CreateObject("Shell.Application")
       oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items

        ' MsgBox "You find the files here: " & FileNameFolder

      On Error Resume Next
      Set FSO = CreateObject("scripting.filesystemobject")
      FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
   End If
End Sub

Somewhere here:

  `Set oApp = CreateObject("Shell.Application")
   oApp.Namespace(FileNameFolder).CopyHere`

a dialog box appears asking me if I want to overwrite the file that have the same names - and Yes I do want to overwrite them, but without answering the dialog box - I would like to hardcode it into the code, please.

I've found this page https://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx  but I just don't know how to add this parameter #16 which is "Respond with "Yes to All" for any dialog box that is displayed."
Can U help me with that?

And the last thing:
can You explain oApp.Namespace(Fname).items line for me.
I've really tried to guess it myself, but I thing I'm to short 4 this.

Body:
the code that results in no questions or no prompting of any kind is as follows:

 Option Explicit

 Sub Bossa_Unzip()
 Dim FSO As Object
 Dim oApp As Object             ' oApp is the object which has the methods you're using in your code to unzip the zip file:
                               'you need to create that object before you can use it.
 Dim Fname As Variant
 Dim FileNameFolder As Variant     ' previously Dim FileNameFolder As Variant
 Dim DefinePath As String

' Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)
 Fname = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl.zip"

 If Fname = False Then
    'Do nothing
 Else
    'Destination folder
     DefinePath = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_mst\"      ' Change to your path / variable
     If Right(DefinePath, 1) <> "\" Then
        DefinePath = DefinePath & "\"
     End If

     FileNameFolder = DefinePath

    '        Delete all the files in the folder DefPath first if you want.
    '        On Error Resume Next
    '        Kill DefPath & "*.*"
    '        On Error GoTo 0

    'Extract the files into the Destination folder
     Set oApp = CreateObject("Shell.Application")            ' you need to create oApp object before you can use it.
               oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items, 16

     'MsgBox "You'll find the files here: " & DefinePath

     On Error Resume Next
     Set FSO = CreateObject("scripting.filesystemobject")
     FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
  End Sub

Of course this site helped me a lot - its CpyHere explanation site.

One thing I don't understand is why Fname and FileNumberFolder need to be declared as variant. In my opinion, they should be declared as String. Just look at this screenshot.

But when I declare them that way, the code gives me error.

Just look here, when the variables already have their values (first picture). The FileNameVariable and DefinePath variable have the exact same value, and it looks like a string 4 me. How is that necessary, that I need to declare another variable - FileNameVariable in that case (in 17th line) with the same value, but variant type.
please explain that to me, someone.


来源: stackexchange

问:
canvas.toDataURL() results black image by trying to resize base64 string
I am currently trying to resize base64 images, since the image files are too big to be processed later on with php. I've found a way to achieve this by resizing the image using canvas. Unfortunately the image I get is just a black field which is 300px wide and 150px high. Maybe it has something to do with img.onload and canvas.toDataURL() order, or I am just using the wrong event (img.onload). Any idea where the mistake can be?

```<code>function exportImg(val){
                var imageData = $('#image-cropper').cropit('export', {originalSize: true});
                imageData = imageData.replace(/^data:image\/[a-z]+;base64,/, "");

                var imageDataRes = resize(imageData);

                $.post('php/upload.php', { imageDataRes: imageDataRes });
        }

function resize(base64){
            // Max size for thumbnail
            var maxWidth = 900;
            var maxHeight = 900;

            // Create and initialize two canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            var canvasCopy = document.createElement("canvas");
            var copyContext = canvasCopy.getContext("2d");

            // Create original image
            var img = new Image();
            img.src = base64;

            img.onload = function(){

                // Determine new ratio based on max size
                var ratio = 1;
                if(img.width > maxWidth) {
                    ratio = maxWidth / img.width;
                }
                else if(img.height > maxHeight) {
                    ratio = maxHeight / img.height;
                }

            // Draw original image in second canvas
            canvasCopy.width = img.width;
            canvasCopy.height = img.height;
            copyContext.drawImage(img, 0, 0);

            // Copy and resize second canvas to first canvas
            canvas.width = img.width * ratio;
            canvas.height = img.height * ratio;
            ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

            }
            alert(canvas.toDataURL());

            return canvas.toDataURL();
        }
</code>```

EDIT:

What is async in this case and how to solve it? Sorry, but unfortunately I don't see how this could help me further. The $.post works perfectly, I get the images. I just don't get the idea of img.onload and toDataURL() and how I should parse them from one function to another. At first, I got a blank result, with no string at all (just data,), but by adding this img.onload I got finally some base64 string...but it was just black screen.

答:
You will need to wait onload event after that use global variable to save data and call upload function on the end .

Try this :

```<code>function exportImg(val){
                var imageData = $('#image-cropper').cropit('export', {originalSize: true});
                imageData = imageData.replace(/^data:image\/[a-z]+;base64,/, "");

                  resize(imageData);

        }

var SendWhenisReady = function(imageDataRes){

 $.post('php/upload.php', { imageDataRes: imageDataRes });

};

function resize(base64){
            // Max size for thumbnail
            var maxWidth = 900;
            var maxHeight = 900;

            // Create and initialize two canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            var canvasCopy = document.createElement("canvas");
            var copyContext = canvasCopy.getContext("2d");

            // Create original image
            var img = new Image();
            img.src = base64;

            img.onload = function(){

                // Determine new ratio based on max size
                var ratio = 1;
                if(img.width > maxWidth) {
                    ratio = maxWidth / img.width;
                }
                else if(img.height > maxHeight) {
                    ratio = maxHeight / img.height;
                }

            // Draw original image in second canvas
            canvasCopy.width = img.width;
            canvasCopy.height = img.height;
            copyContext.drawImage(img, 0, 0);

            // Copy and resize second canvas to first canvas
            canvas.width = img.width * ratio;
            canvas.height = img.height * ratio;
            ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

                 alert(canvas.toDataURL());
                 window['imageDataRes'] = canvas.toDataURL();
                 SendWhenisReady(window['imageDataRes'])
            }

        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently trying to resize base64 images, since the image files are too big to be processed later on with php. I've found a way to achieve this by resizing the image using canvas. Unfortunately the image I get is just a black field which is 300px wide and 150px high. Maybe it has something to do with img.onload and canvas.toDataURL() order, or I am just using the wrong event (img.onload). Any idea where the mistake can be?

function exportImg(val){
                var imageData = $('#image-cropper').cropit('export', {originalSize: true});
                imageData = imageData.replace(/^data:image\/[a-z]+;base64,/, "");

                var imageDataRes = resize(imageData);

                $.post('php/upload.php', { imageDataRes: imageDataRes });
        }

function resize(base64){
            // Max size for thumbnail
            var maxWidth = 900;
            var maxHeight = 900;

            // Create and initialize two canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            var canvasCopy = document.createElement("canvas");
            var copyContext = canvasCopy.getContext("2d");

            // Create original image
            var img = new Image();
            img.src = base64;

            img.onload = function(){

                // Determine new ratio based on max size
                var ratio = 1;
                if(img.width > maxWidth) {
                    ratio = maxWidth / img.width;
                }
                else if(img.height > maxHeight) {
                    ratio = maxHeight / img.height;
                }

            // Draw original image in second canvas
            canvasCopy.width = img.width;
            canvasCopy.height = img.height;
            copyContext.drawImage(img, 0, 0);

            // Copy and resize second canvas to first canvas
            canvas.width = img.width * ratio;
            canvas.height = img.height * ratio;
            ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

            }
            alert(canvas.toDataURL());

            return canvas.toDataURL();
        }

EDIT:

What is async in this case and how to solve it? Sorry, but unfortunately I don't see how this could help me further. The $.post works perfectly, I get the images. I just don't get the idea of img.onload and toDataURL() and how I should parse them from one function to another. At first, I got a blank result, with no string at all (just data,), but by adding this img.onload I got finally some base64 string...but it was just black screen.

Body:
You will need to wait onload event after that use global variable to save data and call upload function on the end .

Try this :

function exportImg(val){
                var imageData = $('#image-cropper').cropit('export', {originalSize: true});
                imageData = imageData.replace(/^data:image\/[a-z]+;base64,/, "");

                  resize(imageData);

        }

var SendWhenisReady = function(imageDataRes){

 $.post('php/upload.php', { imageDataRes: imageDataRes });

};

function resize(base64){
            // Max size for thumbnail
            var maxWidth = 900;
            var maxHeight = 900;

            // Create and initialize two canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            var canvasCopy = document.createElement("canvas");
            var copyContext = canvasCopy.getContext("2d");

            // Create original image
            var img = new Image();
            img.src = base64;

            img.onload = function(){

                // Determine new ratio based on max size
                var ratio = 1;
                if(img.width > maxWidth) {
                    ratio = maxWidth / img.width;
                }
                else if(img.height > maxHeight) {
                    ratio = maxHeight / img.height;
                }

            // Draw original image in second canvas
            canvasCopy.width = img.width;
            canvasCopy.height = img.height;
            copyContext.drawImage(img, 0, 0);

            // Copy and resize second canvas to first canvas
            canvas.width = img.width * ratio;
            canvas.height = img.height * ratio;
            ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

                 alert(canvas.toDataURL());
                 window['imageDataRes'] = canvas.toDataURL();
                 SendWhenisReady(window['imageDataRes'])
            }

        }


问:
Display values in edit
I've been trying to display my edit values in the editContact page. I ran out of ideas as to how I'm supposed to fix this.

Here's my controller for edit

```<code>[HttpGet]
public ActionResult editContact(int? id)
{
    var databaseModel = new database();

    if (id == null)
    {
        return RedirectToAction("Index");
    }

    IEnumerable<contact> contact = databaseModel.displayContact(id);

    return View(contact);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult editContact(contact editModel, int id)
{
    try
    {
        programEntities db = new programEntities();
        var databaseModel = new database();

        if (databaseModel.editContact(editModel, id))
        {
            ViewBag.AlertMsg = "Contact edited successfully";
            return RedirectToAction("Index");
        }

        return View();
    }
    catch (Exception ex)
    {
        return View(ex);
    }
}
</code>```

In my model, I have this code that controls the database manipulation

```<code>   public List<contact> displayContact(int? Id)
   {
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            List<contact> contactList = new List<contact>();

            SqlDataAdapter da = new SqlDataAdapter(comObj);
            DataTable dt = new DataTable();

            //conn.Open();
            da.Fill(dt);
            conn.Close();

            contactList = (from DataRow dr in dt.Rows
                           select new contact()
                           {
                               contactId = Convert.ToInt32(dr["contactId"]),
                               establishmentType = Convert.ToString(dr["establishmentType"]),
                               ownerName = Convert.ToString(dr["ownerName"]),
                               address = Convert.ToString(dr["address"]),
                               city = Convert.ToString(dr["city"]),
                               region = Convert.ToString(dr["region"]),
                               mobileNumber = Convert.ToString(dr["mobileNumber"]),
                               phoneNumber = Convert.ToString(dr["phoneNumber"])
                           }).ToList();

            return contactList;
        }
}
</code>```

My view markup:

```<code>@model directory.Models.contact

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>contact</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.contactId)

    <div class="form-group">
        @Html.LabelFor(model => model.establishmentType, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.establishmentType, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.establishmentType, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ownerName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ownerName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ownerName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.address, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.city, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.region, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.region, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.region, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.mobileNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.mobileNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.mobileNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.phoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.phoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.phoneNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

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

I tried creating a different query to display the edit values, but the exception says my dispayContact stored procedure does not exist even though it does. My other stored procedure works well except for this one.

Edit

So I fixed my stored procedure in SQL Server; it was named "dispayContact". Still the edit values won't display even after adding firstOrDefault() and then changing the declaration in my view from @model directory.Models.contact to @model IEnumerable<directory.Models.contact>

答:
I think the issue is because you are returning a list

return View(contact);

where contact is IEnumerable<contact> and your view model is

@model directory.Models.contact

I guess your code should work once you return the model not list contain the model, in your case return FirstOrDefault() of your contact list

something like this

return View(contact.FirstOrDefault());

Title: Display values in edit

Body:
I've been trying to display my edit values in the editContact page. I ran out of ideas as to how I'm supposed to fix this.

Here's my controller for edit

[HttpGet]
public ActionResult editContact(int? id)
{
    var databaseModel = new database();

    if (id == null)
    {
        return RedirectToAction("Index");
    }

    IEnumerable<contact> contact = databaseModel.displayContact(id);

    return View(contact);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult editContact(contact editModel, int id)
{
    try
    {
        programEntities db = new programEntities();
        var databaseModel = new database();

        if (databaseModel.editContact(editModel, id))
        {
            ViewBag.AlertMsg = "Contact edited successfully";
            return RedirectToAction("Index");
        }

        return View();
    }
    catch (Exception ex)
    {
        return View(ex);
    }
}

In my model, I have this code that controls the database manipulation

   public List<contact> displayContact(int? Id)
   {
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            List<contact> contactList = new List<contact>();

            SqlDataAdapter da = new SqlDataAdapter(comObj);
            DataTable dt = new DataTable();

            //conn.Open();
            da.Fill(dt);
            conn.Close();

            contactList = (from DataRow dr in dt.Rows
                           select new contact()
                           {
                               contactId = Convert.ToInt32(dr["contactId"]),
                               establishmentType = Convert.ToString(dr["establishmentType"]),
                               ownerName = Convert.ToString(dr["ownerName"]),
                               address = Convert.ToString(dr["address"]),
                               city = Convert.ToString(dr["city"]),
                               region = Convert.ToString(dr["region"]),
                               mobileNumber = Convert.ToString(dr["mobileNumber"]),
                               phoneNumber = Convert.ToString(dr["phoneNumber"])
                           }).ToList();

            return contactList;
        }
}

My view markup:

@model directory.Models.contact

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

contact

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.contactId)

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

            @Html.EditorFor(model => model.establishmentType, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.establishmentType, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.ownerName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ownerName, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.region, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.region, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.mobileNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.mobileNumber, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.phoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.phoneNumber, "", new { @class = "text-danger" })

            <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

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

I tried creating a different query to display the edit values, but the exception says my dispayContact stored procedure does not exist even though it does. My other stored procedure works well except for this one.

Edit

So I fixed my stored procedure in SQL Server; it was named "dispayContact". Still the edit values won't display even after adding firstOrDefault() and then changing the declaration in my view from @model directory.Models.contact to @model IEnumerable<directory.Models.contact>


问:
Maintain Unique Array In Mongo
Below code represent that 101 has initiated chat with 102.

```<code>db.chat.insert(
   {
     "mydate" : ISODate(),
     "chatusers" : [101,102]
   }
)
</code>```

To make sure this entry is unique and there should be no duplicate like
[101,102] or [102,101] is tried to add unique index in chatusers but this does not work on pairs as it dont allow to use either of 101 or 102.

Question:
One way is to make sure at application end or should i change my collection schema?
What is the better approach and please suggest schema for the same.

Note:
select Queries will be based on both sender and receiver.

答:
The solution suggested by Sergio seems correct.

```<code>db.chat.insert(
   {
     "mydate" : ISODate(),
     "chatusers" : [101,102],
     "chat_sig" : "101_102"
   }
)
</code>```

The solution suggested by Neil has a basic flaw.

```<code>db.chat.insert(
   {
     "mydate" : ISODate(),
     "sender"  : 101,
     "receiver": 102,
   }
)
</code>```

Adding compound unique index on sender and receiver will guarantee that sender-receiver = 101-102  do not repeat but 102-101 can still exist and hence basic requirement does not meet

Title: Maintain Unique Array In Mongo

Body:
Below code represent that 101 has initiated chat with 102.

db.chat.insert(
   {
     "mydate" : ISODate(),
     "chatusers" : [101,102]
   }
)

To make sure this entry is unique and there should be no duplicate like
[101,102] or [102,101] is tried to add unique index in chatusers but this does not work on pairs as it dont allow to use either of 101 or 102.

Question:
One way is to make sure at application end or should i change my collection schema?
What is the better approach and please suggest schema for the same.

Note:
select Queries will be based on both sender and receiver.

Body:
The solution suggested by Sergio seems correct.

db.chat.insert(
   {
     "mydate" : ISODate(),
     "chatusers" : [101,102],
     "chat_sig" : "101_102"
   }
)

The solution suggested by Neil has a basic flaw.

db.chat.insert(
   {
     "mydate" : ISODate(),
     "sender"  : 101,
     "receiver": 102,
   }
)

Adding compound unique index on sender and receiver will guarantee that sender-receiver = 101-102  do not repeat but 102-101 can still exist and hence basic requirement does not meet


问:
Convert Git submodule to subtree
How can I convert a git submodule (with a folder in the local file system as a remote) to a git subtree, preferably preserving the commit history of the submodule?</p>

答:
Alexander Mikhailian's script modified by @GaspardP did not work for me.

I modified it, and made an improvement. Now, the new subtrees will point to the same commit as the old submodules did. Previously, the script would simply download the latest commit from the target repositories, potentially causing compatibility issues.

https://gist.github.com/Nikita240/0c98cea8f53a15e69699cd8bc40657c4

```<code>#!/bin/bash -x
# This script will convert all your git submodules into git subtrees.
# This script ensures that your new subtrees point to the same commits as the
# old submodules did, unlike most other scripts that do this.
# THIS SCRIPT MUST BE PLACED OUTSIDE OF YOUR REPOSITORY!!!!!!!!!!
# Otherwise, the script will interfere with the git commits.
# Save the script in your home directory as `~/subtrees.sh`
# `cd` into your repository
# Run `~/subtrees.sh`
# Enjoy!

# extract the list of submodules from .gitmodule
cat .gitmodules |while read i
do
if [[ $i == \[submodule* ]]; then
    echo converting $i

    read i

    # extract the module's prefix
    mpath=$(echo $i | grep -E "(\S+)$" -o)

    echo path: $mpath

    read i

    # extract the url of the submodule
    murl=$(echo $i|cut -d\= -f2|xargs)

    echo url: $murl

    # extract the module name
    mname=$(basename $mpath)

    echo name: $mname

    # extract the referenced commit
    mcommit=$(git submodule status $mpath | grep -E "\S+" -o | head -1)

    echo commit: $mcommit

    # deinit the module
    git submodule deinit $mpath

    # remove the module from git
    git rm -r --cached $mpath

    # remove the module from the filesystem
    rm -rf $mpath

    # commit the change
    git commit -m "Removed $mpath submodule at commit $mcommit"

    # add the remote
    git remote add -f $mname $murl

    # add the subtree
    git subtree add --prefix $mpath $mcommit --squash

    # commit any left over uncommited changes
    git commit -a -m "$mname cleaned up"

    # fetch the files
    git fetch $murl master

    echo
fi
done
git rm .gitmodules
git commit -a -m "Removed .gitmodules"
</code>```

Title: Convert Git submodule to subtree

Body:
Alexander Mikhailian's script modified by @GaspardP did not work for me.

I modified it, and made an improvement. Now, the new subtrees will point to the same commit as the old submodules did. Previously, the script would simply download the latest commit from the target repositories, potentially causing compatibility issues.

https://gist.github.com/Nikita240/0c98cea8f53a15e69699cd8bc40657c4

#!/bin/bash -x
# This script will convert all your git submodules into git subtrees.
# This script ensures that your new subtrees point to the same commits as the
# old submodules did, unlike most other scripts that do this.
# THIS SCRIPT MUST BE PLACED OUTSIDE OF YOUR REPOSITORY!!!!!!!!!!
# Otherwise, the script will interfere with the git commits.
# Save the script in your home directory as `~/subtrees.sh`
# `cd` into your repository
# Run `~/subtrees.sh`
# Enjoy!

# extract the list of submodules from .gitmodule
cat .gitmodules |while read i
do
if [[ $i == \[submodule* ]]; then
    echo converting $i

    read i

    # extract the module's prefix
    mpath=$(echo $i | grep -E "(\S+)$" -o)

    echo path: $mpath

    read i

    # extract the url of the submodule
    murl=$(echo $i|cut -d\= -f2|xargs)

    echo url: $murl

    # extract the module name
    mname=$(basename $mpath)

    echo name: $mname

    # extract the referenced commit
    mcommit=$(git submodule status $mpath | grep -E "\S+" -o | head -1)

    echo commit: $mcommit

    # deinit the module
    git submodule deinit $mpath

    # remove the module from git
    git rm -r --cached $mpath

    # remove the module from the filesystem
    rm -rf $mpath

    # commit the change
    git commit -m "Removed $mpath submodule at commit $mcommit"

    # add the remote
    git remote add -f $mname $murl

    # add the subtree
    git subtree add --prefix $mpath $mcommit --squash

    # commit any left over uncommited changes
    git commit -a -m "$mname cleaned up"

    # fetch the files
    git fetch $murl master

    echo
fi
done
git rm .gitmodules
git commit -a -m "Removed .gitmodules"


问:
log4j2 logging to console only
I have a maven web project which requires logging.

I decided to use log4j2 for that purpose and added the required entries in the pom.xml file

Then I created the log4j2.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <RollingFile name="RollingFile" fileName="${logs.path}/text.log"
            filePattern="${logs.path}/%d{YYYYMMdd}-text.%i.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} %-5p %c{1}:%L - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="root" level="info" additivity="false">
            <appender-ref ref="RollingFile" level="info" />
            <appender-ref ref="Console" level="info" />
        </Logger>
        <Root level="info" additivity="false">
            <AppenderRef ref="RollingFile" />
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>
```

I'm starting tomcat with -Dlogs.path="C:\mylogs", where C:\mylogs exists and has public read/write access.

The console logger is working fine, I can see the correct output in my console, the issue is that the file isn't being created, so I have no logfile, everything gets logged to catalina.out only, and the tomcat startup logs don't show errors for log4j.

What am I missing? is there some additional configuration I need to do in order to log to file?

答:
To create a log file with the log4j2 config you first need to define your appender. Here's an example:

```<code><RollingFile name="MGMT"
                 fileName="${logdir}/mgmt.log"
                 filePattern="${logdir}/mgmt.%d{yyyy-MM-dd}.log">
      <PatternLayout pattern="${layout}"/>
      <CronTriggeringPolicy schedule="0 0 0 * * ?"/>
      <DefaultRolloverStrategy>
        <Delete basePath="${logdir}" maxDepth="1">
          <IfFileName glob="mgmt.*.log" />
          <IfAccumulatedFileCount exceeds="10" />
        </Delete>
      </DefaultRolloverStrategy>
    </RollingFile>
</code>```

Afterwards you just need to define a logger that will use it:

```<code><Logger name="the package or name that is displayed in the log line"
            level="ALL"
            additivity="false">
      <AppenderRef ref="MGMT"/>
    </Logger>
</code>```

If you have a log that has com.company.test as package set that package as name for the logger. It's important that they match.

The field additivity will define if you want to pass the catched log to its parent ( true ) or just let this logger handle it ( false )

EDIT:

your config file might need this:

```<code><Configuration status="info">
  <Properties>
    <Property name="logdir">${sys:catalina.base}/logs</Property>
    <Property name="layout">%d [%t] %-5p %c- %m%n</Property>
  </Properties>
  <Appenders>
</code>```

If you don't want to use this you have to define the path static like <RollingFile name="MGMT"
   fileName="C:\path\file.log"

Title: log4j2 logging to console only

Body:
I have a maven web project which requires logging.

I decided to use log4j2 for that purpose and added the required entries in the pom.xml file

Then I created the log4j2.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <RollingFile name="RollingFile" fileName="${logs.path}/text.log"
            filePattern="${logs.path}/%d{YYYYMMdd}-text.%i.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} %-5p %c{1}:%L - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="root" level="info" additivity="false">
            <appender-ref ref="RollingFile" level="info" />
            <appender-ref ref="Console" level="info" />
        </Logger>
        <Root level="info" additivity="false">
            <AppenderRef ref="RollingFile" />
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

I'm starting tomcat with -Dlogs.path="C:\mylogs", where C:\mylogs exists and has public read/write access.

The console logger is working fine, I can see the correct output in my console, the issue is that the file isn't being created, so I have no logfile, everything gets logged to catalina.out only, and the tomcat startup logs don't show errors for log4j.

What am I missing? is there some additional configuration I need to do in order to log to file?

Body:
To create a log file with the log4j2 config you first need to define your appender. Here's an example:

<RollingFile name="MGMT"
                 fileName="${logdir}/mgmt.log"
                 filePattern="${logdir}/mgmt.%d{yyyy-MM-dd}.log">
      <PatternLayout pattern="${layout}"/>
      <CronTriggeringPolicy schedule="0 0 0 * * ?"/>
      <DefaultRolloverStrategy>
        <Delete basePath="${logdir}" maxDepth="1">
          <IfFileName glob="mgmt.*.log" />
          <IfAccumulatedFileCount exceeds="10" />
        </Delete>
      </DefaultRolloverStrategy>
    </RollingFile>

Afterwards you just need to define a logger that will use it:

<Logger name="the package or name that is displayed in the log line"
            level="ALL"
            additivity="false">
      <AppenderRef ref="MGMT"/>
    </Logger>

If you have a log that has com.company.test as package set that package as name for the logger. It's important that they match.

The field additivity will define if you want to pass the catched log to its parent ( true ) or just let this logger handle it ( false )

EDIT:

your config file might need this:

<Configuration status="info">
  <Properties>
    <Property name="logdir">${sys:catalina.base}/logs</Property>
    <Property name="layout">%d [%t] %-5p %c- %m%n</Property>
  </Properties>
  <Appenders>

If you don't want to use this you have to define the path static like <RollingFile name="MGMT"
   fileName="C:\path\file.log"


问:
Starting and monitoring spark application from a Java application
I am working on an application to execute spark batch application from a java application.

There is one main class which starts the thread to start spark application. It uses zookeeper to find the leader among machines which would start the spark application. Main method looks like this:

```<code>public static void main(String[] args) throws IOException {

        final int id = Integer.valueOf(args[0]);
        final String zkURL = args[1];

        final ExecutorService service = Executors.newSingleThreadExecutor();

        final Future<?> status = service.submit(new ProcessNode(id, zkURL));
        try {
            status.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.fatal(e.getMessage(), e);
            service.shutdown();
        }
</code>```

Once the leader is selected , following code would run on it to start spark application.

```<code>protected Boolean executeCommand() {
    try {
        final Runtime rt = Runtime.getRuntime();
        final Process proc = rt.exec("sh start-sparkapp.sh");
        final int exitVal = proc.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = "";
        while ((line=buf.readLine())!=null) {
        System.out.println(line);
        }

        System.out.println(" commandToExecute exited with code: " + exitVal);
        proc.destroy();

    } catch (final Exception e) {
        System.out.println("Exception occurred while Launching process : " + e.getMessage());
        return Boolean.FALSE;
    }
         return Boolean.TRUE;
}
</code>```

But this starts a long running spark job. So I believe, next part of code would be executed only when spark job is finished. My requirement is as soon as  spark application is started , the control goes to the next part of code, where I am monitoring the status of same spark application. i.e I start the spark application and monitor the status of spark application from same java application.
Assume I have a method montior which monitors the status of application

```<code>public String monitor(ApplicationId id)
</code>```

Any suggestion how to achieve this?

答:
Since you will be monitoring your Spark application using the method public String monitor(ApplicationId id) , I am assuming you do not want your current thread to wait on the process using proc.waitFor(). Additionally, you do not want to print the normal output of the process to your console. Both these operations make your thread wait on the spawned process. Moreover, your monitor method should take the process-id of the spawned process, rather than the spark applicationId, as input.
So the modified code could look like:

```<code>protected Boolean executeCommand() {
try {
    final Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec("sh start-sparkapp.sh");

    /*
     *Call to method monitor(ProcessId id)
     */

    } catch (final Exception e) {
        System.out.println("Exception occurred while Launching process : " + e.getMessage());
        return Boolean.FALSE;
    }
     return Boolean.TRUE;
}
</code>```

Body:
I am working on an application to execute spark batch application from a java application.

There is one main class which starts the thread to start spark application. It uses zookeeper to find the leader among machines which would start the spark application. Main method looks like this:

public static void main(String[] args) throws IOException {

        final int id = Integer.valueOf(args[0]);
        final String zkURL = args[1];

        final ExecutorService service = Executors.newSingleThreadExecutor();

        final Future<?> status = service.submit(new ProcessNode(id, zkURL));
        try {
            status.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.fatal(e.getMessage(), e);
            service.shutdown();
        }

Once the leader is selected , following code would run on it to start spark application.

protected Boolean executeCommand() {
    try {
        final Runtime rt = Runtime.getRuntime();
        final Process proc = rt.exec("sh start-sparkapp.sh");
        final int exitVal = proc.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = "";
        while ((line=buf.readLine())!=null) {
        System.out.println(line);
        }

        System.out.println(" commandToExecute exited with code: " + exitVal);
        proc.destroy();

    } catch (final Exception e) {
        System.out.println("Exception occurred while Launching process : " + e.getMessage());
        return Boolean.FALSE;
    }
         return Boolean.TRUE;
}

But this starts a long running spark job. So I believe, next part of code would be executed only when spark job is finished. My requirement is as soon as  spark application is started , the control goes to the next part of code, where I am monitoring the status of same spark application. i.e I start the spark application and monitor the status of spark application from same java application.
Assume I have a method montior which monitors the status of application

public String monitor(ApplicationId id)

Any suggestion how to achieve this?

Body:
Since you will be monitoring your Spark application using the method public String monitor(ApplicationId id) , I am assuming you do not want your current thread to wait on the process using proc.waitFor(). Additionally, you do not want to print the normal output of the process to your console. Both these operations make your thread wait on the spawned process. Moreover, your monitor method should take the process-id of the spawned process, rather than the spark applicationId, as input.
So the modified code could look like:

protected Boolean executeCommand() {
try {
    final Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec("sh start-sparkapp.sh");

    /*
     *Call to method monitor(ProcessId id)
     */

    } catch (final Exception e) {
        System.out.println("Exception occurred while Launching process : " + e.getMessage());
        return Boolean.FALSE;
    }
     return Boolean.TRUE;
}


问:
Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I have an error when I run my app on ionic cordova run android.
My error is : Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I try to resolve it with forums that exists with this solution :

1)Rename your index.html to “main.html”

2)Create a new “index.html” and put the following content into it:

```<code><!doctype html>
<html>
  <head>
   <title>title</title>
   <script>
     window.location='./main.html';
   </script>
  <body>
  </body>
</html>
</code>```

Or modify in the config.xml this line :

```<code><preference name="SplashScreenDelay" value="3000" />
</code>```

to this line :

```<code><preference name="SplashScreenDelay" value="70000" />
</code>```

But when I run my app after saving my new code, the error still appear and when I return into my code, I see that the code is still the same and not has been modified (even if I modified it like I sayed previously !)

Someone know how to resolve my problem ?

Thanks in advance,
Caroline

答:
It's not really an answer but it allowed me to see my app without the error message.

When I run my app with the terminal ionic cordova run android the error still persist.

But if I run my app with Android Studio it's works !

Body:
I have an error when I run my app on ionic cordova run android.
My error is : Connection to the server was unsuccessful. (file ///android_asset/www/index.html)
I try to resolve it with forums that exists with this solution :

1)Rename your index.html to “main.html”

2)Create a new “index.html” and put the following content into it:

<!doctype html>

   <title>title</title>

Or modify in the config.xml this line :

<preference name="SplashScreenDelay" value="3000" />

to this line :

<preference name="SplashScreenDelay" value="70000" />

But when I run my app after saving my new code, the error still appear and when I return into my code, I see that the code is still the same and not has been modified (even if I modified it like I sayed previously !)

Someone know how to resolve my problem ?

Thanks in advance,
Caroline


问:
Use materialize to show simple_form errors
I would like know as i can to utilize the materialize errors on simple_form.

My form is:

```<code>  <div class="input-field col s6 offset-s3">
    <%= f.email_field :email, required: true, autofocus: true, placeholder: "Email", class: "validate" %>
  </div>
</code>```

I want that in addition to showing red the form it also shows an error message.

答:
For simple form you need to use f.input, for example:

```<code><%= f.input :email %>
</code>```

This will give you an input and any errors after the form has been submitted to the server.

You will need a validation in the model to actually generate errors which the form will display. For example:

```<code>class User < ActiveRecord::Base
  validate :email, presence: true
end
</code>```

Body:
I would like know as i can to utilize the materialize errors on simple_form.

My form is:

    <%= f.email_field :email, required: true, autofocus: true, placeholder: "Email", class: "validate" %>

I want that in addition to showing red the form it also shows an error message.

Body:
For simple form you need to use f.input, for example:

<%= f.input :email %>

This will give you an input and any errors after the form has been submitted to the server.

You will need a validation in the model to actually generate errors which the form will display. For example:

class User < ActiveRecord::Base
  validate :email, presence: true
end


问:
How to get 'days' like Monday, Tuesday etc on a given input 'date' in java
I'm working on a task where I need to provide specific day like Wednesday, Thursday etc on given input date like

Input:

6 7 2017

Output:

Wednesday

Any help would be appreciated thank you.

I have tried using java.util.Calendar. I am able to get output like "Sat Sep 05 08:18:27 UTC 2015" but I need only day of week.

答:
I would follow these steps:

Parse the string to a LocalDate using a DateTimeFormatter

Use the LocalDate::getDayOfWeek method to find the day


问:
Tell if PHP's DateTime is midnight
Let's say I have the following dates/datetimes.  How can I best tell which ones are at midnight (i.e. time is 00:00:00)?  The first one should not be midnight, but the next three should be.  Thanks</p>

```<code>$d1=new DateTime('12/10/2012 05:33');
$d2=new DateTime('12/10/2012');
$d3=new DateTime('12/10/2012 00:00');
$d4=new DateTime('12/10/2012 00:00:00');
</code>```

答:
You will have to specify the time zone and use DateTime</p>

```<code>$test = new DateTime('NOW', new DateTimeZone('Asia/Kolkata'));
$h=$test->format('H');
$m=$test->format('i');
$s=$test->format('s');
if( $h == 0 && $m==0 && $s == 0) {
    echo "Midnight!";
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Tell if PHP's DateTime is midnight

Body:
Let's say I have the following dates/datetimes.  How can I best tell which ones are at midnight (i.e. time is 00:00:00)?  The first one should not be midnight, but the next three should be.  Thanks

$d1=new DateTime('12/10/2012 05:33');
$d2=new DateTime('12/10/2012');
$d3=new DateTime('12/10/2012 00:00');
$d4=new DateTime('12/10/2012 00:00:00');

Body:
You will have to specify the time zone and use DateTime

$test = new DateTime('NOW', new DateTimeZone('Asia/Kolkata'));
$h=$test->format('H');
$m=$test->format('i');
$s=$test->format('s');
if( $h == 0 && $m==0 && $s == 0) {
    echo "Midnight!";
}


答:
Using java8 you will need a local date and the call the method getDayOfWeek(), which returns an enum with the info you need

example:

```<code> LocalDate date = LocalDate.now();
 DayOfWeek dayOfWeek = date.getDayOfWeek();
 System.out.println(dayOfWeek);
</code>```

Title: How to get 'days' like Monday, Tuesday etc on a given input 'date' in java

Body:
I'm working on a task where I need to provide specific day like Wednesday, Thursday etc on given input date like

Input:

6 7 2017

Output:

Wednesday

Any help would be appreciated thank you.

I have tried using java.util.Calendar. I am able to get output like "Sat Sep 05 08:18:27 UTC 2015" but I need only day of week.

Body:
Using java8 you will need a local date and the call the method getDayOfWeek(), which returns an enum with the info you need

example:

 LocalDate date = LocalDate.now();
 DayOfWeek dayOfWeek = date.getDayOfWeek();
 System.out.println(dayOfWeek);


问:
using data-attribute inside javascript
I have table rows and each of them has an ID. How can I use data-attribute to button EDIT if my code look like this?

```<code>//some javascript code

var content = '<button type="button" class="btn btn-success edit_shipment" data-id="b.booking_id">Edit</button>';
return content;

//some javascript code again

//when Edit onclick, it shows modal
$('#booking_table tbody').on('click', 'button.edit_shipment', function(){
 $('#edit_shipment_modal').modal('show');
</code>```

data-id="b.booking_id" is not working

Thanks in advance

答:
You can use the jquery-Method attr(); You pass the name of the attribute as a string parameter. It than returns the value of the given attribute.

```<code>$(this).attr('data-id');
</code>```

Here is a working example:
https://jsfiddle.net/TobiObeck/8g6kxxow/

Title: using data-attribute inside javascript

Body:
I have table rows and each of them has an ID. How can I use data-attribute to button EDIT if my code look like this?

//some javascript code

var content = '<button type="button" class="btn btn-success edit_shipment" data-id="b.booking_id">Edit</button>';
return content;

//some javascript code again

//when Edit onclick, it shows modal
$('#booking_table tbody').on('click', 'button.edit_shipment', function(){
 $('#edit_shipment_modal').modal('show');

data-id="b.booking_id" is not working

Thanks in advance

Body:
You can use the jquery-Method attr(); You pass the name of the attribute as a string parameter. It than returns the value of the given attribute.

$(this).attr('data-id');

Here is a working example:
https://jsfiddle.net/TobiObeck/8g6kxxow/


问:
Cannot cast object of type ContentPage to type ContentPage
So I am currently working on my first Xamarin application.
I have a MasterDetailPage with a menu, and when you click on one of the menu items on the left the below I save the object I am working with (to the file system), I create a new 'ContentPage' for the page they have chosen and pass in the object as a constructor parameter.

I then attempt to set the MasterDetailPage Detail object to (ContentPage)obj which is a cast of the content page they have chosen.

Now as you can see, the base for the JobDetails is a ContentPage, yet I cannot cast it to content page!?

I have also tried casting to Page instead to no avail.

Am I missing some fundamental knowledge when it comes to casting, or is something else going on here?

答:
I have solved this.
The issue wasn't with the Content Page cast (casting from obj > content page) but was because I had some xaml which wasn't correct inside JobDetails page.

The offending xaml was a

```<code><ListView Grid.Row="3" Grid.ColumnSpan="2" Grid.Column="0" x:Name="KeySkillsList">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                            </Grid.ColumnDefinitions>

                            <Label Grid.Row="0" Grid.Column="0"  Text="{Binding Name, Mode=TwoWay}"></Label>

                            <Switch Grid.Row="0" Grid.Column="1" IsToggled="{Binding Value, Mode=TwoWay}"></Switch>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
</code>```

This was due to me misunderstanding the list view (and the switch!)
The actual offending line specifically was the , commented out the page works.

I have now changed this so that its just a normal list view, with 1 switchcell, with a Text property.

Body:
I have solved this.
The issue wasn't with the Content Page cast (casting from obj > content page) but was because I had some xaml which wasn't correct inside JobDetails page.

The offending xaml was a

<ListView Grid.Row="3" Grid.ColumnSpan="2" Grid.Column="0" x:Name="KeySkillsList">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                                <ColumnDefinition Width="Auto"></ColumnDefinition>
                            </Grid.ColumnDefinitions>

                            <Label Grid.Row="0" Grid.Column="0"  Text="{Binding Name, Mode=TwoWay}"></Label>

                            <Switch Grid.Row="0" Grid.Column="1" IsToggled="{Binding Value, Mode=TwoWay}"></Switch>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

This was due to me misunderstanding the list view (and the switch!)
The actual offending line specifically was the , commented out the page works.

I have now changed this so that its just a normal list view, with 1 switchcell, with a Text property.


问:
Why/How does .Net allow me to negate a Nullable<T> that's null?
I found myself staring at code that looks similar to this:

```<code>private double? _foo;

public double? Foo
{
    get { return _foo; }
    set { Baz(-value); }
}

public void Baz(double? value)
{
    // Perform stuff with value, including null checks
}
</code>```

And in a test, I had this:

```<code>[Test]
public void Foo_test()
{
    ...
    Foo = null;
    ...
}
</code>```

I anticipated that the test would fail (throw), since I thought that you really can't apply unary minus to null, which I believed would happen in Foos setter. However, the unexpected happened and the test did not fail.

I could probably make an informed guess as to why this happens, but I figured that it'd be better if someone who actually knows what's going on could enlighten me.

(And before someone points out the obvious: Yes, the negation should definitely be pushed down into the innards of Baz.)

Edit and follow up

So, I'm grateful for the inputs from Jon Skeet and JaredPar, who both answered the How part of my question. After some googleing I found this blog post by Eric Lippert explaining the mathematical definition of 'lifted', which makes perfect sense. I also read the relevant parts of the language specification, which are fairly straightforward explaining the mechanics of lifting in c#.

Specifically I now know that early in the process of lifting, a null check is made on the operand, and if the operand is null, null will be the result of applying the operator (unary minus, in my case). So -null is null.

Now, to the "Why" part of the question. If I define my own (unary) operator - on a class (in which I negate a wrapped value), and invoke this operator on a null reference, I will get a NullReferenceException. Why is it, that 'lifting' behaves differently? I'm actually interested in the reasoning behind this design decision. I'm definitely not opposing the decision.

答:
Why is it, that 'lifting' behaves differently? I'm actually interested in the reasoning behind this design decision.

Well, first off, you shouldn't always get a null reference exception. An operator call is statically dispatched; it doesn't need to do a null check. This is perfectly legal:

```<code>class P
{
  public static P operator -(P p)
  { return p; }

  static void Main()
  {
    P p1 = null;
    P p2 = -p1;
    Console.WriteLine(p2 == null);
  }
}
</code>```

Really I think what your question means is "why do nullable value types get automatic lifting from non-nullable operations to nullable operations, but reference types require you to write specific logic in the operator if you want nullable semantics?"

It's a bit of a mess.

The thing is, reference types were always nullable to begin with, so you could always write that code yourself. Since nullable value types were added later, we added a mechanism so that all the existing non-nullable operators would suddenly work correctly with nullable types, so that you would not have to write all that boring code yourself.

There is a more general problem though. The more general problem is that we've conflated "null" to mean two different things. In the reference type world, null means "I do not refer to any object". In the value type world, null means what it means in databases: this quantity might have a value but we don't know what it is. What are the sales figures for November, if all the sales staff have not reported their results yet? There definitely is a dollar value to that quantity, but we don't know what it is, so we mark it as null.

Lifted arithmetic is designed to work on the "database null" semantics; null plus twelve is null. Something you don't know plus twelve is something else you don't know. Unfortunately, since we did not add nullable arithmetic to C# until version 2, there was already all the gear in place to treat null as the "there's an object reference that refers to no object" semantics.

Had we designed the whole thing from scratch, my suspicion is that (1) there would be nullable reference types, non nullable reference types, nullable value types and non nullable value types, and (2) there would be either a more clearly defined difference between null reference and null value, or their semantics would be more aligned when it comes to arithmetic, and (3) there would be automatic lifting of all non-nullable operations to nullable operations.

Note that VB/VBScript implement the more clear distinction by having two separate values: Null, which is database null, and Nothing, which is reference null.

ContentLicense: CC BY-SA 2.5

Body:
I found myself staring at code that looks similar to this:

private double? _foo;

public double? Foo
{
    get { return _foo; }
    set { Baz(-value); }
}

public void Baz(double? value)
{
    // Perform stuff with value, including null checks
}

And in a test, I had this:

[Test]
public void Foo_test()
{
    ...
    Foo = null;
    ...
}

I anticipated that the test would fail (throw), since I thought that you really can't apply unary minus to null, which I believed would happen in Foos setter. However, the unexpected happened and the test did not fail.

I could probably make an informed guess as to why this happens, but I figured that it'd be better if someone who actually knows what's going on could enlighten me.

(And before someone points out the obvious: Yes, the negation should definitely be pushed down into the innards of Baz.)

Edit and follow up

So, I'm grateful for the inputs from Jon Skeet and JaredPar, who both answered the How part of my question. After some googleing I found this blog post by Eric Lippert explaining the mathematical definition of 'lifted', which makes perfect sense. I also read the relevant parts of the language specification, which are fairly straightforward explaining the mechanics of lifting in c#.

Specifically I now know that early in the process of lifting, a null check is made on the operand, and if the operand is null, null will be the result of applying the operator (unary minus, in my case). So -null is null.

Now, to the "Why" part of the question. If I define my own (unary) operator - on a class (in which I negate a wrapped value), and invoke this operator on a null reference, I will get a NullReferenceException. Why is it, that 'lifting' behaves differently? I'm actually interested in the reasoning behind this design decision. I'm definitely not opposing the decision.

Body:
Why is it, that 'lifting' behaves differently? I'm actually interested in the reasoning behind this design decision.

Well, first off, you shouldn't always get a null reference exception. An operator call is statically dispatched; it doesn't need to do a null check. This is perfectly legal:

class P
{
  public static P operator -(P p)
  { return p; }

  static void Main()
  {
    P p1 = null;
    P p2 = -p1;
    Console.WriteLine(p2 == null);
  }
}

Really I think what your question means is "why do nullable value types get automatic lifting from non-nullable operations to nullable operations, but reference types require you to write specific logic in the operator if you want nullable semantics?"

It's a bit of a mess.

The thing is, reference types were always nullable to begin with, so you could always write that code yourself. Since nullable value types were added later, we added a mechanism so that all the existing non-nullable operators would suddenly work correctly with nullable types, so that you would not have to write all that boring code yourself.

There is a more general problem though. The more general problem is that we've conflated "null" to mean two different things. In the reference type world, null means "I do not refer to any object". In the value type world, null means what it means in databases: this quantity might have a value but we don't know what it is. What are the sales figures for November, if all the sales staff have not reported their results yet? There definitely is a dollar value to that quantity, but we don't know what it is, so we mark it as null.

Lifted arithmetic is designed to work on the "database null" semantics; null plus twelve is null. Something you don't know plus twelve is something else you don't know. Unfortunately, since we did not add nullable arithmetic to C# until version 2, there was already all the gear in place to treat null as the "there's an object reference that refers to no object" semantics.

Had we designed the whole thing from scratch, my suspicion is that (1) there would be nullable reference types, non nullable reference types, nullable value types and non nullable value types, and (2) there would be either a more clearly defined difference between null reference and null value, or their semantics would be more aligned when it comes to arithmetic, and (3) there would be automatic lifting of all non-nullable operations to nullable operations.

Note that VB/VBScript implement the more clear distinction by having two separate values: Null, which is database null, and Nothing, which is reference null.


问:
Highcharts: Line graph with half solid line and half dotted line?
I'm trying to show a time series line graph in highcharts - to the left of center is historical data, so the line needs to be solid.  To the right of center is predicted data, so the line needs to be dotted or dashed.  Is this possible?

Thanks!

答:
```<code>var envelopBorder =[[-20, 63], [-20, 85], null, null,null,null,[19, 130], [35,150], [60,150],[65,148], [80,140],[80,100],[65,82],[55,70],[40,67],[20,63],[15,63],[-20,63]] ;

var dasshedBorder =[[-20, 85],[-20, 100],[1, 130],[19, 130]] ;

Highcharts.chart('container', {
    chart: {
        type: 'line'
    },
    title: {
        text: 'Operating Envelop'
    },
        xAxis: {
        title: {
            enabled: true,
            text: 'Evaporating Temperature (°F)'
        },

        gridLineWidth: 0,
        lineWidth:1,
        startOnTick: true,
        endOnTick: true,
        showLastLabel: true
    },
    yAxis: {
        title: {
            text: 'Temperature (°C)'
        }
    },
    plotOptions: {
        line: {
            dataLabels: {
                enabled: true
            },
            enableMouseTracking: false
        }
    },
    series: [{
        name: 'Normal',
        data: envelopBorder
    }, {
        name: 'Dash',
        data: dasshedBorder,
        dashStyle: 'dash'
    }]
});
</code>```

Result :-

jsfiddle.net/7c9929mg

Body:
var envelopBorder =[[-20, 63], [-20, 85], null, null,null,null,[19, 130], [35,150], [60,150],[65,148], [80,140],[80,100],[65,82],[55,70],[40,67],[20,63],[15,63],[-20,63]] ;

var dasshedBorder =[[-20, 85],[-20, 100],[1, 130],[19, 130]] ;

Highcharts.chart('container', {
    chart: {
        type: 'line'
    },
    title: {
        text: 'Operating Envelop'
    },
        xAxis: {
        title: {
            enabled: true,
            text: 'Evaporating Temperature (°F)'
        },

        gridLineWidth: 0,
        lineWidth:1,
        startOnTick: true,
        endOnTick: true,
        showLastLabel: true
    },
    yAxis: {
        title: {
            text: 'Temperature (°C)'
        }
    },
    plotOptions: {
        line: {
            dataLabels: {
                enabled: true
            },
            enableMouseTracking: false
        }
    },
    series: [{
        name: 'Normal',
        data: envelopBorder
    }, {
        name: 'Dash',
        data: dasshedBorder,
        dashStyle: 'dash'
    }]
});

Result :-

jsfiddle.net/7c9929mg


问:
PHP float with 2 decimal places: .00
When I do this typecasting:

```<code>(float) '0.00';
</code>```

I get 0. How do I get 0.00 and still have the data type as a float?

答:
When we format any float value, that means we are changing its data type to string.  So when we apply the formatting on any amount/float value then it will set with all possible notations like dot, comma, etc. For example

```<code>(float)0.00 => (string)'0.00',
(float)10000.56 => (string) '10,000.56'
(float)5000000.20=> (string) '5,000,000.20'
</code>```

So, logically it's not possible to keep the float datatype after formatting.

Title: PHP float with 2 decimal places: .00

Body:
When I do this typecasting:

(float) '0.00';

I get 0. How do I get 0.00 and still have the data type as a float?

Body:
When we format any float value, that means we are changing its data type to string.  So when we apply the formatting on any amount/float value then it will set with all possible notations like dot, comma, etc. For example

(float)0.00 => (string)'0.00',
(float)10000.56 => (string) '10,000.56'
(float)5000000.20=> (string) '5,000,000.20'

So, logically it's not possible to keep the float datatype after formatting.


答:
Try this</p>

```<code>SimpleDateFormat format1=new SimpleDateFormat("MM/dd/yyyy");
      Date dt1=format1.parse(pass your date);
      DateFormat format2=new SimpleDateFormat("EEEE");
      String finalDay=format2.format(dt1);
</code>```

Body:
Try this

SimpleDateFormat format1=new SimpleDateFormat("MM/dd/yyyy");
      Date dt1=format1.parse(pass your date);
      DateFormat format2=new SimpleDateFormat("EEEE");
      String finalDay=format2.format(dt1);


问:
Create dynamic subdomain for each category
I want to create a dynamic subdomain for each category.

E.g. my side is www.bbq.com and when I select the xyz category it will redirect to xyz.bbq.com and when abc it will redirect to abc.bbq.com and so on.

I am using Magento 2 x, PHP 7, MySQL 6

For the above dynamic subdomain, I have created different store on one website. now i am redirecting properly to perticular category.

if suppose, i am redirecting to abc category i.e abc.bbq.com i want to show only those product who belonging to abc category i.e product is sort by category.

In what the way above things should be achieve?

答: Check my post for create the subdomains dynamically for your categories in Create subdomains on the fly with .htaccess (PHP) . Post title is Wildcard subdomain creation methods


问:
select and modify atomically in multi-threaded application
I am working on an Android application which has most of the code in C. I have compiled SQLite in C and using it.

I have following code:

```<code>void func_foo(){

Select X from table1

Update X in table1

}
</code>```

I want that func_foo behaves atomically and this function is getting called from multiple threads.

My concern is that once I ran select statement from thread1, thread2 should not modify the data of the tables in between.

So will wrapping the whole DB operation inside a transaction make it atomic?

Or do I need to use mutex over the function so that only one instance can access the DB?

答:
For the function to be atomic, it must be wrapped in a transaction. (Or you must ensure that the code calling it uses a transaction. The Android database framework has recursive transactions; in C, you'd have to implement that yourself.)

Additionally, you have to ensure that multiple threads do not end up using the same transaction, so you have to

give each thread its own database connection, or

use some kind of lock (e.g., a mutex) to ensure that no two threads run a transaction at the same time.

Body:
I am working on an Android application which has most of the code in C. I have compiled SQLite in C and using it.

I have following code:

void func_foo(){

Select X from table1

Update X in table1

}

I want that func_foo behaves atomically and this function is getting called from multiple threads.

My concern is that once I ran select statement from thread1, thread2 should not modify the data of the tables in between.

So will wrapping the whole DB operation inside a transaction make it atomic?

Or do I need to use mutex over the function so that only one instance can access the DB?


问:
Resources and control position in win32 programming
I'm new in win32 programming and I've some questions about resources.

Must I use a resource editor (from Visual Studio) to make controls? I know it can be post-edited using a Resource Hacker editor. How to prevent it?

GUI created in Windows Forms (.net) or Borland Delphi (VCL) can't be edited using res hacker, maybe it creates controls at runtime.

Is a pointless work make all controls by runtime to prevent it to be edited by res hacker?

```<code>HWND hButton = CreateWindowEx(
    0,
    _T("BUTTON"),
    _T("Click!"),
    WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_LEFTTEXT,
    5, 5, 80, 25, hwnd, (HMENU)IDC_BUTTON1,
    GetModuleHandle(NULL),
    NULL
);
</code>```

Second question: isn't there a easy way to set position of a control in top right of parent window?

Today I'm doing it in this way:

```<code>case WM_SIZE:
    {
        HWND hButton;
        RECT rcParent, rcButton;

        hButton = GetDlgItem(hwnd, IDC_BUTTON1);

        GetClientRect(hwnd, &rcParent);
        GetClientRect(hButton, &rcButton);

        if(!SetWindowPos(hButton, 0, rcParent.right - (rcButton.right - rcButton.left + 5), 5, 0, 0, SWP_NOSIZE))
        {
            MessageBox(hwnd, _T("Error at WM_SIZE"), _T("Error!"), MB_OK | MB_ICONERROR);
        }
    }
    break;
</code>```

Are there something like Anchors in pure win32 programming?

答:
The resource file format for dialogs is ancient. The only thing in its favor is the dialog unit abstraction that means that dialogs automatically scale to take account of the users preferred font face and display dpi settings.

Other than that, there is no support in the dialog format for anchors. Microsoft have sadly not released a new UI building toolkit however for native development so for Native Win32 apps you are stuck creating / positioning your controls at runtime manually for any task that dialog resources cannot cater for.

WPF is clearly superior, but requires .NET

I don't see the point of disallowing res hacking one way or another. What do you gain by preventing it? If your own layout skills are so bad that people will want to re-layout their dialogs "illegally" then... well wtf is all I can say.

To Summarize:

It IS pointless to try and protect dialog layouts. What can you possibly hope to achieve by limiting something people would only resort to if your own layouts were #@%^ anyway.

You WILL however probably want to create the controls at runtime anyway as the dialog resource format lacks modern features like anchors. Allthough it is a good idea to continue the practice of designing forms in units based on font metrics rather than pixels.

If you want a pre-build "form" layout system with anchors, Win32 cannot help you. The QT framework if you want a cross platform c++ solution, or switching to .NET's WPF are both powerful alternatives that may allow you to leverage your existing non UI code.

Body:
I'm new in win32 programming and I've some questions about resources.

Must I use a resource editor (from Visual Studio) to make controls? I know it can be post-edited using a Resource Hacker editor. How to prevent it?

GUI created in Windows Forms (.net) or Borland Delphi (VCL) can't be edited using res hacker, maybe it creates controls at runtime.

Is a pointless work make all controls by runtime to prevent it to be edited by res hacker?

HWND hButton = CreateWindowEx(
    0,
    _T("BUTTON"),
    _T("Click!"),
    WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_LEFTTEXT,
    5, 5, 80, 25, hwnd, (HMENU)IDC_BUTTON1,
    GetModuleHandle(NULL),
    NULL
);

Second question: isn't there a easy way to set position of a control in top right of parent window?

Today I'm doing it in this way:

case WM_SIZE:
    {
        HWND hButton;
        RECT rcParent, rcButton;

        hButton = GetDlgItem(hwnd, IDC_BUTTON1);

        GetClientRect(hwnd, &rcParent);
        GetClientRect(hButton, &rcButton);

        if(!SetWindowPos(hButton, 0, rcParent.right - (rcButton.right - rcButton.left + 5), 5, 0, 0, SWP_NOSIZE))
        {
            MessageBox(hwnd, _T("Error at WM_SIZE"), _T("Error!"), MB_OK | MB_ICONERROR);
        }
    }
    break;

Are there something like Anchors in pure win32 programming?


问:
Hibernate - One-to-one mapping with column name
I have two tables:

CUSTOMERS: ID (key)

PERSONAL_DATA: ID (key), CUSTOMER_ID

Is it possible to create XML configuration:

relation one-to-one CUSTOMERS.ID -> PERSONAL_DATA.CUTOMER.ID

property of type PERSONAL_DATA in CUSTOMERS pojo class?

答:
Yes, xmls may look like:

CUSTOMERS xml:

<hibernate-mapping>
 <class name="QUALIFIED_NAME_OF_CUSTOMERS" table="CUSTOMERS" catalog="YOUR_DATABASE_NAME">
  <id name="id" type="java.lang.Integer">
   <column name="id" />
   <generator class="identity" />
  </id>
  <one-to-one name="PERSONAL_DATA" class="QUALIFIED_NAME_OF_PERSONAL_DATA"
   cascade="save-update"></one-to-one>
 </class>
</hibernate-mapping>```
</div>
</div>
</p>

<ol start="2">
<li>PERSONAL_DATA xml:</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><hibernate-mapping>
    <class name="QUALIFIED_NAME_OF_PERSONAL_DATA" table="PERSONAL_DATA"
          catalog="YOUR_DATABASE_NAME">
        <id name="customer_id" type="java.lang.Integer">
          <column name="customer_id" />
            <generator class="foreign">
            <param name="property">CUSTOMERS</param>
         </generator>
      </id>
        <one-to-one name="CUSTOMERS" class="QUALIFIED_NAME_OF_CUSTOMERS"
           constrained="true">
        </one-to-one>
        <property name="id" type="java.lang.Integer">
            <column name="id" />
        </property>

      </class>
</hibernate-mapping></code>```

Body:
Yes, xmls may look like:

CUSTOMERS xml:

<hibernate-mapping>
 <class name="QUALIFIED_NAME_OF_CUSTOMERS" table="CUSTOMERS" catalog="YOUR_DATABASE_NAME">
  <id name="id" type="java.lang.Integer">
   <column name="id" />
   <generator class="identity" />
  </id>
  <one-to-one name="PERSONAL_DATA" class="QUALIFIED_NAME_OF_PERSONAL_DATA"
   cascade="save-update"></one-to-one>
 </class>
</hibernate-mapping>

PERSONAL_DATA xml:

<hibernate-mapping>
    <class name="QUALIFIED_NAME_OF_PERSONAL_DATA" table="PERSONAL_DATA"
          catalog="YOUR_DATABASE_NAME">
        <id name="customer_id" type="java.lang.Integer">
          <column name="customer_id" />
            <generator class="foreign">
            <param name="property">CUSTOMERS</param>
         </generator>
      </id>
        <one-to-one name="CUSTOMERS" class="QUALIFIED_NAME_OF_CUSTOMERS"
           constrained="true">
        </one-to-one>
        <property name="id" type="java.lang.Integer">
            <column name="id" />
        </property>

      </class>
</hibernate-mapping>


问:
Android Preference. Setting child default value when parent is disable
I'm working on simple Android application. I'm using C# and Xamarin but i believe that programing language doesn't matter in that case since all changes are in .xml file.

Ok so my problem is related with preference that have dependency to other preference. First let me show my code then I will try to explain what i asking about.

```<code>  <PreferenceCategory
  android:title="@string/Pref_battery_settings"
  android:key="pref_key_battery_settings">
<SwitchPreference
    android:title="@string/Pref_battery_track_title"
    android:summary="@string/Pref_battery_track_summary"
    android:key="Pref_battery_track"
    android:defaultValue="true"/>
<CheckBoxPreference
android:dependency="Pref_battery_track"
android:disableDependentsState="true"
android:title="@string/Pref_battery_track_battery_status_title"
android:summary="@string/Pref_battery_track_battery_status_summary"
android:key="Pref_battery_track_status"
android:defaultValue="false"/>
</code>```

As You can see i have 2 preference. First Pref_battery_track is SwitchPreference that will determine is my app will track battery ( levels ect. ) If that preference will be setted to TRUE user will be able to use second preference which will decide if we want to track battery status or nor ( status is e.g Charging, Discharging ect.). In logical thinking if we set first preference to true we can decide do we want to track more information or not but right now i have problem. When i set Pref_battery_track to true then Pref_battery_track_status also to true and switch back first preference to false second will be still as true and we will be able to do code like :

```<code>var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
var t =  prefs.GetBoolean("Pref_battery_track_status", false);
</code>```

This code will return true when Pref_battery_track_status will be true even when Pref_battery_track will be fasle. So my question is : Is there any way to set child preference to default value when parent preference is false ?

Hope you know what i asking about.

And yes i know that i can simply check before i use child preference like`

```<code>var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
if(prefs.GetBoolean("Pref_battery_track", false))
{
var t = prefs.GetBoolean("Pref_battery_track_status", false);
 // Do things
}`
</code>```

But this solution is not nice since every time before i use child preference i will have to check parent.

答:
You can subscribe the PreferenceChange event of your SwitchPreference, for example like this:

```<code>var switchp = PreferenceScreen.FindPreference("Pref_battery_track");
switchp.PreferenceChange += Switchp_PreferenceChange;
</code>```

And then in Switchp_PreferenceChange set the Checked property of CheckBoxPreference for example:

```<code>private void Switchp_PreferenceChange(object sender, PreferenceChangeEventArgs e)
{
    var isenabled = (bool)e.NewValue;
    if (!isenabled)
    {
        var checkp = PreferenceScreen.FindPreference("Pref_battery_track_status") as CheckBoxPreference;
        checkp.Checked = false;
    }
}
</code>```

Body:
I'm working on simple Android application. I'm using C# and Xamarin but i believe that programing language doesn't matter in that case since all changes are in .xml file.

Ok so my problem is related with preference that have dependency to other preference. First let me show my code then I will try to explain what i asking about.

  <PreferenceCategory
  android:title="@string/Pref_battery_settings"
  android:key="pref_key_battery_settings">
<SwitchPreference
    android:title="@string/Pref_battery_track_title"
    android:summary="@string/Pref_battery_track_summary"
    android:key="Pref_battery_track"
    android:defaultValue="true"/>
<CheckBoxPreference
android:dependency="Pref_battery_track"
android:disableDependentsState="true"
android:title="@string/Pref_battery_track_battery_status_title"
android:summary="@string/Pref_battery_track_battery_status_summary"
android:key="Pref_battery_track_status"
android:defaultValue="false"/>

As You can see i have 2 preference. First Pref_battery_track is SwitchPreference that will determine is my app will track battery ( levels ect. ) If that preference will be setted to TRUE user will be able to use second preference which will decide if we want to track battery status or nor ( status is e.g Charging, Discharging ect.). In logical thinking if we set first preference to true we can decide do we want to track more information or not but right now i have problem. When i set Pref_battery_track to true then Pref_battery_track_status also to true and switch back first preference to false second will be still as true and we will be able to do code like :

var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
var t =  prefs.GetBoolean("Pref_battery_track_status", false);

This code will return true when Pref_battery_track_status will be true even when Pref_battery_track will be fasle. So my question is : Is there any way to set child preference to default value when parent preference is false ?

Hope you know what i asking about.

And yes i know that i can simply check before i use child preference like`

var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
if(prefs.GetBoolean("Pref_battery_track", false))
{
var t = prefs.GetBoolean("Pref_battery_track_status", false);
 // Do things
}`

But this solution is not nice since every time before i use child preference i will have to check parent.

Body:
You can subscribe the PreferenceChange event of your SwitchPreference, for example like this:

var switchp = PreferenceScreen.FindPreference("Pref_battery_track");
switchp.PreferenceChange += Switchp_PreferenceChange;

And then in Switchp_PreferenceChange set the Checked property of CheckBoxPreference for example:

private void Switchp_PreferenceChange(object sender, PreferenceChangeEventArgs e)
{
    var isenabled = (bool)e.NewValue;
    if (!isenabled)
    {
        var checkp = PreferenceScreen.FindPreference("Pref_battery_track_status") as CheckBoxPreference;
        checkp.Checked = false;
    }
}


问:
html5 video on internet explorer
i have a problem.
I want to show my video on the page, but it doesn't work on IE 11 windows 7, on other it works fine. The problem is that other mp4 files works on IE 11, windows 7 too.

I don't know what is wrong with my video file that IE 11, windows 7 shows nothing

```<code><div class="my-video">
<div class="my-video-overlay"></div>
<video autoplay="autoplay" loop="loop">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.mp4" type="video/mp4">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.webm" type="video/webm">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.ogv" type="video/ogv">
</video>
</div>
</code>```

答:
Seems to like a no Media Feature installed into your PC (Win-7).Install from here https://www.microsoft.com/en-in/download/details.aspx?id=16546
Video worked fine in Chrome, Firefox, etc, because these browsers can support webm file also.</p>

Title: html5 video on internet explorer

Body:
i have a problem.
I want to show my video on the page, but it doesn't work on IE 11 windows 7, on other it works fine. The problem is that other mp4 files works on IE 11, windows 7 too.

I don't know what is wrong with my video file that IE 11, windows 7 shows nothing

<video autoplay="autoplay" loop="loop">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.mp4" type="video/mp4">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.webm" type="video/webm">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.ogv" type="video/ogv">
</video>


问:
R: Validate Data for Numeric Variables with Different Length
Here's my dataframe

```<code>Key Q1   Q2
1    1   NA
2    2    1
3    8   NA
4    3    2
5    1    32
6    5    3
</code>```

I would like to validate if the data follows the rules

Rule1:

```<code> if Q1==1,  Q2 can only have 1 & 2
</code>```

Rule2:

```<code> if Q1!=1, Q2 has to be empty/without any value
</code>```

I would like to  have the results as stated below:

```<code> Key Q1   Q2   Result
 1    1   NA   TRUE
 2    2    1   TRUE
 3    8   NA   FALSE
 4    3    2   TRUE
 5    1    32  FALSE
 6    5    3   FALSE
</code>```

However, I got the warning error "the condition has length > 1 and only the first element will be used".

Body:
Here's my dataframe

Key Q1   Q2
1    1   NA
2    2    1
3    8   NA
4    3    2
5    1    32
6    5    3

I would like to validate if the data follows the rules

Rule1:

 if Q1==1,  Q2 can only have 1 & 2

Rule2:

 if Q1!=1, Q2 has to be empty/without any value

I would like to  have the results as stated below:

 Key Q1   Q2   Result
 1    1   NA   TRUE
 2    2    1   TRUE
 3    8   NA   FALSE
 4    3    2   TRUE
 5    1    32  FALSE
 6    5    3   FALSE

However, I got the warning error "the condition has length > 1 and only the first element will be used".

Body:
We can do

 with(df1, (Q1==1) & (Q2 %in% 1:2)|(Q1 != 1 & is.na(Q2)))


问:
How to get the key in Collectors.toMap merge function?
When a duplicate key entry is found during Collectors.toMap(), the merge function (o1, o2) is called.

Question: how can I get the key that caused the duplication?

```<code>String keyvalp = "test=one\ntest2=two\ntest2=three";

Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .collect(Collectors.toMap(
        split -> split[0],
        split -> split[1],
        (o1, o2) -> {
            //TODO how to access the key that caused the duplicate? o1 and o2 are the values only
            //split[0]; //which is the key, cannot be accessed here
        },
    HashMap::new));
</code>```

Inside the merge function I want to decide based on the key which if I cancel the mapping, or continue and take on of those values.

答:
You need to use a custom collector or use a different approach.

```<code>Map<String, String> map = new Hashmap<>();
Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .forEach(arr -> map.merge(arr[0], arr[1], (o1, o2) -> /* use arr[0]));
</code>```

Writing a custom collector is rather more complicated. You need a TriConsumer (key and two values) is similar which is not in the JDK which is why I am pretty sure there is no built in function which uses. ;)

Body:
When a duplicate key entry is found during Collectors.toMap(), the merge function (o1, o2) is called.

Question: how can I get the key that caused the duplication?

String keyvalp = "test=one\ntest2=two\ntest2=three";

Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .collect(Collectors.toMap(
        split -> split[0],
        split -> split[1],
        (o1, o2) -> {
            //TODO how to access the key that caused the duplicate? o1 and o2 are the values only
            //split[0]; //which is the key, cannot be accessed here
        },
    HashMap::new));

Inside the merge function I want to decide based on the key which if I cancel the mapping, or continue and take on of those values.

Body:
You need to use a custom collector or use a different approach.

Map<String, String> map = new Hashmap<>();
Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .forEach(arr -> map.merge(arr[0], arr[1], (o1, o2) -> /* use arr[0]));

Writing a custom collector is rather more complicated. You need a TriConsumer (key and two values) is similar which is not in the JDK which is why I am pretty sure there is no built in function which uses. ;)


问:
Angular: Disable Change Detector for an entire class (service or component)
Is there a way to completely disable Angular's change detector if events that normally cause the change detection to run (setTimeout, setInterval, browser events, ajax calls etc..), are coming from a specific class (service or component)?

Namely, it seemed totally wrong to me when I found out that the setInterval registered in my service causes the global change detection to run every second..

I'm aware I can wrap my code inside the NgZone.runOutsideAngular method's callback, but I'd prefer the solution where the change detector can be disabled for an entire class, as I have other chunks of code within the service that are needlessly running the detection too.

Thanks for your help.

答:
Change Detection starts at the very top of your component tree and is triggered by zone.js.
An async operation like setTimeout is picked up by zone.js which notifies angular that changes might have happened. Angular then runs change detection top-down on the component tree.
Detaching a single class from the change detector will cut out that class (i.e. directive) from change detection but won't stop change detection from being run on the rest of your component tree.
For your needs ngZone.runOutsideAngular(...) is the way to go, because it stops zone.js from notifying angular about your async operation thus entirely preventing change detection from being run.