问:
How do i pass php variable to .js file to create function Chart
i done create my chart but i dont know how to pass it, i already try use ?php  but its not working.. and i already define in head like below, but when i try to pass it. the php file returning "''" like function tooltips title

```<code><script src="includes/templates/chart.js"></script>
</code>```

chart.js

```<code>
window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: '<?php echo $dtDateChart1; ?>' ,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}
</code>```

in my php file

```<code>$out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
</code>```

and this is my variable that i want to pass to my .js

```<code>         //result chart1
            @mssql_free_result($graph_query2);
            $dtDateChart1 = $dateTittleChart1;
            $convertChart1 = json_encode($datesChart1);
            $totalChart1 = json_encode($nMaxChart1);
            $labelChart1 =  $convertChart1;
</code>```

i dont know how to pass it when i already succes getelementbyid thanks you if you know something about it that i should know. i dont have a lot knowledge about javascript passing variable.

答:
I believe that you cannot pass variables from php to javascript because they are different things and they are executed in different places.
your php code runs on your server and the javascript code in the client's browser so they are not seen.
what you can do is a php script that echos the content of the variable you want and through javascript and fetch or any library that makes requests to make a request to the php file</p>

Body:
i done create my chart but i dont know how to pass it, i already try use ?php  but its not working.. and i already define in head like below, but when i try to pass it. the php file returning "''" like function tooltips title

chart.js

window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: '<?php echo $dtDateChart1; ?>' ,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}

in my php file

$out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';

and this is my variable that i want to pass to my .js

         //result chart1
            @mssql_free_result($graph_query2);
            $dtDateChart1 = $dateTittleChart1;
            $convertChart1 = json_encode($datesChart1);
            $totalChart1 = json_encode($nMaxChart1);
            $labelChart1 =  $convertChart1;

i dont know how to pass it when i already succes getelementbyid thanks you if you know something about it that i should know. i dont have a lot knowledge about javascript passing variable.


来源: stackexchange

问:
Polymorphic embedded structs
I'm wanting to store a tree structure in Postgres, and I'm hoping to embed an arbitrary Elixir struct on each node of the tree, something like this:

```<code>defmodule Node do
  use Ecto.Schema

  schema "nodes" do
    belongs_to :parent_node, Node
    embeds_one :struct, ArbitraryDataType
  end
end
</code>```

However, I believe embeds_one requires a specific struct data type to be specified, which won't work for my case. Is there a way around this?

My backup plan is to use two fields, one for the struct type and one for the struct fields, like this:

```<code>defmodule Node do
  use Ecto.Schema

  schema "nodes" do
    belongs_to :parent_node, Node
    field :struct_type, :string
    field :fields, :map
  end
end
</code>```

In order to save the record in the first place, I would need to use the __struct__ field to determine the struct type. Then, I would use logic something like the following to rebuild the original struct after retrieving the node from the database:

```<code>Enum.reduce(
  retrieved_node.fields,
  String.to_atom("Elixir.#{retrieved_node.struct_type}") |> struct,
  fn {k,v}, s -> Map.put(s, String.to_atom(k), v) end
)
</code>```

答:
The following library brings support for polymorphic embeds:

https://github.com/mathieuprog/polymorphic_embed

ContentLicense: CC BY-SA 3.0

Title: Polymorphic embedded structs

Body:
I'm wanting to store a tree structure in Postgres, and I'm hoping to embed an arbitrary Elixir struct on each node of the tree, something like this:

defmodule Node do
  use Ecto.Schema

  schema "nodes" do
    belongs_to :parent_node, Node
    embeds_one :struct, ArbitraryDataType
  end
end

However, I believe embeds_one requires a specific struct data type to be specified, which won't work for my case. Is there a way around this?

My backup plan is to use two fields, one for the struct type and one for the struct fields, like this:

defmodule Node do
  use Ecto.Schema

  schema "nodes" do
    belongs_to :parent_node, Node
    field :struct_type, :string
    field :fields, :map
  end
end

In order to save the record in the first place, I would need to use the __struct__ field to determine the struct type. Then, I would use logic something like the following to rebuild the original struct after retrieving the node from the database:

Enum.reduce(
  retrieved_node.fields,
  String.to_atom("Elixir.#{retrieved_node.struct_type}") |> struct,
  fn {k,v}, s -> Map.put(s, String.to_atom(k), v) end
)

ContentLicense: CC BY-SA 4.0


问:
How to get rid of the Close Button of a Console Window?
I have a customer who is using some old but still needed 32Bit-Software, which is running in a Console Window. It is necessary to disable the Close button because closing the Console using this button causes some serious problems in this software.

I thought about the following way:

1) Find the handle of the active Console

2) Disable the Close Button with GetSystemMenu function

Maybe I'm completely wrong, but I did not manage to find a way to do that so far.

Edit:

The problem is just the Close Button. Of course users can also quit the program by Alt+F4 or Task Manager, but they don't do that. They do use Close Button, that's why I want to disable it.

Of course the best solution would by to disable all ways to cancel the program, but to disable the Close Button would work.

To start the program inside a Windows Form would by one possible solution, too.

答:
To interact with a foreign Window, you need to find it/verify it exists first.

We have different methods to find a Window. Here I'm considering FindWindowEx and Process.GetProcessesByName().
UI Automation and EnumWindows provide other options, eventually.

Store the CMD Window caption somewhere, e.g., an instance Field (it could be a Project settings or anything else you can access at run-time).

```<code>Private cmdWindowTitle As String = "The Window Title"
</code>```

→ FindWindowEx is more useful if you know exactly what the Window title is and it doesn't change over time.

→ Process.GetProcessesByName() can be used to find a Window using the Process name and then verify whether the Process.MainWindowTitle.Contains() at least a partial known string.

If instead the Console Window belongs to the current Process, you just need:

```<code>Process.GetCurrentProcess().MainWindowHandle
</code>```

```<code>' -- If the Console Window belongs to the current Process: --
Dim cmdWindowHandle = Process.GetCurrentProcess().MainWindowHandle
' -----------------------------------------------------------

' -- Find it when the exact Window title is known: --
Dim cmdWindowHandle As IntPtr = NativeMethods.GetCmdWindowByCaption(cmdWindowTitle)
' -----------------------------------------------------------

' -- Find it when only a partial caption is available: --
Dim cmdWindowHandle As IntPtr = IntPtr.Zero
Dim cmdProc = Process.GetProcessesByName("cmd").
    FirstOrDefault(Function(p) p.MainWindowTitle.Contains(cmdWindowTitle))
If cmdProc IsNot Nothing Then
    cmdWindowHandle = cmdProc.MainWindowHandle
End If
' -----------------------------------------------------------

' Choose one of the above, then, in any case:
If cmdWindowHanle <> IntPtr.Zero Then
    NativeMethods.WindowDisableSysMenu(cmdWindowHandle)
End If
</code>```

Note: Here, I'm assuming the Process Name is cmd and the Window class name is ConsoleWindowClass. It may not be. Change these as required.

Since now the Window has no SystemMenu or Close buttons (we just hid them all), it cannot be closed using ALT+F4 or any other means except using the Task Manager (or wait for it to close naturally).

To close it from your app, send a WM_CLOSE message:

```<code>' -- find the Window as described before --
Dim cmdWindowHandle As IntPtr = NativeMethods.GetCmdWindowByCaption(cmdWindowTitle)
If Not cmdWindowHandle.Equals(IntPtr.Zero) Then
    NativeMethods.SendCloseMessage(cmdWindowHandle)
End If
</code>```

NativeMethods declarations:

```<code>Public Class NativeMethods

    Private Const WM_CLOSE As Integer = &H10

    Public Enum WinStyles As UInteger
        WS_MAXIMIZE = &H1000000
        WS_MAXIMIZEBOX = &H10000
        WS_MINIMIZE = &H20000000
        WS_MINIMIZEBOX = &H20000
        WS_SYSMENU = &H80000
    End Enum

    Public Enum GWL_Flags As Integer
        GWL_STYLE = -16
        GWL_EXSTYLE = -20
    End Enum

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function SendMessage(hWnd As IntPtr, uMsg As WinMessage, wParam As Integer, lParam As Integer) As Integer
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function FindWindowEx(hwndParent As IntPtr, hwndChildAfter As IntPtr, lpszClass As String, lpszWindow As String) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function GetWindowLong(hWnd As IntPtr, nIndex As GWL_Flags) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function SetWindowLong(hWnd As IntPtr, nIndex As GWL_Flags, dwNewLong As IntPtr) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function GetWindowLongPtr(hWnd As IntPtr, nIndex As GWL_Flags) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function SetWindowLongPtr(hWnd As IntPtr, nIndex As GWL_Flags, dwNewLong As IntPtr) As IntPtr
    End Function

    ' Public wrappers
    Public Shared Function GetWindowLongUni(hWnd As IntPtr, nIndex As GWL_Flags) As Integer
        If IntPtr.Size = 8 Then
            Return GetWindowLongPtr(hWnd, nIndex).ToInt32()
        Else
            Return GetWindowLong(hWnd, nIndex).ToInt32()
        End If
    End Function

    Public Shared Function SetWindowLongUni(hWnd As IntPtr, nIndex As GWL_Flags, dwNewLong As Integer) As Integer
        If IntPtr.Size = 8 Then
            Return SetWindowLongPtr(hWnd, nIndex, New IntPtr(dwNewLong)).ToInt32()
        Else
            Return SetWindowLong(hWnd, nIndex, New IntPtr(dwNewLong)).ToInt32()
        End If
    End Function

    Public Shared Function GetCmdWindowByCaption(cmdCaption As String) As IntPtr
        Return FindWindowEx(IntPtr.Zero, IntPtr.Zero, "ConsoleWindowClass", cmdCaption)
    End Function

    Public Shared Sub WindowDisableSysMenu(windowHandle As IntPtr)
        Dim styles As Integer = GetWindowLongUni(windowHandle, GWL_Flags.GWL_STYLE)
        styles = styles And Not CInt(WinStyles.WS_SYSMENU)
        SetWindowLongUni(windowHandle, GWL_Flags.GWL_STYLE, styles)
    End Sub

    Public Shared Sub SendCloseMessage(windowHandle As IntPtr)
        SendMessage(windowHandle, WM_CLOSE, 0, 0)
    End Sub
End Class
</code>```

Body:
To interact with a foreign Window, you need to find it/verify it exists first.

We have different methods to find a Window. Here I'm considering FindWindowEx and Process.GetProcessesByName().
UI Automation and EnumWindows provide other options, eventually.

Store the CMD Window caption somewhere, e.g., an instance Field (it could be a Project settings or anything else you can access at run-time).

Private cmdWindowTitle As String = "The Window Title"

→ FindWindowEx is more useful if you know exactly what the Window title is and it doesn't change over time.

→ Process.GetProcessesByName() can be used to find a Window using the Process name and then verify whether the Process.MainWindowTitle.Contains() at least a partial known string.

If instead the Console Window belongs to the current Process, you just need:

Process.GetCurrentProcess().MainWindowHandle

' -- If the Console Window belongs to the current Process: --
Dim cmdWindowHandle = Process.GetCurrentProcess().MainWindowHandle
' -----------------------------------------------------------

' -- Find it when the exact Window title is known: --
Dim cmdWindowHandle As IntPtr = NativeMethods.GetCmdWindowByCaption(cmdWindowTitle)
' -----------------------------------------------------------

' -- Find it when only a partial caption is available: --
Dim cmdWindowHandle As IntPtr = IntPtr.Zero
Dim cmdProc = Process.GetProcessesByName("cmd").
    FirstOrDefault(Function(p) p.MainWindowTitle.Contains(cmdWindowTitle))
If cmdProc IsNot Nothing Then
    cmdWindowHandle = cmdProc.MainWindowHandle
End If
' -----------------------------------------------------------

' Choose one of the above, then, in any case:
If cmdWindowHanle <> IntPtr.Zero Then
    NativeMethods.WindowDisableSysMenu(cmdWindowHandle)
End If

Note: Here, I'm assuming the Process Name is cmd and the Window class name is ConsoleWindowClass. It may not be. Change these as required.

Since now the Window has no SystemMenu or Close buttons (we just hid them all), it cannot be closed using ALT+F4 or any other means except using the Task Manager (or wait for it to close naturally).

To close it from your app, send a WM_CLOSE message:

' -- find the Window as described before --
Dim cmdWindowHandle As IntPtr = NativeMethods.GetCmdWindowByCaption(cmdWindowTitle)
If Not cmdWindowHandle.Equals(IntPtr.Zero) Then
    NativeMethods.SendCloseMessage(cmdWindowHandle)
End If

NativeMethods declarations:

Public Class NativeMethods

    Private Const WM_CLOSE As Integer = &H10

    Public Enum WinStyles As UInteger
        WS_MAXIMIZE = &H1000000
        WS_MAXIMIZEBOX = &H10000
        WS_MINIMIZE = &H20000000
        WS_MINIMIZEBOX = &H20000
        WS_SYSMENU = &H80000
    End Enum

    Public Enum GWL_Flags As Integer
        GWL_STYLE = -16
        GWL_EXSTYLE = -20
    End Enum

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function SendMessage(hWnd As IntPtr, uMsg As WinMessage, wParam As Integer, lParam As Integer) As Integer
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function FindWindowEx(hwndParent As IntPtr, hwndChildAfter As IntPtr, lpszClass As String, lpszWindow As String) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function GetWindowLong(hWnd As IntPtr, nIndex As GWL_Flags) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function SetWindowLong(hWnd As IntPtr, nIndex As GWL_Flags, dwNewLong As IntPtr) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function GetWindowLongPtr(hWnd As IntPtr, nIndex As GWL_Flags) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function SetWindowLongPtr(hWnd As IntPtr, nIndex As GWL_Flags, dwNewLong As IntPtr) As IntPtr
    End Function

    ' Public wrappers
    Public Shared Function GetWindowLongUni(hWnd As IntPtr, nIndex As GWL_Flags) As Integer
        If IntPtr.Size = 8 Then
            Return GetWindowLongPtr(hWnd, nIndex).ToInt32()
        Else
            Return GetWindowLong(hWnd, nIndex).ToInt32()
        End If
    End Function

    Public Shared Function SetWindowLongUni(hWnd As IntPtr, nIndex As GWL_Flags, dwNewLong As Integer) As Integer
        If IntPtr.Size = 8 Then
            Return SetWindowLongPtr(hWnd, nIndex, New IntPtr(dwNewLong)).ToInt32()
        Else
            Return SetWindowLong(hWnd, nIndex, New IntPtr(dwNewLong)).ToInt32()
        End If
    End Function

    Public Shared Function GetCmdWindowByCaption(cmdCaption As String) As IntPtr
        Return FindWindowEx(IntPtr.Zero, IntPtr.Zero, "ConsoleWindowClass", cmdCaption)
    End Function

    Public Shared Sub WindowDisableSysMenu(windowHandle As IntPtr)
        Dim styles As Integer = GetWindowLongUni(windowHandle, GWL_Flags.GWL_STYLE)
        styles = styles And Not CInt(WinStyles.WS_SYSMENU)
        SetWindowLongUni(windowHandle, GWL_Flags.GWL_STYLE, styles)
    End Sub

    Public Shared Sub SendCloseMessage(windowHandle As IntPtr)
        SendMessage(windowHandle, WM_CLOSE, 0, 0)
    End Sub
End Class


问:
Learning Python: RuntimeError: wrapped C/C++ object of type StaticBitmap has been deleted
I'm currently learning to program with Python, I got this example code for a simple image viewer (see below), which produces the following error message when I close the app, run it again and open any directory to browse the images in it:

```<code>   File "...\image_viewer4.py", line 103, in update_photo
     self.image_ctrl.SetBitmap(wx.Bitmap(img))

 RuntimeError: wrapped C/C++ object of type StaticBitmap has been
 deleted.
</code>```

This happens every time unless I restart the kernel in Spyder.
I already read through PyQt: RuntimeError: wrapped C/C++ object has been deleted, Understanding the “underlying C/C++ object has been deleted” error, and Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?, but I don't understand what causes the error in the code example above. I mean, the error states that the bitmap object is deleted but i have no clue as to how or why.

I appreciate any productive help anyone can give me. I'd like to understand what exactly causes the error in the code and how to avoid it.

Here is the code:

```<code>import glob
import os
import wx
from pubsub import pub

class ImagePanel(wx.Panel):

    def __init__(self, parent):
        super().__init__(parent)

        disW, disH = wx.DisplaySize()
        self.max_size = 800
        self.photos = []
        self.current_photo = 0
        self.total_photos = 0
        self.layout()

        pub.subscribe(self.update_photos_via_pubsub, "update")

    def layout(self):
        """
        Layout the widgets on the panel
        """

        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)

        img = wx.Image(self.max_size, self.max_size)
        self.image_ctrl = wx.StaticBitmap(self, wx.ID_ANY,
                                             wx.Bitmap(img))
        self.main_sizer.Add(self.image_ctrl, 0, wx.ALL|wx.CENTER, 5)
        self.image_label = wx.StaticText(self, label="")
        self.main_sizer.Add(self.image_label, 0, wx.ALL|wx.CENTER, 5)

        btn_data = [("Previous", btn_sizer, self.on_previous),
                    ("Next", btn_sizer, self.on_next)]
        for data in btn_data:
            label, sizer, handler = data
            self.btn_builder(label, sizer, handler)

        self.main_sizer.Add(btn_sizer, 0, wx.CENTER)
        self.SetSizer(self.main_sizer)

    def btn_builder(self, label, sizer, handler):
        """
        Builds a button, binds it to an event handler and adds it to a sizer
        """
        btn = wx.Button(self, label=label)
        btn.Bind(wx.EVT_BUTTON, handler)
        sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)

    def on_next(self, event):
        """
        Loads the next picture in the directory
        """
        if not self.photos:
            return

        if self.current_photo == self.total_photos - 1:
            self.current_photo = 0
        else:
            self.current_photo += 1
        self.update_photo(self.photos[self.current_photo])

    def on_previous(self, event):
        """
        Displays the previous picture in the directory
        """
        if not self.photos:
            return

        if self.current_photo == 0:
            self.current_photo = self.total_photos - 1
        else:
            self.current_photo -= 1
        self.update_photo(self.photos[self.current_photo])

    def update_photos_via_pubsub(self, photos):
        self.photos = photos
        self.total_photos = len(self.photos)
        self.update_photo(self.photos[0])
        self.current_photo = 0

    def update_photo(self, image):
        """
        Update the currently shown photo
        """
        img = wx.Image(image, wx.BITMAP_TYPE_ANY)
        # scale the image, preserving the aspect ratio
        W = img.GetWidth()
        H = img.GetHeight()
        if W > H:
            NewW = self.max_size
            NewH = self.max_size * H / W
        else:
            NewH = self.max_size
            NewW = self.max_size * W / H
        img = img.Scale(NewW, NewH)

        self.image_ctrl.SetBitmap(wx.Bitmap(img))
        self.Refresh()

    def reset(self):
        img = wx.Image(self.max_size,
                       self.max_size)
        bmp = wx.Bitmap(img)
        self.image_ctrl.SetBitmap(bmp)
        self.current_photo = 0
        self.photos = []

class MainFrame(wx.Frame):

    def __init__(self):

        disW, disH = wx.DisplaySize()
        super().__init__(None, title='Image Viewer',
                                        size=(disW-500, disH-100))
        self.panel = ImagePanel(self)

        # create status bar
        self.CreateStatusBar()

        # create the menu bar
        menuBar = wx.MenuBar()

        # create a menu
        fileMenu = wx.Menu()

        openBut = wx.MenuItem(fileMenu, wx.ID_OPEN, '&Open', 'Open Working Directory')
        fileMenu.Append(openBut)

        fileMenu.Bind(wx.EVT_MENU, self.on_open_directory, openBut)

        # add a line separator to the file menu
        fileMenu.AppendSeparator()

        # add a quit button to fileMenu
        quitBut = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit', 'Exit the Programm')
        fileMenu.Append(quitBut)

        # connect the quit button to the actual event of quitting the app
        fileMenu.Bind(wx.EVT_MENU, self.onQuit, quitBut)

        # give the menu a title
        menuBar.Append(fileMenu, "&File")

        # connect the menu bar to the frame
        self.SetMenuBar(menuBar)

        self.create_toolbar()
        self.Show()

    def create_toolbar(self):
        """
        Create a toolbar
        """
        self.toolbar = self.CreateToolBar()
        self.toolbar.SetToolBitmapSize((16,16))

        open_ico = wx.ArtProvider.GetBitmap(
            wx.ART_FILE_OPEN, wx.ART_TOOLBAR, (16,16))
        openTool = self.toolbar.AddTool(
            wx.ID_ANY, "Open", open_ico, "Open an Image Directory")
        self.Bind(wx.EVT_MENU, self.on_open_directory, openTool)

        self.toolbar.Realize()

    def on_open_directory(self, event):
        """
        Open a directory dialog
        """
        with wx.DirDialog(self, "Choose a directory",
                          style=wx.DD_DEFAULT_STYLE) as dlg:
            if dlg.ShowModal() == wx.ID_OK:
                self.folder_path = dlg.GetPath()

                photos = glob.glob(os.path.join(self.folder_path, '*.jpg'))
                if photos:
                    pub.sendMessage("update", photos=photos)
                else:
                    self.panel.reset()

    def onQuit(self, event):
        # get the frame's top level parent and close it
        wx.GetTopLevelParent(self).Destroy()

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = MainFrame()
    app.MainLoop()
</code>```

In case they are needed, here is the traceback:

```<code>  File "...\image_viewer4.py", line 183, in on_open_directory
    pub.sendMessage("update", photos=photos)

  File "C:\Anaconda\lib\site-packages\pubsub\core\publisher.py", line 216, in sendMessage
    topicObj.publish(**msgData)

  File "C:\Anaconda\lib\site-packages\pubsub\core\topicobj.py", line 452, in publish
    self.__sendMessage(msgData, topicObj, msgDataSubset)

  File "C:\Anaconda\lib\site-packages\pubsub\core\topicobj.py", line 482, in __sendMessage
    listener(data, self, allData)

  File "C:\Anaconda\lib\site-packages\pubsub\core\listener.py", line 237, in __call__
    cb(**kwargs)

  File "...\image_viewer4.py", line 84, in update_photos_via_pubsub
    self.update_photo(self.photos[0])
</code>```

答:
It isn't immediately obvious but I notice that you don't cancel your pubsub subscription.

Try:

```<code>def onQuit(self, event):
    # get the frame's top level parent and close it
    pub.unsubscribe(self.panel.update_photos_via_pubsub, "update")
    wx.GetTopLevelParent(self).Destroy()
</code>```

See if that makes a difference.

To ensure that onQuit is also executed when closing the application by using the X in the top right of the frame, use the following (in MainFrame) :

```<code>    self.Bind(wx.EVT_CLOSE, self.onQuit)
</code>```

That should cover all the bases.

Body:
I'm currently learning to program with Python, I got this example code for a simple image viewer (see below), which produces the following error message when I close the app, run it again and open any directory to browse the images in it:

   File "...\image_viewer4.py", line 103, in update_photo
     self.image_ctrl.SetBitmap(wx.Bitmap(img))

 RuntimeError: wrapped C/C++ object of type StaticBitmap has been
 deleted.

This happens every time unless I restart the kernel in Spyder.
I already read through PyQt: RuntimeError: wrapped C/C++ object has been deleted, Understanding the “underlying C/C++ object has been deleted” error, and Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?, but I don't understand what causes the error in the code example above. I mean, the error states that the bitmap object is deleted but i have no clue as to how or why.

I appreciate any productive help anyone can give me. I'd like to understand what exactly causes the error in the code and how to avoid it.

Here is the code:

import glob
import os
import wx
from pubsub import pub

class ImagePanel(wx.Panel):

    def __init__(self, parent):
        super().__init__(parent)

        disW, disH = wx.DisplaySize()
        self.max_size = 800
        self.photos = []
        self.current_photo = 0
        self.total_photos = 0
        self.layout()

        pub.subscribe(self.update_photos_via_pubsub, "update")

    def layout(self):
        """
        Layout the widgets on the panel
        """

        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)

        img = wx.Image(self.max_size, self.max_size)
        self.image_ctrl = wx.StaticBitmap(self, wx.ID_ANY,
                                             wx.Bitmap(img))
        self.main_sizer.Add(self.image_ctrl, 0, wx.ALL|wx.CENTER, 5)
        self.image_label = wx.StaticText(self, label="")
        self.main_sizer.Add(self.image_label, 0, wx.ALL|wx.CENTER, 5)

        btn_data = [("Previous", btn_sizer, self.on_previous),
                    ("Next", btn_sizer, self.on_next)]
        for data in btn_data:
            label, sizer, handler = data
            self.btn_builder(label, sizer, handler)

        self.main_sizer.Add(btn_sizer, 0, wx.CENTER)
        self.SetSizer(self.main_sizer)

    def btn_builder(self, label, sizer, handler):
        """
        Builds a button, binds it to an event handler and adds it to a sizer
        """
        btn = wx.Button(self, label=label)
        btn.Bind(wx.EVT_BUTTON, handler)
        sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)

    def on_next(self, event):
        """
        Loads the next picture in the directory
        """
        if not self.photos:
            return

        if self.current_photo == self.total_photos - 1:
            self.current_photo = 0
        else:
            self.current_photo += 1
        self.update_photo(self.photos[self.current_photo])

    def on_previous(self, event):
        """
        Displays the previous picture in the directory
        """
        if not self.photos:
            return

        if self.current_photo == 0:
            self.current_photo = self.total_photos - 1
        else:
            self.current_photo -= 1
        self.update_photo(self.photos[self.current_photo])

    def update_photos_via_pubsub(self, photos):
        self.photos = photos
        self.total_photos = len(self.photos)
        self.update_photo(self.photos[0])
        self.current_photo = 0

    def update_photo(self, image):
        """
        Update the currently shown photo
        """
        img = wx.Image(image, wx.BITMAP_TYPE_ANY)
        # scale the image, preserving the aspect ratio
        W = img.GetWidth()
        H = img.GetHeight()
        if W > H:
            NewW = self.max_size
            NewH = self.max_size * H / W
        else:
            NewH = self.max_size
            NewW = self.max_size * W / H
        img = img.Scale(NewW, NewH)

        self.image_ctrl.SetBitmap(wx.Bitmap(img))
        self.Refresh()

    def reset(self):
        img = wx.Image(self.max_size,
                       self.max_size)
        bmp = wx.Bitmap(img)
        self.image_ctrl.SetBitmap(bmp)
        self.current_photo = 0
        self.photos = []

class MainFrame(wx.Frame):

    def __init__(self):

        disW, disH = wx.DisplaySize()
        super().__init__(None, title='Image Viewer',
                                        size=(disW-500, disH-100))
        self.panel = ImagePanel(self)

        # create status bar
        self.CreateStatusBar()

        # create the menu bar
        menuBar = wx.MenuBar()

        # create a menu
        fileMenu = wx.Menu()

        openBut = wx.MenuItem(fileMenu, wx.ID_OPEN, '&Open', 'Open Working Directory')
        fileMenu.Append(openBut)

        fileMenu.Bind(wx.EVT_MENU, self.on_open_directory, openBut)

        # add a line separator to the file menu
        fileMenu.AppendSeparator()

        # add a quit button to fileMenu
        quitBut = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit', 'Exit the Programm')
        fileMenu.Append(quitBut)

        # connect the quit button to the actual event of quitting the app
        fileMenu.Bind(wx.EVT_MENU, self.onQuit, quitBut)

        # give the menu a title
        menuBar.Append(fileMenu, "&File")

        # connect the menu bar to the frame
        self.SetMenuBar(menuBar)

        self.create_toolbar()
        self.Show()

    def create_toolbar(self):
        """
        Create a toolbar
        """
        self.toolbar = self.CreateToolBar()
        self.toolbar.SetToolBitmapSize((16,16))

        open_ico = wx.ArtProvider.GetBitmap(
            wx.ART_FILE_OPEN, wx.ART_TOOLBAR, (16,16))
        openTool = self.toolbar.AddTool(
            wx.ID_ANY, "Open", open_ico, "Open an Image Directory")
        self.Bind(wx.EVT_MENU, self.on_open_directory, openTool)

        self.toolbar.Realize()

    def on_open_directory(self, event):
        """
        Open a directory dialog
        """
        with wx.DirDialog(self, "Choose a directory",
                          style=wx.DD_DEFAULT_STYLE) as dlg:
            if dlg.ShowModal() == wx.ID_OK:
                self.folder_path = dlg.GetPath()

                photos = glob.glob(os.path.join(self.folder_path, '*.jpg'))
                if photos:
                    pub.sendMessage("update", photos=photos)
                else:
                    self.panel.reset()

    def onQuit(self, event):
        # get the frame's top level parent and close it
        wx.GetTopLevelParent(self).Destroy()

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = MainFrame()
    app.MainLoop()

In case they are needed, here is the traceback:

  File "...\image_viewer4.py", line 183, in on_open_directory
    pub.sendMessage("update", photos=photos)

  File "C:\Anaconda\lib\site-packages\pubsub\core\publisher.py", line 216, in sendMessage
    topicObj.publish(**msgData)

  File "C:\Anaconda\lib\site-packages\pubsub\core\topicobj.py", line 452, in publish
    self.__sendMessage(msgData, topicObj, msgDataSubset)

  File "C:\Anaconda\lib\site-packages\pubsub\core\topicobj.py", line 482, in __sendMessage
    listener(data, self, allData)

  File "C:\Anaconda\lib\site-packages\pubsub\core\listener.py", line 237, in __call__
    cb(**kwargs)

  File "...\image_viewer4.py", line 84, in update_photos_via_pubsub
    self.update_photo(self.photos[0])

Body:
It isn't immediately obvious but I notice that you don't cancel your pubsub subscription.

Try:

def onQuit(self, event):
    # get the frame's top level parent and close it
    pub.unsubscribe(self.panel.update_photos_via_pubsub, "update")
    wx.GetTopLevelParent(self).Destroy()

See if that makes a difference.

To ensure that onQuit is also executed when closing the application by using the X in the top right of the frame, use the following (in MainFrame) :

    self.Bind(wx.EVT_CLOSE, self.onQuit)

That should cover all the bases.


问:
I have a Turkish character problem when I use innerHTML in js
This is the result when I enter a Turkish character in span with innerHTML.The result is like this, "�r�n Favorilere Eklendi"</p>

```<code><a href="javascript:;" onclick="Main.AddRemoveFavorite(this)" id="true" data-favoriteid="@Model.product.FavoriteId">
<i id="icon" style="font-size:1.2rem; color:#798499;" class="icon-star"></i>
<span id="text" style="font-size:1rem; font-weight:400; color:#798499;cursor:pointer;">Ürünü Favorilerime Ekle</span>
</a>
</code>```

```<code>document.getElementById("icon").className = "icon-star_alt"
document.getElementById("text").innerHTML = 'Ürün Favorilere Eklendi';
$(btn).data('favoriteid', data)
</code>```

答: The problem was solved by converting the file to utf-8.</p>

Body:
This is the result when I enter a Turkish character in span with innerHTML.The result is like this, "�r�n Favorilere Eklendi"

Ürünü Favorilerime Ekle

document.getElementById("icon").className = "icon-star_alt"
document.getElementById("text").innerHTML = 'Ürün Favorilere Eklendi';
$(btn).data('favoriteid', data)


问:
SQL Server database not updating after using |DataDirectory| in C# Windows Form project
I've made connection string in app.config and used it whenever I needed to make a SQL connection using this code:

```<code>static string connectionString = ConfigurationManager.ConnectionStrings["name"].ConnectionString;
</code>```

It works perfectly if I use full path to the database but I want to make it universal (so I could install my application on any other PC) and I used |DataDirectory| like this:

```<code>connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Biblioteka.mdf;Integrated Security=True"
</code>```

After using |DataDirectory|, I can access the database (I'm not getting any errors while debugging) through my app but I cannot update it, delete records from tables etc...

Is there a way I can keep using app.config for connection string and making it universal at the same time?

答:
|DataDirectory| can resolve to many different things depending on your application and how it is installed, but typically it is a read-only folder shared among all users which you should not change. Moreover, repairing or uninstalling your app will typically overwrite or erase |DataDirectory|, so even if you could update it your updates would soon be deleted.

|DataDirectory| is a good location for data which must not change, or for a source or seed database for your applications. If you want users to update data, you should copy the data from |DataDirectory| to the user data folder, that location is writeable and does not get overwritten or deleted, then make all user changes to the copy.

For more information read How do I update |DataDirectory|.

Body:
I've made connection string in app.config and used it whenever I needed to make a SQL connection using this code:

static string connectionString = ConfigurationManager.ConnectionStrings["name"].ConnectionString;

It works perfectly if I use full path to the database but I want to make it universal (so I could install my application on any other PC) and I used |DataDirectory| like this:

connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Biblioteka.mdf;Integrated Security=True"

After using |DataDirectory|, I can access the database (I'm not getting any errors while debugging) through my app but I cannot update it, delete records from tables etc...

Is there a way I can keep using app.config for connection string and making it universal at the same time?


问:
Stop all Pods in a StatefulSet before scaling it up or down
My team is currently working on migrating a Discord chat bot to Kubernetes. We plan on using a StatefulSet for the main bot service, as each Shard (pod) should only have a single connection to the Gateway. Whenever a shard connects to said Gateway, it tells it its ID (in our case the pod's ordinal index) and how many shards we are running in total (the amount of replicas in the StatefulSet).

Having to tell the gateway the total number of shards means that in order to scale our StatefulSet up or down we'd have to stop all pods in that StatefulSet before starting new ones with the updated value.

How can I achieve that? Preferrably through configuration so I don't have to run a special command each time.

答:
Before any kubectl scale, since you need more control on your nodes, you might consider a kubectl drain first

When you are ready to put the node back into service, use kubectl uncordon, which will make the node schedulable again.

By draining the node where your pods are maanged, you would stop all pods, with the opportunity to scale the statefulset with the new value.

See also "How to Delete Pods from a Kubernetes Node" by Keilan Jackson

Start at least with kubectl cordon <nodename> to mark the node as unschedulable.

If your pods are controlled by a StatefulSet, first make sure that the pod that will be deleted can be safely deleted.

  How you do this depends on the pod and your application’s tolerance for one of the stateful pods to become temporarily unavailable.

For example you might want to demote a MySQL or Redis writer to just a read-only slave, update and release application code to no longer reference the pod in question temporarily, or scale up the ReplicaSet first to handle the extra traffic that may be caused by one pod being unavailable.

Once this is done, delete the pod and wait for its replacement to appear on another node.


问:
Angular shuffle array elements of two ngFor loops
i am try to build Angular project ,  i have tow different API news sources . l want to display the tow API news as randomly like :

element news 1

element news 2

element news 1

element news 2

But what i have in my code below is

element news 1 loop

element news 2 loop

news.ts

```<code> news_one_array:any
 news_tow_array:any

ngOnInit() {

this.news_one()
this.news_tow()
}

async news_one() {
    this.http.get("/nodes/25/iq/0/20/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_one_array = data
        })

  }

  async news_tow() {
    this.http.get("/nodes/25/iq/0/21/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_tow_array = data
        })

  }
</code>```

HTML  :

```<code>// *ngfor news 1

<div *ngFor="let items of news_one_array; let i=index">
<p>{{items.title}}</p>
</div>

// *ngfor news 2
<div *ngFor="let items of news_tow_array; let i=index">
<p>{{items.title}}</p>
</div>
</code>```

output :

答:
Have only one ngFor loop in your template on new array formed below :-

make a new array of both news like :-

```<code>public newArray = [];

    async news_one() {
        this.http.get("/nodes/25/iq/0/20/xlarge")
          .pipe(timeout(5000),
            catchError(err => {
              console.log(err)
              return Observable.throw("Timeout has occurred");
            })).subscribe(data => {

              this.news_one_array = data
              this.newsArray = [...this.news_one_arraynewsArray, ...data];
              //shuffle array here
            })

      }

      async news_tow() {
        this.http.get("/nodes/25/iq/0/21/xlarge")
          .pipe(timeout(5000),
            catchError(err => {
              console.log(err)
              return Observable.throw("Timeout has occurred");
            })).subscribe(data => {

              this.news_tow_array = data
              this.newsArray = [...this.news_one_array];newsArray, ...data];
              //shuffle array here
            })

      }
</code>```

then shuffle this array. To know how to shuffle a array. find method on link below :-

How to randomize (shuffle) a JavaScript array?

Picked up shuffle function from above link :-

```<code>public shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
</code>```

Should be used like

```<code>this.newsArray = this.shuffle(this.newsArray);
</code>```

Body:
i am try to build Angular project ,  i have tow different API news sources . l want to display the tow API news as randomly like :

element news 1

element news 2

element news 1

element news 2

But what i have in my code below is

element news 1 loop

element news 2 loop

news.ts

 news_one_array:any
 news_tow_array:any

ngOnInit() {

this.news_one()
this.news_tow()
}

async news_one() {
    this.http.get("/nodes/25/iq/0/20/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_one_array = data
        })

  }

  async news_tow() {
    this.http.get("/nodes/25/iq/0/21/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_tow_array = data
        })

  }

HTML  :

// *ngfor news 1

{{items.title}}

// *ngfor news 2

{{items.title}}

output :

Body:
Have only one ngFor loop in your template on new array formed below :-

make a new array of both news like :-

public newArray = [];

    async news_one() {
        this.http.get("/nodes/25/iq/0/20/xlarge")
          .pipe(timeout(5000),
            catchError(err => {
              console.log(err)
              return Observable.throw("Timeout has occurred");
            })).subscribe(data => {

              this.news_one_array = data
              this.newsArray = [...this.news_one_arraynewsArray, ...data];
              //shuffle array here
            })

      }

      async news_tow() {
        this.http.get("/nodes/25/iq/0/21/xlarge")
          .pipe(timeout(5000),
            catchError(err => {
              console.log(err)
              return Observable.throw("Timeout has occurred");
            })).subscribe(data => {

              this.news_tow_array = data
              this.newsArray = [...this.news_one_array];newsArray, ...data];
              //shuffle array here
            })

      }

then shuffle this array. To know how to shuffle a array. find method on link below :-

How to randomize (shuffle) a JavaScript array?

Picked up shuffle function from above link :-

public shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

Should be used like

this.newsArray = this.shuffle(this.newsArray);


问:
How to save data to firebase using react native?
I'm using https://github.com/expo-community/expo-firebase-starter as a starter template to build a react native app using firebase.

I am working with the following file in Home.js and want to save data to firebase but am getting an error. The error.

```<code>firebase.database is not a function. (In 'firebase.database(reflection)', 'firebase.database' is undefined)
</code>```

Here is the code I'm using. When someone writes a reflection, I'm trying to save that reflection text along with the user ID.

```<code>import React, {useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Container, Content, Header, Form, Input, Item, Label } from 'native-base';
import { Button } from "react-native-elements";
import { withFirebaseHOC } from "../config/Firebase";
import * as firebase from 'firebase';
import "firebase/database";

function Home({ navigation, firebase }) {

  const [reflection, setReflection] = useState('');
  const[member, setMember] = useState('');

  useEffect(() => {
    try {

      firebase.checkUserAuth(user => {
        if (user) {
          // if the user has previously logged in

          setMember(user);
          console.log(member);

        } else {
          // if the user has previously logged out from the app
          navigation.navigate("Auth");
        }
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  async function postReflection() {

    try {
      await console.log(reflection);
      await console.log(member.email);

    firebase.database(reflection).ref('Posts/').set({
        reflection,
    }).then((data)=>{
        //success callback
        console.log('data ' , data)
    }).catch((error)=>{
        //error callback
        console.log('error ' , error)
    })

    } catch (error) {
      console.log(error);
    }

  }

  async function handleSignout() {
    try {
      await firebase.signOut();
      navigation.navigate("Auth");
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <Container style={styles.container}>

          <Form>
            <Item floatingLabel>
              <Label>Reflection</Label>
              <Input
                autoCapitalize='none'
                autoCorrect={false}
                onChangeText={text => setReflection(text)}
              />
            </Item>

              <Button style = {{ marginTop: 10, marginHorizontal:30 }}
                title="Share"
                rounded
                onPress= {postReflection}
                >
              </Button>
              </Form>

      <Button
        title="Signout"
        onPress={handleSignout}
        titleStyle={{
          color: "#F57C00"
        }}
        type="clear"
      />
    </Container>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // justifyContent: "center"
  }
});

export default withFirebaseHOC(Home);
</code>```

答:
Add the following after import * as firebase from 'firebase';

```<code>import "firebase/database";
</code>```

Each Firebase product has separate APIs that must be added, as described in the documentation.

Body:
I'm using https://github.com/expo-community/expo-firebase-starter as a starter template to build a react native app using firebase.

I am working with the following file in Home.js and want to save data to firebase but am getting an error. The error.

firebase.database is not a function. (In 'firebase.database(reflection)', 'firebase.database' is undefined)

Here is the code I'm using. When someone writes a reflection, I'm trying to save that reflection text along with the user ID.

import React, {useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Container, Content, Header, Form, Input, Item, Label } from 'native-base';
import { Button } from "react-native-elements";
import { withFirebaseHOC } from "../config/Firebase";
import * as firebase from 'firebase';
import "firebase/database";

function Home({ navigation, firebase }) {

  const [reflection, setReflection] = useState('');
  const[member, setMember] = useState('');

  useEffect(() => {
    try {

      firebase.checkUserAuth(user => {
        if (user) {
          // if the user has previously logged in

          setMember(user);
          console.log(member);

        } else {
          // if the user has previously logged out from the app
          navigation.navigate("Auth");
        }
      });
    } catch (error) {
      console.log(error);
    }
  }, []);

  async function postReflection() {

    try {
      await console.log(reflection);
      await console.log(member.email);

    firebase.database(reflection).ref('Posts/').set({
        reflection,
    }).then((data)=>{
        //success callback
        console.log('data ' , data)
    }).catch((error)=>{
        //error callback
        console.log('error ' , error)
    })

    } catch (error) {
      console.log(error);
    }

  }

  async function handleSignout() {
    try {
      await firebase.signOut();
      navigation.navigate("Auth");
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <Container style={styles.container}>

          <Form>
            <Item floatingLabel>
              Reflection
              <Input
                autoCapitalize='none'
                autoCorrect={false}
                onChangeText={text => setReflection(text)}
              />
            </Item>

              <Button style = {{ marginTop: 10, marginHorizontal:30 }}
                title="Share"
                rounded
                onPress= {postReflection}
                >
              </Button>
              </Form>

      <Button
        title="Signout"
        onPress={handleSignout}
        titleStyle={{
          color: "#F57C00"
        }}
        type="clear"
      />
    </Container>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    // justifyContent: "center"
  }
});

export default withFirebaseHOC(Home);

Body:
Add the following after import * as firebase from 'firebase';

import "firebase/database";

Each Firebase product has separate APIs that must be added, as described in the documentation.


问:
Client side showing , hiding is risky
I have a div which contains a button .I am initially setting div display:none & depending upon the user rights i am showing it to user using javascript.

```<code><div id="mydiv" style="display:none">
    <asp:Button id="btn" runat="server"/>
</div>

PageMethods.GetRights(onsuccess);

function onsuccess(result){
   if(result.isaccessible)
   {
      $("#mydiv").show();
   }
}
</code>```

Is Showing,Hiding at client risky. I dont want to use updatepanel if it is risky what is an alternative to this i have?

答: It all depends on y our app structure.  If the data in the hidden div confidential, then by no means setting it's display to none a secure method since the client has full access to all client side data.  But when talking about a button that invokes a back-end behavior, you should also be doing back-end validation on all requests.</p>

Title: Client side showing , hiding is risky

Body:
I have a div which contains a button .I am initially setting div display:none & depending upon the user rights i am showing it to user using javascript.

    <asp:Button id="btn" runat="server"/>

PageMethods.GetRights(onsuccess);

function onsuccess(result){
   if(result.isaccessible)
   {
      $("#mydiv").show();
   }
}

Is Showing,Hiding at client risky. I dont want to use updatepanel if it is risky what is an alternative to this i have?


问:
Difference between different generators, "yield" and returning tuple iteration in a function
What is the proper difference between doing yield i from an iteration and return (i for i in range(10)).

def generator1():
    for i in range(10):
        yield i

def generator2():
    return (i for i in range(10))
```

<p>For example, see these functions <code>generator1()</code> and <code>generator2()</code> both are differently written but both return a generator.</p>

<p><em>Outputs of IDLE:-</em></p>

<pre class="lang-py prettyprint-override"><code>>>> generator1()
>>> <generator object generator1 at 0x107870468>

>>> generator2()
>>> <generator object generator2.<locals>.<genexpr> at 0x107870db0>

>>> import sys

>>> sys.getsizeof(generator1())
>>> 88
>>> sys.getsizeof(generator2())
>>> 88
</code>```

As we can tell generator2() has fewer LOC (line of code) than generator2 and also the size of the object is the same, I've some questions.

What is the difference between both functions?

What does <genexpr> means when printing generator2()?

Which is the more suitable and efficient way of creating a generator?

答:
The difference is where the generator is defined.  generator1 is a special generator function, because it contains a yield statement.  generator functions always return generators.  The generator is defined when you invoke generator1.
 generator2 is a regular function that uses a generator expression to construct a generator, and then returns it.  The generator is defined when the line (i for i in range(10)) is executed. But if you add more logic, generator2 can return anything else, like None.  For example:

```<code>def generator2(do_generator):
    if do_generator:
        return (i for i in range(10))
    else:
        return "I quit"
</code>```

You can't do anything like that with generator1.  It cannot return anything except a generator.

<genexpr> is short for generator expression.  In your case, that's (i for i in range(10)).  Generator expressions are very similar to list comprehensions, but they produce generators rather than lists.

Body:
What is the proper difference between doing yield i from an iteration and return (i for i in range(10)).

def generator1():
    for i in range(10):
        yield i

def generator2():
    return (i for i in range(10))

For example, see these functions generator1() and generator2() both are differently written but both return a generator.

Outputs of IDLE:-

>>> generator1()
>>> <generator object generator1 at 0x107870468>

>>> generator2()
>>> <generator object generator2.<locals>.<genexpr> at 0x107870db0>

>>> import sys

>>> sys.getsizeof(generator1())
>>> 88
>>> sys.getsizeof(generator2())
>>> 88

As we can tell generator2() has fewer LOC (line of code) than generator2 and also the size of the object is the same, I've some questions.

What is the difference between both functions?

What does <genexpr> means when printing generator2()?

Which is the more suitable and efficient way of creating a generator?

Body:
The difference is where the generator is defined.  generator1 is a special generator function, because it contains a yield statement.  generator functions always return generators.  The generator is defined when you invoke generator1.
 generator2 is a regular function that uses a generator expression to construct a generator, and then returns it.  The generator is defined when the line (i for i in range(10)) is executed. But if you add more logic, generator2 can return anything else, like None.  For example:

def generator2(do_generator):
    if do_generator:
        return (i for i in range(10))
    else:
        return "I quit"

You can't do anything like that with generator1.  It cannot return anything except a generator.

<genexpr> is short for generator expression.  In your case, that's (i for i in range(10)).  Generator expressions are very similar to list comprehensions, but they produce generators rather than lists.


问:
programmatic creation of jupyter 4 notebooks?
I would like to programmatically generate some *.ipnb as part of my modeling work, so that i can dump annotated figures and code with markdown annotation to a public git repo. Ideally, I will create a new notebook and publish it every time I run new models.

from this gist, i found a pattern for doing this that involves: from IPython.nbformat import current as nbf

However, IPython.nbformat.current has been deprecated since last spring, and in fact is not present in jupyter/ipython 4.0.1, so this won't work for me.

What's the right pattern for this now?

答:
an updated version for v4

there are probably better versions, this worked for me.

from nbformat import v4 as nbf
import nbformat
from os import path

def make_notebook(outPath: str, description: str):
    nb = nbf.new_notebook()
    code = "1+2"
    cells = [nbf.new_markdown_cell( description), nbf.new_code_cell(code)]
    nb['cells'] = cells

    fname = 'test.ipynb'
    print(nb)
    with open(path.join(outPath,fname), 'w') as _:
        nbformat.write(nb, _)
```


问:
Snowflake "Max LOB size (16777216) exceeded" error when loading data from Parquet
I am looking to load data from S3 into Snowflake.  My files are in Parquet format, and were created by a spark job.  There are 199 parquet files in my folder in S3, each with about 5500 records.  Each parquet file is snappy compressed and is about 485 kb.

I have successfully created a storage integration and staged my data.  However, when I read my data, I get the following message:

```<code>Max LOB size (16777216) exceeded, actual size of parsed column is 19970365
</code>```

I believe I have followed the General File Sizing Recommendations but I have not been able to figure out a solution to this issue, or even a clear description of this error message.

Here is the basics of my SQL query:

```<code>CREATE OR REPLACE TEMPORARY STAGE my_test_stage
            FILE_FORMAT = (TYPE = PARQUET)
            STORAGE_INTEGRATION = MY_STORAGE_INTEGRATION
            URL = 's3://my-bucket/my-folder';

SELECT $1 FROM @my_test_stage(PATTERN => '.*\\.parquet')
</code>```

I seem to be able to read each parquet file individually by changing the URL parameter in the CREATE STAGE query to the full path of the parquet file.  I really don't want to have to iterate through each file to load them.

答: There may be issue with one or more records from your file, try to run copy command with "ON_ERROR" option, to debug whether all the records has similar problem or only few.</p>

Body:
I am looking to load data from S3 into Snowflake.  My files are in Parquet format, and were created by a spark job.  There are 199 parquet files in my folder in S3, each with about 5500 records.  Each parquet file is snappy compressed and is about 485 kb.

I have successfully created a storage integration and staged my data.  However, when I read my data, I get the following message:

Max LOB size (16777216) exceeded, actual size of parsed column is 19970365

I believe I have followed the General File Sizing Recommendations but I have not been able to figure out a solution to this issue, or even a clear description of this error message.

Here is the basics of my SQL query:

CREATE OR REPLACE TEMPORARY STAGE my_test_stage
            FILE_FORMAT = (TYPE = PARQUET)
            STORAGE_INTEGRATION = MY_STORAGE_INTEGRATION
            URL = 's3://my-bucket/my-folder';

SELECT $1 FROM @my_test_stage(PATTERN => '.*\\.parquet')

I seem to be able to read each parquet file individually by changing the URL parameter in the CREATE STAGE query to the full path of the parquet file.  I really don't want to have to iterate through each file to load them.


问:
how do i build gcc on a mac?
I'd like to build the latest version of gcc on a mac. I have the latest xcode but I'm looking for some of the c++0x features that are in more recent versions (the lambda functions, etc).

Are there any good step-by-step tutorials on doing this?

答:
One option is to install MacPorts and install the gcc46 package:

```<code>sudo port install gcc46
</code>```

Another option is to download the source code and build it as follows:

```<code>tar xzvf gcc-4.6.0.tar.gz
cd gcc-4.6.0
./configure
make
</code>```

Note that GCC 4.6.0 requires as prerequisites GMP 4.2+, MPFR 2.3.1+, and MPC 0.8.0+.  If ./configure fails, it's probably because you're missing one of these (though it should give you a helpful error message in any case).

Building will take a while—likely several hours, depending on your hardware.

Title: how do i build gcc on a mac?

Body:
One option is to install MacPorts and install the gcc46 package:

sudo port install gcc46

Another option is to download the source code and build it as follows:

tar xzvf gcc-4.6.0.tar.gz
cd gcc-4.6.0
./configure
make

Note that GCC 4.6.0 requires as prerequisites GMP 4.2+, MPFR 2.3.1+, and MPC 0.8.0+.  If ./configure fails, it's probably because you're missing one of these (though it should give you a helpful error message in any case).

Building will take a while—likely several hours, depending on your hardware.


问:
Vue.js and input's value that is never displayed
I'm making a simple shopping list app in Vue.js and I was curious if there's a standard way of doing what I need to do. I have a list of items with add and delete buttons:

const app = new Vue({
    el: '#app',
    data: {
        items: [
            'Chocolate',
            'Pizza',
            'Coca-Cola',
        ],
        newItem: ''
    },
    template: `

{{ items.length }} item{{ items.length !== 1 ? 's' : '' }}

                    {{ item }}
                    <button @click="deleteItem(index)">X</button>

                    <input type="text" v-model="newItem" placeholder="Item name">
                    <button @click="addItem">+</button>

    `,
    methods: {
        addItem() {
            const item = this.newItem.trim();
            if (item === '') return;
            this.items.push(item);
            this.newItem = '';
        },
        deleteItem(index) {
            this.items.splice(index, 1);
        }
    }
});

```

<p>It works just as it should, but I'm not sure about using data entry that is never displayed anywhere. There's also another approach with <code>$refs</code>:</p>

<pre class="lang-js prettyprint-override"><code>const app = new Vue({
    el: '#app',
    data: {
        items: [
            'Chocolate',
            'Pizza',
            'Coca-Cola',
        ],
    },
    template: `
        <div>
            <div>{{ items.length }} item{{ items.length !== 1 ? 's' : '' }}</div>
            <ul>
                <li v-for="(item, index) of items">
                    {{ item }}
                    <button @click="deleteItem(index)">X</button>
                </li>
                <li>
                    <input type="text" placeholder="Item name" ref="newItem">
                    <button @click="addItem($refs.newItem.value)">+</button>
                </li>
            </ul>
        </div>
    `,
    methods: {
        addItem(item) {
            item = item.trim();
            if (item === '') return;
            this.items.push(item);
            this.$refs.newItem.value = '';
        },
        deleteItem(index) {
            this.items.splice(index, 1);
        }
    }
});
</code>```

Instead of using separate data entry and v-model, I'm using $refs directly. Is any of these approaches more widely accepted in Vue.js community or guidelines? Or perhaps there's even more popular way?

答:
I just wanted to share my views here. Personally I like to use v-model as it provides few added benefits like:

We can use .trim modifier with v-model which automatically trims whitespace from user input like:

```<code>  <input v-model.trim="msg">
</code>```

This way you don't need to write additional code to trim text like item = item.trim();. Few lines of code saved here.

Using this.newItem = '' we can easily clear out the previously entered text after button click using v-model reactivity feature. So, again less line of code instead of doing this.$refs.newItem.value = '';

Another advantage of using v-model is that, instead of doing

```<code>  <button @click="addItem($refs.newItem.value)">
</code>```

You can simply call the function like:

```<code>    <button @click="addItem">
</code>```

So, you can see these are the few benefits of using a simple v-model, which is mostly related to the developer experience (DX) point of view.

Working Demo:

const app = new Vue({
    el: '#app',
    data: {
        items: [
            'Chocolate',
            'Pizza',
            'Coca-Cola',
        ],
        newItem: ''
    },
    template: `

{{ items.length }} item{{ items.length !== 1 ? 's' : '' }}

                    {{ item }}
                    <button @click="deleteItem(index)">X</button>

                    <input type="text" placeholder="Item name" v-model.trim="newItem">
                    <button @click="addItem">+</button>

    `,
    methods: {
        addItem() {
            if (this.newItem === '') return;
            this.items.push(this.newItem);
            this.newItem = '';
        },
        deleteItem(index) {
            this.items.splice(index, 1);
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
</div></code>```

Body:
I'm making a simple shopping list app in Vue.js and I was curious if there's a standard way of doing what I need to do. I have a list of items with add and delete buttons:

const app = new Vue({
    el: '#app',
    data: {
        items: [
            'Chocolate',
            'Pizza',
            'Coca-Cola',
        ],
        newItem: ''
    },
    template: `

{{ items.length }} item{{ items.length !== 1 ? 's' : '' }}

                    {{ item }}
                    <button @click="deleteItem(index)">X</button>

                    <input type="text" v-model="newItem" placeholder="Item name">
                    <button @click="addItem">+</button>

    `,
    methods: {
        addItem() {
            const item = this.newItem.trim();
            if (item === '') return;
            this.items.push(item);
            this.newItem = '';
        },
        deleteItem(index) {
            this.items.splice(index, 1);
        }
    }
});

It works just as it should, but I'm not sure about using data entry that is never displayed anywhere. There's also another approach with $refs:

const app = new Vue({
    el: '#app',
    data: {
        items: [
            'Chocolate',
            'Pizza',
            'Coca-Cola',
        ],
    },
    template: `

{{ items.length }} item{{ items.length !== 1 ? 's' : '' }}

                    {{ item }}
                    <button @click="deleteItem(index)">X</button>

                    <input type="text" placeholder="Item name" ref="newItem">
                    <button @click="addItem($refs.newItem.value)">+</button>

    `,
    methods: {
        addItem(item) {
            item = item.trim();
            if (item === '') return;
            this.items.push(item);
            this.$refs.newItem.value = '';
        },
        deleteItem(index) {
            this.items.splice(index, 1);
        }
    }
});

Instead of using separate data entry and v-model, I'm using $refs directly. Is any of these approaches more widely accepted in Vue.js community or guidelines? Or perhaps there's even more popular way?

Body:
I just wanted to share my views here. Personally I like to use v-model as it provides few added benefits like:

We can use .trim modifier with v-model which automatically trims whitespace from user input like:

  <input v-model.trim="msg">

This way you don't need to write additional code to trim text like item = item.trim();. Few lines of code saved here.

Using this.newItem = '' we can easily clear out the previously entered text after button click using v-model reactivity feature. So, again less line of code instead of doing this.$refs.newItem.value = '';

Another advantage of using v-model is that, instead of doing

  <button @click="addItem($refs.newItem.value)">

You can simply call the function like:

    <button @click="addItem">

So, you can see these are the few benefits of using a simple v-model, which is mostly related to the developer experience (DX) point of view.

Working Demo:

const app = new Vue({
    el: '#app',
    data: {
        items: [
            'Chocolate',
            'Pizza',
            'Coca-Cola',
        ],
        newItem: ''
    },
    template: `
        <div>
            <div>{{ items.length }} item{{ items.length !== 1 ? 's' : '' }}</div>
            <ul>
                <li v-for="(item, index) of items">
                    {{ item }}
                    <button @click="deleteItem(index)">X</button>
                </li>
                <li>
                    <input type="text" placeholder="Item name" v-model.trim="newItem">
                    <button @click="addItem">+</button>
                </li>
            </ul>
        </div>
    `,
    methods: {
        addItem() {
            if (this.newItem === '') return;
            this.items.push(this.newItem);
            this.newItem = '';
        },
        deleteItem(index) {
            this.items.splice(index, 1);
        }
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
</div>


问:
What is the Oracle equivalent of SQL Server credential
Environment : Oracle 12C

In SQL Server, a credential is a record that contains the authentication information (credentials) required to connect to a resource outside SQL Server. This information is used internally by SQL Server. Most credentials contain a Windows user name and password.Here is Microsoft doc about Credentials in SQL Server .In SQL Server, the default is to use the service account credentials to access the resource outside SQL Server.
What is the SQL Server credential equivalent in Oracle ?

答:
There is no direct equivalence as it depends on the resource.

For database links (which are equivalent to SQL Server linked servers), credentials are not stored as a separate object but are considered as part of the database link itself.

For local external jobs, remote external jobs, and remote database used by DBMS_SCHEDULER jobs, you need to use DBMS_CREDENTIAL.CREATE_CREDENTIAL procedure. External procedures are also using DBMS_CREDENTIAL.CREATE_CREDENTIAL.

The view DBA_CREDENTIALS can be used for DBMS_SCHEDULER jobs and external procedures but not for database links.

There may be other resources that are using credentials in a different way.


问:
Bash linux loop throu file and send email
I have a file which have in every row email recipient,header and body .
So the structure is like that:

```<code>receipient|header|body

george@gmail.com,Alertheader,CheckYourData

rafal@gmail.com,GreenLight,GoWithYourProcess
</code>```

I would like to write a script which process every row and send an email to each person with header and body.

Please keep in mind that i am writing it on Informatica ETL tool (if that makes any difference)

So below script is working for sending email to 1 person from file(so file just have 1 email and nothing else),but got stuck on multiple persons and how to loop thru all those values.

```<code>echo "Please check the session log in /ciwetl/SessLogs directory.CIW-SUPPORT TEAM" | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." `cat /filelocation/emailsrc.txt`
</code>```

EDIT:
I have this working with this script :)

```<code>cat 'location/emailsrc.txt' | while IFS=, read -r line line2 || [[ -n $line ]]; do  echo $line2 | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." $line; done
</code>```

But there is another thing i didnt anticipated ....
In a body we can have commas so that would probably ruin my file.I was thinking to change delimiter in file to | .
I tried to change IFS=| but that didnt work out. Any tips ?

答:
So while i posted it i almost immediatly found a solution :</p>

```<code>cat '/location/emailsrc.txt' | while IFS='|', read -r line line2 || [[ -n $line ]]; do  echo $line2 | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." $line; done
</code>```

Body:
I have a file which have in every row email recipient,header and body .
So the structure is like that:

receipient|header|body

george@gmail.com,Alertheader,CheckYourData

rafal@gmail.com,GreenLight,GoWithYourProcess

I would like to write a script which process every row and send an email to each person with header and body.

Please keep in mind that i am writing it on Informatica ETL tool (if that makes any difference)

So below script is working for sending email to 1 person from file(so file just have 1 email and nothing else),but got stuck on multiple persons and how to loop thru all those values.

echo "Please check the session log in /ciwetl/SessLogs directory.CIW-SUPPORT TEAM" | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." `cat /filelocation/emailsrc.txt`

EDIT:
I have this working with this script :)

cat 'location/emailsrc.txt' | while IFS=, read -r line line2 || [[ -n $line ]]; do  echo $line2 | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." $line; done

But there is another thing i didnt anticipated ....
In a body we can have commas so that would probably ruin my file.I was thinking to change delimiter in file to | .
I tried to change IFS=| but that didnt work out. Any tips ?

Body:
So while i posted it i almost immediatly found a solution :

cat '/location/emailsrc.txt' | while IFS='|', read -r line line2 || [[ -n $line ]]; do  echo $line2 | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." $line; done


问:
issue with .get() in tkinter, python 3.7
I am having an issue with my code where the .get() returns "   " when I enter something into the Tkinter entry box. the purpose of the code is to take the entry and store it in a database using sqlite3. I can't put my code on the internet because it is an assignment that will be put through a plagiarism software however I will put an image of the code that isn't working (https://imgur.com/a/BEhOuZO) and if you email me at cyrilthomasalex@gmail.com I will send you the full code. I'm new to stack overflow and I know you guys hate it when it's inconvenient to access the code but please help me I've been stuck on this for over 2 hours!!</p>

答:
What you're looking for is the textvariable option for entry widgets. This allows you to have a variable that is automatically updated to the current entry value.

This short example illustrates this system, obviously you would be using your database instead of simply printing the results to the terminal:

import tkinter as tk

class login_win:
    def __init__(self, master):
        self.master = master

        self.username = tk.StringVar()
        signusername = tk.Entry(self.master, borderwidth=0, textvariable=self.username)
        signusername.grid(row=0, column=0)

        self.password = tk.StringVar()
        signpassword = tk.Entry(self.master, borderwidth=0, textvariable=self.password)
        signpassword.grid(row=1, column=0)

        login_butt = tk.Button(self.master, text="Login", command=self.login)
        login_butt.grid(row=2, column=0)

    def login(self):
        print(self.username.get(), self.password.get())

def main():
    root = tk.Tk()
    login_win(root)
    root.mainloop()

if __name__ == '__main__':
    main()
```

Hope this helps,

If you want to read more about tkinter and its features I would thoroughly recommend checking out effbot

James

Body:
What you're looking for is the textvariable option for entry widgets. This allows you to have a variable that is automatically updated to the current entry value.

This short example illustrates this system, obviously you would be using your database instead of simply printing the results to the terminal:

import tkinter as tk

class login_win:
    def __init__(self, master):
        self.master = master

        self.username = tk.StringVar()
        signusername = tk.Entry(self.master, borderwidth=0, textvariable=self.username)
        signusername.grid(row=0, column=0)

        self.password = tk.StringVar()
        signpassword = tk.Entry(self.master, borderwidth=0, textvariable=self.password)
        signpassword.grid(row=1, column=0)

        login_butt = tk.Button(self.master, text="Login", command=self.login)
        login_butt.grid(row=2, column=0)

    def login(self):
        print(self.username.get(), self.password.get())

def main():
    root = tk.Tk()
    login_win(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Hope this helps,

If you want to read more about tkinter and its features I would thoroughly recommend checking out effbot

James


问:
Implement radio/checkbox logic to custom widgets
I want to create two widgets.
Both displaying a 2 column grid with buttons that can be selected/unselected.
One should have radio logic (single selection) where as the other should have checkbox logic (multiple selection).

This is my android implementation I'm trying to recreate in Flutter:

I tried using a GridView with RadioListTiles, thinking I could replace the RadioButton icon with my own widget while retaining the logic.
I can't see any way to do this.
I also realized GridView in Flutter does not auto wrap it's children, resulting in each radio tile only taking up the first 10% of the entire cell.

This is where I'm at the moment:

```<code>class RadioSelect extends StatefulWidget {
    final QuestionData question;

    RadioSelect({this.question});

    @override
    RadioSelectState createState() => RadioSelectState(question);
}

class RadioSelectState extends State<RadioSelect> {
  RadioSelectState(this._question);

  final QuestionData _question;
  final SliverGridDelegate delegate =
    SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2);
  int _selectedIndex;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: delegate,
      padding: EdgeInsets.all(0),
      itemCount: _question.selectOptions.length,
      itemBuilder: (context, index) {
        return RadioListTile(
          groupValue: _selectedIndex,
          title: Text(_question.selectOptions[index]),
          value: index,
          onChanged: (newIndex) {
           setState(() {
              _selectedIndex = newIndex;
            });
          },
        );
      },
    );
  }
}
</code>```

Resulting in:

I want to follow the most "Fluttery" way possible.
What do you reckon is my best cause of action?

答:
I created this package for this purpose. Go and check this out.
Group radio button plugin

https://github.com/Dineth95/radio_grouped_buttons

```<code>Container(
                padding: EdgeInsets.all(10),
                width: MediaQuery.of(context).size.width,
                height: 160,
                child: CustomRadioButton(
                  buttonLables: buttonList,
                  buttonValues: buttonList,
                  radioButtonValue: (value)=>print(value),
                  horizontal: true,
                  enableShape: true,
                  buttonSpace: 5,
                  buttonColor: Colors.white,
                  selectedColor: Colors.cyan,
                ),
              ),
</code>```

Using this widget you can do anything you want

Body:
I want to create two widgets.
Both displaying a 2 column grid with buttons that can be selected/unselected.
One should have radio logic (single selection) where as the other should have checkbox logic (multiple selection).

This is my android implementation I'm trying to recreate in Flutter:

I tried using a GridView with RadioListTiles, thinking I could replace the RadioButton icon with my own widget while retaining the logic.
I can't see any way to do this.
I also realized GridView in Flutter does not auto wrap it's children, resulting in each radio tile only taking up the first 10% of the entire cell.

This is where I'm at the moment:

class RadioSelect extends StatefulWidget {
    final QuestionData question;

    RadioSelect({this.question});

    @override
    RadioSelectState createState() => RadioSelectState(question);
}

class RadioSelectState extends State<RadioSelect> {
  RadioSelectState(this._question);

  final QuestionData _question;
  final SliverGridDelegate delegate =
    SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2);
  int _selectedIndex;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: delegate,
      padding: EdgeInsets.all(0),
      itemCount: _question.selectOptions.length,
      itemBuilder: (context, index) {
        return RadioListTile(
          groupValue: _selectedIndex,
          title: Text(_question.selectOptions[index]),
          value: index,
          onChanged: (newIndex) {
           setState(() {
              _selectedIndex = newIndex;
            });
          },
        );
      },
    );
  }
}

Resulting in:

I want to follow the most "Fluttery" way possible.
What do you reckon is my best cause of action?

Body:
I created this package for this purpose. Go and check this out.
Group radio button plugin

https://github.com/Dineth95/radio_grouped_buttons

Container(
                padding: EdgeInsets.all(10),
                width: MediaQuery.of(context).size.width,
                height: 160,
                child: CustomRadioButton(
                  buttonLables: buttonList,
                  buttonValues: buttonList,
                  radioButtonValue: (value)=>print(value),
                  horizontal: true,
                  enableShape: true,
                  buttonSpace: 5,
                  buttonColor: Colors.white,
                  selectedColor: Colors.cyan,
                ),
              ),

Using this widget you can do anything you want


问:
What's the correct syntax for if conditional when working with calling components in React + Typescript?
I'm currently trying to display a component and pass in a function as a prop only if one of its state properties is true. However, I'm having trouble with the syntax. Here's what I have:

```<code>render = () => {
return (
  <ParentComponent>

       {if (this.onlyRenderIfTrue) {
          <ChildComponent prop1={this.usefulFunction()}/>
       }}

  </ParentComponent>
);
</code>```

}

The JSX is a bit confusing for me. I know anytime I have to use Javascript I have to put it in {}, but for something a bit more nested like this, it's throwing me off a bit.

答:
You cannot write conditional statement directly in React render hook. You may use && operator or ternary operator however:

```<code>render = () => {
  return (
   <ParentComponent>
   {
      this.onlyRenderIfTrue &&
      <ChildComponent prop1={this.usefulFunction()}/>
   }
   </ParentComponent>
  );
}
</code>```

If you wish to use conditional statement, then you may define a function like:

```<code>const renderComponent = () => {
  if (somethingIsTrue) {
   return <h1>True</h1>
  } else {
   return <p>False</p>
  }
}
</code>```

Now, inside your component render, you can call:

```<code>{renderComponent()}
</code>```

Body:
I'm currently trying to display a component and pass in a function as a prop only if one of its state properties is true. However, I'm having trouble with the syntax. Here's what I have:

render = () => {
return (
  <ParentComponent>

       {if (this.onlyRenderIfTrue) {
          <ChildComponent prop1={this.usefulFunction()}/>
       }}

  </ParentComponent>
);

}

The JSX is a bit confusing for me. I know anytime I have to use Javascript I have to put it in {}, but for something a bit more nested like this, it's throwing me off a bit.

Body:
You cannot write conditional statement directly in React render hook. You may use && operator or ternary operator however:

render = () => {
  return (
   <ParentComponent>
   {
      this.onlyRenderIfTrue &&
      <ChildComponent prop1={this.usefulFunction()}/>
   }
   </ParentComponent>
  );
}

If you wish to use conditional statement, then you may define a function like:

const renderComponent = () => {
  if (somethingIsTrue) {
   return <h1>True</h1>
  } else {
   return <p>False</p>
  }
}

Now, inside your component render, you can call:

{renderComponent()}