问:
How to enable Dragging in UITextfield in iOS 11
I know its too early to ask about development of latest feature of iOS 11 Drag and Drop. This also says All drag and drop features are available on iPad. On iPhone, drag and drop is available only within an app.

So I'm looking to move textfield within single app in iPhone. I looked into UIDragInteraction class but I don't know how to enable or active dragging feature in UITextfield and I also noticed that .textDragDelegate property added to UITextfield but I don't know how to active dragging.

Looking for suggestion or help who already practiced this.

Thanks

答:
For iPhone, if the DnD is for the same screen, it's tricky:

Detect touch on the UITextField

Create a "visual copy" of this textfield if the user still touch the screen and move the finger.

Move this "visual copy" when the finger is moving

When user release the finger, detect the position to put this "visual copy"

Create the copy of uitextfield object, call addSubview to add to the right position

Adjust the autolayout constraint of this new uitextfield

Remove the old uitextfield + adjust the autolayout of the view that are related with it.

For DnD between screen, technically, it's possible but the application must be designed for that requirement.

To enable dragging on an UIView object for iPad, you have to create a dragInteraction and add it to your UIViewObject. Then, you will have to enable the dropInteraction to your ViewController as well.

For example (not tested):

```<code>@IBOutlet weak var dragableTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    //enable drag for your 'dragableTextField'
    let dragInteraction = UIDragInteraction(delegate: self)
    self.dragableTextField.addInteraction(dragInteraction)

    //set up drop interaction delegate to this ViewController.
    let dropInteraction = UIDropInteraction(delegate: self)
    self.view.addInteraction(dropInteraction)
}
</code>```

and implement those delegate

```<code>extension ViewController : UIDragInteractionDelegate {
    //this is mandatory
    func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
        //implement your code

    }
}

extension ViewController : UIDropInteractionDelegate {
    //this is optional
    func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
        // If you want to enable drag-drop on UITextField object only:
        return session.canLoadObjects(ofClass: [UITextField.self])
    }
}
</code>```

You need more works to load data or update UI at the destination target. You can read more at:

https://developer.apple.com/documentation/uikit/drag_and_drop/making_a_view_into_a_drop_destination

and
https://developer.apple.com/documentation/uikit/drag_and_drop/adopting_drag_and_drop_in_a_custom_view

Body:
For iPhone, if the DnD is for the same screen, it's tricky:

Detect touch on the UITextField

Create a "visual copy" of this textfield if the user still touch the screen and move the finger.

Move this "visual copy" when the finger is moving

When user release the finger, detect the position to put this "visual copy"

Create the copy of uitextfield object, call addSubview to add to the right position

Adjust the autolayout constraint of this new uitextfield

Remove the old uitextfield + adjust the autolayout of the view that are related with it.

For DnD between screen, technically, it's possible but the application must be designed for that requirement.

To enable dragging on an UIView object for iPad, you have to create a dragInteraction and add it to your UIViewObject. Then, you will have to enable the dropInteraction to your ViewController as well.

For example (not tested):

@IBOutlet weak var dragableTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    //enable drag for your 'dragableTextField'
    let dragInteraction = UIDragInteraction(delegate: self)
    self.dragableTextField.addInteraction(dragInteraction)

    //set up drop interaction delegate to this ViewController.
    let dropInteraction = UIDropInteraction(delegate: self)
    self.view.addInteraction(dropInteraction)
}

and implement those delegate

extension ViewController : UIDragInteractionDelegate {
    //this is mandatory
    func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
        //implement your code

    }
}

extension ViewController : UIDropInteractionDelegate {
    //this is optional
    func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
        // If you want to enable drag-drop on UITextField object only:
        return session.canLoadObjects(ofClass: [UITextField.self])
    }
}

You need more works to load data or update UI at the destination target. You can read more at:

https://developer.apple.com/documentation/uikit/drag_and_drop/making_a_view_into_a_drop_destination

and
https://developer.apple.com/documentation/uikit/drag_and_drop/adopting_drag_and_drop_in_a_custom_view


来源: stackexchange

问:
How to redirect to an external site that requires a POST with parameters?
Additional requirements:

Make it generic

Make it open in a new tab

Make it open in a new tab with IE11 (tougher still)

Make it post to an external/different domain

答:
The issue is that we cannot POST into a named tab cross domains in IE11.

Instead let's create a file that will build out a form using the query string params.

Now it's just a matter of issuing a get request to that file.

First, create a file called PostRedirect.htm with the following code:

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="HTMLClient/Scripts/jquery-2.2.4.min.js"></script>
    <script type="text/javascript">

        //This adapter file allows POSTing to any url via a GET
        //Main advantage of this method is that it is IE11 compatible (posting to new named tab is no longer possible in IE11 w/o adjusting the security policy)

        //Must pass a param called url

        $(document).ready(function () {

            //get all the params from the query string
            var urlParams;
            (window.onpopstate = function () {
                var match,
                    pl = /\+/g,  // Regex for replacing addition symbol with a space
                    search = /([^&=]+)=?([^&]*)/g,
                    decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
                    query = window.location.search.substring(1);

                urlParams = {};
                while (match = search.exec(query))
                    urlParams[decode(match[1])] = decode(match[2]);
            })();

            var postLaunch = function (url, params) {

                var form = document.createElement("form");
                form.setAttribute("method", "post");
                form.setAttribute("action", url);
                for (var i in params) {
                    if (params.hasOwnProperty(i)
                        && i != 'url' //no need to submit the url param itself
                        ) {
                        var input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = i;
                        input.value = params[i];
                        form.appendChild(input);
                    }
                }
                document.body.appendChild(form);
                form.submit();
            };

            postLaunch(urlParams['url'], urlParams);
        });
    </script>
</body>
</html>
</code>```

Now you simply call the above file with the params of your choice like so:

```<code>    var params = {
        url: 'http://oris.co.palm-beach.fl.us/or_web1/new_sch.asp',
        search_by: 'Official Book/Page',
        RecSetSize: 100,
        PageSize: 20,
        search_entry: '24799-0613'
    };
    window.open('/postredirect.htm?' + $.param(params), '_blank');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The issue is that we cannot POST into a named tab cross domains in IE11.

Instead let's create a file that will build out a form using the query string params.

Now it's just a matter of issuing a get request to that file.

First, create a file called PostRedirect.htm with the following code:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="HTMLClient/Scripts/jquery-2.2.4.min.js"></script>
    <script type="text/javascript">

        //This adapter file allows POSTing to any url via a GET
        //Main advantage of this method is that it is IE11 compatible (posting to new named tab is no longer possible in IE11 w/o adjusting the security policy)

        //Must pass a param called url

        $(document).ready(function () {

            //get all the params from the query string
            var urlParams;
            (window.onpopstate = function () {
                var match,
                    pl = /\+/g,  // Regex for replacing addition symbol with a space
                    search = /([^&=]+)=?([^&]*)/g,
                    decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
                    query = window.location.search.substring(1);

                urlParams = {};
                while (match = search.exec(query))
                    urlParams[decode(match[1])] = decode(match[2]);
            })();

            var postLaunch = function (url, params) {

                var form = document.createElement("form");
                form.setAttribute("method", "post");
                form.setAttribute("action", url);
                for (var i in params) {
                    if (params.hasOwnProperty(i)
                        && i != 'url' //no need to submit the url param itself
                        ) {
                        var input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = i;
                        input.value = params[i];
                        form.appendChild(input);
                    }
                }
                document.body.appendChild(form);
                form.submit();
            };

            postLaunch(urlParams['url'], urlParams);
        });
    </script>
</body>
</html>

Now you simply call the above file with the params of your choice like so:

    var params = {
        url: 'http://oris.co.palm-beach.fl.us/or_web1/new_sch.asp',
        search_by: 'Official Book/Page',
        RecSetSize: 100,
        PageSize: 20,
        search_entry: '24799-0613'
    };
    window.open('/postredirect.htm?' + $.param(params), '_blank');


问:
How to print errors in error log in Django?
I have example code in view:

try
   bla-bla-bla
  except
    return 500 status

How to view error in this try in error.log for Django ( for example if Django run on mod-python in Apache ) ?

答:
this answer your question:

Django Unhandled Exception

ContentLicense: CC BY-SA 2.5


问:
Methods to use the serial port in multiple forms
I'm designing a windows userform to interact with a microcontroller through the serial port.

The GUI includes multiple userforms which will use the same serialport. I researched how to do that and I found different ideas. Some I don't know if it works the others I'm not sure how to implement it in code. Let's say I have

Form1: Start.vb
Form2: Shield1.vb

1) Can I declare the serial port in the start userform as:

```<code>Public Shared SerialPort1 As New System.IO.Ports.SerialPort
</code>```

And use it in the other forms ?

2) First alternative: Use a Module to declare a new Serialport

```<code>Module Module1
Public WithEvents mySerialPort1 As New IO.Ports.SerialPort

Private Sub mySerialPort1_DataReceived(sender As Object, _
                                       e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                   Handles mySerialPort1.DataReceived
End Sub
End Module
</code>```

Is this method right? If yes How do I use it in the code of my forms ? How to include the DataReceived Event in the code of the forms ?

3) Second alternative: Constructor of the Serialport in the start form and then pass the data to the other forms as mentionned in this post: Alternate Solution 1

```<code>private void OnSetup(object sender, EventArgs e)
{
this.port = new SerialPort(...);
// TODO: initialize port

Form2 f2 = new Form2(this.port);
f2.Show();
Form3 f3 = new Form3(this.port);
f3.Show();
Form4 f4 = new Form4(this.port);
f4.Show();
</code>```

}

Are then the Events also included ? How do I use them?

4) Third alternative: Use a static class like done in this solution:
Alternate Solution 2

Is the code written in C# here right ? I'm writing my programm in VB.net but I could take this as a reference.

Which is the recommended solution for a beginner ? Could you please write it in a small code if you have another suggestion or a correction ?

I apologize in advance for any ambiguity or falsly used terms.

Thanks you!

答:
I found this very helpful example of a sigleton C# class for serial port:
C# Singleton Example

As a beginner I used a Code converter to have it in VB.Net. Can you guys let me know if the resulting code is correct and I can use it ? Thanks a lot!!

```<code>Imports System
Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Namespace HeiswayiNrird.Singleton

Public NotInheritable Class SerialPortManager

    Private Shared lazy As Lazy(Of SerialPortManager) = New Lazy(Of SerialPortManager)(() => {  }, New SerialPortManager)

    Public Shared ReadOnly Property Instance As SerialPortManager
        Get
            Return lazy.Value
        End Get
    End Property

    Private _serialPort As SerialPort

    Private _readThread As Thread

    Private _keepReading As Boolean

    Private Sub New()
        MyBase.New
        Me._serialPort = New SerialPort
        Me._readThread = Nothing
        Me._keepReading = false
    End Sub

    ''' <summary>
    ''' Update the serial port status to the event subscriber
    ''' </summary>
    Public Event OnStatusChanged As EventHandler(Of String)

    ''' <summary>
    ''' Update received data from the serial port to the event subscriber
    ''' </summary>
    Public Event OnDataReceived As EventHandler(Of String)

    ''' <summary>
    ''' Update TRUE/FALSE for the serial port connection to the event subscriber
    ''' </summary>
    Public Event OnSerialPortOpened As EventHandler(Of Boolean)

    ''' <summary>
    ''' Return TRUE if the serial port is currently connected
    ''' </summary>
    Public ReadOnly Property IsOpen As Boolean
        Get
            Return Me._serialPort.IsOpen
        End Get
    End Property

    ''' <summary>
    ''' Open the serial port connection using basic serial port settings
    ''' </summary>
    ''' <param name="portname">COM1 / COM3 / COM4 / etc.</param>
    ''' <param name="baudrate">0 / 100 / 300 / 600 / 1200 / 2400 / 4800 / 9600 / 14400 / 19200 / 38400 / 56000 / 57600 / 115200 / 128000 / 256000</param>
    ''' <param name="parity">None / Odd / Even / Mark / Space</param>
    ''' <param name="databits">5 / 6 / 7 / 8</param>
    ''' <param name="stopbits">None / One / Two / OnePointFive</param>
    ''' <param name="handshake">None / XOnXOff / RequestToSend / RequestToSendXOnXOff</param>
    Public Sub Open(Optional ByVal portname As String = "COM1", Optional ByVal baudrate As Integer = 9600, Optional ByVal parity As Parity = Parity.None, Optional ByVal databits As Integer = 8, Optional ByVal stopbits As StopBits = StopBits.One, Optional ByVal handshake As Handshake = Handshake.None)
        Me.Close

        Try
            Me._serialPort.PortName = portname
            Me._serialPort.BaudRate = baudrate
            Me._serialPort.Parity = parity
            Me._serialPort.DataBits = databits
            Me._serialPort.StopBits = stopbits
            Me._serialPort.Handshake = handshake
            Me._serialPort.ReadTimeout = 50
            Me._serialPort.WriteTimeout = 50
            Me._serialPort.Open
            Me.StartReading

        Catch  As IOException
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("{0} does not exist.", portname))
            End If

        Catch  As UnauthorizedAccessException
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("{0} already in use.", portname))
            End If

        Catch ex As Exception
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, ("Error: " + ex.Message))
            End If

        End Try

        If Me._serialPort.IsOpen Then
            Dim sb As String = StopBits.None.ToString.Substring(0, 1)
            Select Case (Me._serialPort.StopBits)
                Case StopBits.One
                    sb = "1"
                Case StopBits.OnePointFive
                    sb = "1.5"
                Case StopBits.Two
                    sb = "2"
            End Select

            Dim p As String = Me._serialPort.Parity.ToString.Substring(0, 1)
            Dim hs As String = "No Handshake"
            'TODO: Warning!!!, inline IF is not supported ?
            (Me._serialPort.Handshake = Handshake.None)
            Me._serialPort.Handshake.ToString
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("Connected to {0}: {1} bps, {2}{3}{4}, {5}.", Me._serialPort.PortName, Me._serialPort.BaudRate, Me._serialPort.DataBits, p, sb, hs))
            End If

            If (Not (OnSerialPortOpened) Is Nothing) Then
                OnSerialPortOpened(Me, true)
            End If

        Else
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("{0} already in use.", portname))
            End If

            If (Not (OnSerialPortOpened) Is Nothing) Then
                OnSerialPortOpened(Me, false)
            End If

        End If

    End Sub

    ''' <summary>
    ''' Close the serial port connection
    ''' </summary>
    Public Sub Close()
        Me.StopReading
        Me._serialPort.Close
        If (Not (OnStatusChanged) Is Nothing) Then
            OnStatusChanged(Me, "Connection closed.")
        End If

        If (Not (OnSerialPortOpened) Is Nothing) Then
            OnSerialPortOpened(Me, false)
        End If

    End Sub

    ''' <summary>
    ''' Send/write string to the serial port
    ''' </summary>
    ''' <param name="message"></param>
    Public Sub SendString(ByVal message As String)
        If Me._serialPort.IsOpen Then
            Try
                Me._serialPort.Write(message)
                If (Not (OnStatusChanged) Is Nothing) Then
                    OnStatusChanged(Me, String.Format("Message sent: {0}", message))
                End If

            Catch ex As Exception
                If (Not (OnStatusChanged) Is Nothing) Then
                    OnStatusChanged(Me, String.Format("Failed to send string: {0}", ex.Message))
                End If

            End Try

        End If

    End Sub

    Private Sub StartReading()
        If Not Me._keepReading Then
            Me._keepReading = true
            Me._readThread = New Thread(ReadPort)
            Me._readThread.Start
        End If

    End Sub

    Private Sub StopReading()
        If Me._keepReading Then
            Me._keepReading = false
            Me._readThread.Join
            Me._readThread = Nothing
        End If

    End Sub

    Private Sub ReadPort()

        While Me._keepReading
            If Me._serialPort.IsOpen Then
                'byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1];
                Try
                    'int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
                    'string data = Encoding.ASCII.GetString(readBuffer, 0, count);
                    Dim data As String = Me._serialPort.ReadLine
                    If (Not (OnDataReceived) Is Nothing) Then
                        OnDataReceived(Me, data)
                    End If

                Catch  As TimeoutException

                End Try

            Else
                Dim waitTime As TimeSpan = New TimeSpan(0, 0, 0, 0, 50)
                Thread.Sleep(waitTime)
            End If

        End While

    End Sub
End Class
End Namespace
</code>```

Body:
I'm designing a windows userform to interact with a microcontroller through the serial port.

The GUI includes multiple userforms which will use the same serialport. I researched how to do that and I found different ideas. Some I don't know if it works the others I'm not sure how to implement it in code. Let's say I have

Form1: Start.vb
Form2: Shield1.vb

1) Can I declare the serial port in the start userform as:

Public Shared SerialPort1 As New System.IO.Ports.SerialPort

And use it in the other forms ?

2) First alternative: Use a Module to declare a new Serialport

Module Module1
Public WithEvents mySerialPort1 As New IO.Ports.SerialPort

Private Sub mySerialPort1_DataReceived(sender As Object, _
                                       e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                   Handles mySerialPort1.DataReceived
End Sub
End Module

Is this method right? If yes How do I use it in the code of my forms ? How to include the DataReceived Event in the code of the forms ?

3) Second alternative: Constructor of the Serialport in the start form and then pass the data to the other forms as mentionned in this post: Alternate Solution 1

private void OnSetup(object sender, EventArgs e)
{
this.port = new SerialPort(...);
// TODO: initialize port

Form2 f2 = new Form2(this.port);
f2.Show();
Form3 f3 = new Form3(this.port);
f3.Show();
Form4 f4 = new Form4(this.port);
f4.Show();

}

Are then the Events also included ? How do I use them?

4) Third alternative: Use a static class like done in this solution:
Alternate Solution 2

Is the code written in C# here right ? I'm writing my programm in VB.net but I could take this as a reference.

Which is the recommended solution for a beginner ? Could you please write it in a small code if you have another suggestion or a correction ?

I apologize in advance for any ambiguity or falsly used terms.

Thanks you!

Body:
I found this very helpful example of a sigleton C# class for serial port:
C# Singleton Example

As a beginner I used a Code converter to have it in VB.Net. Can you guys let me know if the resulting code is correct and I can use it ? Thanks a lot!!

Imports System
Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Namespace HeiswayiNrird.Singleton

Public NotInheritable Class SerialPortManager

    Private Shared lazy As Lazy(Of SerialPortManager) = New Lazy(Of SerialPortManager)(() => {  }, New SerialPortManager)

    Public Shared ReadOnly Property Instance As SerialPortManager
        Get
            Return lazy.Value
        End Get
    End Property

    Private _serialPort As SerialPort

    Private _readThread As Thread

    Private _keepReading As Boolean

    Private Sub New()
        MyBase.New
        Me._serialPort = New SerialPort
        Me._readThread = Nothing
        Me._keepReading = false
    End Sub

    ''' <summary>
    ''' Update the serial port status to the event subscriber
    ''' </summary>
    Public Event OnStatusChanged As EventHandler(Of String)

    ''' <summary>
    ''' Update received data from the serial port to the event subscriber
    ''' </summary>
    Public Event OnDataReceived As EventHandler(Of String)

    ''' <summary>
    ''' Update TRUE/FALSE for the serial port connection to the event subscriber
    ''' </summary>
    Public Event OnSerialPortOpened As EventHandler(Of Boolean)

    ''' <summary>
    ''' Return TRUE if the serial port is currently connected
    ''' </summary>
    Public ReadOnly Property IsOpen As Boolean
        Get
            Return Me._serialPort.IsOpen
        End Get
    End Property

    ''' <summary>
    ''' Open the serial port connection using basic serial port settings
    ''' </summary>
    ''' <param name="portname">COM1 / COM3 / COM4 / etc.</param>
    ''' <param name="baudrate">0 / 100 / 300 / 600 / 1200 / 2400 / 4800 / 9600 / 14400 / 19200 / 38400 / 56000 / 57600 / 115200 / 128000 / 256000</param>
    ''' <param name="parity">None / Odd / Even / Mark / Space</param>
    ''' <param name="databits">5 / 6 / 7 / 8</param>
    ''' <param name="stopbits">None / One / Two / OnePointFive</param>
    ''' <param name="handshake">None / XOnXOff / RequestToSend / RequestToSendXOnXOff</param>
    Public Sub Open(Optional ByVal portname As String = "COM1", Optional ByVal baudrate As Integer = 9600, Optional ByVal parity As Parity = Parity.None, Optional ByVal databits As Integer = 8, Optional ByVal stopbits As StopBits = StopBits.One, Optional ByVal handshake As Handshake = Handshake.None)
        Me.Close

        Try
            Me._serialPort.PortName = portname
            Me._serialPort.BaudRate = baudrate
            Me._serialPort.Parity = parity
            Me._serialPort.DataBits = databits
            Me._serialPort.StopBits = stopbits
            Me._serialPort.Handshake = handshake
            Me._serialPort.ReadTimeout = 50
            Me._serialPort.WriteTimeout = 50
            Me._serialPort.Open
            Me.StartReading

        Catch  As IOException
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("{0} does not exist.", portname))
            End If

        Catch  As UnauthorizedAccessException
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("{0} already in use.", portname))
            End If

        Catch ex As Exception
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, ("Error: " + ex.Message))
            End If

        End Try

        If Me._serialPort.IsOpen Then
            Dim sb As String = StopBits.None.ToString.Substring(0, 1)
            Select Case (Me._serialPort.StopBits)
                Case StopBits.One
                    sb = "1"
                Case StopBits.OnePointFive
                    sb = "1.5"
                Case StopBits.Two
                    sb = "2"
            End Select

            Dim p As String = Me._serialPort.Parity.ToString.Substring(0, 1)
            Dim hs As String = "No Handshake"
            'TODO: Warning!!!, inline IF is not supported ?
            (Me._serialPort.Handshake = Handshake.None)
            Me._serialPort.Handshake.ToString
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("Connected to {0}: {1} bps, {2}{3}{4}, {5}.", Me._serialPort.PortName, Me._serialPort.BaudRate, Me._serialPort.DataBits, p, sb, hs))
            End If

            If (Not (OnSerialPortOpened) Is Nothing) Then
                OnSerialPortOpened(Me, true)
            End If

        Else
            If (Not (OnStatusChanged) Is Nothing) Then
                OnStatusChanged(Me, String.Format("{0} already in use.", portname))
            End If

            If (Not (OnSerialPortOpened) Is Nothing) Then
                OnSerialPortOpened(Me, false)
            End If

        End If

    End Sub

    ''' <summary>
    ''' Close the serial port connection
    ''' </summary>
    Public Sub Close()
        Me.StopReading
        Me._serialPort.Close
        If (Not (OnStatusChanged) Is Nothing) Then
            OnStatusChanged(Me, "Connection closed.")
        End If

        If (Not (OnSerialPortOpened) Is Nothing) Then
            OnSerialPortOpened(Me, false)
        End If

    End Sub

    ''' <summary>
    ''' Send/write string to the serial port
    ''' </summary>
    ''' <param name="message"></param>
    Public Sub SendString(ByVal message As String)
        If Me._serialPort.IsOpen Then
            Try
                Me._serialPort.Write(message)
                If (Not (OnStatusChanged) Is Nothing) Then
                    OnStatusChanged(Me, String.Format("Message sent: {0}", message))
                End If

            Catch ex As Exception
                If (Not (OnStatusChanged) Is Nothing) Then
                    OnStatusChanged(Me, String.Format("Failed to send string: {0}", ex.Message))
                End If

            End Try

        End If

    End Sub

    Private Sub StartReading()
        If Not Me._keepReading Then
            Me._keepReading = true
            Me._readThread = New Thread(ReadPort)
            Me._readThread.Start
        End If

    End Sub

    Private Sub StopReading()
        If Me._keepReading Then
            Me._keepReading = false
            Me._readThread.Join
            Me._readThread = Nothing
        End If

    End Sub

    Private Sub ReadPort()

        While Me._keepReading
            If Me._serialPort.IsOpen Then
                'byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1];
                Try
                    'int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
                    'string data = Encoding.ASCII.GetString(readBuffer, 0, count);
                    Dim data As String = Me._serialPort.ReadLine
                    If (Not (OnDataReceived) Is Nothing) Then
                        OnDataReceived(Me, data)
                    End If

                Catch  As TimeoutException

                End Try

            Else
                Dim waitTime As TimeSpan = New TimeSpan(0, 0, 0, 0, 50)
                Thread.Sleep(waitTime)
            End If

        End While

    End Sub
End Class
End Namespace


问:
Why is Array.fill() not available whit ES6 target
I'm migrating some js code to typescript and I'm facing some issues with Array.fill.

I used to have this code

```<code>Array(4).fill(0).map()
</code>```

and I changed it to

```<code>Array<number>(4).fill(0).map()
</code>```

but I get this error

```<code>Error:(22, 49) TS2339:Property 'fill' does not exist on type 'number[]'.
</code>```

My tsconfig.json looks like

```<code>{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": false,
    "outDir": "dist",
    "allowJs": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.js"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "src/**/*.spec.ts",
    "src/**/*.spec.js"
  ]
}
</code>```

I already check this issue #9436.

Did I miss something ?

答:
try this : </p>

```<code>let arr:Array<Number>=new Array(8);
arr.fill(0);
</code>```

<p>hope it helps :) </p>

Body:
I'm migrating some js code to typescript and I'm facing some issues with Array.fill.

I used to have this code

Array(4).fill(0).map()

and I changed it to

Array<number>(4).fill(0).map()

but I get this error

Error:(22, 49) TS2339:Property 'fill' does not exist on type 'number[]'.

My tsconfig.json looks like

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": false,
    "outDir": "dist",
    "allowJs": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.js"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "src/**/*.spec.ts",
    "src/**/*.spec.js"
  ]
}

I already check this issue #9436.

Did I miss something ?

Body:
try this :

let arr:Array<Number>=new Array(8);
arr.fill(0);

hope it helps :)


问:
How do I persist a MySQL timestamp field as a long (epoch) field in java using JPA?
I have a column in a MySQL table like:

```<code>createdAt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP`.
</code>```

I want it to be stored in a field like:

```<code>private Long createdAt;
</code>```

How would I do this?

答:
Best if you use the supported types in TemporalType enum. Longs would require a converter.

Here's a converter for longs:

```<code>import java.sql.Timestamp;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class LongConverter implements AttributeConverter<Long, Timestamp> {

   @Override
   public Timestamp convertToDatabaseColumn(Long attribute) {
      if (attribute == null)
         return null;
      return new Timestamp(attribute);
   }

   @Override
   public Long convertToEntityAttribute(Timestamp dbData) {
      if (dbData == null)
         return null;
      return dbData.getTime();

   }

}
</code>```

Body:
I have a column in a MySQL table like:

createdAt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP`.

I want it to be stored in a field like:

private Long createdAt;

How would I do this?

Body:
Best if you use the supported types in TemporalType enum. Longs would require a converter.

Here's a converter for longs:

import java.sql.Timestamp;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class LongConverter implements AttributeConverter<Long, Timestamp> {

   @Override
   public Timestamp convertToDatabaseColumn(Long attribute) {
      if (attribute == null)
         return null;
      return new Timestamp(attribute);
   }

   @Override
   public Long convertToEntityAttribute(Timestamp dbData) {
      if (dbData == null)
         return null;
      return dbData.getTime();

   }

}


问:
Create a new pandas column with a value from a user-defined function
I am getting a SettingWithCopyWarning when attempting to create a new column on a pandas dataframe using a function I created to return a value for that new column. I am using the movielens dataset and predicting the rating of a user on a movie.

This is an example of my dataframe:

Now if I want to add a new column called 'prediction' that sends the user_id and item_id to my function and return the prediction I have followed the advice of this other question

Hence using the code:

```<code>df['pred'] = df.apply(lambda x: predict_rating(x['user_id'], x['item_id']), axis =1)
</code>```

Yet I keep getting the SettingWithCopyWarning.

:44: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Any advice would be welcome.

答:
Do this ,

df.loc[:,'pred'] = df.apply(lambda x: predict_rating(x['user_id'], x['item_id']), axis =1)

Body:
I am getting a SettingWithCopyWarning when attempting to create a new column on a pandas dataframe using a function I created to return a value for that new column. I am using the movielens dataset and predicting the rating of a user on a movie.

This is an example of my dataframe:

Now if I want to add a new column called 'prediction' that sends the user_id and item_id to my function and return the prediction I have followed the advice of this other question

Hence using the code:

df['pred'] = df.apply(lambda x: predict_rating(x['user_id'], x['item_id']), axis =1)

Yet I keep getting the SettingWithCopyWarning.

:44: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Any advice would be welcome.


问:
index syntax ('content['xxx']") for accessing members of .SWF
I was actually looking for the adobe docs online that would cover syntax like the following:

SWFLoader(event.target).content['wrFont']

That's from my own code, so obivously I know it works, its just that after 2 years of Flex programming,  I have still not encountered any sort of formal documentation on the rules governing this access method (i.e. like in the above where I'm accessing the wrFont member of the loaded SWF via an array index syntax and a string.

Specifically, it would be things like, determining if the referenced member even exists - what would be the standard method for doing that (Surely not just a try-catch block right?).  But not just that, but formal Adobe Documentation on all relevant aspects of the above. I've downloaded all zipped adobe docs off of their live docs site - where is all this fully documented.

ON a side note, something that's always bugged me about google, is that with a search string like ".content["  it just ignores the "[" character as irrelevant, though if I could just find that search string I would have my answer.  But google doesnt search for characters like "[" evidently. Neither does Bing.  Does any search engine do this.

答:
The [ and ] - "array" access - can be used on ANY object, or a derivate of one (that is everything except numbers, strings, booleans).

To properly see if a child exists, use the .hasOwnProperty method.


问:
Java: How to set a socket timeout with a "try with resources"
I want to set a socket connection timeout. I know that I can set it using the connect method but this is my code:</p>

```<code>try(Socket socket = new Socket(InetAddress.getByName(ip), port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)){
</code>```

答:
It's not really clear from your question where you are stuck, but you can just keep using the connect method:

```<code>int timeout = 25000;
try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress("abc", 123), timeout);
    try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
         PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)) {

    }
}
</code>```

Body:
I want to set a socket connection timeout. I know that I can set it using the connect method but this is my code:

try(Socket socket = new Socket(InetAddress.getByName(ip), port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)){

Body:
It's not really clear from your question where you are stuck, but you can just keep using the connect method:

int timeout = 25000;
try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress("abc", 123), timeout);
    try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
         PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true)) {

    }
}


问:
Can a Rails attribute be an array?
I recently learned about the json datatype in Rails 5, which allows you to store a hash in a PostgreSQL database. For some reason I can't find a full list of Rails 5 datatypes. Is there any sort of datatype that similarly allows you to store an array?

Such that example_record.array_datatype => ["1", "2", "3"]

答:
Yes indeed. Here is a sample migration to add an integer and a string array to a model:

```<code>class AddToBooks < ActiveRecord::Migration
  def change
    add_column :books, :category_ids, :integer, array: true, default: [], null: false
    add_column :books, :subjects    , :text   , array: true, default: [], null: false
  end
end
</code>```

For arrays of strings, use :text as the type.

I'd strongly recommend using an empty array instead of a null to indicate "no data", and this migration ensures that.

Title: Can a Rails attribute be an array?

Body:
Yes indeed. Here is a sample migration to add an integer and a string array to a model:

class AddToBooks < ActiveRecord::Migration
  def change
    add_column :books, :category_ids, :integer, array: true, default: [], null: false
    add_column :books, :subjects    , :text   , array: true, default: [], null: false
  end
end

For arrays of strings, use :text as the type.

I'd strongly recommend using an empty array instead of a null to indicate "no data", and this migration ensures that.


问:
MS Graph API - Accessing "policies" endpoint with application permissions
According to the docs, this endpoint requires Directory.AccessAsUser.All which is a delegated permission. Is there any reason why this endpoint doesn't include the application-level permission Directory.Read.All?

I understand that this endpoint is still in beta, but where does one make these kinds of suggestions/requests?

答: Excellent question, there is a User Voice set up that covers both Office and Graph developer requests/feedback. </p>


问:
how can I store my data in a global variable?
```<code>$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});
</code>```

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

答:
Exposing variables in window/global scope is bad in my opinion. You should wrap it in a function (like a class of sorts) and expose it like this:

```<code>function Values(type) {
    this.value1 = "something";
}
</code>```

From this point you can use prototype to define additional functions on "Values" like so:

```<code>Values.prototype.doStuff = function() {
    return this.value1 + ' addsomething';
};
</code>```

Inside of the prototype function you can define/return promises or do whatever you want including assigning values to the instance. You can also assign the instance to a global variable to make it a singleton of sorts. Granted your still using a global variable for that but its the instance of Values assigned to the variable not the actual values that are stored.

This is a bit of an over simplification perhaps, but in a way this is how the global variables for lodash or jquery work, although they have a LOT more going on to check for existing global variables and such before attempting to define it on global scope as typically you want to avoid that.

Body:
$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

Body:
Exposing variables in window/global scope is bad in my opinion. You should wrap it in a function (like a class of sorts) and expose it like this:

function Values(type) {
    this.value1 = "something";
}

From this point you can use prototype to define additional functions on "Values" like so:

Values.prototype.doStuff = function() {
    return this.value1 + ' addsomething';
};

Inside of the prototype function you can define/return promises or do whatever you want including assigning values to the instance. You can also assign the instance to a global variable to make it a singleton of sorts. Granted your still using a global variable for that but its the instance of Values assigned to the variable not the actual values that are stored.

This is a bit of an over simplification perhaps, but in a way this is how the global variables for lodash or jquery work, although they have a LOT more going on to check for existing global variables and such before attempting to define it on global scope as typically you want to avoid that.


问:
Permission denied on accessing host directory in Docker
I am trying to mount a host directory in Docker, but then I cannot access it from within the container, even if the access permissions look good.

I am doing

```<code>sudo docker run -i -v /data1/Downloads:/Downloads ubuntu bash
</code>```

and then

```<code>ls -al
</code>```

It gives me:

```<code>total 8892
drwxr-xr-x.  23 root root    4096 Jun 18 14:34 .
drwxr-xr-x.  23 root root    4096 Jun 18 14:34 ..
-rwxr-xr-x.   1 root root       0 Jun 18 14:34 .dockerenv
-rwx------.   1 root root 9014486 Jun 17 22:09 .dockerinit
drwxrwxr-x.  18 1000 1000   12288 Jun 16 11:40 Downloads
drwxr-xr-x.   2 root root    4096 Jan 29 18:10 bin
drwxr-xr-x.   2 root root    4096 Apr 19  2012 boot
drwxr-xr-x.   4 root root     340 Jun 18 14:34 dev
drwxr-xr-x.  56 root root    4096 Jun 18 14:34 etc
drwxr-xr-x.   2 root root    4096 Apr 19  2012 home
</code>```

and a lot more lines like that (I think this is the relevant portion).

If I do

```<code>cd /Downloads
ls
</code>```

the result is

```<code>ls: cannot open directory .: Permission denied
</code>```

The host is Fedora 20, with Docker 1.0.0 and go1.2.2.

What is going wrong?

答:
I resolved that issue by using a data container. This also has the advantage of isolating the data from the application layer. You could run it like this:

```<code>docker run --volumes-from=<container-data-name> ubuntu
</code>```

This tutorial provides a good explanation on the use of data containers.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to mount a host directory in Docker, but then I cannot access it from within the container, even if the access permissions look good.

I am doing

sudo docker run -i -v /data1/Downloads:/Downloads ubuntu bash

and then

ls -al

It gives me:

total 8892
drwxr-xr-x.  23 root root    4096 Jun 18 14:34 .
drwxr-xr-x.  23 root root    4096 Jun 18 14:34 ..
-rwxr-xr-x.   1 root root       0 Jun 18 14:34 .dockerenv
-rwx------.   1 root root 9014486 Jun 17 22:09 .dockerinit
drwxrwxr-x.  18 1000 1000   12288 Jun 16 11:40 Downloads
drwxr-xr-x.   2 root root    4096 Jan 29 18:10 bin
drwxr-xr-x.   2 root root    4096 Apr 19  2012 boot
drwxr-xr-x.   4 root root     340 Jun 18 14:34 dev
drwxr-xr-x.  56 root root    4096 Jun 18 14:34 etc
drwxr-xr-x.   2 root root    4096 Apr 19  2012 home

and a lot more lines like that (I think this is the relevant portion).

If I do

cd /Downloads
ls

the result is

ls: cannot open directory .: Permission denied

The host is Fedora 20, with Docker 1.0.0 and go1.2.2.

What is going wrong?

Body:
I resolved that issue by using a data container. This also has the advantage of isolating the data from the application layer. You could run it like this:

docker run --volumes-from=<container-data-name> ubuntu

This tutorial provides a good explanation on the use of data containers.


问:
Register, Modules View in Eclipse IDE for Java?
I dont see how Register, Modules View work in Eclipse Debug View ?. I run a class and have breakpoints. I can see Variables Expressions but why dont Registers and Modules View work ?</p>

答: Those views are for C/C++ development.  They're not for use with Java.  I don't know why they are installed with the base Eclipse SDK, rather than with the C/C++ development tools (the CDT).  I have used Eclipse for 10 years, developing Java, and I've never used those views.  </p>


问:
Nullable column not behaving as such
I have a table actor with a nullable column first_name. I set a specific row to null:

```<code>update actor set first_name=null where actor_id=201;
Query OK, 1 rows affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1
</code>```

I then try to query that table using the null value in my where clause and get nothing back:

```<code>select * from actor where first_name is null;
Empty set (0.00 sec)
</code>```

But if I select checking if that column is an empty string, I get the right value back:

```<code>select * from actor where first_name = '';
[...]
1 row in set (0.00 sec)
</code>```

Storage engine is MyISAM. Why is a nulled column being set to empty string?

Update

I see the 1 warning but mysql CLI does not show any warnings. How can I make it do so?

Also:

```<code>desc actor;
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| Field       | Type                 | Null | Key | Default           | Extra                       |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| actor_id    | smallint(5) unsigned | NO   | PRI | NULL              | auto_increment              |
| first_name  | varchar(45)          | NO   |     | NULL              |                             |
| last_name   | varchar(45)          | NO   | MUL | NULL              |                             |
| last_update | timestamp            | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
</code>```

答: From the Table description, looks like all columns including first_name are not null. Are you sure it is nullable column?</p>

Title: Nullable column not behaving as such

Body:
I have a table actor with a nullable column first_name. I set a specific row to null:

update actor set first_name=null where actor_id=201;
Query OK, 1 rows affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

I then try to query that table using the null value in my where clause and get nothing back:

select * from actor where first_name is null;
Empty set (0.00 sec)

But if I select checking if that column is an empty string, I get the right value back:

select * from actor where first_name = '';
[...]
1 row in set (0.00 sec)

Storage engine is MyISAM. Why is a nulled column being set to empty string?

Update

I see the 1 warning but mysql CLI does not show any warnings. How can I make it do so?

Also:

desc actor;
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| Field       | Type                 | Null | Key | Default           | Extra                       |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| actor_id    | smallint(5) unsigned | NO   | PRI | NULL              | auto_increment              |
| first_name  | varchar(45)          | NO   |     | NULL              |                             |
| last_name   | varchar(45)          | NO   | MUL | NULL              |                             |
| last_update | timestamp            | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+----------------------+------+-----+-------------------+-----------------------------+


问:
Asp.NetCore bringing table into existing DbContext
I have successfully created a DbContext with tables in asp.netcore.

However, I have realized there are a few more tables that I need to add.  I know that .edmx files and updating the database model are no longer available in .netcore and was wondering if it is possible to automatically generate these tables into classes if the dbcontext has already been created.

答: You need to use EntityFramework Core, and just search it up online, you can get a ton of tutorials on how to do it. I learned it in only one day.</p>


问:
how to update row based on value of another row sql server
i would like to know what is the best way to update a row based on another row , lets say for example i have table like this:

```<code>ID   |   NAME    |  VALUE  |
----------------------------
 1   |   a  |   10   |
 2   |   b  |  NULL  |
 3   |   c  |  NULL  |
 4   |   d  |  NULL  |
 5   |   a  |   10   |
 6   |   b  |  NULL  |
 7   |   c  |  NULL  |
 8   |   d  |  NULL  |
 9   |   a  |  NULL  |
.
.
.
</code>```

now i need an UPDATE query that will compare all the rows with the name = d to rows with name = a and if row with name = a have in value = 10 then row with name = d will get value = 10 and then row with name = a value will set to NULL and if not then not. its like i need to switch between the values of the rows (a to d , b to c , c to d , d to a) in that order. in every 4 rows(a,b,c,d) will allways be only one row that value is not null.

i hope it was clear.
thanks!!

答:
I don't think I fully understand what you are trying to achieve here, but here's something to start a discussion:

```<code>--Create sample data
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp;
CREATE TABLE #temp (ID INT, NAME VARCHAR(50), [VALUE] INT);
INSERT INTO #temp SELECT 1, 'a', 10;
INSERT INTO #temp SELECT 2, 'b', NULL;
INSERT INTO #temp SELECT 3, 'c', NULL;
INSERT INTO #temp SELECT 4, 'd', NULL;
INSERT INTO #temp SELECT 5, 'a', 10;
INSERT INTO #temp SELECT 6, 'b', NULL;
INSERT INTO #temp SELECT 7, 'c', NULL;
INSERT INTO #temp SELECT 8, 'd', NULL;
INSERT INTO #temp SELECT 9, 'a', NULL;
</code>```

All this does is to swap a's and d's around if there is a value in the a's:

```<code>WITH Best AS (
    SELECT NAME, MAX([VALUE]) AS MAXVALUE FROM #temp GROUP BY NAME)
UPDATE
    t
SET
    [VALUE] =
        CASE
            WHEN t.NAME = 'a' AND b.MAXVALUE IS NOT NULL THEN NULL
            WHEN t.NAME = 'd' AND b.MAXVALUE IS NOT NULL THEN b.MAXVALUE
        END
FROM
    #temp t
    CROSS JOIN Best b
WHERE
    t.NAME IN ('a', 'd')
    AND b.NAME = 'a';

SELECT * FROM #temp;
</code>```

On completion I can see that all the a values have moved to the d rows.  That doesn't cope with b to c, c to d, etc. though.  Is this anything like what you want?

Now it looks like you actually need each group of four rows to be handled separately, so this might work better?

```<code>WITH Groups AS (
    SELECT ID, (ID - 1) / 4 AS group_id, NAME, [VALUE] FROM #temp),
Best AS (
    SELECT group_id, NAME, MAX([VALUE]) AS MAXVALUE FROM Groups GROUP BY group_id, NAME)
UPDATE
    t
SET
    [VALUE] =
        CASE
            WHEN t.NAME = 'a' AND b.MAXVALUE IS NOT NULL THEN NULL
            WHEN t.NAME = 'd' AND b.MAXVALUE IS NOT NULL THEN b.MAXVALUE
        END
FROM
    #temp t
    INNER JOIN Groups g ON g.ID = t.ID
    INNER JOIN Best b ON b.group_id = g.group_id
WHERE
    t.NAME IN ('a', 'd')
    AND b.NAME = 'a';
</code>```

Here's a new query for you, now I finally think I understand what this is supposed to do.  First here's my understanding of what you actually want:

you have data that is ordered by an ID;

the data is organised into groups of 4, starting at "a", then "b", then "c", then "d";

for each group of 4 items find the single item that has a non-NULL value;

move this one forward, i.e. if the a value is there move it to b, etc.

the d value moves back round to a again;

each group is independent of the others.

I created a slightly different set of data to show this working in practice:

```<code>--Create sample data
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp;
CREATE TABLE #temp (ID INT, NAME VARCHAR(50), [VALUE] INT);
INSERT INTO #temp SELECT 1, 'a', 10;
INSERT INTO #temp SELECT 2, 'b', NULL;
INSERT INTO #temp SELECT 3, 'c', NULL;
INSERT INTO #temp SELECT 4, 'd', NULL;
INSERT INTO #temp SELECT 5, 'a', NULL;
INSERT INTO #temp SELECT 6, 'b', NULL;
INSERT INTO #temp SELECT 7, 'c', NULL;
INSERT INTO #temp SELECT 8, 'd', 5;
INSERT INTO #temp SELECT 9, 'a', NULL;
INSERT INTO #temp SELECT 10, 'b', 90;
INSERT INTO #temp SELECT 11, 'c', NULL;
INSERT INTO #temp SELECT 12, 'd', NULL;
</code>```

...and here's my amended query:

```<code>WITH Groups AS (
    SELECT
        (ID - 1) / 4 AS group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        #temp),
Best AS (
    SELECT
        group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        Groups
    WHERE
        [VALUE] IS NOT NULL)
UPDATE
    t
SET
    [VALUE] =
        CASE
            WHEN t.NAME = 'a' AND b.NAME = 'a' THEN NULL
            WHEN t.NAME = 'a' AND b.NAME = 'd' THEN b.[VALUE]
            WHEN t.NAME = 'b' AND b.NAME = 'b' THEN NULL
            WHEN t.NAME = 'b' AND b.NAME = 'a' THEN b.[VALUE]
            WHEN t.NAME = 'c' AND b.NAME = 'c' THEN NULL
            WHEN t.NAME = 'c' AND b.NAME = 'b' THEN b.[VALUE]
            WHEN t.NAME = 'd' AND b.NAME = 'd' THEN NULL
            WHEN t.NAME = 'd' AND b.NAME = 'c' THEN b.[VALUE]
        END
FROM
    #temp t
    INNER JOIN Groups g ON g.ID = t.ID
    INNER JOIN Best b ON b.group_id = g.group_id;
</code>```

So my data starts off like this:

```<code>ID  NAME    VALUE
1   a   10
2   b   NULL
3   c   NULL
4   d   NULL
5   a   NULL
6   b   NULL
7   c   NULL
8   d   5
9   a   NULL
10  b   90
11  c   NULL
12  d   NULL
</code>```

...and when I run the UPDATE query:

```<code>ID  NAME    VALUE
1   a   NULL
2   b   10
3   c   NULL
4   d   NULL
5   a   5
6   b   NULL
7   c   NULL
8   d   NULL
9   a   NULL
10  b   NULL
11  c   90
12  d   NULL
</code>```

If I run the query again then everything moves one more step:

```<code>ID  NAME    VALUE
1   a   NULL
2   b   NULL
3   c   10
4   d   NULL
5   a   NULL
6   b   5
7   c   NULL
8   d   NULL
9   a   NULL
10  b   NULL
11  c   NULL
12  d   90
</code>```

If this still isn't what you want then either show me what you think the values should be after the first/ second iteration, or come up with a new before -> after example in your question.

Hopefully this will be the final attempt :D

```<code>WITH Groups AS (
    SELECT
        (ID - 1) / 4 AS group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        #temp),
Best AS (
    SELECT
        group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        Groups
    WHERE
        [VALUE] IS NOT NULL)
UPDATE
    t
SET
    [VALUE] =
        CASE
            --a to d
            WHEN t.NAME = 'd' AND b.NAME = 'a' THEN b.[VALUE]

            --b to c
            WHEN t.NAME = 'c' AND b.NAME = 'b' THEN b.[VALUE]

            --c to d (seems wrong?)
            WHEN t.NAME = 'd' AND b.NAME = 'c' THEN b.[VALUE]

            --d to a
            WHEN t.NAME = 'a' AND b.NAME = 'd' THEN b.[VALUE]

            --Set the moving item to NULL
            WHEN t.NAME = b.NAME THEN NULL
        END
FROM
    #temp t
    INNER JOIN Groups g ON g.ID = t.ID
    INNER JOIN Best b ON b.group_id = g.group_id;
</code>```

Body:
i would like to know what is the best way to update a row based on another row , lets say for example i have table like this:

ID   |   NAME    |  VALUE  |
----------------------------
 1   |   a  |   10   |
 2   |   b  |  NULL  |
 3   |   c  |  NULL  |
 4   |   d  |  NULL  |
 5   |   a  |   10   |
 6   |   b  |  NULL  |
 7   |   c  |  NULL  |
 8   |   d  |  NULL  |
 9   |   a  |  NULL  |
.
.
.

now i need an UPDATE query that will compare all the rows with the name = d to rows with name = a and if row with name = a have in value = 10 then row with name = d will get value = 10 and then row with name = a value will set to NULL and if not then not. its like i need to switch between the values of the rows (a to d , b to c , c to d , d to a) in that order. in every 4 rows(a,b,c,d) will allways be only one row that value is not null.

i hope it was clear.
thanks!!

Body:
I don't think I fully understand what you are trying to achieve here, but here's something to start a discussion:

--Create sample data
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp;
CREATE TABLE #temp (ID INT, NAME VARCHAR(50), [VALUE] INT);
INSERT INTO #temp SELECT 1, 'a', 10;
INSERT INTO #temp SELECT 2, 'b', NULL;
INSERT INTO #temp SELECT 3, 'c', NULL;
INSERT INTO #temp SELECT 4, 'd', NULL;
INSERT INTO #temp SELECT 5, 'a', 10;
INSERT INTO #temp SELECT 6, 'b', NULL;
INSERT INTO #temp SELECT 7, 'c', NULL;
INSERT INTO #temp SELECT 8, 'd', NULL;
INSERT INTO #temp SELECT 9, 'a', NULL;

All this does is to swap a's and d's around if there is a value in the a's:

WITH Best AS (
    SELECT NAME, MAX([VALUE]) AS MAXVALUE FROM #temp GROUP BY NAME)
UPDATE
    t
SET
    [VALUE] =
        CASE
            WHEN t.NAME = 'a' AND b.MAXVALUE IS NOT NULL THEN NULL
            WHEN t.NAME = 'd' AND b.MAXVALUE IS NOT NULL THEN b.MAXVALUE
        END
FROM
    #temp t
    CROSS JOIN Best b
WHERE
    t.NAME IN ('a', 'd')
    AND b.NAME = 'a';

SELECT * FROM #temp;

On completion I can see that all the a values have moved to the d rows.  That doesn't cope with b to c, c to d, etc. though.  Is this anything like what you want?

Now it looks like you actually need each group of four rows to be handled separately, so this might work better?

WITH Groups AS (
    SELECT ID, (ID - 1) / 4 AS group_id, NAME, [VALUE] FROM #temp),
Best AS (
    SELECT group_id, NAME, MAX([VALUE]) AS MAXVALUE FROM Groups GROUP BY group_id, NAME)
UPDATE
    t
SET
    [VALUE] =
        CASE
            WHEN t.NAME = 'a' AND b.MAXVALUE IS NOT NULL THEN NULL
            WHEN t.NAME = 'd' AND b.MAXVALUE IS NOT NULL THEN b.MAXVALUE
        END
FROM
    #temp t
    INNER JOIN Groups g ON g.ID = t.ID
    INNER JOIN Best b ON b.group_id = g.group_id
WHERE
    t.NAME IN ('a', 'd')
    AND b.NAME = 'a';

Here's a new query for you, now I finally think I understand what this is supposed to do.  First here's my understanding of what you actually want:

you have data that is ordered by an ID;

the data is organised into groups of 4, starting at "a", then "b", then "c", then "d";

for each group of 4 items find the single item that has a non-NULL value;

move this one forward, i.e. if the a value is there move it to b, etc.

the d value moves back round to a again;

each group is independent of the others.

I created a slightly different set of data to show this working in practice:

--Create sample data
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp;
CREATE TABLE #temp (ID INT, NAME VARCHAR(50), [VALUE] INT);
INSERT INTO #temp SELECT 1, 'a', 10;
INSERT INTO #temp SELECT 2, 'b', NULL;
INSERT INTO #temp SELECT 3, 'c', NULL;
INSERT INTO #temp SELECT 4, 'd', NULL;
INSERT INTO #temp SELECT 5, 'a', NULL;
INSERT INTO #temp SELECT 6, 'b', NULL;
INSERT INTO #temp SELECT 7, 'c', NULL;
INSERT INTO #temp SELECT 8, 'd', 5;
INSERT INTO #temp SELECT 9, 'a', NULL;
INSERT INTO #temp SELECT 10, 'b', 90;
INSERT INTO #temp SELECT 11, 'c', NULL;
INSERT INTO #temp SELECT 12, 'd', NULL;

...and here's my amended query:

WITH Groups AS (
    SELECT
        (ID - 1) / 4 AS group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        #temp),
Best AS (
    SELECT
        group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        Groups
    WHERE
        [VALUE] IS NOT NULL)
UPDATE
    t
SET
    [VALUE] =
        CASE
            WHEN t.NAME = 'a' AND b.NAME = 'a' THEN NULL
            WHEN t.NAME = 'a' AND b.NAME = 'd' THEN b.[VALUE]
            WHEN t.NAME = 'b' AND b.NAME = 'b' THEN NULL
            WHEN t.NAME = 'b' AND b.NAME = 'a' THEN b.[VALUE]
            WHEN t.NAME = 'c' AND b.NAME = 'c' THEN NULL
            WHEN t.NAME = 'c' AND b.NAME = 'b' THEN b.[VALUE]
            WHEN t.NAME = 'd' AND b.NAME = 'd' THEN NULL
            WHEN t.NAME = 'd' AND b.NAME = 'c' THEN b.[VALUE]
        END
FROM
    #temp t
    INNER JOIN Groups g ON g.ID = t.ID
    INNER JOIN Best b ON b.group_id = g.group_id;

So my data starts off like this:

ID  NAME    VALUE
1   a   10
2   b   NULL
3   c   NULL
4   d   NULL
5   a   NULL
6   b   NULL
7   c   NULL
8   d   5
9   a   NULL
10  b   90
11  c   NULL
12  d   NULL

...and when I run the UPDATE query:

ID  NAME    VALUE
1   a   NULL
2   b   10
3   c   NULL
4   d   NULL
5   a   5
6   b   NULL
7   c   NULL
8   d   NULL
9   a   NULL
10  b   NULL
11  c   90
12  d   NULL

If I run the query again then everything moves one more step:

ID  NAME    VALUE
1   a   NULL
2   b   NULL
3   c   10
4   d   NULL
5   a   NULL
6   b   5
7   c   NULL
8   d   NULL
9   a   NULL
10  b   NULL
11  c   NULL
12  d   90

If this still isn't what you want then either show me what you think the values should be after the first/ second iteration, or come up with a new before -> after example in your question.

Hopefully this will be the final attempt :D

WITH Groups AS (
    SELECT
        (ID - 1) / 4 AS group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        #temp),
Best AS (
    SELECT
        group_id,
        ID,
        NAME,
        [VALUE]
    FROM
        Groups
    WHERE
        [VALUE] IS NOT NULL)
UPDATE
    t
SET
    [VALUE] =
        CASE
            --a to d
            WHEN t.NAME = 'd' AND b.NAME = 'a' THEN b.[VALUE]

            --b to c
            WHEN t.NAME = 'c' AND b.NAME = 'b' THEN b.[VALUE]

            --c to d (seems wrong?)
            WHEN t.NAME = 'd' AND b.NAME = 'c' THEN b.[VALUE]

            --d to a
            WHEN t.NAME = 'a' AND b.NAME = 'd' THEN b.[VALUE]

            --Set the moving item to NULL
            WHEN t.NAME = b.NAME THEN NULL
        END
FROM
    #temp t
    INNER JOIN Groups g ON g.ID = t.ID
    INNER JOIN Best b ON b.group_id = g.group_id;


问:
CodeIgniter htaccess and URL rewrite issues
I have never used CodeIgniter before, let alone ANY php framework and I thought I would give it a try. Everything is going fine except I cannot seem to remove the index.php from the URL and still access my pages.

I have never used the MVC structure so I am learning as I go, so forgive me if I'm doing this wrong.

I am trying to access a view I created called 'about_page.php' by simply typing in localhost/ci/about but currently I can only access it by using localhost/ci/index.php/about

The controller for the page is: /application/controllers/about.php

The Model for the page is: /application/models/about_model.php

And the View for the page is: /application/views/about_page.php

I have searched for a solution to this issue, but haven't been able to find one. Here is where I have already searched:

CodeIgniter - removing index.php

Codeigniter - how to remove the index.php from url?

http://www.farinspace.com/codeigniter-htaccess-file/

CodeIgniter comes with a .htaccess file in the 'application' folder which contains only Allow Deny From All. So I created a new .htaccess file in the root directory, http://localhost/ci/.htaccess and added this code to it:

```<code>RewriteEngine On
RewriteBase /ci
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

When the .htaccess file is in the root directory I get a 500 Internal Server Error. When I copy the exact same file into the applications folder the 500 error goes away, but I still cannot access the about page by using localhost/ci/about

I have already changed $config['index_page'] = 'index.php'; to $config['index_page'] = ''; AND I tried changing $config['uri_protocol']    = 'AUTO'; to $config['uri_protocol']  = 'REQUEST_URI'; but I am still getting the Internal Server Error.

I went into the httpd.conf file and uncommented the mod_rewrite.so module so I know mod_rewrite is active.

Does anyone have any ideas why this isn't working or how I can get this work? I know there are alot of questions on StackOverflow on this subject but I couldn't find one that answered my question.

Am I doing this right? Should I even be able to access the about page by visiting localhost/ci/about or do I have to create an 'about' directory in the 'application' directory?

答:
Just add this in the .htaccess file:</p>

```<code>DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
</code>```

Body:
I have never used CodeIgniter before, let alone ANY php framework and I thought I would give it a try. Everything is going fine except I cannot seem to remove the index.php from the URL and still access my pages.

I have never used the MVC structure so I am learning as I go, so forgive me if I'm doing this wrong.

I am trying to access a view I created called 'about_page.php' by simply typing in localhost/ci/about but currently I can only access it by using localhost/ci/index.php/about

The controller for the page is: /application/controllers/about.php

The Model for the page is: /application/models/about_model.php

And the View for the page is: /application/views/about_page.php

I have searched for a solution to this issue, but haven't been able to find one. Here is where I have already searched:

CodeIgniter - removing index.php

Codeigniter - how to remove the index.php from url?

http://www.farinspace.com/codeigniter-htaccess-file/

CodeIgniter comes with a .htaccess file in the 'application' folder which contains only Allow Deny From All. So I created a new .htaccess file in the root directory, http://localhost/ci/.htaccess and added this code to it:

RewriteEngine On
RewriteBase /ci
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

When the .htaccess file is in the root directory I get a 500 Internal Server Error. When I copy the exact same file into the applications folder the 500 error goes away, but I still cannot access the about page by using localhost/ci/about

I have already changed $config['index_page'] = 'index.php'; to $config['index_page'] = ''; AND I tried changing $config['uri_protocol']    = 'AUTO'; to $config['uri_protocol']  = 'REQUEST_URI'; but I am still getting the Internal Server Error.

I went into the httpd.conf file and uncommented the mod_rewrite.so module so I know mod_rewrite is active.

Does anyone have any ideas why this isn't working or how I can get this work? I know there are alot of questions on StackOverflow on this subject but I couldn't find one that answered my question.

Am I doing this right? Should I even be able to access the about page by visiting localhost/ci/about or do I have to create an 'about' directory in the 'application' directory?

Body:
Just add this in the .htaccess file:

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]


问:
Create SEO Friendly URLs With Htaccess Mod Rewrite
I want to Create SEO Friendly URLs With Htaccess Mod Rewrite like this:

```<code>http://localhost/try/pagination/page/4
</code>```

but now output showing when we click on next button

```<code>http://localhost/try/pagination.php/page/pagination.php/page/2
</code>```

My php  code is :

```<code><?php

//include 'config.php';
define('DB_HOST', 'localhost');
define('DB_NAME', 'wr');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

echo $_GET['page'];

$rowsPerPage = 1;

if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
$pageNum = 1;
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM articles LIMIT $previousRows, $rowsPerPage";
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "<table border=1>\n";
echo "<tr><th>ID</th><th>Name</th><th>Password</th><th>Perm</th><th>Email</th>
<th>Date</th></tr>";
while(list($id,$title,$content) = mysql_fetch_array($result))
{
echo "<tr><td>$id</td><td>$title</td><td>$content</td></tr>";
}
echo '</table>';
$query = "SELECT COUNT(title) AS numrows FROM articles";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
echo $lastPage;
$phpself = "pagination.php";
echo $phpself;
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a href=\"$phpself?page=$page\" title=\"Page $page\">[Back]</a> ";
$first = " <a href=\"$phpself?page=1\" title=\"Page 1\">[First Page]</a> ";
}
else
{
$prev = ' [Back] ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$next = " <a href=\"$phpself/page/$page\" title=\"Page $page\">[Next]</a> ";
$last = " <a href=\"$phpself?page=$lastPage\" title=\"Page $lastPage\">[Last Page]</a> ";
}
else
{
$next = ' [Next] ';
$last = ' [Last Page] ';
}
echo $first . $prev . " Showing page <bold>$pageNum</bold> of
<bold>$lastPage</bold> pages " . $next . $last;
?>
</code>```

.htaccess file code is:

```<code>Options +FollowSymLinks

RewriteEngine On
RewriteRule ^pagination/page/([0-9]+)\.html$ pagination.php?page=$1
</code>```

Next requirement is if we are pass the two variable

```<code>http://localhost/try/pagination/tag/php/page/2
</code>```

How I can change in Php code and .htaccess file?

答:
Assuming your .htaccess file is in the docroot - and that you mean you want your URLs to appear in the "SEO Friendly" format of /try/pagination/page/4

```<code>RewriteEngine On
RewriteRule ^try/pagination/page/([0-9]+)/?$ /try/pagination.php?page=$1 [L]
</code>```

Then you need to update the code that generates the URLs; for instance, replace:

```<code>$prev = " <a href=\"$phpself?page=$page\" title=\"Page $page\">[Back]</a> ";
</code>```

with:

```<code>$prev = " <a href=\"/try/pagination/page/{$page}\" title=\"Page $page\">[Back]</a> ";
</code>```

Body:
I want to Create SEO Friendly URLs With Htaccess Mod Rewrite like this:

http://localhost/try/pagination/page/4

but now output showing when we click on next button

http://localhost/try/pagination.php/page/pagination.php/page/2

My php  code is :

<?php

//include 'config.php';
define('DB_HOST', 'localhost');
define('DB_NAME', 'wr');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

echo $_GET['page'];

$rowsPerPage = 1;

if(isset($_GET['page']))
{
$pageNum= $_GET['page'];
}
else
$pageNum = 1;
$previousRows =($pageNum - 1) * $rowsPerPage;
$query = "SELECT * FROM articles LIMIT $previousRows, $rowsPerPage";
$result = mysql_query($query) or die('Error couldn\'t get the data').mysql_error();
echo "
\n";
echo "
ID	Name	Password	Perm	Email
Date
";
while(list($id,$title,$content) = mysql_fetch_array($result))
{
echo "
$id	$title	$content
";
}
echo '
';
$query = "SELECT COUNT(title) AS numrows FROM articles";
$result = mysql_query($query) or die('Error, couldn\'t get count title=\"$page\"').mysql_error();
$row = mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$lastPage = ceil($numrows/$rowsPerPage);
echo $lastPage;
$phpself = "pagination.php";
echo $phpself;
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " [Back] ";
$first = " [First Page] ";
}
else
{
$prev = ' [Back] ';
$first = ' [First Page] ';
}
if ($pageNum < $lastPage)
{
$page = $pageNum + 1;
$next = " [Next] ";
$last = " [Last Page] ";
}
else
{
$next = ' [Next] ';
$last = ' [Last Page] ';
}
echo $first . $prev . " Showing page <bold>$pageNum</bold> of
<bold>$lastPage</bold> pages " . $next . $last;
?>

.htaccess file code is:

Options +FollowSymLinks

RewriteEngine On
RewriteRule ^pagination/page/([0-9]+)\.html$ pagination.php?page=$1

Next requirement is if we are pass the two variable

http://localhost/try/pagination/tag/php/page/2

How I can change in Php code and .htaccess file?

Body:
Assuming your .htaccess file is in the docroot - and that you mean you want your URLs to appear in the "SEO Friendly" format of /try/pagination/page/4

RewriteEngine On
RewriteRule ^try/pagination/page/([0-9]+)/?$ /try/pagination.php?page=$1 [L]

Then you need to update the code that generates the URLs; for instance, replace:

$prev = " <a href=\"$phpself?page=$page\" title=\"Page $page\">[Back]</a> ";

with:

$prev = " <a href=\"/try/pagination/page/{$page}\" title=\"Page $page\">[Back]</a> ";


问:
Convert currency to USD using specific value date
I have this spreadsheet:

```<code>| date      | amount | currency | USD value |
|-----------|--------|----------|-----------|
|12/31/2017 | 100    | EUR      | formula   |
</code>```

formula is:

```<code>=B1*GoogleFinance(CONCATENATE("CURRENCY:"; C1; "USD");"close";DATE(YEAR(A1);MONTH(A1);DAY(A1)))
</code>```

It should take amount and convert it from currency to USD using the value date of date.

The problem is that I get:

Error

  Parameter 2 of function MULTIPLY expects numeric values, but "Date" is of type text and cannot be interpreted as number.

What am I doing wrong?

Notes:

I'm using ; as separator because my locale uses , as decimals separator.

答:
Try this:</p>

```<code>=INDEX(GoogleFinance("USD"&C1, "close", A1),2,2)*B1
</code>```

Body:
I have this spreadsheet:

| date      | amount | currency | USD value |
|-----------|--------|----------|-----------|
|12/31/2017 | 100    | EUR      | formula   |

formula is:

=B1*GoogleFinance(CONCATENATE("CURRENCY:"; C1; "USD");"close";DATE(YEAR(A1);MONTH(A1);DAY(A1)))

It should take amount and convert it from currency to USD using the value date of date.

The problem is that I get:

Error

  Parameter 2 of function MULTIPLY expects numeric values, but "Date" is of type text and cannot be interpreted as number.

What am I doing wrong?

Notes:

I'm using ; as separator because my locale uses , as decimals separator.

Body:
Try this:

=INDEX(GoogleFinance("USD"&C1, "close", A1),2,2)*B1


问:
REGGEX Matching just once inside multiple delimiters
In a pattern X-Y-Z where the delimiters are "-" i want to check if Y has the size 8 without repetions.

Y could be a subset like Y = (A-B-C) but Y just has a value 1 if there's no

1 - num-12345678-num -> In this case I want that Y has a value.
2 - num-12345678-234-213-num -> Since Y is a subset (12345678-234-213) Y should have a different value.

The reggex i'm using is '-([0-9]*)-' and works for the 1st case however gets the same value for the second. Could anyone help me?

Thanks in advance

答:
You may add a hyphen to the character class:

```<code>-([0-9-]*)-
      ^
</code>```

See the regex demo

If you put it at the end of the char class, you do not need to escape it.

Details:

- - a hyphen

([0-9-]*) - Group 1 capturing zero or more (due to the * quantifier) digits or/and hyphens

- - a literal hyphen again.

Body:
You may add a hyphen to the character class:

-([0-9-]*)-
      ^

See the regex demo

If you put it at the end of the char class, you do not need to escape it.

Details:

- - a hyphen

([0-9-]*) - Group 1 capturing zero or more (due to the * quantifier) digits or/and hyphens

- - a literal hyphen again.


问:
Using Groovy-Eclipse plugin to develop in Grails
I am evaluating Groovy/Grails for a new project and I am wondering: Can the free Groovy-Eclipse plugin be used to develop Grails applications, and if so, what are the limitations? I am aware of the SpringSource Tool Suite, which includes full support for Grails in Eclipse, but it also includes a bunch of other stuff I don't care about, so I'm looking for a lighter-weight alternative. </p>

答:
Unfortunately there is no full-featured support for Groovy/Grails in any of the IDE's.

For example, none o fthe IDE's support full code completion. But you can use it to build your projects.

I moved to intellij because it currently has the best support. Have a look at this to re-evaluate your decision. The list on the grails platform will give you a hint what is (at lest in one of the IDE's) not possible currently.


问:
Comparing the difference of two C++ projects in VS
I wanted to create a new project of the same code as the kinect v2 standard bunch of code .

I made a new project in Visual Studio and add the copy of sample files of the other project in a new directory and added it to my project.

Also I added all the headers etc.

Then try to compile it and it make a lot of errors ! but it works fine in the sample project .

the CPP files and the headers are all the same.

So what can be wrong ?

I cahnged the Include directories in VC++ Directories to $(KINECTSDK20_DIR)\inc;$(IncludePath) and some errors get away but still there are errors!

These are the errors :

```<code>HCURSOR LoadCursorW(HINSTANCE,LPCWSTR)
HICON LoadIconW(HINSTANCE,LPCWSTR)
'=': cannot convert from 'const wchar_t [25]' to 'LPCSTR'
'ATOM RegisterClassW(const WNDCLASSW *)': cannot convert argument 1 from 'WNDCLASS *' to 'const WNDCLASSW *'
'HWND CreateDialogParamW(HINSTANCE,LPCWSTR,HWND,DLGPROC,LPARAM)': cannot convert argument 2 from 'LPSTR' to 'LPCWSTR'
'HRESULT StringCchPrintfA(STRSAFE_LPSTR,std::size_t,STRSAFE_LPCSTR,...)': cannot convert argument 1 from 'WCHAR [64]' to 'STRSAFE_LPSTR'
'BOOL SetDlgItemTextA(HWND,int,LPCSTR)': cannot convert argument 3 from 'WCHAR *' to 'LPCSTR'
</code>```

sorry for my bad English grammer in advance!

答:
Your project most certainly has the wrong character set setting. You can find how to change it here.

A dead giveaway is lots of cannot convert 'WCHAR *' to 'LPCSTR' and similar. WCHAR* is LPWSTR. LPWSTR will convert to LPCWSTR1, but not to LPCSTR - this typically means that a wide-character literal is being passed to the function which resolves to a narrow-character version under the current project settings.

A carefully written project can compile under both settings, but most of the time only one of them is used and as such has to be picked correctly before building.

1 You can pass non-const where a const is required, but you can't change the character type pointed to.

Body:
I wanted to create a new project of the same code as the kinect v2 standard bunch of code .

I made a new project in Visual Studio and add the copy of sample files of the other project in a new directory and added it to my project.

Also I added all the headers etc.

Then try to compile it and it make a lot of errors ! but it works fine in the sample project .

the CPP files and the headers are all the same.

So what can be wrong ?

I cahnged the Include directories in VC++ Directories to $(KINECTSDK20_DIR)\inc;$(IncludePath) and some errors get away but still there are errors!

These are the errors :

HCURSOR LoadCursorW(HINSTANCE,LPCWSTR)
HICON LoadIconW(HINSTANCE,LPCWSTR)
'=': cannot convert from 'const wchar_t [25]' to 'LPCSTR'
'ATOM RegisterClassW(const WNDCLASSW *)': cannot convert argument 1 from 'WNDCLASS *' to 'const WNDCLASSW *'
'HWND CreateDialogParamW(HINSTANCE,LPCWSTR,HWND,DLGPROC,LPARAM)': cannot convert argument 2 from 'LPSTR' to 'LPCWSTR'
'HRESULT StringCchPrintfA(STRSAFE_LPSTR,std::size_t,STRSAFE_LPCSTR,...)': cannot convert argument 1 from 'WCHAR [64]' to 'STRSAFE_LPSTR'
'BOOL SetDlgItemTextA(HWND,int,LPCSTR)': cannot convert argument 3 from 'WCHAR *' to 'LPCSTR'

sorry for my bad English grammer in advance!


问:
Update rows par lot SQL Server
I need to change a value of column in a table, so I need to do this :

```<code>update members
set frequence = 1
where frequence <> 1
</code>```

I have 7 million rows impacted, I need to make the update in batches of 100000 rows and then sleep for 2 minutes (time to replications to other datebases).

How can I do this please?

Regrads

答:
I think you should look at Micheal J. Schwartz's article on this very subject:

http://michaeljswart.com/2014/09/take-care-when-scripting-batches/

It appears that if you are not using memberId to filter on you are going to end up scanning the whole table by the time to get down to the end of the process because frequence is not very selective.

Title: Update rows par lot SQL Server

Body:
I need to change a value of column in a table, so I need to do this :

update members
set frequence = 1
where frequence <> 1

I have 7 million rows impacted, I need to make the update in batches of 100000 rows and then sleep for 2 minutes (time to replications to other datebases).

How can I do this please?

Regrads


问:
VB.net, SQL 2012, selecting phone data where date is today
I'm making a wallboard app that displays all call records from a database in SQL 2012 server. I've been trying stuff left and right but everything gives one of 2 errors executing the select command:

"Conversion failed when converting date and/or time from character
  string"

or

"Invalid column name '07/07/2017 15:03:35'."

Here is an SQL select command example i have:

```<code>SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > """ & DateToday & """"
</code>```

I've worked on a different wallboard program for the company i'm on and when I tried retrieving data from the current date it worked with the select command above (tweaked obviously) and only with this has it started having problems on me.

edit: oops, where it says DateToday i mean DateYesterday, my bad

edit*: This is the code im using to essentially count the number of calls that happened today, it might be rubbish, but it was from the person who was here before me had this and when i was told to continue his work I just used and improvised his code since it was working and the databases i've worked with are all similar if not the same

```<code>SDACallsP = New SqlDataAdapter(cmdCallsP, conn)
Dim num_calls_parceiros = SDACallsP.Fill(data_set, "dbo.tblCallList")
cs_parceiros.Text = num_calls_parceiros

cmdCallsP = String.Format("SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > ''" & DateYesterday & "''")
Dim DateYesterday As Date = Date.Today.AddDays(-1).ToString("yyyy-MM-dd")
</code>```

答:
Your first problem is the use of double quotes ("). In SQL Server you should use single quote (')

```<code>SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > '" & DateToday & "'"
</code>```

However, you shouldn't be querying by a date with time. May be the best solution for you is the following:

```<code>SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > cast('" & DateToday & "' as date)"
</code>```

Body:
I'm making a wallboard app that displays all call records from a database in SQL 2012 server. I've been trying stuff left and right but everything gives one of 2 errors executing the select command:

"Conversion failed when converting date and/or time from character
  string"

or

"Invalid column name '07/07/2017 15:03:35'."

Here is an SQL select command example i have:

SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > """ & DateToday & """"

I've worked on a different wallboard program for the company i'm on and when I tried retrieving data from the current date it worked with the select command above (tweaked obviously) and only with this has it started having problems on me.

edit: oops, where it says DateToday i mean DateYesterday, my bad

edit*: This is the code im using to essentially count the number of calls that happened today, it might be rubbish, but it was from the person who was here before me had this and when i was told to continue his work I just used and improvised his code since it was working and the databases i've worked with are all similar if not the same

SDACallsP = New SqlDataAdapter(cmdCallsP, conn)
Dim num_calls_parceiros = SDACallsP.Fill(data_set, "dbo.tblCallList")
cs_parceiros.Text = num_calls_parceiros

cmdCallsP = String.Format("SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > ''" & DateYesterday & "''")
Dim DateYesterday As Date = Date.Today.AddDays(-1).ToString("yyyy-MM-dd")

Body:
Your first problem is the use of double quotes ("). In SQL Server you should use single quote (')

SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > '" & DateToday & "'"

However, you shouldn't be querying by a date with time. May be the best solution for you is the following:

SELECT * FROM dbo.tblCallList WHERE CategoryId = 1 AND CreateDate > cast('" & DateToday & "' as date)"


问:
Go lang is it possible to create a struct that can also be used as a slice?
Is it possible to have a struct in go that can also be accessed as a slice?
So, for example, I'd want something like this:

```<code>type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    []Item
}
</code>```

And then I could access an Item in the ItemList as a slice.

```<code>myItemList[0].Name
</code>```

Or access the members of ItemList in the normal struct way.

```<code>myItemList.PackDate
</code>```

If this is not possible, are there any recommended patterns for handling a sort of slice with metadata like this in go?

答:
The recommended thing to do is to simply access the slice as a struct field:

```<code>type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    Items    []Item
}
</code>```

Accessing the values:

```<code>myItemList.Items[0].Name
myItemList.PackDate
</code>```

Iterating over the slice:

```<code>for _, item := range myItemList.Items {
    // do something with item.Name
}
</code>```

Body:
Is it possible to have a struct in go that can also be accessed as a slice?
So, for example, I'd want something like this:

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    []Item
}

And then I could access an Item in the ItemList as a slice.

myItemList[0].Name

Or access the members of ItemList in the normal struct way.

myItemList.PackDate

If this is not possible, are there any recommended patterns for handling a sort of slice with metadata like this in go?

Body:
The recommended thing to do is to simply access the slice as a struct field:

type Item struct {
    Name string
}

type ItemList struct {
    PackDate time.Time
    Items    []Item
}

Accessing the values:

myItemList.Items[0].Name
myItemList.PackDate

Iterating over the slice:

for _, item := range myItemList.Items {
    // do something with item.Name
}


问:
highlighting the textbox without using javascript or jquery
can we highlight our textbox without using javasript/jquery or css ?if yes then how? i am on jsp page, can jsp help?</p>

答:
You can do it with CSS inline, without using an external stylesheet. If you really must:</p>

```<code><input type="text" style="background-color:#FFFFCC;" /></code>```

Body:
You can do it with CSS inline, without using an external stylesheet. If you really must:

<input type="text" style="background-color:#FFFFCC;" />


问:
Exception while setting NSDictionary to UserDefaults
How to fix exception:

```<code>[User Defaults] Attempt to set a non-property-list object {
4 = 5;
} as an NSUserDefaults/CFPreferences value for key MyKey
</code>```

thrown by executing following code (Swift 3)

```<code>let ns = NSDictionary(dictionary: [4: 5])
UserDefaults.standard.set(ns, forKey: "MyKey")
</code>```

Code above correctly saves String type, but has problem with NSDictionary

答:
Your dictionary must have strings as keys for you to be able to save it to UserDefaults

this works for me:

```<code>let ns = NSDictionary(dictionary: ["4": 5])
UserDefaults.standard.set(ns, forKey: "MyKey")
</code>```

Body:
How to fix exception:

[User Defaults] Attempt to set a non-property-list object {
4 = 5;
} as an NSUserDefaults/CFPreferences value for key MyKey

thrown by executing following code (Swift 3)

let ns = NSDictionary(dictionary: [4: 5])
UserDefaults.standard.set(ns, forKey: "MyKey")

Code above correctly saves String type, but has problem with NSDictionary

Body:
Your dictionary must have strings as keys for you to be able to save it to UserDefaults

this works for me:

let ns = NSDictionary(dictionary: ["4": 5])
UserDefaults.standard.set(ns, forKey: "MyKey")


问:
Database NullPointerException while Testing
I got a method in Presenter that calls a database. Now, when I try to test method that actually communicate with database, it gives me NullPointerException.

How do we actually handle such cases?

```<code>public void getRoleFromSQLite(){
    if ("tutor".equalsIgnoreCase(userDB.getValueFromSqlite("role",1)))
        view.userRole("tutor");
    else
        view.userRole("student");
}
</code>```

TEST:

```<code>@Test
public void getRoleFromSqliteDatabaseTest(){
    Mockito.doReturn("tutor").when(userDB).getValueFromSqlite("role",1)
    presenter.getRoleFromSQLite();
    Mockito.verify(viewMock).userRole("tutor");
}
</code>```

Exception:

```<code>java.lang.NullPointerException
    at com.dolevel.level.db.UserDB.getValueFromSqlite(UserDB.java:130)
    at com.dolevel.level.presenters.UserProfileScreenPresenter.getRoleFromSQLite(UserProfileScreenPresenter.java:28)
    at com.dolevel.level.UserProfileScreenPresenterTest.getRoleFromSqliteDatabaseTest(UserProfileScreenPresenterTest.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
</code>```

答:
You just need to change your doReturn sentence from:

```<code>Mockito.doReturn("tutor").when(userDB).getValueFromSqlite("role",1)
</code>```

to

```<code>Mockito.doReturn("tutor").when(userDB.getValueFromSqlite("role",1))
</code>```

This way you would be mocking or recording the call to getValueFromSqlite method instead of calling it directly while specifying the mocked behavior.

Body:
I got a method in Presenter that calls a database. Now, when I try to test method that actually communicate with database, it gives me NullPointerException.

How do we actually handle such cases?

public void getRoleFromSQLite(){
    if ("tutor".equalsIgnoreCase(userDB.getValueFromSqlite("role",1)))
        view.userRole("tutor");
    else
        view.userRole("student");
}

TEST:

@Test
public void getRoleFromSqliteDatabaseTest(){
    Mockito.doReturn("tutor").when(userDB).getValueFromSqlite("role",1)
    presenter.getRoleFromSQLite();
    Mockito.verify(viewMock).userRole("tutor");
}

Exception:

java.lang.NullPointerException
    at com.dolevel.level.db.UserDB.getValueFromSqlite(UserDB.java:130)
    at com.dolevel.level.presenters.UserProfileScreenPresenter.getRoleFromSQLite(UserProfileScreenPresenter.java:28)
    at com.dolevel.level.UserProfileScreenPresenterTest.getRoleFromSqliteDatabaseTest(UserProfileScreenPresenterTest.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

Body:
You just need to change your doReturn sentence from:

Mockito.doReturn("tutor").when(userDB).getValueFromSqlite("role",1)

to

Mockito.doReturn("tutor").when(userDB.getValueFromSqlite("role",1))

This way you would be mocking or recording the call to getValueFromSqlite method instead of calling it directly while specifying the mocked behavior.


问:
SQL - string combine based on id
Need suggestion to split string in table 1, match its Ids with table 2 and concatenate the values.

Table - 1

```<code>Id  Tbl1Col
1   2
2   2,4
3
4   6
5   3
</code>```

Table - 2

```<code>Id  Tbl2Col
1   E
2   F
3   M
4   U
5   P
6   C
7   N
8   G
</code>```

Query -

```<code>SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = @Id
</code>```

Now If @Id = 1, Output is F -- works fine

Now If @Id = 2, Output should be FU -- should not be F,U

答:
Yuck!  But you can use LIKE:

```<code>SELECT T2.Tbl2Col
FROM Table1 T1 LEFT JOIN
     Table2 T2
     WHERE ',' + T1.Tbl1Col + ',' LIKE '%,' + CAST(T2.Id as VARCHAR(255)) + ',%'
WHERE T1.Id = @Id;
</code>```

You have a lousy data format, so this cannot make use of indexes.  You should really have a separate table, with one row per Table1.id and Table2.id.  Such a table is called a junction table or an association table.

Title: SQL - string combine based on id

Body:
Need suggestion to split string in table 1, match its Ids with table 2 and concatenate the values.

Table - 1

Id  Tbl1Col
1   2
2   2,4
3
4   6
5   3

Table - 2

Id  Tbl2Col
1   E
2   F
3   M
4   U
5   P
6   C
7   N
8   G

Query -

SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = @Id

Now If @Id = 1, Output is F -- works fine

Now If @Id = 2, Output should be FU -- should not be F,U

Body:
Yuck!  But you can use LIKE:

SELECT T2.Tbl2Col
FROM Table1 T1 LEFT JOIN
     Table2 T2
     WHERE ',' + T1.Tbl1Col + ',' LIKE '%,' + CAST(T2.Id as VARCHAR(255)) + ',%'
WHERE T1.Id = @Id;

You have a lousy data format, so this cannot make use of indexes.  You should really have a separate table, with one row per Table1.id and Table2.id.  Such a table is called a junction table or an association table.


问:
What are some optimization techniques for MySQL table with 300+ million records?
I am looking at storing some JMX data from JVMs on many servers for about 90 days.  This data would be statistics like heap size and thread count.  This will mean that one of the tables will have around 388 million records.

From this data I am building some graphs so you can compare the stats retrieved from the Mbeans.  This means I will be grabbing some data at an interval using timestamps.

So the real question is, Is there anyway to optimize the table or query so you can perform these queries in a reasonable amount of time?

Thanks,

Josh

答:
There are several things you can do:

Build your indexes to match the queries you are running. Run EXPLAIN to see the types of queries that are run and make sure that they all use an index where possible.

Partition your table. Paritioning is a technique for splitting a large table into several smaller ones by a specific (aggregate) key. MySQL supports this internally from ver. 5.1.

If necessary, build summary tables that cache the costlier parts of your queries. Then run your queries against the summary tables. Similarly, temporary in-memory tables can be used to store a simplified view of your table as a pre-processing stage.

OwnerDisplayName: Josh Harris

OwnerDisplayName: Eran Galperin


问:
Read weight from Metler Toledo BC60 Network Enabled Weight Scale via PHP Sockets
I have a Metler Toledo BC60 Network Enabled Scale.
Its on my local network with a local IP address. I can ping it and connect to it via terminal on port 82. If I sent it a "W" and press enter I get a number returned from it that is the weight at that moment.

How can I access this weight via PHP for use in my application?

My thought was something like this, but Im not getting anything back:

```<code><?php
// host and port to connect to
$host = "192.168.0.115";
$port = 82;

// connect to the port
$fp = fsockopen($host, $port, $errno, $errstr);

// if connection not successfull, display error
if (!$fp)
{
   die("no connection");
}
else
{
   // connection successfull
   fwrite($fp, "W\r\n"); //Request Weight
   $got = fgets($fp);
   // display the data
   echo  $got;
   fclose($fp);
   die();
}
?>
</code>```

答:
Thank you so much Alex!    You got it!

```<code>ini_set("auto_detect_line_endings", true);
</code>```

Did the trick!

Body:
I have a Metler Toledo BC60 Network Enabled Scale.
Its on my local network with a local IP address. I can ping it and connect to it via terminal on port 82. If I sent it a "W" and press enter I get a number returned from it that is the weight at that moment.

How can I access this weight via PHP for use in my application?

My thought was something like this, but Im not getting anything back:

<?php
// host and port to connect to
$host = "192.168.0.115";
$port = 82;

// connect to the port
$fp = fsockopen($host, $port, $errno, $errstr);

// if connection not successfull, display error
if (!$fp)
{
   die("no connection");
}
else
{
   // connection successfull
   fwrite($fp, "W\r\n"); //Request Weight
   $got = fgets($fp);
   // display the data
   echo  $got;
   fclose($fp);
   die();
}
?>

Body:
Thank you so much Alex!    You got it!

ini_set("auto_detect_line_endings", true);

Did the trick!