问:
Run different code based type
I want to call a method for my WPF-App with subtype objects of my Piece class. My problem is that the subtype objects have more properties than e.g the the Text objects.

Do you know a way to cope with this better than I do in my FillForm example?

```<code>namespace Namespace
{
    public abstract class Piece
        {
            public int id { get; set; }
            public string title { get; set; }
            public string description { get; set; }

        }

        public class Text : Piece
        {

        }

        public class Image: Piece{
             public string filePath { get; set; }
            public string fileformat { get; set; }
        }

        public class Video : Image
        {

        }
    }
}
</code>```

Example method:

```<code>public void FillForm(Piece currentPiece)
{
            pieceIdTextBox.Text = currentPiece.id.ToString();
            pieceNameTextBox.Text = currentPiece.title;
            pieceDescriptionTextBox.Text = currentPiece.description;
            if (!currentPiece.GetType().ToString().Equals("Namespace.Text"))
            {
                pieceFileSelectURLTextBlock.Text = (currentPiece as Namespace.Image).filePath;
                SetPreviews((currentPiece as Namespace.Image).filePath);
            }

}
</code>```

Thanks!

答:
Why not just change the method to the following with more type-safety</p>

```<code>public void FillForm(Piece currentPiece)
{
    pieceIdTextBox.Text = currentPiece.id.ToString();
    pieceNameTextBox.Text = currentPiece.title;
    pieceDescriptionTextBox.Text = currentPiece.description;
    if (currentPiece as Namespace.Image imagePiece)
    {
        pieceFileSelectURLTextBlock.Text = imagePiece.filePath;
        SetPreviews(imagePiece.filePath);
    }
}
</code>```

Title: Run different code based type

Body:
I want to call a method for my WPF-App with subtype objects of my Piece class. My problem is that the subtype objects have more properties than e.g the the Text objects.

Do you know a way to cope with this better than I do in my FillForm example?

namespace Namespace
{
    public abstract class Piece
        {
            public int id { get; set; }
            public string title { get; set; }
            public string description { get; set; }

        }

        public class Text : Piece
        {

        }

        public class Image: Piece{
             public string filePath { get; set; }
            public string fileformat { get; set; }
        }

        public class Video : Image
        {

        }
    }
}

Example method:

public void FillForm(Piece currentPiece)
{
            pieceIdTextBox.Text = currentPiece.id.ToString();
            pieceNameTextBox.Text = currentPiece.title;
            pieceDescriptionTextBox.Text = currentPiece.description;
            if (!currentPiece.GetType().ToString().Equals("Namespace.Text"))
            {
                pieceFileSelectURLTextBlock.Text = (currentPiece as Namespace.Image).filePath;
                SetPreviews((currentPiece as Namespace.Image).filePath);
            }

}

Thanks!

Body:
Why not just change the method to the following with more type-safety

public void FillForm(Piece currentPiece)
{
    pieceIdTextBox.Text = currentPiece.id.ToString();
    pieceNameTextBox.Text = currentPiece.title;
    pieceDescriptionTextBox.Text = currentPiece.description;
    if (currentPiece as Namespace.Image imagePiece)
    {
        pieceFileSelectURLTextBlock.Text = imagePiece.filePath;
        SetPreviews(imagePiece.filePath);
    }
}


来源: stackexchange

问:
Getting Assembly Version of a class that implements interface through interface method
My classes all implement an interface. This interface stores some funtions for general functionality.

One of those funtionalities is Logging. In this Logging function I want to get the AssemblyVersion of the Class that implements the interface.

My problem is that Assembly.GetExectuingAssembly() will return the AssemblyVersion of the Interface.

How can I get the Assembly Version of the implementing class?

答:
This should work:</p>

```<code>this.GetType().Assembly.GetName().Version
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This should work:

this.GetType().Assembly.GetName().Version


问:
why is it not possible to use value as keyword argument in print function?
If I write my function f as this:

```<code>def f(a, b, c, d = 4, e = 5, f = 6):
    print(a, b, c, d, e, f)
</code>```

I can call it normally with positional arguments:

```<code>f(1, 2, 3)
</code>```

And I can also call it using the positional arguments as keyword arguments:

```<code>f(c=3, a=1, b=2)
</code>```

However, if I do that with the print function, I get an error:

```<code>>>> print(value=42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'value' is an invalid keyword argument for this function
</code>```

I tried to use value as keyword because it was what it showed me when I did help(print):

```<code>Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
</code>```

edit:

Now I understand the *objects and I get that print is looking for a tuple of values. The pow function illustrates what I ask better:

```<code>>>> pow(x=2, y=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pow() takes no keyword arguments
</code>```

Why can't I never seem to refer to the parameters by their names if I use python functions? As I showed above it worked for my f function.

答:
The implementation of print is this:

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

The objects parameter has a * before, so it is expected to be a variable number of positional arguments*

*Edited after @brunodesthuilliers comment.

Body:
If I write my function f as this:

def f(a, b, c, d = 4, e = 5, f = 6):
    print(a, b, c, d, e, f)

I can call it normally with positional arguments:

f(1, 2, 3)

And I can also call it using the positional arguments as keyword arguments:

f(c=3, a=1, b=2)

However, if I do that with the print function, I get an error:

>>> print(value=42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'value' is an invalid keyword argument for this function

I tried to use value as keyword because it was what it showed me when I did help(print):

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

edit:

Now I understand the *objects and I get that print is looking for a tuple of values. The pow function illustrates what I ask better:

>>> pow(x=2, y=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pow() takes no keyword arguments

Why can't I never seem to refer to the parameters by their names if I use python functions? As I showed above it worked for my f function.


问:
Python 2.7 File Handling saving username
Ok im doing some coding work making a username saver, I need to save multiple users to different text files, But I get an error when trying to set the file directory,

```<code>fileloc = "N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
filename = fileloc+newname+".txt"
print filename
adduserfile = open(filename, "rw+")
</code>```

I get the error "EOL while scanning string literal", It then highlights the last quotation mark at the end of line 1, Im not sure how to fix this, Please help

Sorry for asking such a simple question, I understand that it was my use of the address because of the special characters () causing it to break, thanks for the time and help

答:
You need to be carefull about special chars "\":

fileloc = "N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\\"
filename = fileloc+"newname"+".txt"
print filename
N:\Documents) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\newname.txt

I used "newname" as a string here, you can set it and change as a var.

ContentLicense: CC BY-SA 4.0

Body:
Ok im doing some coding work making a username saver, I need to save multiple users to different text files, But I get an error when trying to set the file directory,

fileloc = "N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
filename = fileloc+newname+".txt"
print filename
adduserfile = open(filename, "rw+")

I get the error "EOL while scanning string literal", It then highlights the last quotation mark at the end of line 1, Im not sure how to fix this, Please help

Sorry for asking such a simple question, I understand that it was my use of the address because of the special characters () causing it to break, thanks for the time and help


问:
How to use z-index in svg elements?
I'm using the svg circles in my project like this,

```<code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
</svg>
</code>```

And I'm using the z-index in the g tag to show the elements the first. In my project I need to use only z-index value, but I can't use the z-index to my svg elements. I have googled a lot but I didn't find anything relatively.
So please help me to use z-index in my svg.

Here is the DEMO.

答:
Using D3:

If you want to re-inserts each selected element, in order, as the last child of its parent.

```<code>selection.raise()
</code>```

Title: How to use z-index in svg elements?

Body:
I'm using the svg circles in my project like this,

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
    <g>
        <g id="one">
            <circle fill="green" cx="100" cy="105" r="20" />
        </g>
        <g id="two">
            <circle fill="orange" cx="100" cy="95" r="20" />
        </g>
    </g>
</svg>

And I'm using the z-index in the g tag to show the elements the first. In my project I need to use only z-index value, but I can't use the z-index to my svg elements. I have googled a lot but I didn't find anything relatively.
So please help me to use z-index in my svg.

Here is the DEMO.

Body:
Using D3:

If you want to re-inserts each selected element, in order, as the last child of its parent.

selection.raise()


问:
undefined response, ajax is not working?
I'm Very Green when it comes to the Front End Development, I'm trying to Insert Data using Modal, I have two text boxes the first is code and the second is name..
I need them to be unique:

```<code> $.validator.addMethod("codeNotUsed", function (value, element) {
                    var response;
                    $.ajax({
                        type: "POST",
                        url: "Profile_ValidatieProfileCode.ashx",
                        data: { code: $('#txtCode').val() },
                        async: false,
                        success: function (data) {
                            response = eval(data);
                        }
                    });
                    alert(response);
                    return response;

                }, "Code already used");

 $.validator.addMethod("nameNotUsed", function (value, element) {
                    var response;
                    $.ajax({
                        type: "POST",
                        url: "Profile_ValidateProfileName.ashx",
                        data: { name: $('#txtName').val() },
                        async: false,
                        success: function (data) {
                            response = eval(data);
                        }
                    });

                    return response;

                }, "Name already used");
</code>```

the content of one of the .ashx files:

```<code> Imports System.Web
 Imports System.Web.Services

 Public Class Profile_ValidateProfileName
Implements System.Web.IHttpHandler

Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

    context.Response.ContentType = "text/plain"

    Dim name = context.Request.Form("name")

    Try
        Dim type = DataFactory.Instance.GetProfileByName(UserIdentity.ClientConfig.ConnectionString, name)

        If IsNothing(type) Then
            context.Response.Write("true")
        Else
            context.Response.Write("false")
        End If

    Catch ex As Exception
        context.Response.Write("false")
    End Try

End Sub

ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
        Return False
    End Get
End Property
</code>```

End Class

HTML Code:

```<code> <form id="InputForm" name="InputForm" action="javascript:void(0);" novalidate="novalidate"><div id="InputFormContent">
        <br>
        <div class="row">
            <div class="col-xs-12">
                <div class="form-group">
                    <label>Code</label>
                    <div class="icon-addon">
                        <input id="txtCode" name="txtCode" class="form-control required" maxlength="10">
                        <i class="fa fa-edit"></i>
                    </div>
                </div>
            </div>
        </div>

         <div class="row">
            <div class="col-xs-12">
                <div class="form-group">
                    <label>Name</label>
                    <div class="icon-addon">
                        <input id="txtName" name="txtName" class="form-control required" maxlength="30">
                        <i class="fa fa-edit"></i>
                    </div>
                </div>
            </div>
        </div>

    </div>
</code>```

The unique validation is not working and I thing that's the ajax code is not working well, the alert gives me 'Undefined'..

答:
the alert statement was executed before success function is even called, executing the alert statement after ajax request is done is working better in this case:
   The Code:</p>

```<code>$.validator.addMethod("codeNotUsed", function (value, element) {

                    var response;
                    $.ajax({
                        type: "POST",
                        url: "Profile_ValidatieProfileCode.ashx",
                        data: { code: $('#txtCode').val() },
                        async: false,
                        error: function (xhr, status, error) {
                            alert(error)
                        }
                    }).done(function (data) {
                        response = eval(data);
                        alert(response); // this will give true or false accourding to server response
                    });
                    return response;

                }, "Code already used");

                $.validator.addMethod("nameNotUsed", function (value, element) {

                        var response;
                        $.ajax({
                            type: "POST",
                            url: "Profile_ValidateProfileName.ashx",
                            data: { name: $('#txtName').val() },
                            async: false,
                            error: function (xhr, status, error) {
                                alert(error)
                            }
                        }).done(function (data) {
                            response = eval(data);
                            alert(response); // this will give true or false accourding to server response

                        });

                        return response;
                    }, "Name already used");
</code>```

Body:
I'm Very Green when it comes to the Front End Development, I'm trying to Insert Data using Modal, I have two text boxes the first is code and the second is name..
I need them to be unique:

 $.validator.addMethod("codeNotUsed", function (value, element) {
                    var response;
                    $.ajax({
                        type: "POST",
                        url: "Profile_ValidatieProfileCode.ashx",
                        data: { code: $('#txtCode').val() },
                        async: false,
                        success: function (data) {
                            response = eval(data);
                        }
                    });
                    alert(response);
                    return response;

                }, "Code already used");

 $.validator.addMethod("nameNotUsed", function (value, element) {
                    var response;
                    $.ajax({
                        type: "POST",
                        url: "Profile_ValidateProfileName.ashx",
                        data: { name: $('#txtName').val() },
                        async: false,
                        success: function (data) {
                            response = eval(data);
                        }
                    });

                    return response;

                }, "Name already used");

the content of one of the .ashx files:

 Imports System.Web
 Imports System.Web.Services

 Public Class Profile_ValidateProfileName
Implements System.Web.IHttpHandler

Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

    context.Response.ContentType = "text/plain"

    Dim name = context.Request.Form("name")

    Try
        Dim type = DataFactory.Instance.GetProfileByName(UserIdentity.ClientConfig.ConnectionString, name)

        If IsNothing(type) Then
            context.Response.Write("true")
        Else
            context.Response.Write("false")
        End If

    Catch ex As Exception
        context.Response.Write("false")
    End Try

End Sub

ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
        Return False
    End Get
End Property

End Class

HTML Code:

 <form id="InputForm" name="InputForm" action="javascript:void(0);" novalidate="novalidate">

                    Code

                        <input id="txtCode" name="txtCode" class="form-control required" maxlength="10">

                    Name

                        <input id="txtName" name="txtName" class="form-control required" maxlength="30">

The unique validation is not working and I thing that's the ajax code is not working well, the alert gives me 'Undefined'..

Body:
the alert statement was executed before success function is even called, executing the alert statement after ajax request is done is working better in this case:
   The Code:

$.validator.addMethod("codeNotUsed", function (value, element) {

                    var response;
                    $.ajax({
                        type: "POST",
                        url: "Profile_ValidatieProfileCode.ashx",
                        data: { code: $('#txtCode').val() },
                        async: false,
                        error: function (xhr, status, error) {
                            alert(error)
                        }
                    }).done(function (data) {
                        response = eval(data);
                        alert(response); // this will give true or false accourding to server response
                    });
                    return response;

                }, "Code already used");

                $.validator.addMethod("nameNotUsed", function (value, element) {

                        var response;
                        $.ajax({
                            type: "POST",
                            url: "Profile_ValidateProfileName.ashx",
                            data: { name: $('#txtName').val() },
                            async: false,
                            error: function (xhr, status, error) {
                                alert(error)
                            }
                        }).done(function (data) {
                            response = eval(data);
                            alert(response); // this will give true or false accourding to server response

                        });

                        return response;
                    }, "Name already used");


问:
Xcode 9 storyboard window position autosave
I start new project in Xcode 9 (macOS Game with SceneKit technology). I got storyboard containing NSWindowController with NSWindow and related GameViewController with SCNView. Project runs fine (spins a plane).

Now in storyboard I set Autosave value to "MainWindow" for NSWindow, run project, resize window and then quit. I know that with Autosave set on quit window position will be saved using NSUserDefaults, so I check in Terminal:

```<code>$ defaults read com.koati.Bloks                                           ⏎
{
    "NSWindow Frame MainWindow" = "415 228 450 322 0 0 1280 777 ";
}
</code>```

That's expected behaviour. Now I run project once again, but I see that window position is not restored. If in storyboard I remove GameViewController relation, then position is saved and restored correctly, so I suppose that GameViewController somehow influences window size and position.
In older Xcode with XIBs there were no such problem.

EDIT: After some doing some tests, I now think it is not related to SceneKit at all, as replacing SCNView with NSView in NSViewController produces same results. So I think the problem is that NSViewController attached via Storyboard to NSWindow content influences window position and size.

Maybe some one knows how to fix this issue?

答:
Strangely enough, this answer: https://stackoverflow.com/a/33707356/3736845
still applies, even in XCode9. After programmatic setup of autosave name (for Swift4 a bit different notation):

```<code>class MainWindowController: NSWindowController {

  override func windowDidLoad() {
    super.windowDidLoad()

    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    self.windowFrameAutosaveName = NSWindow.FrameAutosaveName.init(rawValue: "position")
  }
}
</code>```

it started restoring positions on restart of the Application.

What I don't understand however is what's saved into defaults:

```<code>defaults read com.ne.TestWindowPosition
{
   "NSWindow Frame Position" = "510 428 901 322 0 0 1920 1177 ";
   "NSWindow Frame position" = "0 0 901 322 0 0 1920 1177 ";
}
</code>```

I played a bit with the IB Window Autosave identifier - you see it appears as first line in the defaults ("Position") and it doesn't seem to be read properly on Application startup.
After I added manual set of autosave name to "position" - it's changing, when I move the window.

Body:
I start new project in Xcode 9 (macOS Game with SceneKit technology). I got storyboard containing NSWindowController with NSWindow and related GameViewController with SCNView. Project runs fine (spins a plane).

Now in storyboard I set Autosave value to "MainWindow" for NSWindow, run project, resize window and then quit. I know that with Autosave set on quit window position will be saved using NSUserDefaults, so I check in Terminal:

$ defaults read com.koati.Bloks                                           ⏎
{
    "NSWindow Frame MainWindow" = "415 228 450 322 0 0 1280 777 ";
}

That's expected behaviour. Now I run project once again, but I see that window position is not restored. If in storyboard I remove GameViewController relation, then position is saved and restored correctly, so I suppose that GameViewController somehow influences window size and position.
In older Xcode with XIBs there were no such problem.

EDIT: After some doing some tests, I now think it is not related to SceneKit at all, as replacing SCNView with NSView in NSViewController produces same results. So I think the problem is that NSViewController attached via Storyboard to NSWindow content influences window position and size.

Maybe some one knows how to fix this issue?

Body:
Strangely enough, this answer: https://stackoverflow.com/a/33707356/3736845
still applies, even in XCode9. After programmatic setup of autosave name (for Swift4 a bit different notation):

class MainWindowController: NSWindowController {

  override func windowDidLoad() {
    super.windowDidLoad()

    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    self.windowFrameAutosaveName = NSWindow.FrameAutosaveName.init(rawValue: "position")
  }
}

it started restoring positions on restart of the Application.

What I don't understand however is what's saved into defaults:

defaults read com.ne.TestWindowPosition
{
   "NSWindow Frame Position" = "510 428 901 322 0 0 1920 1177 ";
   "NSWindow Frame position" = "0 0 901 322 0 0 1920 1177 ";
}

I played a bit with the IB Window Autosave identifier - you see it appears as first line in the defaults ("Position") and it doesn't seem to be read properly on Application startup.
After I added manual set of autosave name to "position" - it's changing, when I move the window.


问:
c# ignoring else if statement
I am trying to make a winforms application so when something is clicked it checks a webpage for it's response.

I have tested the web page to see if it is a PHP error but it works fine from that side.

It is completely ignoring the else if statement and skips to the else statement below it even though the response is "Unassigned".

Here is my code:

```<code>private void button1_Click(object sender, EventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://fms.psrpc.co.uk/apiconfirmD.php?" + ApiKey);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        using (response)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            if (reader.ReadToEnd() == "Changed")
            {
                label2.Visible = false;
                button1.Enabled = false;
                button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
                button5.Enabled = true;
                button6.Enabled = true;
                button7.Enabled = true;
                button8.Enabled = true;
                timer1.Enabled = true;
            }
            else if (reader.ReadToEnd() == "Unassigned")
            {
                string message = "Error Code: B66794O37945O46791K@@Error booking on.@Please make sure you have been assigned to a vehicle.@@If this error persists please contact K.McCrudden.";
                message = message.Replace("@", "" + System.Environment.NewLine);
                string title = "Error!";

                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
            }
            else
            {
                string message = "Error Code: B002875O46883O84655K@@Error booking on.@Please make sure you have booked a shift and have been assigned.@@If this error persists please contact K.McCrudden.";
                message = message.Replace("@", "" + System.Environment.NewLine);
                string title = "Error!";

                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
            }
        }
    }
</code>```

答:
No, it is not being ignored. You are reading all the data in your first if block by calling reader.ReadToEnd(). This way, there is no further data available to read in your else if statement; it returns empty string. Thus condition does not match and final else block gets executed.

Modify the code something like below. Notice the temporary data variable in below code.

```<code>StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();//Read the data in temp variable.
//Use this variable to check the conditions further.
if (data == "Changed")
{
    //Your code here
}
else if (data == "Unassigned")
{
    //Your code here
}
else
{
    //Your code here
}
</code>```

Title: c# ignoring else if statement

Body:
I am trying to make a winforms application so when something is clicked it checks a webpage for it's response.

I have tested the web page to see if it is a PHP error but it works fine from that side.

It is completely ignoring the else if statement and skips to the else statement below it even though the response is "Unassigned".

Here is my code:

private void button1_Click(object sender, EventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://fms.psrpc.co.uk/apiconfirmD.php?" + ApiKey);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        using (response)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            if (reader.ReadToEnd() == "Changed")
            {
                label2.Visible = false;
                button1.Enabled = false;
                button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
                button5.Enabled = true;
                button6.Enabled = true;
                button7.Enabled = true;
                button8.Enabled = true;
                timer1.Enabled = true;
            }
            else if (reader.ReadToEnd() == "Unassigned")
            {
                string message = "Error Code: B66794O37945O46791K@@Error booking on.@Please make sure you have been assigned to a vehicle.@@If this error persists please contact K.McCrudden.";
                message = message.Replace("@", "" + System.Environment.NewLine);
                string title = "Error!";

                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
            }
            else
            {
                string message = "Error Code: B002875O46883O84655K@@Error booking on.@Please make sure you have booked a shift and have been assigned.@@If this error persists please contact K.McCrudden.";
                message = message.Replace("@", "" + System.Environment.NewLine);
                string title = "Error!";

                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
            }
        }
    }

Body:
No, it is not being ignored. You are reading all the data in your first if block by calling reader.ReadToEnd(). This way, there is no further data available to read in your else if statement; it returns empty string. Thus condition does not match and final else block gets executed.

Modify the code something like below. Notice the temporary data variable in below code.

StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();//Read the data in temp variable.
//Use this variable to check the conditions further.
if (data == "Changed")
{
    //Your code here
}
else if (data == "Unassigned")
{
    //Your code here
}
else
{
    //Your code here
}


问:
Upgrading Aurora RDS does it automatically adjust the parameters?
I am going to upgrade my RDS  for a much bigger instance type (r3.large to r3.2xlarge) and I would like to know if AWS will adjust the mysql parameters accordantly.. what are the may concerns should I have on this procedure? Is fining customization lost when it exist?

```<code>instance        cpu   Memory    PIOPS-Optimized   Network Performance
Price
db.r3.large     2     15        No                Moderate              $0.32
db.r3.2xlarge   8     61        Yes               High                  $1.28
</code>```

My main concern is regarding the caching configuration.

innodb_buffer_pool_size is currently 7GB and I thinking about leaving it as 50GB after upgrade. will this be adjusted automatically?

Just to complement the question, I am upgrading due to lack of memory as showed on this:

```<code>mysql> show status like '%qcache%';
+-------------------------+----------+
| Variable_name           | Value    |
+-------------------------+----------+
| Qcache_free_blocks      | 134      |
| Qcache_free_memory      | 148080   |
| Qcache_hits             | 42459186 |
| Qcache_inserts          | 14059268 |
| Qcache_lowmem_prunes    | 2455035  |
| Qcache_not_cached       | 22422639 |
| Qcache_queries_in_cache | 241632   |
| Qcache_total_blocks     | 772112   |
+-------------------------+----------+
8 rows in set (0.01 sec)
</code>```

As it state mysql cannot cache some stuff and has loads of prunes.

答:
The value of parameter innodb_buffer_pool_size, by default, is assigned using the formula {DBInstanceClassMemory*3/4}. So if you change the db instance class(upgrade or downgrade), then the value is changed accordingly. This is valid as long as you have not changed the value manually and set it to a numeric value(without using the formula).

In your case,If you are upgrading the instance class to a higher class and If you have updated the value of the parameter(without using the formula), then the same is preserved after the db instance class is upgraded.

Body:
I am going to upgrade my RDS  for a much bigger instance type (r3.large to r3.2xlarge) and I would like to know if AWS will adjust the mysql parameters accordantly.. what are the may concerns should I have on this procedure? Is fining customization lost when it exist?

instance        cpu   Memory    PIOPS-Optimized   Network Performance
Price
db.r3.large     2     15        No                Moderate              $0.32
db.r3.2xlarge   8     61        Yes               High                  $1.28

My main concern is regarding the caching configuration.

innodb_buffer_pool_size is currently 7GB and I thinking about leaving it as 50GB after upgrade. will this be adjusted automatically?

Just to complement the question, I am upgrading due to lack of memory as showed on this:

mysql> show status like '%qcache%';
+-------------------------+----------+
| Variable_name           | Value    |
+-------------------------+----------+
| Qcache_free_blocks      | 134      |
| Qcache_free_memory      | 148080   |
| Qcache_hits             | 42459186 |
| Qcache_inserts          | 14059268 |
| Qcache_lowmem_prunes    | 2455035  |
| Qcache_not_cached       | 22422639 |
| Qcache_queries_in_cache | 241632   |
| Qcache_total_blocks     | 772112   |
+-------------------------+----------+
8 rows in set (0.01 sec)

As it state mysql cannot cache some stuff and has loads of prunes.


问:
MaskedTextBox inside KendoGrid
Is it possible to use the Kendo MaskedTextBox inside a Kendo Grid? If so, how?

I am using an Editor template for the MaskedTextBox.

```<code>@model object

@Html.Kendo().MaskedTextBoxFor(m => m).Mask("(000) 000-0000")
</code>```

The Kendo Grid has a telephone field that uses the MaskedTextBox, but it doesn't grab the mask.

```<code>    @(Html.Kendo().Grid(new ContactViewModel[] { })
        .Name("ServiceLocationContactsGrid")
        .Columns(column =>
        {
            column.ForeignKey(c => c.ContactTypeId, (System.Collections.IEnumerable)ViewData["contactTypes"], "ContactTypeId", "Description").EditorTemplateName("GridForeignKey");
            column.Bound(c => c.LastName).Width(700);
            column.Bound(c => c.FirstName);
            column.Bound(c => c.Title);
            column.Bound(c => c.EmailAddress);
            column.Bound(c => c.TelephoneNumber).EditorTemplateName("Telephone");
            column.Bound(c => c.TelephoneExtension);
            column.Bound(c => c.FaxNumber).EditorTemplateName("String");
            column.Command(command => { command.Edit().Text(" ").UpdateText(" ").CancelText(" "); command.Destroy().Text(" "); }).Width(180).Visible(!ViewBag.ReadOnlyView);
        })
            .ToolBar(toolBar =>
            {
                if(!ViewBag.ReadOnlyView) toolBar.Create().Text("Add New Contact");
            })
        .Sortable()
        .Filterable()
        .Editable(editable => editable.Mode(GridEditMode.InLine))
        .DataSource(dataSource =>
            dataSource
            .Ajax()
            .ServerOperation(false)
            .Model(model =>
            {
                model.Id(c => c.ContactId);
                model.Field(c => c.ContactId).Editable(false);
            })
            .Create(create => create.Action("CreateContact", "Contact"))
            .Update(update => update.Action("UpdateContact", "Contact"))
            .Read(read => read.Action("ListContacts", "Contact"))
            .Destroy(destroy => destroy.Action("DestroyContact", "Contact"))
        )
    )
</code>```

答:
after making editor template, you should put it on the cell you want.
Editor Template

@(Html.kendo().MaskedTextBoxFor(m=>m).Name("test").mask("00/00/000"))

then you should put your editor template in grid:

```<code>columns.Bound(x=>x.test).EditorTemplateName("Test");
</code>```

this code worked for me

Title: MaskedTextBox inside KendoGrid

Body:
Is it possible to use the Kendo MaskedTextBox inside a Kendo Grid? If so, how?

I am using an Editor template for the MaskedTextBox.

@model object

@Html.Kendo().MaskedTextBoxFor(m => m).Mask("(000) 000-0000")

The Kendo Grid has a telephone field that uses the MaskedTextBox, but it doesn't grab the mask.

    @(Html.Kendo().Grid(new ContactViewModel[] { })
        .Name("ServiceLocationContactsGrid")
        .Columns(column =>
        {
            column.ForeignKey(c => c.ContactTypeId, (System.Collections.IEnumerable)ViewData["contactTypes"], "ContactTypeId", "Description").EditorTemplateName("GridForeignKey");
            column.Bound(c => c.LastName).Width(700);
            column.Bound(c => c.FirstName);
            column.Bound(c => c.Title);
            column.Bound(c => c.EmailAddress);
            column.Bound(c => c.TelephoneNumber).EditorTemplateName("Telephone");
            column.Bound(c => c.TelephoneExtension);
            column.Bound(c => c.FaxNumber).EditorTemplateName("String");
            column.Command(command => { command.Edit().Text(" ").UpdateText(" ").CancelText(" "); command.Destroy().Text(" "); }).Width(180).Visible(!ViewBag.ReadOnlyView);
        })
            .ToolBar(toolBar =>
            {
                if(!ViewBag.ReadOnlyView) toolBar.Create().Text("Add New Contact");
            })
        .Sortable()
        .Filterable()
        .Editable(editable => editable.Mode(GridEditMode.InLine))
        .DataSource(dataSource =>
            dataSource
            .Ajax()
            .ServerOperation(false)
            .Model(model =>
            {
                model.Id(c => c.ContactId);
                model.Field(c => c.ContactId).Editable(false);
            })
            .Create(create => create.Action("CreateContact", "Contact"))
            .Update(update => update.Action("UpdateContact", "Contact"))
            .Read(read => read.Action("ListContacts", "Contact"))
            .Destroy(destroy => destroy.Action("DestroyContact", "Contact"))
        )
    )

Body:
after making editor template, you should put it on the cell you want.
Editor Template

@(Html.kendo().MaskedTextBoxFor(m=>m).Name("test").mask("00/00/000"))

then you should put your editor template in grid:

columns.Bound(x=>x.test).EditorTemplateName("Test");

this code worked for me


问:
How to "decode" eexec of font file?
I have a .pfa font file and I would like to read the "algorithm" for rendering the font. However, most of the information is hidden in binary in the line:

```<code>currentfile eexec
743F8413F3636CA85A9FFEFB50B4BB27302A5F6C876586CCC1670A7EF5521E6ADE15AAB4
DD2DDDB83735311FC63DB80D2C96AECFA05BB67F865EA35934B4B79A203A8DD489B09C79
FF6EB9DBCFD889C3E73F8C94BC342AF671D6F688870A62EE1A0DF216E150FFEC64A8C2B7
509AD05C011599C1AD84E6C4B668E07EA219BD72663D8AF4CA8EC8E23AA90DE90BE940C6
6DB849CEDB3B64961365A7CCE47F4FC9E30FDEE4B14B90C2E0D8C344EBC974EABF417B3D
28251A78ACEE2BFC4212B1E3E9C7EBC3262821EE98E538713C64DF0BC13C19337B1307DB
D795D285F959C924FC14AEF7E9D406406CDEE1A35377887A16B13DD51717A86284369FA7
6ABB6A4488B9174A561DA854C33821F3172E4CF956EC9B65F829D69E02BC0EE23044DB1D
9A4D45A14A3998115BEE5DDC582F158DB2E..................
</code>```

How do we "decode" this information?

答:
I found this document very helpful in decrypting eexec encryption. A simple example in python using the code mentioned there.

```<code>#Getting the eexec binary, make sure you exclude the ascii part in the end, after the binary portion
text = open('fontfile.pfa').read()
raw_hex = text.split('eexec')[1]
decarr = list()
count = 0
hex_code = str()

#Converting pairs of the hexadecimal digits to decimal, e.g. ff -> 255, and storing it in an array decarr
for i in range(len(raw_hex)):
    if raw_hex[i] == '\n':
        decarr.append(raw_hex[i])
        continue
    else:
        hex_code = hex_code + raw_hex[i]
        count += 1
        if count == 2:
            decarr.append(int(hex_code, 16))
            count = 0
            hex_code = str()
</code>```

Once we have an array of the decimal equivalents of pairs of hexadecimal digits, we perform decryption as mentioned in Chapter 7 of Adobe Type 1 Font Format Specification. The constants are as mentioned in the specification.

```<code>c1 = 52845
c2 =  22719
R = 55665
p = list()
for i in range(0,len(decarr)):
    if decarr[i] is not '\n':
        p.append(decarr[i]^(R >> 8))
        R = ((decarr[i] + R)*c1 + c2) & ((1 << 16) - 1)
    else:
        p.append(decarr[i])
decrypted = list()
for i in range(len(p)):
    if p[i] is not '\n':
        decrypted.append(chr(p[i]))
    else:
        decrypted.append(p[i])
</code>```

Hope it helps!

Title: How to "decode" eexec of font file?

Body:
I have a .pfa font file and I would like to read the "algorithm" for rendering the font. However, most of the information is hidden in binary in the line:

currentfile eexec
743F8413F3636CA85A9FFEFB50B4BB27302A5F6C876586CCC1670A7EF5521E6ADE15AAB4
DD2DDDB83735311FC63DB80D2C96AECFA05BB67F865EA35934B4B79A203A8DD489B09C79
FF6EB9DBCFD889C3E73F8C94BC342AF671D6F688870A62EE1A0DF216E150FFEC64A8C2B7
509AD05C011599C1AD84E6C4B668E07EA219BD72663D8AF4CA8EC8E23AA90DE90BE940C6
6DB849CEDB3B64961365A7CCE47F4FC9E30FDEE4B14B90C2E0D8C344EBC974EABF417B3D
28251A78ACEE2BFC4212B1E3E9C7EBC3262821EE98E538713C64DF0BC13C19337B1307DB
D795D285F959C924FC14AEF7E9D406406CDEE1A35377887A16B13DD51717A86284369FA7
6ABB6A4488B9174A561DA854C33821F3172E4CF956EC9B65F829D69E02BC0EE23044DB1D
9A4D45A14A3998115BEE5DDC582F158DB2E..................

How do we "decode" this information?

Body:
I found this document very helpful in decrypting eexec encryption. A simple example in python using the code mentioned there.

#Getting the eexec binary, make sure you exclude the ascii part in the end, after the binary portion
text = open('fontfile.pfa').read()
raw_hex = text.split('eexec')[1]
decarr = list()
count = 0
hex_code = str()

#Converting pairs of the hexadecimal digits to decimal, e.g. ff -> 255, and storing it in an array decarr
for i in range(len(raw_hex)):
    if raw_hex[i] == '\n':
        decarr.append(raw_hex[i])
        continue
    else:
        hex_code = hex_code + raw_hex[i]
        count += 1
        if count == 2:
            decarr.append(int(hex_code, 16))
            count = 0
            hex_code = str()

Once we have an array of the decimal equivalents of pairs of hexadecimal digits, we perform decryption as mentioned in Chapter 7 of Adobe Type 1 Font Format Specification. The constants are as mentioned in the specification.

c1 = 52845
c2 =  22719
R = 55665
p = list()
for i in range(0,len(decarr)):
    if decarr[i] is not '\n':
        p.append(decarr[i]^(R >> 8))
        R = ((decarr[i] + R)*c1 + c2) & ((1 << 16) - 1)
    else:
        p.append(decarr[i])
decrypted = list()
for i in range(len(p)):
    if p[i] is not '\n':
        decrypted.append(chr(p[i]))
    else:
        decrypted.append(p[i])

Hope it helps!


问:
data binding Angular 4
I have a component with a variable say 'id' and in this component i'm calling a service that's take that variable(id) as parameter,
in my template I assign the value of a radio Button to the variable(id)..
the problem is ..I'm calling my Service in "ngOnInit()", so it doesn't take the value of the radio button , but takes the initial value of the "id"..
Here is my code:

in my component:

```<code> import { Component, OnInit } from '@angular/core';
 import { BartersService } from '../../core/services/barters.service';

 export class BarterViewComponent implements OnInit {
 id:string="";
 allCategories ;
 constructor( private barServ: BartersService) { }
  ngOnInit() {
   this.barServ.findByPage(this.id)
   .subscribe(respone => {
   this.allCategories = respone.data;
    });

    }
 onSelectionChange(val) {
  this.id = val;
 }

}
</code>```

in my Template :

```<code><div *ngFor="let cat of allCategories ; let i=index;">
   <input  style="margin-bottom: 10px;" type="radio" #R
      (change)="onSelectionChange(R.value )" name="rad"  value="cat['id']">
      {{cat['name']}}
</div>
</code>```

Target:

the target is updating the view based on the selection of the radio button.

答:
You can try this:</p>

```<code>export class BarterViewComponent implements OnInit {
 id:string="";
 allCategories ;

 constructor( private barServ: BartersService) { }
 ngOnInit() {
    refreshCategories()
 }

 onSelectionChange(val) {
  this.id = val;
  refreshCategories()
 }

 refreshCategories() {
   this.barServ.findByPage(this.id).subscribe(respone => {
       this.allCategories = respone.data;
   });
 }
}
</code>```

Title: data binding Angular 4

Body:
I have a component with a variable say 'id' and in this component i'm calling a service that's take that variable(id) as parameter,
in my template I assign the value of a radio Button to the variable(id)..
the problem is ..I'm calling my Service in "ngOnInit()", so it doesn't take the value of the radio button , but takes the initial value of the "id"..
Here is my code:

in my component:

 import { Component, OnInit } from '@angular/core';
 import { BartersService } from '../../core/services/barters.service';

 export class BarterViewComponent implements OnInit {
 id:string="";
 allCategories ;
 constructor( private barServ: BartersService) { }
  ngOnInit() {
   this.barServ.findByPage(this.id)
   .subscribe(respone => {
   this.allCategories = respone.data;
    });

    }
 onSelectionChange(val) {
  this.id = val;
 }

}

in my Template :

   <input  style="margin-bottom: 10px;" type="radio" #R
      (change)="onSelectionChange(R.value )" name="rad"  value="cat['id']">
      {{cat['name']}}

Target:

the target is updating the view based on the selection of the radio button.

Body:
You can try this:

export class BarterViewComponent implements OnInit {
 id:string="";
 allCategories ;

 constructor( private barServ: BartersService) { }
 ngOnInit() {
    refreshCategories()
 }

 onSelectionChange(val) {
  this.id = val;
  refreshCategories()
 }

 refreshCategories() {
   this.barServ.findByPage(this.id).subscribe(respone => {
       this.allCategories = respone.data;
   });
 }
}


问:
Get some random and some specific records in a single query?
So I have a cover-flow style image carousel populated by a query like

```<code>SELECT foo FROM `imageTable` ORDER BY RAND() LIMIT 0, 12;
</code>```

My client would like to add to this a set of permanent images.  Due to the way the results are used it would be very handy if I could make those records part of my original query.

I tried

```<code>SELECT foo FROM `imageTable` WHERE `id` = 'x' OR `id` = 'y'
  OR `id` IS NOT NULL ORDER BY RAND() LIMIT 0, 12;
</code>```

I was hoping the records with the ids would necessarily be in the result set but nope the RAND() shuffles the whole set.

So my question is whether any single query could provide the x permanent records and then y random records?

// EDIT WITH REVISED QUERY USING Adrian Serafin's answer:

```<code>(SELECT * FROM `imageTable` ORDER BY RAND() LIMIT 0, 6)
UNION
(SELECT * FROM `imageTable`  WHERE `id` = 'foo' OR `id` = 'bar' OR `id` = 'baz')
</code>```

答:
You might try a union...

```
(SELECT foo FROM <code>imageTable</code> WHERE <code>id</code> not in ( 'x','y') ORDER BY RAND() LIMIT 0, 12; )
UNION
(SELECT foo FROM <code>imageTable</code> WHERE <code>id</code> in ('x','y')
ORDER BY a LIMIT 10;
```

Body:
So I have a cover-flow style image carousel populated by a query like

SELECT foo FROM `imageTable` ORDER BY RAND() LIMIT 0, 12;

My client would like to add to this a set of permanent images.  Due to the way the results are used it would be very handy if I could make those records part of my original query.

I tried

SELECT foo FROM `imageTable` WHERE `id` = 'x' OR `id` = 'y'
  OR `id` IS NOT NULL ORDER BY RAND() LIMIT 0, 12;

I was hoping the records with the ids would necessarily be in the result set but nope the RAND() shuffles the whole set.

So my question is whether any single query could provide the x permanent records and then y random records?

// EDIT WITH REVISED QUERY USING Adrian Serafin's answer:

(SELECT * FROM `imageTable` ORDER BY RAND() LIMIT 0, 6)
UNION
(SELECT * FROM `imageTable`  WHERE `id` = 'foo' OR `id` = 'bar' OR `id` = 'baz')

Body:
You might try a union...

(SELECT foo FROM imageTable WHERE id not in ( 'x','y') ORDER BY RAND() LIMIT 0, 12; )
UNION
(SELECT foo FROM imageTable WHERE id in ('x','y')
ORDER BY a LIMIT 10;

ContentLicense: CC BY-SA 2.5


问:
Gridview scroll width
I have this Gridview

```<code><GridView
    android:id="@+id/gridview_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:numColumns="3"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:fadeScrollbars="false"
    android:scrollbarStyle="outsideInset"
    android:scrollbarSize="30dp"
    android:smoothScrollbar="true">
</GridView>
</code>```

for which I'm trying to increase the scroll width. I've tried using scrollbarSize but nothing changes. Is there a way to increase the width of the scrollbar without customizing it?

I'm new in Android development so please be gentle :)

Update: Tested this possible solution and added my gridview inside the scrollview

```<code><ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:layout_above="@+id/bottomMenu"
    android:scrollbarSize="50dip">
    <GridView
        android:id="@+id/gridview_holes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:horizontalSpacing="10dp"
        android:verticalSpacing="10dp">
    </GridView>
</ScrollView>
</code>```

But the gridview is much more smaller and I'm seeing just the gridview thin scroll.

答:
please try this

android:scrollbarAlwaysDrawVerticalTrack=true

android:scrollbars=vertical

Title: Gridview scroll width

Body:
I have this Gridview

<GridView
    android:id="@+id/gridview_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:numColumns="3"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:fadeScrollbars="false"
    android:scrollbarStyle="outsideInset"
    android:scrollbarSize="30dp"
    android:smoothScrollbar="true">
</GridView>

for which I'm trying to increase the scroll width. I've tried using scrollbarSize but nothing changes. Is there a way to increase the width of the scrollbar without customizing it?

I'm new in Android development so please be gentle :)

Update: Tested this possible solution and added my gridview inside the scrollview

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:layout_above="@+id/bottomMenu"
    android:scrollbarSize="50dip">
    <GridView
        android:id="@+id/gridview_holes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:horizontalSpacing="10dp"
        android:verticalSpacing="10dp">
    </GridView>
</ScrollView>

But the gridview is much more smaller and I'm seeing just the gridview thin scroll.


答:
You have an error in your general logic. When you enter the first if statement, you're reading to the end of the stream with the code reader.ReadToEnd(). In the next statement (the else), you're reading the stream again, but it has already been read, so it will return an empty string, thus the last else statement will effectively be hit.

You can also read about this on MSDN: StreamReader.ReadToEnd() Method.

Definition of the return value:

The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns an empty string ("").

Your code should look like this:

```<code>StreamReader reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();

if(result == "Changed")
{
    label2.Visible = false;
    button1.Enabled = false;
    button2.Enabled = true;
    button3.Enabled = true;
    button4.Enabled = true;
    button5.Enabled = true;
    button6.Enabled = true;
    button7.Enabled = true;
    button8.Enabled = true;
    timer1.Enabled = true;
}
else if(result == "Unassigned")
{
    string message = "Error Code: B66794O37945O46791K@@Error booking on.@Please make sure you have been assigned to a vehicle.@@If this error persists please contact K.McCrudden.";
    message = message.Replace("@", "" + System.Environment.NewLine);
    string title = "Error!";

    MessageBoxButtons buttons = MessageBoxButtons.OK;
    DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
    string message = "Error Code: B002875O46883O84655K@@Error booking on.@Please make sure you have booked a shift and have been assigned.@@If this error persists please contact K.McCrudden.";
    message = message.Replace("@", "" + System.Environment.NewLine);
    string title = "Error!";

    MessageBoxButtons buttons = MessageBoxButtons.OK;
    DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
</code>```

Title: c# ignoring else if statement

Body:
You have an error in your general logic. When you enter the first if statement, you're reading to the end of the stream with the code reader.ReadToEnd(). In the next statement (the else), you're reading the stream again, but it has already been read, so it will return an empty string, thus the last else statement will effectively be hit.

You can also read about this on MSDN: StreamReader.ReadToEnd() Method.

Definition of the return value:

The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns an empty string ("").

Your code should look like this:

StreamReader reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();

if(result == "Changed")
{
    label2.Visible = false;
    button1.Enabled = false;
    button2.Enabled = true;
    button3.Enabled = true;
    button4.Enabled = true;
    button5.Enabled = true;
    button6.Enabled = true;
    button7.Enabled = true;
    button8.Enabled = true;
    timer1.Enabled = true;
}
else if(result == "Unassigned")
{
    string message = "Error Code: B66794O37945O46791K@@Error booking on.@Please make sure you have been assigned to a vehicle.@@If this error persists please contact K.McCrudden.";
    message = message.Replace("@", "" + System.Environment.NewLine);
    string title = "Error!";

    MessageBoxButtons buttons = MessageBoxButtons.OK;
    DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
    string message = "Error Code: B002875O46883O84655K@@Error booking on.@Please make sure you have booked a shift and have been assigned.@@If this error persists please contact K.McCrudden.";
    message = message.Replace("@", "" + System.Environment.NewLine);
    string title = "Error!";

    MessageBoxButtons buttons = MessageBoxButtons.OK;
    DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}


问:
How do I install gulp 4
I've been using gulp-watch. The current version of gulp-watch relies on the call gulp.parrallel. This call is only available from gulp 4.

However gulp 4 is not available via the npm repo.
npm info gulp dist-tags returns: { latest: '3.9.0' }.

I can see that there is a 4.0 branch within the git repo. But attempting to install it with variations on this command fails: npm install https://github.com/gulpjs/gulp#v4.0.0.

答:
My installation was a bit different.

Running

```<code>npm install 'gulpjs/gulp.git#4.0' --save-dev
</code>```

Or

```<code>npm install 'gulpjs/gulp#4.0' --save-dev
</code>```

Gave me an error:

npm ERR! code EINVALIDTAGNAME npm ERR! Invalid tag name "gulp#4.0": Tags
  may not have any characters that encodeURIComponent encodes.

NB I was only having problems installing my local gulp-4 so I took a look at my last package.json installation and saw this:

```<code>"gulp": "github:gulpjs/gulp#4.0",
</code>```

So my move was to install local gulp with

```<code>npm install "github:gulpjs/gulp#4.0" --save-dev
</code>```

and that worked, installing local gulp 4 successfully.

```<code>[15:45:55] CLI version 1.4.0
[15:45:55] Local version 4.0.0-alpha.2
</code>```

Title: How do I install gulp 4

Body:
My installation was a bit different.

Running

npm install 'gulpjs/gulp.git#4.0' --save-dev

Or

npm install 'gulpjs/gulp#4.0' --save-dev

Gave me an error:

npm ERR! code EINVALIDTAGNAME npm ERR! Invalid tag name "gulp#4.0": Tags
  may not have any characters that encodeURIComponent encodes.

NB I was only having problems installing my local gulp-4 so I took a look at my last package.json installation and saw this:

"gulp": "github:gulpjs/gulp#4.0",

So my move was to install local gulp with

npm install "github:gulpjs/gulp#4.0" --save-dev

and that worked, installing local gulp 4 successfully.

[15:45:55] CLI version 1.4.0
[15:45:55] Local version 4.0.0-alpha.2


答:
Do a safecast:</p>

```<code>public void FillForm(Piece currentPiece)
{
            pieceIdTextBox.Text = currentPiece.id.ToString();
            pieceNameTextBox.Text = currentPiece.title;
            pieceDescriptionTextBox.Text = currentPiece.description;

            var imagePiece = currentPiece as Image;
            if(imagePiece != null)
                pieceFileSelectURLTextBlock.Text = imagePiece .filePath;
                SetPreviews(imagePiece .filePath);
            }

}
</code>```

Title: Run different code based type

Body:
I want to call a method for my WPF-App with subtype objects of my Piece class. My problem is that the subtype objects have more properties than e.g the the Text objects.

Do you know a way to cope with this better than I do in my FillForm example?

namespace Namespace
{
    public abstract class Piece
        {
            public int id { get; set; }
            public string title { get; set; }
            public string description { get; set; }

        }

        public class Text : Piece
        {

        }

        public class Image: Piece{
             public string filePath { get; set; }
            public string fileformat { get; set; }
        }

        public class Video : Image
        {

        }
    }
}

Example method:

public void FillForm(Piece currentPiece)
{
            pieceIdTextBox.Text = currentPiece.id.ToString();
            pieceNameTextBox.Text = currentPiece.title;
            pieceDescriptionTextBox.Text = currentPiece.description;
            if (!currentPiece.GetType().ToString().Equals("Namespace.Text"))
            {
                pieceFileSelectURLTextBlock.Text = (currentPiece as Namespace.Image).filePath;
                SetPreviews((currentPiece as Namespace.Image).filePath);
            }

}

Thanks!

Body:
Do a safecast:

public void FillForm(Piece currentPiece)
{
            pieceIdTextBox.Text = currentPiece.id.ToString();
            pieceNameTextBox.Text = currentPiece.title;
            pieceDescriptionTextBox.Text = currentPiece.description;

            var imagePiece = currentPiece as Image;
            if(imagePiece != null)
                pieceFileSelectURLTextBlock.Text = imagePiece .filePath;
                SetPreviews(imagePiece .filePath);
            }

}


问:
Convert any object to a byte[]
I am writing a prototype TCP connection and I am having some trouble homogenizing the data to be sent.

At the moment, I am sending nothing but strings, but in the future we want to be able to send any object.

The code is quite simple at the moment, because I thought everything could be cast into a byte array:

```<code>void SendData(object headerObject, object bodyObject)
{
  byte[] header = (byte[])headerObject;  //strings at runtime,
  byte[] body = (byte[])bodyObject;      //invalid cast exception

  // Unable to cast object of type 'System.String' to type 'System.Byte[]'.
  ...
}
</code>```

This of course is easily enough solved with a

```<code>if( state.headerObject is System.String ){...}
</code>```

The problem is, if I do it that way, I need to check for EVERY type of object that can't be cast to a byte[] at runtime.

Since I do not know every object that can't be cast into a byte[] at runtime, this really isn't an option.

How does one convert any object at all into a byte array in C# .NET 4.0?

答:
How about something simple like this?</p>

```<code>return ((object[])value).Cast<byte>().ToArray();
</code>```

Title: Convert any object to a byte[]

Body:
I am writing a prototype TCP connection and I am having some trouble homogenizing the data to be sent.

At the moment, I am sending nothing but strings, but in the future we want to be able to send any object.

The code is quite simple at the moment, because I thought everything could be cast into a byte array:

void SendData(object headerObject, object bodyObject)
{
  byte[] header = (byte[])headerObject;  //strings at runtime,
  byte[] body = (byte[])bodyObject;      //invalid cast exception

  // Unable to cast object of type 'System.String' to type 'System.Byte[]'.
  ...
}

This of course is easily enough solved with a

if( state.headerObject is System.String ){...}

The problem is, if I do it that way, I need to check for EVERY type of object that can't be cast to a byte[] at runtime.

Since I do not know every object that can't be cast into a byte[] at runtime, this really isn't an option.

How does one convert any object at all into a byte array in C# .NET 4.0?

Body:
How about something simple like this?

return ((object[])value).Cast<byte>().ToArray();


答:
By ending your string with a \ you're escaping the next character (which is ") hence the string is not terminated.
Beware that you're also escaping the character next to every \

What you probably want

```<code>fileloc = "N:\\Documents\\1) Subjects, Word and Powerpoint\\GCSE Computing\\NEA\\GCSE 2017\\users\\"
</code>```

learn more about character escape here: https://en.wikipedia.org/wiki/Escape_character

Title: Python 2.7 File Handling saving username

Body:
Ok im doing some coding work making a username saver, I need to save multiple users to different text files, But I get an error when trying to set the file directory,

fileloc = "N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
filename = fileloc+newname+".txt"
print filename
adduserfile = open(filename, "rw+")

I get the error "EOL while scanning string literal", It then highlights the last quotation mark at the end of line 1, Im not sure how to fix this, Please help

Sorry for asking such a simple question, I understand that it was my use of the address because of the special characters () causing it to break, thanks for the time and help

Body:
By ending your string with a \ you're escaping the next character (which is ") hence the string is not terminated.
Beware that you're also escaping the character next to every \

What you probably want

fileloc = "N:\\Documents\\1) Subjects, Word and Powerpoint\\GCSE Computing\\NEA\\GCSE 2017\\users\\"

learn more about character escape here: https://en.wikipedia.org/wiki/Escape_character


问:
chrome.runtime.sendMessage not working in Chrome Extension
I am trying to create a new extension. I was able to use the chrome.runtime.sendMessage function a while back but right now, I have tried everything and it still is not able to send the message to the background script. The console is getting populated with the log messages from the content-script.js but not from the background.js

content-script.js

```<code>console.log("Hello World!s");
$(document).ready(function() {
    console.log("DOM READY!");
    $(document.documentElement).keydown(function (e) {
        console.log("Key Has Been Pressed!");
        chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
                if (response.fileData) {
                    alert("Contents Of Text File = ");
                }
                else {
                    console.log("No Response Received");
                }
            })

    })
});
</code>```

background.js

```<code>console.log("Atleast reached background.js")
        chrome.runtime.onMessage.addListener (
            function (request, sender, sendResponse) {
                console.log("Reached Background.js");
                if (request.Message == "getTextFile") {
                    console.log("Entered IF Block");
                        $.get("http://localhost:8000/quicklyusercannedspeechbucket/helloWorld1", function(response) {
                    console.log(response);
                    sendResponse({fileData: response})
                })
            }
            else {
                console.log("Did not receive the response!!!")
            }
        }
    );
</code>```

manifest.json

```<code>{
  "manifest_version": 2,
  "name": "My Cool Extension",
  "version": "0.1",
  "content_scripts": [ {
    "all_frames": true,
    "js": [ "jquery-2.1.4.min.js", "content-script.js" ],
    "matches": [ "http://*/*", "https://*/*", "file://*/*" ]
  } ],
  "permissions": [ "http://*/*", "https://*/*", "storage" ],
  "background": {
    "scripts": [
      "jquery-2.1.4.min.js",
      "background.js"
    ]
  }
}
</code>```

Any help is appreciated :)

Thanks!

答: Per the text at the end of https://developer.chrome.com/extensions/messaging#simple if you return true from onMessage handler in background.js then you can call sendResponse asynchronously.

Body:
I am trying to create a new extension. I was able to use the chrome.runtime.sendMessage function a while back but right now, I have tried everything and it still is not able to send the message to the background script. The console is getting populated with the log messages from the content-script.js but not from the background.js

content-script.js

console.log("Hello World!s");
$(document).ready(function() {
    console.log("DOM READY!");
    $(document.documentElement).keydown(function (e) {
        console.log("Key Has Been Pressed!");
        chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
                if (response.fileData) {
                    alert("Contents Of Text File = ");
                }
                else {
                    console.log("No Response Received");
                }
            })

    })
});

background.js

console.log("Atleast reached background.js")
        chrome.runtime.onMessage.addListener (
            function (request, sender, sendResponse) {
                console.log("Reached Background.js");
                if (request.Message == "getTextFile") {
                    console.log("Entered IF Block");
                        $.get("http://localhost:8000/quicklyusercannedspeechbucket/helloWorld1", function(response) {
                    console.log(response);
                    sendResponse({fileData: response})
                })
            }
            else {
                console.log("Did not receive the response!!!")
            }
        }
    );

manifest.json

{
  "manifest_version": 2,
  "name": "My Cool Extension",
  "version": "0.1",
  "content_scripts": [ {
    "all_frames": true,
    "js": [ "jquery-2.1.4.min.js", "content-script.js" ],
    "matches": [ "http://*/*", "https://*/*", "file://*/*" ]
  } ],
  "permissions": [ "http://*/*", "https://*/*", "storage" ],
  "background": {
    "scripts": [
      "jquery-2.1.4.min.js",
      "background.js"
    ]
  }
}

Any help is appreciated :)

Thanks!


问:
Looking for light text rich editor for enterprise website ,more light then tinymce with basic buttons for comment form
I am Looking for light text rich editor for enterprise website ,more light then tinymce with basic buttons for comment form.
Its important that editor will also work in IE6.
until now I try cleditor 15KB, but he have problem with IE when 'enter' press.

cleditor have issue -  (Jquery-Rich Text Editor) How can be fixed bug in rich text editor - when press enter in firefox created 'br' tag but in IE created 'p' tag?

YUI Editor 76kb - still prefer something lighter like cleditor 15kb and use jquery and not yui 2 framework.

HtmlBox editor- only for personal use according lisence and also have some bugs in simple demo.

markitUp editor - not show result , only in other window.

tinymce/ckeditor - not light editor

jHtmlArea - not support IE6

jwysiwyg - still beta version, not tested on IE6?

Update: I alreay use jquery.

please if you have good suggestion,
Thanks,
Yosef

答:
7kb jQuery minimalist rich text editor that works in everything as far as I know (including IE6 but I never tried it with IE9):

http://batiste.dosimple.ch/blog/posts/2007-09-11-1/rich-text-editor-jquery.html


问:
Queries stop working after idle
The website I'm developing relies on jQuery AJAX calls a lot.
It's built on Laravel.
When you click an item it triggers a jQuery function that makes an AJAX call to Laravel controller (shows a preloader, than on success finishes it).

It all works perfect, but when the website stays open in your browser without you doing anything in it for some hours all those clicks just show the preloader and the AJAX call never returns a success.

That's really hard to debug since I have to wait hours to test one solution.

I think that if the controller wasn't responding the AJAX would just fire a 404 (as it has happened before) so it must be the sql server failing to do the query?

答:
If u stay idle for sometime, the csrf token will expire and you will get error with status 419.

You may try to exclude that particular route from csrf protection:
https://laravel.com/docs/5.5/csrf#csrf-excluding-uris

Title: Queries stop working after idle


问:
For a small MongoDB collection, is it safe to design as if it's all in memory?
There are many uses of MongoDB for which I would like to treat a collection as if it's in memory.   For example, for a collection of user Session objects (for a website).  Prior to using MongoDB, I would store such data in a memcached server, etc.  But, it seems silly to have to run both memcached+MongoDB for cases like this.

Is it reasonably safe to assume that for a small-sized (small ~= 1% of total system RAM) collection of frequently accessed data, that the collection is essentially always held in-memory?  I'm always going to be doing direct lookup by _id, and have no indexes on the data.

Would it help this assumption if the Session collection were held in its own database?  I ask because of the nature of MongoDB's buffer cache based memory mapping scheme.

答: In general, it is fine to be keeping big collections in memory, as long as you control your collections for memory leak (e.g., unused objects are eventually released). The reason why this is not a problem is that any server these days has virtual memory, where the unused pages are being swapped to. This way, even if memory is allocated for some objects which are not used often, performance of the system will not suffer.</p>


问:
How to find out which release(s) contain a given GIT commit?
Someone fixed a bug in HHVM in this commit:

https://github.com/facebook/hhvm/commit/796f986aba300b3f00b9ece0bf654c452ee217be

I want to know if this commit is already part of the official releases.

Is there a way to list the releases/tags that contain this commit, either on GitHub, or in a local clone of the GIT repository on my machine?

答: GitHub now shows you the tags containing a commit automatically when you open a commit (click on the ... to show all tags):


问:
Upgrade from Angular 4 to 5: "NodeInvocationException: No provider for PlatformRef!"
I've upgraded an app from Angular 4.2 to 5, but got this error:
 unhandled exception occurred while processing the request, more specifically:

NodeInvocationException: No provider for PlatformRef! Error: No
  provider for PlatformRef! at injectionError
  (e:\myapp\ClientApp\dist\vendor.js:12066:90)

The app also uses webpack and ASP.NET Core.

I have installed node v9.1, and typescript 2.6.1.

I also have updated package.json, with the command:

```<code>npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest
</code>```

And afterwards, ran the following:

```<code> npm install --save-dev @ngtools/webpack@latest
</code>```

I've also used HttpClient instead of Http:

```<code>import { HttpClient } from '@angular/common/http';
.....
 getThings() {
        return this.http.get('/api/things');

  }
</code>```

If I downgrade back Angular 4, the app works fine, is there anything in my line of thought that has been done incorrectly?

答:
I found a solving solution:
I've used this  Angular 5 Asp Core template

I've updated dependecies to latest angular 5 version: npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest

```<code>npm install --save-dev @ngtools/webpack@latest
</code>```

I've recompiled  webpack --config webpack.config.vendor.js (must have webpack installed globally:  npm install -g webpack@2.5.1)

I've replaced ClientApp/ASP files with my project files
Manully changed in app.module:

```<code>import { HttpModule } from '@angular/http';
</code>```

to

```<code>import { HttpClientModule } from '@angular/common/http';
</code>```

in services files instead of Http  I've used HttpClient:

```<code>import { HttpClient } from '@angular/common/http';
</code>```

Body:
I've upgraded an app from Angular 4.2 to 5, but got this error:
 unhandled exception occurred while processing the request, more specifically:

NodeInvocationException: No provider for PlatformRef! Error: No
  provider for PlatformRef! at injectionError
  (e:\myapp\ClientApp\dist\vendor.js:12066:90)

The app also uses webpack and ASP.NET Core.

I have installed node v9.1, and typescript 2.6.1.

I also have updated package.json, with the command:

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest

And afterwards, ran the following:

 npm install --save-dev @ngtools/webpack@latest

I've also used HttpClient instead of Http:

import { HttpClient } from '@angular/common/http';
.....
 getThings() {
        return this.http.get('/api/things');

  }

If I downgrade back Angular 4, the app works fine, is there anything in my line of thought that has been done incorrectly?

Body:
I found a solving solution:
I've used this  Angular 5 Asp Core template

I've updated dependecies to latest angular 5 version: npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest

npm install --save-dev @ngtools/webpack@latest

I've recompiled  webpack --config webpack.config.vendor.js (must have webpack installed globally:  npm install -g webpack@2.5.1)

I've replaced ClientApp/ASP files with my project files
Manully changed in app.module:

import { HttpModule } from '@angular/http';

to

import { HttpClientModule } from '@angular/common/http';

in services files instead of Http  I've used HttpClient:

import { HttpClient } from '@angular/common/http';


问:
Vue/Vuex > Cannot track state changed when I use Object.defineProperty() method
I use Vue.js and Vuex.

I make a simple todolist app.

I make a done toggle button with Vuex using Object.defineProperty() method.

When I click done toggle button, Vue and Vuex cannot trace change immediately.

It only trace change when I just reassign property's value.

For example

This works:

```<code>Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            const changeState = state;
            changeState.todolist[payload.index].done = !state.todolist[payload.index].done;
        },
        ...
    }
});
</code>```

But this does NOT work!

```<code>Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            Object.defineProperty(state.todolist[payload.index], 'done', { value: !state.todolist[payload.index].done });
        },
        ...
    }
});
</code>```

below code trace changes of done toggle only OTHER mutations change state.

Why it does?

Here is my github repository link.

My app is in /EX11/todolistapp.

My Vuex file is in /EX11/todolistapp/src/store/index.js

Thanks for reading my question.
Sorry for not good at English.
Have a nice day!

答:
I am not sure ... is this what you want to achieve?</p>

```<code>Vuex.Store({
  state: {
    todolist: [
      { todo: 'test1', done: false },
      { todo: 'test2', done: true },
      { todo: 'test3', done: false },
      { todo: 'test4', done: false }
    ]
  },
  mutations: {
    ...
    [Constant.DONE_TOGGLE]: (state, payload) => {
      var val = !state.todolist[payload.index].done
      state.todolist[payload.index] = Object.assign(state.todolist[payload.index], {done: {value: val}})
    },
    ...
  }
})
</code>```

Body:
I use Vue.js and Vuex.

I make a simple todolist app.

I make a done toggle button with Vuex using Object.defineProperty() method.

When I click done toggle button, Vue and Vuex cannot trace change immediately.

It only trace change when I just reassign property's value.

For example

This works:

Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            const changeState = state;
            changeState.todolist[payload.index].done = !state.todolist[payload.index].done;
        },
        ...
    }
});

But this does NOT work!

Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            Object.defineProperty(state.todolist[payload.index], 'done', { value: !state.todolist[payload.index].done });
        },
        ...
    }
});

below code trace changes of done toggle only OTHER mutations change state.

Why it does?

Here is my github repository link.

My app is in /EX11/todolistapp.

My Vuex file is in /EX11/todolistapp/src/store/index.js

Thanks for reading my question.
Sorry for not good at English.
Have a nice day!

Body:
I am not sure ... is this what you want to achieve?

Vuex.Store({
  state: {
    todolist: [
      { todo: 'test1', done: false },
      { todo: 'test2', done: true },
      { todo: 'test3', done: false },
      { todo: 'test4', done: false }
    ]
  },
  mutations: {
    ...
    [Constant.DONE_TOGGLE]: (state, payload) => {
      var val = !state.todolist[payload.index].done
      state.todolist[payload.index] = Object.assign(state.todolist[payload.index], {done: {value: val}})
    },
    ...
  }
})


问:
Text-based game code not working?
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Here is my code:

```<code><!DOCTYPE html>
<html>
<head>
<title>game</title>
<style>
</style>
</head>
<body>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
/*var input;
var room;

function submitFunction() {
    alert("hello")
}
*/
</script>
<script type="text/javascript">
    var input;
    var room;
    room = "Main Enterence"

    $(document).ready(function () {
        $("#mainForm").submit(function() {
            input = document.getElementById("textInput").value;

            if (input == "east") {
                if (room == "Main Enterence") {
                    room = "Bedroom"
                    enterBedroom();
                }

            }
            if (input == "west") {

            }
            if (input == "north") {

            }
            if (input == "south") {

            }

        })
    })

function enterBedroom() {
    $( "#consoleOutput" ).append( "<p>Test</p>" );

}
</script>

<div id="consoleOutput">
    <p id="welcomeText"></p>
</div>

<form onsubmit="submitFunction()" id="mainForm">
    <input type="text" id="textInput">
    <input type="submit" name="sumbit">
</form>

</body>
</html>
</code>```

Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

答:
This happens, because the page is refreshed - you submit form. You have to add first parametr to submit event and use preventDefault() function on it

```<code>$("#mainForm").submit(function(event) {
    event.preventDefault();
});
</code>```

Title: Text-based game code not working?

Body:
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Here is my code:

<!DOCTYPE html>

<title>game</title>

<form onsubmit="submitFunction()" id="mainForm">
    <input type="text" id="textInput">
    <input type="submit" name="sumbit">
</form>

Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Body:
This happens, because the page is refreshed - you submit form. You have to add first parametr to submit event and use preventDefault() function on it

$("#mainForm").submit(function(event) {
    event.preventDefault();
});


问:
Laravel 5.5 three table join
Edit: I am using API routes, so i have no views and such

I have a database like this

```<code>User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number
</code>```

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

```<code>user.id = card.user_id
card.card_number = swipe.card_number
</code>```

In Larvel i have 3 models.

```<code>user
card
swipe
</code>```

user Model

```<code>class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}
</code>```

in a controller if i do

```<code>$model = user::with('card')->get();
</code>```

i get the card data joined with the user data as expected.

```<code>class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}
</code>```

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

答:
I don't know if this is right solution, but you can try:</p>

```<code>public function swipe(){
    return $this->hasMany('App\swipe')->where('card_number','card_number');
}
</code>```

Title: Laravel 5.5 three table join

Body:
Edit: I am using API routes, so i have no views and such

I have a database like this

User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

user.id = card.user_id
card.card_number = swipe.card_number

In Larvel i have 3 models.

user
card
swipe

user Model

class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}

in a controller if i do

$model = user::with('card')->get();

i get the card data joined with the user data as expected.

class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

Body:
I don't know if this is right solution, but you can try:

public function swipe(){
    return $this->hasMany('App\swipe')->where('card_number','card_number');
}


问:
Mpchart float value not showing in array list
I am using mpandroid chart library, I want to show float value in line graph but it shows normal value.

Screenshot.

My code:

```<code>if (cursor != null) {

            for (int h = 0; h < cursor.getCount(); h++) {

                cursor.moveToNext();

                ans = cursor.getString(cursor.getColumnIndex("pnt_triiodothyronine"));

                entry1.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_triiodothyronine")),h));
                entry2.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_thyroxine")),h));
                entry3.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_tsh")),h));
                entry4.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_weight")),h));
                entry5.add((cursor.getString(cursor.getColumnIndex("date"))));

                ansText.setText(ans);
            }

            cursor.close();

        }

lDataSet1 = new LineDataSet(entry1, "T3");
        //lDataSet1.setDrawFilled(true);
        lDataSet1.setColors(new int[]{getResources().getColor(R.color.purple)}); //resolved color
        lDataSet1.setCircleColor(Color.parseColor("#ffffff"));
        lDataSet1.setLineWidth(1.5f);
        lDataSet1.setCircleColorHole(Color.parseColor("#9c27b0"));
        lDataSet1.setHighLightColor(Color.rgb(190, 190, 190));
        lDataSet1.setDrawCubic(true);
        //lDataSet1.setDrawFilled(true);
        lines.add(lDataSet1);
</code>```

答:
look into ValueFormatter

As described there in the wiki, create your own ValueFormatter and set the format you wish.

```<code>public class MyValueFormatter implements IValueFormatter {

    private DecimalFormat mFormat;

    public MyValueFormatter() {
        mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
    }

    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        // write your logic here
        return mFormat.format(value) + " $"; // e.g. append a dollar-sign
    }
}
</code>```

Then apply your Formatter to the ChartData or DataSet object:

```<code>// usage on whole data object
lineData.setValueFormatter(new MyValueFormatter());

// usage on individual dataset object
lineDataSet.setValueFormatter(new MyValueFormatter());
</code>```

Body:
I am using mpandroid chart library, I want to show float value in line graph but it shows normal value.

Screenshot.

My code:

if (cursor != null) {

            for (int h = 0; h < cursor.getCount(); h++) {

                cursor.moveToNext();

                ans = cursor.getString(cursor.getColumnIndex("pnt_triiodothyronine"));

                entry1.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_triiodothyronine")),h));
                entry2.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_thyroxine")),h));
                entry3.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_tsh")),h));
                entry4.add( new Entry(cursor.getFloat(cursor.getColumnIndex("pnt_weight")),h));
                entry5.add((cursor.getString(cursor.getColumnIndex("date"))));

                ansText.setText(ans);
            }

            cursor.close();

        }

lDataSet1 = new LineDataSet(entry1, "T3");
        //lDataSet1.setDrawFilled(true);
        lDataSet1.setColors(new int[]{getResources().getColor(R.color.purple)}); //resolved color
        lDataSet1.setCircleColor(Color.parseColor("#ffffff"));
        lDataSet1.setLineWidth(1.5f);
        lDataSet1.setCircleColorHole(Color.parseColor("#9c27b0"));
        lDataSet1.setHighLightColor(Color.rgb(190, 190, 190));
        lDataSet1.setDrawCubic(true);
        //lDataSet1.setDrawFilled(true);
        lines.add(lDataSet1);

Body:
look into ValueFormatter

As described there in the wiki, create your own ValueFormatter and set the format you wish.

public class MyValueFormatter implements IValueFormatter {

    private DecimalFormat mFormat;

    public MyValueFormatter() {
        mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
    }

    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        // write your logic here
        return mFormat.format(value) + " $"; // e.g. append a dollar-sign
    }
}

Then apply your Formatter to the ChartData or DataSet object:

// usage on whole data object
lineData.setValueFormatter(new MyValueFormatter());

// usage on individual dataset object
lineDataSet.setValueFormatter(new MyValueFormatter());


问:
Pre Calculate Date in Oracle SQL Statement
I have a sql query which looks like this

```<code>select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > sysdate - 1
and TIME_END < sysdate + 1;
</code>```

Works super fast.
Now I have the adjust the time_start and time_end a litte bit:

```<code>select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > CONVERTtoTimeZone(sysdate - 1, 'UTC')
and TIME_END <CONVERTtoTimeZone(sysdate + 1, 'UTC')
</code>```

Now the query is getting really slow. Is there a way to pre calculate the time_start and time_end in advance?

答:
Define CONVERTTOTIMEZONE() as a DETERMINISTIC.  Like this:

```<code>CREATE OR REPLACE FUNCTION CONVERTTOTIMEZONE (x_date DATE)
  RETURN DATE DETERMINISTIC IS...
</code>```

Without being defined as deterministic, Oracle does not know that your function will return the same output for the same input every time.  So, it must evaluate your function for each row instead of just running it once at the beginning.  That's a waste of time in itself, but it also prevents the use of any indexes.

NOTE: the function really needs to be deterministic or else you'll get wrong results.  Based on your comments, your function is deterministic though.

For more information on DETERMINISTIC, see the latest database documentation: https://docs.oracle.com/database/122/LNPLS/DETERMINISTIC-clause.htm#LNPLS-GUID-6AECC957-27CC-4334-9F43-0FBE88F92654

Body:
I have a sql query which looks like this

select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > sysdate - 1
and TIME_END < sysdate + 1;

Works super fast.
Now I have the adjust the time_start and time_end a litte bit:

select
*
from TABLE@REMOTE
where 1=1
and (NODE = 3521 or node = 3787)
and TIME_START > CONVERTtoTimeZone(sysdate - 1, 'UTC')
and TIME_END <CONVERTtoTimeZone(sysdate + 1, 'UTC')

Now the query is getting really slow. Is there a way to pre calculate the time_start and time_end in advance?

Body:
Define CONVERTTOTIMEZONE() as a DETERMINISTIC.  Like this:

CREATE OR REPLACE FUNCTION CONVERTTOTIMEZONE (x_date DATE)
  RETURN DATE DETERMINISTIC IS...

Without being defined as deterministic, Oracle does not know that your function will return the same output for the same input every time.  So, it must evaluate your function for each row instead of just running it once at the beginning.  That's a waste of time in itself, but it also prevents the use of any indexes.

NOTE: the function really needs to be deterministic or else you'll get wrong results.  Based on your comments, your function is deterministic though.

For more information on DETERMINISTIC, see the latest database documentation: https://docs.oracle.com/database/122/LNPLS/DETERMINISTIC-clause.htm#LNPLS-GUID-6AECC957-27CC-4334-9F43-0FBE88F92654