text:
Q: Re-organize json-format with python I want the output to be easily readable by all people in Json format. Right now the output is a big long string of data. The goal is to be able to see the data at a glance. So in the original format of JSON.
Wanted output (example)
[
 {
  "Employee ID": 1,
  "Name": "Abhishek",
  "Designation": "Software Engineer"
 },
 {
  "Employee ID": 2,
  "Name": "Garima",
  "Designation": "Email Marketing Specialist"
 }
]
[
   {
      "Employee ID": 1,
      "Name": "Abhishek",
      "Designation": "Software Engineer"
   },
   {
      "Employee ID": 2,
      "Name": "Garima",
      "Designation": "Email Marketing Specialist"
   }
]

Python main code:
if __name__ == "__main__":
    print("Start-up")
    api = APIClient(AMV_TOKEN, AMV_IP2)
    print(api.batch.get())
    print("Done")

Output:
Start-up
{'count': 8, 'next': None, 'previous': None, 'results': [{'url': 'http://192.168.0.18/api/batch/bmw_problem/', 'created': '2021-05-11T16:56:04.944370+02:00', 'modified': '2021-05-11T16:56:04.944384+02:00', 'id': 'bmw_problem', 'title': 'bmw_problem', 'archived': False, 'view': None, 'query': 'tray=bmw_problem', 'summary':
{'prints': 11, 'assigned': 11, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '677d2328-6276-4206-9a69-2f6b10fd67ea', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_set_3/', 'created': '2021-03-22T12:37:51.240377+01:00', 'modified': '2021-04-12T12:27:07.124319+02:00', 'id': 'demo_set_3', 'title': 'demo_set_3', 'archived': False, 'view': 'by_tray', 'query': 'tray=demo_set_3', 'summary': {'prints': 318, 'assigned': 0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': False}, 'has_bin_assignments': False, 'active_scan_session': None, 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_all/', 'created': '2021-03-04T11:52:05.236265+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'demo_all', 'title': 'All demo parts', 'archived': False, 'view': 'by_tray', 'query': 'tray__istartswith=demo_set_', 'summary': {'prints': 1252, 'assigned': 218, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '50d5119e-57ef-4577-b0b4-090839f27f0d', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/priority/', 'created': '2021-03-04T11:50:06.446579+01:00', 'modified': '2021-03-22T13:09:14.910389+01:00', 'id': 'priority', 'title': 'Priority Prints', 'archived': False, 'view': None, 'query':
'flags__contains=PRIORITY', 'summary': {'prints': 434, 'assigned': 0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '15403217-a468-498e-b150-b900a16cd5cc', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/MJF/', 'created': '2021-03-04T11:50:06.446557+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'MJF', 'title': 'MJF Prints', 'archived': False, 'view': 'by_tech', 'query': 'technology=MJF', 'summary': {'prints': 138, 'assigned': 0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': False, 'active_scan_session': '81f0ffdd-1e82-4e42-b8fb-89a661b03924', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/SLS/', 'created': '2021-03-04T11:50:06.446534+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'SLS', 'title': 'SLS Prints', 'archived': False, 'view': 'by_tech', 'query': 'technology=SLS', 'summary': {'prints': 1114, 'assigned': 1, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '99b3a0a3-05f6-4225-bbe6-9814a31dca80', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_set_2/', 'created': '2021-03-04T11:50:06.446508+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'demo_set_2', 'title': 'demo_set_2', 'archived': False, 'view': 'by_tray', 'query': 'tray=demo_set_2', 'summary': {'prints': 323, 'assigned': 22, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': True}, 'has_bin_assignments': True, 'active_scan_session': '82e8e71a-0c1f-41c5-b021-bd399eb2d6b3', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_set_1/', 'created': '2021-03-04T11:50:06.446461+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'demo_set_1', 'title': 'demo_set_1', 'archived': False, 'view': 'by_tray', 'query': 'tray=demo_set_1', 'summary': {'prints': 611, 'assigned':
0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': False, 'active_scan_session': 'becc3aba-bba4-4061-8a19-65abec2acbcd', 'auto_delete': False}], 'num_pages': 1, 'processing': False}
Done

A: Why don't you just use the standard json library.  In your case this would make it easier to read:
import json

my_dict = {'count': 8, 'next': None, 'previous': None, 'results': [{'url': 'http://192.168.0.18/api/batch/bmw_problem/', 'created': '2021-05-11T16:56:04.944370+02:00', 'modified': '2021-05-11T16:56:04.944384+02:00', 'id': 'bmw_problem', 'title': 'bmw_problem', 'archived': False, 'view': None, 'query': 'tray=bmw_problem', 'summary':
{'prints': 11, 'assigned': 11, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '677d2328-6276-4206-9a69-2f6b10fd67ea', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_set_3/', 'created': '2021-03-22T12:37:51.240377+01:00', 'modified': '2021-04-12T12:27:07.124319+02:00', 'id': 'demo_set_3', 'title': 'demo_set_3', 'archived': False, 'view': 'by_tray', 'query': 'tray=demo_set_3', 'summary': {'prints': 318, 'assigned': 0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': False}, 'has_bin_assignments': False, 'active_scan_session': None, 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_all/', 'created': '2021-03-04T11:52:05.236265+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'demo_all', 'title': 'All demo parts', 'archived': False, 'view': 'by_tray', 'query': 'tray__istartswith=demo_set_', 'summary': {'prints': 1252, 'assigned': 218, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '50d5119e-57ef-4577-b0b4-090839f27f0d', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/priority/', 'created': '2021-03-04T11:50:06.446579+01:00', 'modified': '2021-03-22T13:09:14.910389+01:00', 'id': 'priority', 'title': 'Priority Prints', 'archived': False, 'view': None, 'query':
'flags__contains=PRIORITY', 'summary': {'prints': 434, 'assigned': 0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '15403217-a468-498e-b150-b900a16cd5cc', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/MJF/', 'created': '2021-03-04T11:50:06.446557+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'MJF', 'title': 'MJF Prints', 'archived': False, 'view': 'by_tech', 'query': 'technology=MJF', 'summary': {'prints': 138, 'assigned': 0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': False, 'active_scan_session': '81f0ffdd-1e82-4e42-b8fb-89a661b03924', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/SLS/', 'created': '2021-03-04T11:50:06.446534+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'SLS', 'title': 'SLS Prints', 'archived': False, 'view': 'by_tech', 'query': 'technology=SLS', 'summary': {'prints': 1114, 'assigned': 1, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': True, 'active_scan_session': '99b3a0a3-05f6-4225-bbe6-9814a31dca80', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_set_2/', 'created': '2021-03-04T11:50:06.446508+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'demo_set_2', 'title': 'demo_set_2', 'archived': False, 'view': 'by_tray', 'query': 'tray=demo_set_2', 'summary': {'prints': 323, 'assigned': 22, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': True}, 'has_bin_assignments': True, 'active_scan_session': '82e8e71a-0c1f-41c5-b021-bd399eb2d6b3', 'auto_delete': False}, {'url': 'http://192.168.0.18/api/batch/demo_set_1/', 'created': '2021-03-04T11:50:06.446461+01:00', 'modified': '2021-05-12T12:05:58.546004+02:00', 'id': 'demo_set_1', 'title': 'demo_set_1', 'archived': False, 'view': 'by_tray', 'query': 'tray=demo_set_1', 'summary': {'prints': 611, 'assigned':
0, 'rejected': 0, 'conflicted': 0, 'needs_processing': False, 'processing_ratio': 1.0, 'processing_status': 'READY', 'currently_scanning': None}, 'has_bin_assignments': False, 'active_scan_session': 'becc3aba-bba4-4061-8a19-65abec2acbcd', 'auto_delete': False}], 'num_pages': 1, 'processing': False}

print(json.dumps(my_dict, indent=4, sort_keys=True)) # or use my_dict['results'] if you just want the results

>>
{
    "count": 8,
    "next": null,
    "num_pages": 1,
    "previous": null,
    "processing": false,
    "results": [
        {
            "active_scan_session": "677d2328-6276-4206-9a69-2f6b10fd67ea",
            "archived": false,
            "auto_delete": false,
            "created": "2021-05-11T16:56:04.944370+02:00",
            "has_bin_assignments": true,
            "id": "bmw_problem",
            "modified": "2021-05-11T16:56:04.944384+02:00",
            "query": "tray=bmw_problem",
            "summary": {
                "assigned": 11,
                "conflicted": 0,
                "currently_scanning": null,
                "needs_processing": false,
                "prints": 11,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "bmw_problem",
            "url": "http://192.168.0.18/api/batch/bmw_problem/",
            "view": null
        },
        {
            "active_scan_session": null,
            "archived": false,
            "auto_delete": false,
            "created": "2021-03-22T12:37:51.240377+01:00",
            "has_bin_assignments": false,
            "id": "demo_set_3",
            "modified": "2021-04-12T12:27:07.124319+02:00",
            "query": "tray=demo_set_3",
            "summary": {
                "assigned": 0,
                "conflicted": 0,
                "currently_scanning": false,
                "needs_processing": false,
                "prints": 318,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "demo_set_3",
            "url": "http://192.168.0.18/api/batch/demo_set_3/",
            "view": "by_tray"
        },
        {
            "active_scan_session": "50d5119e-57ef-4577-b0b4-090839f27f0d",
            "archived": false,
            "auto_delete": false,
            "created": "2021-03-04T11:52:05.236265+01:00",
            "has_bin_assignments": true,
            "id": "demo_all",
            "modified": "2021-05-12T12:05:58.546004+02:00",
            "query": "tray__istartswith=demo_set_",
            "summary": {
                "assigned": 218,
                "conflicted": 0,
                "currently_scanning": null,
                "needs_processing": false,
                "prints": 1252,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "All demo parts",
            "url": "http://192.168.0.18/api/batch/demo_all/",
            "view": "by_tray"
        },
        {
            "active_scan_session": "15403217-a468-498e-b150-b900a16cd5cc",
            "archived": false,
            "auto_delete": false,
            "created": "2021-03-04T11:50:06.446579+01:00",
            "has_bin_assignments": true,
            "id": "priority",
            "modified": "2021-03-22T13:09:14.910389+01:00",
            "query": "flags__contains=PRIORITY",
            "summary": {
                "assigned": 0,
                "conflicted": 0,
                "currently_scanning": null,
                "needs_processing": false,
                "prints": 434,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "Priority Prints",
            "url": "http://192.168.0.18/api/batch/priority/",
            "view": null
        },
        {
            "active_scan_session": "81f0ffdd-1e82-4e42-b8fb-89a661b03924",
            "archived": false,
            "auto_delete": false,
            "created": "2021-03-04T11:50:06.446557+01:00",
            "has_bin_assignments": false,
            "id": "MJF",
            "modified": "2021-05-12T12:05:58.546004+02:00",
            "query": "technology=MJF",
            "summary": {
                "assigned": 0,
                "conflicted": 0,
                "currently_scanning": null,
                "needs_processing": false,
                "prints": 138,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "MJF Prints",
            "url": "http://192.168.0.18/api/batch/MJF/",
            "view": "by_tech"
        },
        {
            "active_scan_session": "99b3a0a3-05f6-4225-bbe6-9814a31dca80",
            "archived": false,
            "auto_delete": false,
            "created": "2021-03-04T11:50:06.446534+01:00",
            "has_bin_assignments": true,
            "id": "SLS",
            "modified": "2021-05-12T12:05:58.546004+02:00",
            "query": "technology=SLS",
            "summary": {
                "assigned": 1,
                "conflicted": 0,
                "currently_scanning": null,
                "needs_processing": false,
                "prints": 1114,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "SLS Prints",
            "url": "http://192.168.0.18/api/batch/SLS/",
            "view": "by_tech"
        },
        {
            "active_scan_session": "82e8e71a-0c1f-41c5-b021-bd399eb2d6b3",
            "archived": false,
            "auto_delete": false,
            "created": "2021-03-04T11:50:06.446508+01:00",
            "has_bin_assignments": true,
            "id": "demo_set_2",
            "modified": "2021-05-12T12:05:58.546004+02:00",
            "query": "tray=demo_set_2",
            "summary": {
                "assigned": 22,
                "conflicted": 0,
                "currently_scanning": true,
                "needs_processing": false,
                "prints": 323,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "demo_set_2",
            "url": "http://192.168.0.18/api/batch/demo_set_2/",
            "view": "by_tray"
        },
        {
            "active_scan_session": "becc3aba-bba4-4061-8a19-65abec2acbcd",
            "archived": false,
            "auto_delete": false,
            "created": "2021-03-04T11:50:06.446461+01:00",
            "has_bin_assignments": false,
            "id": "demo_set_1",
            "modified": "2021-05-12T12:05:58.546004+02:00",
            "query": "tray=demo_set_1",
            "summary": {
                "assigned": 0,
                "conflicted": 0,
                "currently_scanning": null,
                "needs_processing": false,
                "prints": 611,
                "processing_ratio": 1.0,
                "processing_status": "READY",
                "rejected": 0
            },
            "title": "demo_set_1",
            "url": "http://192.168.0.18/api/batch/demo_set_1/",
            "view": "by_tray"
        }
    ]
}


text:
Q: System.Net.Http not found after migrating from .netcore 2.1 to asp.net 4.7.2 I recently migrated my project from .netcore 2.1 to asp.net 4.7.2, because of some 3rd party .dll. The solution builds and runs locally. It also builds on our dev environment in TeamCity. However, it does not work in Azure. On checking the logs I get the following error:

[ERR] An unhandled exception has occurred while executing the request.
  System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

The file does exist! After some research I came upon this post: Single-name references are removed by the SDK when targeting .NET Framework 4.7.2 and referencing a package with the same assembly
I removed the System.Http.Net reference hoping it will use it from the framework, same error. Next, I tried the workaround stated there:
<ItemGroup>
  <PackageReference Include="System.Net.Http" Version="4.2.0">
    <ExcludeAssets>All</ExcludeAssets>
  </PackageReference>
</ItemGroup>

Same error.
Any help or troubling shooting ideas would be welcome

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Count Row Value in SQL Server database? I have a table called TimeSheet :
Card_No    Name    1    2    3    4
123        GGG    A    P    P    P
123        GGG    A    P    A    P
123        GGG    A    P    P    P
123        GGG    A    A    A    P

I want to count total A in one row. Result should be like this
Card_No    Name    1    2    3    4    TotalA
123         GGG    A    P    P    P    1
123         GGG    A    P    A    P    2
123         GGG    A    P    P    P    1
123         GGG    A    A    A    P    3

How can I do it ? Please help me.

A: One way
SELECT
      *,
      CASE WHEN [1] = 'A' THEN 1 ELSE 0 END +
      CASE WHEN [2] = 'A' THEN 1 ELSE 0 END +
      CASE WHEN [3] = 'A' THEN 1 ELSE 0 END +
      CASE WHEN [4] = 'A' THEN 1 ELSE 0 END AS TotalA
FROM TimeSheet

or
SELECT *,
       (SELECT count(*)
        FROM   (VALUES([1]),
                      ([2]),
                      ([3]),
                      ([4])) V(c)
        WHERE  c = 'A') AS TotalA
FROM   TimeSheet


text:
Q: Displaying VideoCapture using OpenCV with python and wxPython in a wx.panel: Show only small region of the video I'm trying to display OpenCV with Python interface in wxPython.
I can display it but only a small region in the top left corner of the video.
What is the problem with my code?
is it the size of parent panel or something else?
note that I use code from this https://stackoverflow.com/a/14818080/2389238
and It can run perfectly but I need to display it in a panel (or other parent frame).
Thank in Advance.
import wx
import cv, cv2

class MainWindow(wx.Panel):
    def __init__(self, parent,capture):
        wx.Panel.__init__(self, parent)
        mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.inputBox = wx.TextCtrl(self)
        mainSizer.Add(self.inputBox, 0, wx.ALL, 5)

        # video
        videoWarper = wx.StaticBox(self, label="Video",size=(640,480))
        videoBoxSizer = wx.StaticBoxSizer(videoWarper, wx.VERTICAL)
        videoFrame = wx.Panel(self, -1,size=(640,480))
        cap = ShowCapture(videoFrame, capture)
        videoBoxSizer.Add(videoFrame,0)
        mainSizer.Add(videoBoxSizer,0)

        parent.Centre()
        self.Show()
        self.SetSizerAndFit(mainSizer)

class ShowCapture(wx.Panel):
    def __init__(self, parent, capture, fps=24):
        wx.Panel.__init__(self, parent)

        self.capture = capture
        ret, frame = self.capture.read()

        height, width = frame.shape[:2]

        parent.SetSize((width, height))

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        self.bmp = wx.BitmapFromBuffer(width, height, frame)

        self.timer = wx.Timer(self)
        self.timer.Start(1000./fps)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_TIMER, self.NextFrame)

    def OnPaint(self, evt):
        dc = wx.BufferedPaintDC(self)
        dc.DrawBitmap(self.bmp, 0, 0)

    def NextFrame(self, event):
        ret, frame = self.capture.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.bmp.CopyFromBuffer(frame)
            self.Refresh()

capture = cv2.VideoCapture(0)

app = wx.App(False)
frame = wx.Frame(None,-1,'HGA Count',size=(400, 400))
panel = MainWindow(frame,capture)
frame.Show()
app.MainLoop()

This is the image: http://i58.tinypic.com/2u5t7kh.png
Sorry for the link I can't put image here due to low reputation.

A: Thank to the answer posted by VZ
Now I understand my problem.
The small region is caused by the default size of wx.Panel that ShowCapture was inherited.
It made the dc in  dc = wx.BufferedPaintDC(self) had only 20px*20px in dimension,
so the self.bmp, which is 640px * 480px, was drawn on only the small region and everything lied beyond 20px*20px is ignored.
the solution is to change the panel __init__ argument to
class ShowCapture(wx.Panel):
    def __init__(self, parent, capture, fps=24):
        wx.Panel.__init__(self, parent, wx.ID_ANY, (0,0), (640,480))

Note that:

*

*I don't know whether it could be configured for auto re-size panel

*videoFrame is still needed because ShowCapture need a parent frame (for layout in sizer). Don't know whether there is a better approach.

A: Basically, nothing sets your ShowCapture window size to the desired size, so it remains stuck at some default size. The simplest solution would probably be to do without videoFrame at all as it seems to be not needed and just create cap itself with the desired initial size, which will also become the minimal window size.

Follow up after the question update:

*

*You can resize it automatically using the sizers and ensuring that:

*

*The item itself grows, i.e. has positive proportion if you want it to grow in the major direction of the sizer (vertical for wxVERTICAL box sizer, horizontal for... you guessed it) or wxEXPAND flag if you want it to grow in the other direction. Or both, of course, if you want it to grow in both direction.

*Very important as often forgotten: the containing sizer itself grows as well. I.e. nothing will happen if the window itself grows inside its sizer if its sizer doesn't grow inside its own containing sizer.

*videoFrame is not necessary and, in fact, you ought to make your video window child of videoWarper if you're using 3.0 for the best results: since 3.0, the contents of a wxStaticBoxSizer should be created with its wxStaticBox as parent.

A: Here's what I came up with, it uses GenStaticBitmap, which is a subclass of wx.Panel and does the dc.DrawBitmap in its OnPaint method. I added in ROI selection with SpinCtrl and also by hovering on the right-side ROI GenStaticBitmap control. I also added in a button that when right-clicked saves both images, but when left-clicked freezes on the current images and allows the user to save either image or both. Drawing the hover and ROI selection cross-hairs was fun, hope it helps someone else!
import wx
from wx.lib import statbmp
import cv, cv2
import numpy as np
import os
import traceback

class ChooseSaveDialog(wx.Dialog):
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent)
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        btn1 = wx.Button(panel, -1, 'Save Original Image')
        btn2 = wx.Button(panel, -1, 'Save ROI Image')
        btn3 = wx.Button(panel, -1, 'Save Both')
        sizer.Add(btn1, 0)
        sizer.Add(btn2, 0)
        sizer.Add(btn3, 0)
        panel.SetSizer(sizer)

        btn1.Bind(wx.EVT_BUTTON, self.save_orig)
        btn2.Bind(wx.EVT_BUTTON, self.save_roi)
        btn3.Bind(wx.EVT_BUTTON, self.save_both)

    def save_orig(self, evt):
        save_dialog = wx.FileDialog(self, "Save Original to JPEG", "", "", "JPG files(*.jpg)", wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)#|wx.FD_CHANGE_DIR)

        if save_dialog.ShowModal() == wx.ID_OK:
            save_path = save_dialog.GetPath()
            if save_path[:-4].lower() != '.jpg':
                save_path += '.jpg'
            print save_path
            cv2.imwrite(save_path, self.GetParent().orig_frame)
        self.EndModal(wx.OK)

    def save_roi(self, evt):
        save_dialog = wx.FileDialog(self, "Save ROI to JPEG", "", "", "JPG files(*.jpg)", wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)#|wx.FD_CHANGE_DIR)

        if save_dialog.ShowModal() == wx.ID_OK:
            save_path = save_dialog.GetPath()
            if save_path[:-4].lower() != '.jpg':
                save_path += '.jpg'
            print save_path
            cv2.imwrite(save_path, self.GetParent().frameRoi)
        try:
            self.EndModal(wx.OK)
        except wx.PyAssertionError:
            pass

    def save_both(self, evt):
        self.save_orig(evt)
        self.save_roi(evt)

class ShowCapture(wx.Frame):
    def __init__(self, capture, fps=15):
        wx.Frame.__init__(self, None)
        panel = wx.Panel(self, -1)

        #create a grid sizer with 5 pix between each cell
        sizer = wx.GridBagSizer(5, 5)

        self.capture = capture
        ret, frame = self.capture.read()

        height, width = frame.shape[:2]
        self.orig_height = height
        self.orig_width = width

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        self.bmp = wx.BitmapFromBuffer(width, height, frame)

        self.dummy_element = wx.TextCtrl(panel, -1,'')
        self.dummy_element.Hide()

        #create SpinCtrl widgets, these have vertical up/down buttons and a TextCtrl that increments with up/down press
        self.roi_x = wx.SpinCtrl(panel, -1, "ROI X",  style=wx.TE_PROCESS_ENTER|wx.SP_ARROW_KEYS, min=0, max=width, initial=0, size=(60,-1))
        self.roi_y = wx.SpinCtrl(panel, -1, "ROI Y",  style=wx.TE_PROCESS_ENTER|wx.SP_ARROW_KEYS, min=0, max=height, initial=0, size=(60,-1))
        self.roi_width = wx.SpinCtrl(panel, -1, "ROI W",  style=wx.TE_PROCESS_ENTER|wx.SP_ARROW_KEYS, min=0, max=width, initial=width, size=(60,-1))
        self.roi_height = wx.SpinCtrl(panel, -1, "ROI H",  style=wx.TE_PROCESS_ENTER|wx.SP_ARROW_KEYS, min=0, max=height, initial=height, size=(60,-1))

        save_bmp_path = os.path.join(os.path.dirname(__file__), 'icons', 'ic_action_save.png')
        if os.path.isfile(save_bmp_path):
            save_bmp = wx.Image(save_bmp_path).ConvertToBitmap()
            save_button = wx.BitmapButton(panel,wx.ID_ANY, bitmap=save_bmp, style = wx.NO_BORDER, size=(32,32)) # )
        else:
            save_button = wx.Button(panel, -1, 'Save')

        settings_bmp_path = os.path.join(os.path.dirname(__file__), 'icons', 'ic_action_settings.png')
        if os.path.isfile(settings_bmp_path):
            settings_bmp = wx.Image(settings_bmp_path).ConvertToBitmap()
            settings_button = wx.BitmapButton(panel,wx.ID_ANY, bitmap=settings_bmp, style = wx.NO_BORDER, size=(32,32)) # )
        else:
            settings_button = wx.Button(panel, -1, 'Settings')

        #create image display widgets
        self.ImgControl = statbmp.GenStaticBitmap(panel, wx.ID_ANY, self.bmp)
        self.ImgControl2 = statbmp.GenStaticBitmap(panel, wx.ID_ANY, self.bmp)

        #add text to the sizer grid
        sizer.Add(wx.StaticText(panel, -1, 'ROI'), (0, 0), (1,2),  wx.ALL, 5)
        sizer.Add(wx.StaticText(panel, -1, 'X'), (1, 0), wx.DefaultSpan,  wx.ALL, 5)
        sizer.Add(wx.StaticText(panel, -1, 'Y'), (2, 0), wx.DefaultSpan,  wx.ALL, 5)
        sizer.Add(wx.StaticText(panel, -1, 'width,'), (1, 2), wx.DefaultSpan,  wx.ALL, 5)
        sizer.Add(wx.StaticText(panel, -1, 'height'), (2, 2), wx.DefaultSpan,  wx.ALL, 5)
        sizer.Add(wx.StaticText(panel, -1, 'Right-click image to reset ROI'), (2, 4), wx.DefaultSpan,  wx.ALL, 5)

        tool_button_sizer = wx.BoxSizer(wx.HORIZONTAL)
        tool_button_sizer.Add(save_button, 0)
        tool_button_sizer.Add(settings_button, 0)
        #sizer.Add(, (0, 6), wx.DefaultSpan, wx.ALIGN_RIGHT)#,  wx.ALL, 5)
        sizer.Add(tool_button_sizer, (0, 7), wx.DefaultSpan, wx.ALIGN_RIGHT)#,  wx.ALL, 5)

        #add SpinCtrl widgets to the sizer grid
        sizer.Add(self.roi_x, (1, 1), wx.DefaultSpan,  wx.ALL, 5)
        sizer.Add(self.roi_y, (2, 1), wx.DefaultSpan,  wx.ALL, 5)
        sizer.Add(self.roi_width, (1, 3), wx.DefaultSpan,  wx.ALL, 5)
        sizer.Add(self.roi_height, (2, 3), wx.DefaultSpan,  wx.ALL, 5)

        #add image widgets to the sizer grid
        sizer.Add(self.ImgControl, (3, 0), (1,4), wx.EXPAND|wx.CENTER|wx.LEFT|wx.BOTTOM, 5)
        sizer.Add(self.ImgControl2, (3, 4), (1,4), wx.EXPAND|wx.CENTER|wx.RIGHT|wx.BOTTOM, 5)

        #set the sizer and tell the Frame about the best size
        panel.SetSizer(sizer)
        sizer.SetSizeHints(self)
        panel.Layout()
        panel.SetFocus()

        #start a timer that's handler grabs a new frame and updates the image widgets
        self.timer = wx.Timer(self)
        self.fps = fps
        self.timer.Start(1000./self.fps)

        #bind timer events to the handler
        self.Bind(wx.EVT_TIMER, self.NextFrame)

        #bind events to ROI image widget
        self.ImgControl2.Bind(wx.EVT_LEFT_DOWN, self.On_ROI_Click)
        self.ImgControl2.Bind(wx.EVT_LEFT_UP, self.On_ROI_ClickRelease)
        self.ImgControl2.Bind(wx.EVT_RIGHT_DOWN, self.On_ROI_RightClick)
        self.ImgControl2.Bind(wx.EVT_MOTION, self.On_ROI_Hover)
        self.ImgControl2.Bind(wx.EVT_ENTER_WINDOW, self.On_ROI_mouse_enter)
        self.ImgControl2.Bind(wx.EVT_LEAVE_WINDOW, self.On_ROI_mouse_leave)

        #bind save button
        save_button.Bind(wx.EVT_BUTTON, self.on_save_click)
        save_button.Bind(wx.EVT_RIGHT_DOWN, self.on_quick_save)

        #bind settings button
        settings_button.Bind(wx.EVT_BUTTON, self.on_settings_click)
        settings_button.Bind(wx.EVT_LEFT_UP, self.on_settings_click_release)

    def on_settings_click(self, evt):
        pass

    def on_settings_click_release(self, evt):
        self.dummy_element.SetFocus()

    def on_save_click(self, evt):
        modal = ChooseSaveDialog(self)
        self.timer.Stop()
        modal.ShowModal()
        modal.Destroy()
        self.timer.Start(1000./self.fps)

    def on_quick_save(self, evt):
        cv2.imwrite('orig_frame.jpg', self.orig_frame)
        cv2.imwrite('frameRoi.jpg', self.frameRoi)

    def On_ROI_RightClick(self, evt):
        self.roi_x.SetValue(0)
        self.roi_y.SetValue(0)
        self.roi_width.SetValue(self.orig_width)
        self.roi_height.SetValue(self.orig_height)

    def On_ROI_Hover(self, evt):
        self.ROI_crosshair_pos = evt.GetPosition()

    def On_ROI_mouse_enter(self, evt):
        self.enable_crosshairs = True

    def On_ROI_mouse_leave(self, evt):
        try:
            self.enable_crosshairs = False
            if hasattr(self, 'roi_click_down_pos'):
                self.update_spinners(evt.GetPosition())
            del self.roi_click_down_pos
        except AttributeError:
            pass

    def On_ROI_Click(self, evt):
        self.roi_click_down_pos = evt.GetPosition()

    def On_ROI_ClickRelease(self, evt):
        roi_click_up_pos = evt.GetPosition()
        #if roi_click_up_pos[0] >= 0 and roi_click_up_pos[1] >= 0:
        if hasattr(self, 'roi_click_down_pos'):
            self.update_spinners(roi_click_up_pos)
        try:
            del self.roi_click_down_pos
        except AttributeError:
            pass

    def update_spinners(self, new_pos):
        self.roi_width.SetValue(abs(new_pos[0] - self.roi_click_down_pos[0]))
        self.roi_height.SetValue(abs(new_pos[1] - self.roi_click_down_pos[1]))
        self.roi_x.SetValue(min(self.roi_click_down_pos[0], new_pos[0]))
        self.roi_y.SetValue(min(self.roi_click_down_pos[1], new_pos[1]))

    def NextFrame(self, event):
        ret, self.orig_frame = self.capture.read()
        if ret:
            frame = cv2.cvtColor(self.orig_frame, cv2.COLOR_BGR2RGB)

            self.bmp.CopyFromBuffer(frame)
            self.ImgControl.SetBitmap(self.bmp)

            try:
                orig_height, orig_width = frame.shape[:2]
                y1 = self.roi_y.GetValue()
                y2 = y1 + self.roi_height.GetValue()
                y2 = min(y2, orig_height)
                x1 = self.roi_x.GetValue()
                x2 = x1 + self.roi_width.GetValue()
                x2 = min(x2, orig_width)

                frameRoi = self.orig_frame[y1:y2, x1:x2]
                roi_width = x2-x1
                roi_height = y2-y1
                #frameRoi = cv2.cvtColor(frameRoi, cv2.COLOR_BGR2GRAY )
                #print len(frameRoi)

                #frameRoi -= 110#frameRoi #* 1.25
                #print len(frameRoi)

                #frameRoi = frameRoi.clip(255.)
                #frameRoi = (255./1)*((frameRoi/(255./1))**0.5)# 0.5

                if hasattr(self, 'ROI_crosshair_pos') and self.enable_crosshairs:
                    try:
                        cross_x = self.ROI_crosshair_pos[0]
                        cross_y = self.ROI_crosshair_pos[1]
                        frameRoi[0:roi_height, cross_x:cross_x+1] = [42,0,255]
                        frameRoi[cross_y:cross_y+1, 0:roi_width] = [42,0,255]

                        if hasattr(self, 'roi_click_down_pos'):
                            roi_x1 = self.roi_click_down_pos[0]
                            roi_y1 = self.roi_click_down_pos[1]

                            if cross_y>roi_y1:
                                frameRoi[0:roi_y1, 0:roi_width] = frameRoi[0:roi_y1, 0:roi_width]*.50
                                frameRoi[cross_y:roi_height, 0:roi_width] = frameRoi[cross_y:roi_height, 0:roi_width]*.50
                            else:
                                frameRoi[roi_y1:roi_height, 0:roi_width] = frameRoi[roi_y1:roi_height, 0:roi_width]*.50
                                frameRoi[0:cross_y, 0:roi_width] = frameRoi[0:cross_y, 0:roi_width]*.50

                            if cross_x>roi_x1:
                                frameRoi[0:roi_height, 0:roi_x1] = frameRoi[0:roi_height, 0:roi_x1]*.50
                                frameRoi[0:roi_height, cross_x:roi_width] = frameRoi[0:roi_height, cross_x:roi_width]*.50
                            else:
                                frameRoi[0:roi_height, roi_x1:roi_width] = frameRoi[0:roi_height, roi_x1:roi_width]*.50
                                frameRoi[0:roi_height, 0:cross_x] = frameRoi[0:roi_height, 0:cross_x]*.50

                    except:
                        print 'couldn\'t draw crosshairs'
                        traceback.print_exc()
                self.frameRoi = np.array(frameRoi , dtype = np.uint8)

                #frameRoi = np.repeat(frameRoi, 3)
                #frameRoi = array(newImage0,dtype=uint8)

                frameRoi = cv2.cvtColor(self.frameRoi, cv2.COLOR_BGR2RGB)#GRAY2RGB)
                self.bmp2 = wx.BitmapFromBuffer(roi_width, roi_height, frameRoi)
                self.ImgControl2.SetBitmap(self.bmp2)

            except:
                traceback.print_exc()

capture = cv2.VideoCapture(0)
#capture.set(cv.CV_CAP_PROP_FRAME_WIDTH, 320)
#capture.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 240)

app = wx.App()
frame = ShowCapture( capture)
frame.Show()
app.MainLoop()


text:
Q: Template 10: Hide HamBurgerMenu if no internet I am devloping an uwp app in which if there is no internet then the user is shown an error  no internet connection at start.So I checked for internet connection if not then i did this in my App.xaml.:
 public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
    {
        // long-running startup tasks go here
        await Task.Delay(TimeSpan.FromSeconds(6));
           if (!NoInternet)
            {

                NavigationService.Navigate(typeof(Views.Error));
            }
            }
        await Task.CompletedTask;
    }

Now when no internet connection is there then it navigates to my Error Page but the HamburgerMenu is still visible.How do i hide the HamburgerMenu.?I am using HamburgerMenu Template of Template10.Thanks in advance!.

A: To do this use the IsFullScreen property.
You can do it in the OnNavigationToAsync() going to the Errors page or do it at your logic check prior to navigation.
IsFullScreen = true;
The latest versions of the template 1.18 / library v1.1.11 have a property already setup for you in the SettingsService for IsFullScreen, keep in mind when it changes it gets persisted to the settings file.

A: I ran into similar problem for my app.Assuming that you have not edited shell.xaml.cs and also the Hamburgermenu name,just add this into shall.xaml.cs
   public HamburgerMenu _THamburgerMenu
    {
        get { return MyHamburgerMenu;}

        set { MyHamburgerMenu = value;}
    }

and your app.xaml.cs should be like this:
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
    // long-running startup tasks go here
    await Task.Delay(TimeSpan.FromSeconds(6));
       if (!NoInternet)
        {

            Shell.Instance._THamburgerMenu.IsFullScreen = true;

            NavigationService.Navigate(typeof(Views.Error));
        }
        }
    await Task.CompletedTask;
}

Ps:add using youappname.Views in app.xaml.cs


text:
Q: Are single loops or dense loops more computationlly efficent in matlab? Im am currently writing a code to implement a numerical approximation to the 3D steady state heat equation using finite difference matrix methods. This involves discritising the 2nd order PDE into the matrix A and solving Ax=b. where x is temperature at each of the specified grid points. Further information on this type of question can be found here:
http://people.nas.nasa.gov/~pulliam/Classes/New_notes/Matrix_ODE.pdf
To complete this problem, I have represented the 3D matrix A by a 2D array calling the values in the 1D array b using an indexing function of the form:
i+(j-1)*Nx+Nx*Ny*(k-1)

for the (i,j,k)th element of the 3D matrix where Nx, Ny, Nz are the number of points in the x,y,z coordinates. There ends up being a lot of loop computation in order to create the matrix A and b and I was wondering what is the most computationally efficient and less memory exhaustive way to run these loops, i.e. is it better to use something like
for j=1:Ny
    for i=2:Nx-1
        b(i+(j-1)*Nx)=D4;
    end
end

for j=1:Ny
    for i=2:Nx-1
        b(i+(j-1)*Nx+Nx*Ny*(Nz-1))=D3;
    end
end

or should I condense these into a single loop like:
for j=1:Ny
    for i=2:Nx-1
        b(i+(j-1)*Nx)=D4;
        b(i+(j-1)*Nx+Nx*Ny*(Nz-1))=D3;
    end
end

I have preallocated both the arrays A and b. Is there a vectorised way to do this also?

A: Assuming Nx, Ny, Nz, D3 and D4 to be scalars and that you are using pre-allocation for b with zeros, you may try this vectorized approach -
I = 2:Nx-1; %// Vectors to represent i
J = 1:Ny; %// Vectors to represent j

ind1 = bsxfun(@plus,I,[(J-1)*Nx]'); %//' Indices, 1st set of nested loops
ind2 = bsxfun(@plus,I,[(J-1)*Nx+Nx*Ny*(Nz-1)]'); %//' Indices, 2nd set of loops

b(ind1) = D4; %// Assign values for 1st set
b(ind2) = D3; %// Assign values for 2nd set

A: The second method should be slightly faster since it performs the same number of calculations with fewer increments of the loop variables. You can look into MATLAB's built-in stopwatch commands tic and toc to time your code. http://www.mathworks.com/help/matlab/ref/tic.html
Something more vectorized might be possible but I would need to know more about the format of the arrays that contain D3 and D4. The reshape() function might be able to help.


text:
Q: How to create slide switch in android? I want to create slide switch for example(on/off) currently shows on if i slide to off will enable and also know which status is currently shows pls help me.

A: Use Switch and its setOnCheckedChangeListener and a OnCheckedChangeListener(CompoundButton buttonView, boolean isChecked), that gets called whenever the switch is touched, and check the value of isChecked to know the state of the switch. This also applies to ToggleButton; check the Tutorial on both of them for more information. (I think Switch is only available from Android 4.0 on)

A: You can use ToggleButton There is more information about ToggleButton


text:
Q: How to set timezone and Display name format from user settings in database I am working on a multi-tenant application using Web API 2.0 and MVC 5 + Angular 1 as client-side scripting. In the application each tenant has the option to configure the display name format(FirstName + LastName or LastName + FirstName) , DateFormat(dd/mm/yyyy or mm/dd/yyyy).
How can I achieve this?

*

*Do I need to apply to format in web API and send data to the client?

*Do I need to take care of the client side while rendering the page?

*Or in My DTO classes, I need to put some logic to convert based on the configuration

A: Your question is quite broad but I will try to answer. You have a choice to do the formatting for FormatName and FormatDate on a client-side (Angular 1) or in the backend (Web API 2.0). I prefer to do the formatting in the backend because:-

*

*Today, you are consuming the Backend is consumed only by Angular, but I imagine in
future the same backend can be consumed by mobile apps too.

*The front-end code doesn't need to worry about formatting.

*Prefer to do the heavy lifting in the backend, keep the front-end simple.


text:
Q: In Automic 12 bash, special characters in mailx body result in body being attached as a binary file I am trying to send an email using mailx through Automic Workload Automation 12.0's bash jobs. The message needs to have a special character, in this case the percent sign "°".
The message should have the body This is the ° sign., for this example.
I am using this code to send the message. printf '\xB0' prints the ° sign.
(
  printf 'This is the '
  printf '\xB0'
  printf ' sign.'
) | mailx [etc]

If I copy and paste this directly into a bash terminal, the email sends fine with the special character printed in the message body.
However, when I use the same code in Automic bash jobs, the email body is blank. There is a file attached, named ATT00001.bin. If I open ATT00001.bin using notepad.exe, the file contains the text that should have been in the body, This is the ° sign. With the characters printed exactly as they should be in the body.
The following when used in Automic results in a message being sent with the correct body. No files are attached. So it seems clear that the special character is causing this issue with Automic.
(
  printf 'This is the '
  printf 'placeholder'
  printf ' sign.'
) | mailx [etc]

Does anyone know why this happens, or how to resolve it?

A: Mailx is a evolved MUA. For just sending a mail, if you use sendmail, you could build your own mail header:
/usr/sbin/sendmail destuser@desthost <<eomail
To: destuser@desthost
Subject: Any interesting thing
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: 8bit

This is the ° sign
eomail

Or you could use html encoding:
/usr/sbin/sendmail destuser@desthost <<eomail
To: destuser@desthost
Subject: Any interesting thing
MIME-Version: 1.0
Content-Type: text/html; charset="ASCII"
Content-Transfer-Encoding: 8bit

This is the ° sign
eomail

Care, use only ASCII characters there!


text:
Q: Unity 3d How to make the player to stay at the target position after the animation completes Hello I have the Problem that the Animation Pos not stay. I need this for a Dodge(Combat) system. Root Motion Doesn't work!
.

A: You can make another state in animation and make your animation to go to that state. In script don't let player move when animation is in that state.
Return to idle state whenever you want to make things normal again.
Other way to do is use other animations libs (like leantween) and make a callback after animation ends.


text:
Q: JacksonFeature breaks JsonIgnoreProperties I have pojo's like these:
@JsonIgnoreProperties(ignoreUnknown = true)
public class SNAPIResponse {

    public String status;
    public String message;
    public int errorCode;

    public ConsumerProfile consumerProfile;

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class ConsumerProfile {
        public String accountId;
    }
}

and my Jersey client works just fine even though the ConsumerProfile responses contain a lot of extra fields.
Then I add a line:
client.register(JacksonFeature.class);

to my Jersey Client setup. And after that, the ignore's don't work anymore:
Unrecognized field "authService" (Class com.xyz..SNAPIResponse$ConsumerProfile), not marked as ignorable

Why?

A: I stumbled across this post which helped me get JsonIgnoreProperties working again: http://jersey.576304.n2.nabble.com/Beware-of-JacksonFeature-in-Jersey-td7581633.html
I didn't research enough to be 100% sure on the underlying cause of the issue, but it seems registering JacksonFeature.class pulls in an outdated version of a library needed for this.
Doing as suggested in that link worked for me.


text:
Q: Are there any sites that show how to recreate specific iOS UI paradigms? iDevRecipes is an awesome site that goes into some detail on how some popular and specific iPhone components have been developed. I was wondering if the SO crew knew of any other sites similar to this? It would be a great help to all iOS developers.

A: I stumbled across Custom Controls for iOS last night and it looks like there are links to the source code for at least a few of the custom controls on iDev Recipes, and there are some plenty more custom controls not featured on the recipes site.  I guess it's not necessarily as pedagogical as the recipes website, but you can still browse the source code which is definitely a great way to learn about making your own custom controls.


text:
Q: How to identify how many users are still having the app after installation on iOS? 1) Some users install the app and use it for some time and uninstall it.
2) Some users keep it but do not open for months.
How to differentiate and know the users count on such scenarios?
If users open the app, I can inform the server and know how many users are having the app. But If they uninstall the app or do not open the app at all for some months, is there a way to know how many users are still having the app after installation?
Is it possible to identify programmatically when the user is uninstalling the app?
I didn't see any option on iTunesConnect to identify how many users are still having the app after installation.

FYI,
For Android, PlayStore dashboard has the information on how many users still have the app on their devices.
The info icon on Active / Total installs says:

Installs on Active Devices (devices online in the past 30 days with
  this app installed) / Total User Installs (total number of unique
  users who have ever installed this app on one or more of their
  devices)

Thanks!

A: There is not a simple metric available in iTunes Connect for this.  You would need to implement your own tracking with a combination of tracking launches of the app, as well as a "creative" use of the Apple Push Notification Service (APNS) that will tell you when either a user has uninstalled the app, or has turned of notifications for your app.  Because you get the same response from APNS if the user uninstalls vs. disables notification, you'll have to be creative with combining that information with the app launch data. Even then, it will not be 100% accurate, but should get you in the ballpark.
More details can be found here.


text:
Q: Add response example in SwashBuckle using methods/filters instead of controller attributes I have an API which controllers are defined inside another project in a NuGet that I don't have control over, so I can't add attributes to the controller method or classes as it is usually done with SwashBuckle .
I need to add the swagger documentation externally from another project using SwashBuckle API methods, like a custom IDocumentFilter or ISchemaFilter.
The problem comes trying to do the following:
[ProducesResponseType(typeof(MyClass), (int)HttpStatusCode.Accepted)]
public async Task<IActionResult> Get(MyClass request)

I need to do the same but instead of using the method attribute, using SwashBuckle methods, I'm trying using a custom IDocumentFilter with no luck, like so:
public class MyCustomDocFilter : IDocumentFilter
{
  public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
  {
    var pathInfo = swaggerDoc.Paths.FirstOrDefault(p =>...);
    var operationInfo = pathInfo.Value.Operations.First(op => ...);
    var exampleOperationResponse = operationInfo.Value.Responses.First(op => op.Key == "200");
    exampleOperationResponse.Value.Content.Add(MediaTypeNames.Application.Json, new     OpenApiMediaType {
    // Example = new OpenApiString(@"{ ""someProp"": ""someVal""}"),
    Schema = new OpenApiSchema
    {
        Reference = new OpenApiReference
        {
            Id = typeof(MyClass).Name,
            Type = ReferenceType.Schema
        }
    },

  }
}

If I uncomment above's "Example" line, swagger takes it as if the response is a string instead of using the schema for MyClass which is what I need. The code works well in SwaggerUI, the issue is that using the ReDoc UI from Swashbuckle.AspNetCore.ReDoc shows the following:
Bad response format (what I'm getting):

Expected good response example format (would require to define the response schema):

A: To add your own response model in response of swagger operation, before that you need to add your model to swagger SchemaRepository, after that you can create new response, with your model included in it.
See code below, my model: ErrorResponse
public class ErrorResponse
{
    public int Code { get; set; }

    public string Detail { get; set; }
}

And my swagger OperationFilter code:
public class YourOperationFilter: IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // Try to get my model from swagger schema repository
        context.SchemaRepository.TryLookupByType(typeof(ErrorResponse), out var schema);

        if (schema is null)
        {
            // Add schema inside if to exclude multiple adding situation
            schema = context.SchemaGenerator.GenerateSchema(typeof(ErrorResponse), context.SchemaRepository);
        }

        var content = new Dictionary<string, OpenApiMediaType>()
            {
                {"application/json", new OpenApiMediaType { Schema = schema } }
            };

        // Add response
        operation.Responses.Add("500", new OpenApiResponse { Content = content });
    }
}

Add OperationFilter in swagger gen:
public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(x =>
    {
        x.OperationFilter<YourOperationFilter>();
    });
}

see swagger result here


text:
Q: Cannot summarize the qty in SQL Server I currently make a query DB to summary the Qty based on ShipNo, but it could not be summarized- due to the different date are exists. I have tried to convert the date  format using yyyy-mm-dd but It does not solve it. Did I miss something ?
Here is the code that I used.
SELECT DISTINCT  T1.ShipNo
            ,    CONVERT(VARCHAR,T1.EndDt,23) EndDt
            ,    SUM(T2.ShipQty) AS ShipQty
FROM WNTPRD.ASSY_2022.dbo.T_MetalShip AS T1
INNER JOIN WNTPRD.ASSY_2022.dbo.T_MetalShip_Lot AS T2 ON T1.MetalShipID = T2.MetalShipID
WHERE 0=0
AND T1.ShipNo = 'TIC1P03Q00010'
GROUP BY T1.ShipNo, T1.EndDt

And here is the result of the query above;
enter image description here


text:
Q: +'0' wont give char value of int I was trying to make this int to char program.  The +'0' in the do while loop wont convert the int value to ascii, whereas, +'0' in main is converting.  I have tried many statements, but it won't work in convert() .
#include<stdio.h>
#include<string.h>
void convert(int input,char s[]);
void reverse(char s[]);

int main()
{
        int input;
        char string[5];
        //prcharf("enter int\n");
        printf("enter int\n");
        scanf("%d",&input);
        convert(input,string);
        printf("Converted Input is : %s\n",string);
        int i=54;
        printf("%c\n",(i+'0')); //This give ascii char value of int
        printf("out\n");
}

void convert(int input,char s[])
{
        int sign,i=0;

        char d;
        if((sign=input)<0)
                input=-input;

        do
        {
                s[i++]='0'+input%10;//but this gives int only
        } while((input/=10)>0);

        if(sign<0)
                s[i++]='-';

        s[i]=EOF;
        reverse(s);
}

void reverse(char s[])
{
        int i,j;
        char temp;
        for(i=0,j=strlen(s)-1;i<j;i++,j--)
        {
                temp=s[i];
                s[i]=s[j];
                s[j]=temp;
        }
}

Output screenshot
Code screenshot

A: I tried your program and it is working for the most part.  I get some goofy output because of this line:
s[i]=EOF;

EOF is a negative integer macro that represents "End Of File."  Its actual value is implementation defined.  It appears what you actually want is a null terminator:
s[i]='\0';

That will remove any goofy characters in the output.
I would also make that string in main a little bigger.  No reason we couldn't use something like
char string[12];

I would use a bare minimum of 12 which will cover you to a 32 bit INT_MAX with sign.
EDIT
It appears (based on all the comments) you may be actually trying to make a program that simply outputs characters using numeric ascii values.  What the convert function actually does is converts an integer to a string representation of that integer.  For example:
int num = 123;            /* Integer input */
char str_num[12] = "123"; /* char array output */

convert is basically a manual implementation of itoa.
If you are trying to simply output characters given ascii codes, this is a much simpler program.  First, you should understand that this code here is a mis-interpretation of what convert was trying to do:
int i=54;
printf("%c\n",(i+'0'));

The point of adding '0' previously, was to convert single digit integers to their ascii code version.  For reference, use this: asciitable.  For example if you wanted to convert the integer 4 to a character '4', you would add 4 to '0' which is ascii code 48 to get 52.  52 being the ascii code for the character '4'.  To print out the character that is represented by ascii code, the solution is much more straightforward.  As others have stated in the comments, char is a essentially a numeric type already.  This will give you the desired behavior:
int i = 102    /* The actual ascii value of 'f' */
printf("%c\n", i);

That will work, but to be safe that should be cast to type char.  Whether or not this is redundant may be implementation defined.  I do believe that sending incorrect types to printf is undefined behavior whether it works in this case or not.  Safe version:
printf("%c\n", (char) i);

So you can write the entire program in main since there is no need for the convert function:
int main()
{
        /* Make initialization a habit */
        int input = 0;

        /* Loop through until we get a value between 0-127 */
        do {
                printf("enter int\n");
                scanf("%d",&input);
        } while (input < 0 || input > 127);

        printf("Converted Input is : %c\n", (char)input);
}

We don't want anything outside of 0-127.  char has a range of 256 bits (AKA a byte!) and spans from -127 to 127.  If you wanted literal interpretation of higher characters, you could use unsigned char (0-255).  This is undesirable on the linux terminal which is likely expecting UTF-8 characters.  Values above 127 will be represent portions of multi-byte characters.  If you wanted to support this, you will need a char[] and the code will become a lot more complex.

A:
The +'0' in the do while loop wont convert the int value to ascii

Your own screenshot shows otherwise (assuming an ASCII-based terminal).
Your code printed 56, so it printed the bytes 0x35 and 0x36, so string[0] and string[1] contain 0x35 and 0x36 respectively, and 0x35 and 0x36 are the ASCII encodings of 5 and 6 respectively.
You can also verify this by printing the elements of string individually.
for (int i=0; string[i]; ++i)
   printf("%02X ", string[i]);

printf("\n");


text:
Q: Horizontal Listview and Rss Im feeding my listview with Rss.
just i want to change my listview to horizontal position.
i had try to set with this codes here but i couldnt. how can i include my rss reader in this code.
thank you.
codes which make ur listview horizontal (from link)
public class HorizontalListViewDemo extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.listviewdemo);

    HorizontialListView listview = (HorizontialListView) findViewById(R.id.listview);
    listview.setAdapter(mAdapter);

}

private static String[] dataObjects = new String[]{ "Text #1",
    "Text #2",
    "Text #3" };

private BaseAdapter mAdapter = new BaseAdapter() {

    @Override
    public int getCount() {
        return dataObjects.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewitem, null);
        TextView title = (TextView) retval.findViewById(R.id.title);
        title.setText(dataObjects[position]);

        return retval;
    }

};


text:
Q: How can I pass modal data? bootstrap modal My javascript code like this :

My modal like this :
@for($i = 1; $i <= 5; $i++)

    ...

            ...

                Edit

            ...

    ...

@endfor

data-photo and data-id have value
If the td clicked, it will call modal
I want to display the value of data photo and data id from javascript to data photo and data id in the modal
So if the modal open, data photo and data id in the modal have value
How can I do it?


text:
Q: trying to display json data with angularjs ng-repeat not working I've seen so many ways to do this, but most are pretty old and I want to make sure I'm doing this correctly. Right now, the way I'm using isn't working and I feel like I'm missing something.
I'm getting the JSON back fine, I just need to get it to display in a table after I click the button.
Here is the JSON. This is how I'm going to get it from our server, I can't add any "var JSON =" or add any scope like "$scope.carrier" to the data, unless there's a way to add it after I've fetched the data.
{
    "carrier":
    [
        {
        "entity": "carrier",
        "id": 1,
        "parentEntity": "ORMS",
        "value": "Medica"
    }, {
        "entity": "carrier",
        "id": 2,
        "parentEntity": "ORMS",
        "value": "UHG"
    }, {
        "entity": "carrier",
        "id": 3,
        "parentEntity": "ORMS",
        "value": "Optum"
    }, {
        "entity": "carrier",
        "id": 4,
        "parentEntity": "ORMS",
        "value": "Insight"
    }, {
        "entity": "carrier",
        "id": 5,
        "parentEntity": "ORMS",
        "value": "Insight"
    }
    ]
}

Here is the app.js file to bring back the JSON data:
var app = angular.module('myTestApp', []);

app.controller('myController', ['$scope', '$http', function($scope, $http) {
var url = 'test.json';
  $scope.clickButton = function() {
    $http.get(url).success(function(data) {
        console.log(data);
      });
  }
}]);

And then of course the HTML:

             <button type=button class="btn btn-primary load" ng-click="clickButton()">Click!</button>

{{ module.entity }}

{{ module.id }}

{{ module.parentEntity }}

{{ module.value }}

I'm also wondering if I can use the ng-grid to put this in a table. I know they just upgraded it to ui grid so I'm not sure if this is still a feasible approach.
Also, I'm not getting errors, the data just won't display in the table right now. All I know is its returning the data properly, just not displaying in the table.
Any help is appreciated.

A: You never assign the value of the returned array to $scope.carriers.
At the line where you say console.log(data); add this:
$scope.carriers = data.data;

Here is the updated clickButton function (with a variable name change to reduce confusion):
$scope.clickButton = function() {
  $http.get(url).success(function(returnValue) {
    $scope.carriers = returnValue.data;
  });
};

A: I looked at your plunker seems like you need to:

*

*add angular script

*wire the app and the controller

*your variable in the repeater is wrong, I change it

take a look to this fixed plunker:
http://plnkr.co/edit/TAjnUCMOBxQTC6lNJL8j?p=preview
 $scope.clickButton = function() {
     $http.get(url).success(function(returnValue) {
         alert(JSON.stringify(returnValue.carrier));
         $scope.carriers = returnValue.carrier;
      });
  }


text:
Q: help me identify this novel from my childhood I remember a quote about "it's eye was bigger than alaska". It's about a monster dragon that was huge and constantly demanded to be fed

A: Just to close off the question as per comments, it was The Iron Man by Ted Hughes.


text:
Q: Facebook - call canvas application from page I have develop simple facebook canvas application.
http://apps.facebook.com/myappname/
I want to create page and call this application when user click on page.
Any idea how to do this?
-Thanks

A: It's called a "page tab app". Excellent walk thru located here: https://developers.facebook.com/docs/appsonfacebook/pagetabs/


text:
Q: Listview binding works with shared runtime but not when it's disabled (Xamarin Forms / Visual Studio) I have a ListView that gets data bound from a DataTable. It works and shows the data when I have "Shared Runtime" enabled. When that's disabled the data doesn't appear.
 DataTable DataTableContactList = new DataTable();
                DataTableContactList.Columns.Add("AccountId");
                DataTableContactList.Columns.Add("Username");

                foreach (Contact c in encryptedContactList.Contact)
                {
                    DataRow row = DataTableContactList.NewRow();
                    row["AccountId"] = Security.DecryptStringAES(c.encryptedContactAccountId, Utility.Prefs.Get("guid"));
                    row["Username"] = Security.DecryptStringAES(c.encryptedContactUsername, Utility.Prefs.Get("guid"));
                    //await DisplayAlert("Alert", "row['Username']: " + row["Username"].ToString(), "", "ok");
                    DataTableContactList.Rows.Add(row);

                }

                ListViewContactList.ItemsSource = DataTableContactList.DefaultView;
                ListViewContactList.EndRefresh();
                lblNoContacts.IsVisible = false;

A: What worked for me was changing ".Android>Android Options>Linker properties>Linking" to "None". I tried both "Sdk Assemblies Only" and "Sdk and User Assemblies" but neither of them worked for me. Now I don't understand why this worked, and I hope I haven't caused some other component to stop working. If anyone has extra input on this, I would appreciate it. As far as I can tell I still have all the functionality I need, so I'll just continue forward without question.... for now...


text:
Q: Is there a cleaner way of converting an Either to an ExceptT? I have some functions which return Either values and I'd like to use them in an IO do block with what I think is called "short circuit" behaviour so that any Left values cause the rest of the items on the IO block to be bypassed. The best I've come up with so far looks something like this (an artificial example which illustrates what I'm trying to do):
import Control.Monad.Except

main :: IO ()
main = handleErrors <=< runExceptT $ do
  liftIO $ putStrLn "Starting..."
  let n = 6
  n' <- ExceptT . return . f1 $ n
  liftIO $ putStrLn "First check complete."
  n'' <- ExceptT . return . f2 $ n'
  liftIO $ putStrLn "Second check complete."
  liftIO $ putStrLn $ "Done: " ++ show n''

handleErrors :: Either String () -> IO ()
handleErrors (Left err) = putStrLn $ "*** ERROR: " ++ err
handleErrors (Right _) = return ()

f1 :: Integer -> Either String Integer
f1 n
  | n < 5 = Left "Too small"
  | otherwise = Right n

f2 :: Integer -> Either String Integer
f2 n
  | n == 10 = Left "Don't want 10"
  | otherwise = Right n

The ExceptT . return looks clumsy - is there a better way? I don't want to change the functions themselves to return ExceptT values.

A: If I'm reading the types right, ExceptT . return does the same thing as liftEither. (It has a mildly more complicated implementation in order to work with any instance of MonadError)

A: If you have control of f1 and f2, then one way would be to generalize them:
f1 :: MonadError String m => Integer -> m Integer
f1 n | n < 5 = throwError "Too small" | otherwise = pure n

f2 :: MonadError String m => Integer -> m Integer
f2 n | n == 10 = throwError "Don't want 10" | otherwise = pure n

Actually, I'd be tempted to even abstract this pattern:
avoiding :: MonadError e m => (a -> Bool) -> e -> a -> m a
avoiding p e a = if p a then throwError e else pure a

f1 = avoiding (<5) "Too small"
f2 = avoiding (==10) "Don't want 10"

Anyway, once you have the more general type, then you can use it directly either as an Either or an ExceptT.
main = ... $ do
    ...
    n' <- f1 n
    n'' <- f2 n'
    ...

If you do not have control of f1 and f2, then you might enjoy the errors package, which offers, among many other handy things, hoistEither. (This function may be available other places as well, but the errors package offers many useful things for converting between error types when you must call other people's functions.)

A: The answers above are good, but it's worth knowing about a package which solves this problem in three very common cases - lifting Maybe, Either and ExceptT into monads that look like ExceptT - hoist-error
It defines this somewhat cryptic looking class
class Monad m => HoistError m t e e' | t -> e where

  -- | Given a conversion from the error in @t a@ to @e'@, we can hoist the
  -- computation into @m@.
  --
  -- @
  -- 'hoistError' :: 'MonadError' e m -> (() -> e) -> 'Maybe'       a -> m a
  -- 'hoistError' :: 'MonadError' e m -> (a  -> e) -> 'Either'  a   b -> m b
  -- 'hoistError' :: 'MonadError' e m -> (a  -> e) -> 'ExceptT' a m b -> m b
  -- @
  hoistError
    :: (e -> e')
    -> t a
    -> m a

and several operators, such as:
-- Take the error returns and wrap it in your own error type
(<%?>) :: HoistError m t e e' => t a -> (e -> e') -> m a
-- If an error occurs, return this specific error
(<?>) :: HoistError m t e e' => t a -> e' -> m a

Through the instances of the class, these functions can have these types:
(<%?>) :: MonadError e m => Maybe       a -> (() -> e) ->           m a
(<%?>) :: MonadError e m => Either  a   b -> (a  -> e) ->           m b
(<%?>) :: MonadError e m => ExceptT a m b -> (a  -> e) -> ExceptT e m b

(<?>) :: MonadError e m => Maybe       a -> e ->           m a
(<?>) :: MonadError e m => Either  a   b -> e ->           m b
(<?>) :: MonadError e m => ExceptT a m b -> e -> ExceptT e m b

which make working with errors simpler:
data Errors
  = ValidationError String
  | ValidationNonNegative
  | DatabaseError DBError
  | GeneralError String

storeResult :: Integer -> ExceptT DBError IO ()
storeResult n = <write to the database>

log :: MonadIO m => String -> m ()
log str = liftIO $ putStrLn str

validateNonNeg :: Integer -> Maybe Integer
validateNonNeg n | n < 0 = Nothing | otherwise = Just n

main :: IO ()
main = handleErrors <=< runExceptT $ do
  liftIO $ putStrLn "Starting..."
  let n = 6
  n' <- f1 n                      <%?> ValidationError
  log "First check complete."
  n'' <- f2 n'                    <%?> ValidationError
  log "Second check complete."
  validateNonNeg                  <?>  ValidationNonNegative
  storeResult n''                 <%?> DatabaseError
  log "Stored to database"
  log $ "Done: " ++ show n''

In this example, you can see that we can now treat Either, Maybe and ExceptT as if they are native to our own applications monad.
The alignment of the operators is something I've always done when I use the package, so you can ignore them and just read the happy path code. In large applications, this style works really well and makes code review high nicer because you can ignore the error related code and focus on the logic.


text:
Q: Getting "can not find channel named "stdout" error" while using C# WPF I am trying to build a WPF GUI to control IXIA interface which is written in TCL (IXIA is application which control hardware), TCL version is 86.
For this purpose, I have created the following:

*

*C# project which consists of

*

*TCL_API.cs class - contains the tcl DLLs.

*IXIA.cs class - Contains all methods to access IXIA additianlly the evalScript method that invoke the TCL_API.cs class which is handle with the TCL commands.

*WPF in visual Studio 2013. With calling methods to IXIA.cs.

The problem is that one of TCL commands get an error "can not find channel named "stdout".
As I found out, its probably happens because this TCL command contains puts method inside.
I think puts override can solve this issue but don"t know how to do is as I don"t have entire TCL code but only the DLLs.
See the code:

*

*TclAPI.cs
class TclAPI
{
    [DllImport("tcl86.DLL", CallingConvention = CallingConvention.Cdecl)]
    public static extern int Tcl_Init(IntPtr interp);
    [DllImport("tcl86.DLL", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr Tcl_CreateInterp();
    [DllImport("tcl86.Dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int Tcl_Eval(IntPtr interp, string skript);
    [DllImport("tcl86.Dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr Tcl_GetObjResult(IntPtr interp);
    [DllImport("tcl86.Dll", CallingConvention = CallingConvention.Cdecl)]
    unsafe public static extern char* Tcl_GetStringFromObj(IntPtr tclObj, IntPtr length);
}

*IXIA.cs constructor:
public IXIA(string ip, string username="admin", string password = "admin")
{
    interp = TclAPI.Tcl_CreateInterp();
    TclAPI.Tcl_Init(interp);
    if (interp == IntPtr.Zero)
    {
        throw new SystemException("can not ini tialize Tcl interpreter");
    }
    _ip = ip;
    _userName = username;
    _password = password;
}

*evalScript method in IXIA.cs class:
public int evalScript(string script)
    {
        int Evalres = TclAPI.Tcl_Eval(interp, script);
        return Evalres;
    }

A: Since you're interfacing to a real Tcl interpreter, the problem is that the standard channels (of which stdout is a member) are not being registered. I'm not exactly sure what is wrong, but the problem is either that Tcl's incompletely initialised, or that you've built your overall application in a mode that doesn't support standard channels.
If it is the former, adding a registration for Tcl_FindExecutable (takes a single char*, which can be NULL, and returns void) and calling it once, before any other Tcl API functions will fix it. (That function is a bit mis-named; it really should be called something like Tcl_InitLibrary or something like that.)
[DllImport("tcl86.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern void Tcl_FindExecutable(string argv0);

TclAPI.Tcl_FindExecutable(null);

(See How can I run a static initializer method in C# before the Main() method? for a good way to make that call happen exactly once; this is exactly the sort of code that belongs in a static constructor.)
If the latter, you need to either build your application in a mode that ensures that there's a console available, or use Tcl_SetStdChannel to install a replacement. That's a public API, but not one designed to be easy to call from any languages other than C (or C++ in a pinch) since it involves creating a general Tcl channel instance first via Tcl_CreateChannel and that's a non-trivial API; I think you probably ought to regard it as off-limits as it requires quite a lot of knowledge of Tcl's channel model to use well.
Because of the API complexity involved, I'll not guide you through doing a new channel.

You could try replacing the puts command prior to running the problem script… but as that is used for all file and socket writing, not just writing to the console, you need to be careful. Try evaluating the script below before running the problem script:
rename puts puts_original
proc puts {args} {
    if {[llength $args] == 1} {
        set args [linsert $args 0 stdout]
    } elseif {[llength $args] == 2 && [lindex $args 0] eq "-nonewline"} {
        set args [linsert $args 1 stdout]
    }
    if {[lindex $args end-1] eq "stdout"} {
        # Doing nothing here, but might want to log somehow?
    } else {
        puts_original {*}$args
    }
}

This isn't code that I'd recommend normally — it's much better to actually fix the standard channels so that they work, and this is all rather flaky — but sometimes it is the best that can be done. Unless the code also creates sub-interpreters or threads, in which case you're really stuck.


text:
Q: Set up user inbox service with Phoenix and RethinkDB I am trying to set up a messaging system similar to LinkedIn for my app.  I am using Phoenix Framework and RethinkDB for persistence.  I am using RethinkDB instead of the default Postgres because the site is very fluid right now and in its infancy.  I can't really lock in a firm schema and relationships with things more than likely going to change as the app matures.  I am having a lot of trouble figuring out how to set up the documents and fields for the database, and leverage Phoenix to create the proper form field to accept an array of recipients.  I would like to set it up with the following guidelines:

*

*A User can create a message.

*The message can be sent to one or more people.

*A message can be saved as a draft.

*The message can be replied to with the previous messages attached as a chain.

The main issues I am having are with collecting multiple recipients with form fields, and setting up the database to support the above mentioned guidelines.  If someone could get me started and on the right track, it would be a great help.

A: If you are just prototyping and getting to know the framework you might be better off with Postgres because it's so well supported. Migrations are there for a reason so you won't be stuck with a schema just because you are using Postgres. You should create data models that represent the problem prior to selecting a database, or at least treat it as a separate concern.
The form is going to be generated from a changeset. When using Rethink, changesets will be used for generation and validation but will not be applied the way they are with postgres. Start with a User model and a Message model. Have a "published" field in the Message model and it should be represented by a checkbox in the generated form.


text:
Q: AGPL - passwords in code I'm looking at putting up a fan site for an author using code released under the AGPL. Under the AGPL, as I understand it, I would need to publish my code modifications. This is entirely fine.
However, the website is in django. I will probably be deploying with Docker, and forking the project to do so. If I want to automate deployment I will probably need to write code that at least sets some passwords as environment variables or something.
Is the AGPL "contagious"? If so, how do I get around a requirement to make available for download code that contains the private database passwords and such?

A: Never ever commit secrets to source control. And by extension, never build a container image that includes secrets. Instead, secrets should be provided during deployment, e.g. as environment variables. If you are using some cloud provider, they probably have special tooling to manage keys and other secrets.
If you need to store secrets during development, perhaps use a config file but never commit these files. Instead, explicitly .gitignore them.
Now that you aren't version-controlling any secrets, your repository is already in a publishable state, and complying with the AGPL is easy. The (A)GPL does not force you to make any passwords, API keys, or other secrets publicly available, except under the very limited circumstances that you are embedding (A)GPLv3 software into an embedded device, and such secrets are necessary for installing modified versions on that device.
Recommended reading: The twelve-factor app, a short guide to web app architecture and deployment. Especially consider their definition of configuration and their distinction between build, release, and run phases.


text:
Q: PHP - get checkbox value and change it if checked in database Table
id  name            level   delete_user

1   visitor         1       N
2   user            2       N
3   moderator       3       N
4   administrator   4       Y

Then I fetch array from database:
$groups = array (
    array ( 'id' => 1, 'name' => 'visitor', 'level' => 1, 'delete_user' => 'N'),
    array ( 'id' => 2, 'name' => 'user', 'level' => 2, 'delete_user' => 'N'),
    array ( 'id' => 3, 'name' => 'moderator', 'level' => 3, 'delete_user' => 'N'),
    array ( 'id' => 4, 'name' => 'administrator', 'level' => 4, 'delete_user' => 'Y')
);

Then I create simple FORM to show actual settings of groups.
<form action="" method="post">

                name
                level
                delete user

            <?php foreach ($groups as $group) { ?>
                <?php
                    $checkbox['delete_user_' . $group['id']] = 'N';
                    $checked = ($group['delete_user'] === 'Y') ? 'checked="checked"' : '';
                ?>

                    <?php echo $group['name']; ?>
                    <?php echo $group['level']; ?>

                        <input type="checkbox" name="delete_user_<?php echo $group['id']; ?>" <?php echo $checked; ?> value="Y">

                <?php
            }
            ?>

    <input type="submit" name="save_groups" value="Save" class="save_button">
</form>

Question: How to check if checkbox checked or not, and if checked then change it in database?
My work:
This is raw idea, but not pretty ...
<?php
if (isset($_POST['save_groups'])) {

    foreach ($_POST as $k => $v) {
        if (array_key_exists($k, $checkbox)) {
            $checkbox[$k] = $v;
        }
    }
    echo 'NEW';
    print_r($checkbox);
    echo '
';
    foreach($checkbox as $k => $v) {
        $id = str_replace('delete_user_', '', $k);
        echo 'changing '. $id . ' to '. $v. '
';
        // changing value
        /**
         * $id int - id of group
         * $v string - value in delete_user ('Y' / 'N')
         */
        $this->change_value($id, $v);
    }

}

A: While unchecked checkboxes will not be serialized during form submission, you can simply take advantage of this very common trick:
To determine whether checkbox is checked or not, you can prepend <input type="hidden" /> before a checkbox itself, like this:
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1" />

So if a checkbox is checked, $_POST['foo'] will contain 1, and if its not checked, then $_POST['foo'] will contain 0

A: One approach would be to make the checkbox into an array and change it so it returns the group ID, not just a "Y". UPDATE: Based on Anthony's comment below, you need to track the existing check state too:

    <?php if ($group['delete_user'] === 'Y') { ?>
    <input type="hidden" name="existing[]" value="<?php echo <?php echo $group['id']; ?>">
    <?php } ?>
    <input type="checkbox" name="delete_user[]" <?php echo $checked; ?> value="<?php echo <?php echo $group['id']; ?>">

Now all you have to do in your POST code is:
<?php
$previously_checked = $_POST['existing'];
$group_ids = $_POST['delete_user'];
$updated_state = array();

// Check if previously-selected checkbox has been unchecked
foreach($previously_checked as $group_id) {
   if (!in_array($group_id, $group_ids)) {
      $updated_state[] = array('group_id' => $group_id, 'delete_user' => 'N');
   }
}
// Check for currently-selected checkbox was previously unchecked
foreach($group_ids as $group_id) {
   if (!in_array($group_id, $previously_checked)) {
      $updated_state[] = array('group_id' => $group_id, 'delete_user' => 'Y');
   }
}

// Do the update...

A: Don't do what @Scorpion, @Ken, or what I wrote earlier. Simply give all your checkbox input controls their own name based on the id (primary key) (like you started out doing) and during your input validation, use isset($_POST['yourKeyHere']) to detrmine if the record's checkbox has been successfully submitted or not. If so, run a "positive" UPDATE on the associated record. If not, run a "negative" update on the record. Simple and sweet, if not a bit wasteful. This method does not compromise the security of your form application, but it may run unnecessary updates on your table (because the field is already either 'N' or 'Y').
You don't want to invite people to submit garbage to your app. Oh, there's a way to do that simply by changing the HTML, but when the checkbox is unchecked, I do not want my backend to receive anything for that input control!


text:
Q: xfbml like button hide the possibility to add a comment to the like I added a like button in a facebook application (not iframe in order to capture the liked evenment...),
and when a user click on like, then he has the possibility to add a comment to the like.
I want to hide/remove this possibility to adda comment when he click on like.
Do you know if it's possible and how to do that?
Thanks

A: Set a fixed height and overflow hidden on the div that contains your like button so that it is hidden after the user clicks 'like'.

A: I added these CSS classes to my css file and it got rid of the comment box for me.
.fb_edge_widget_with_comment .fb_edge_comment_widget .fb_ltr {
display: none !important;
}


text:
Q: using delimiter but not delete spaces I am writing a program where I want to split a string separated by comma. My problem is a user can pass or input the string to the program like this:
   Hello,,hey,123

So, is there a way that I can add a space between the hello and hey before I append it to a arraylist. Also my delimiter is ignoring the double ,, and just going to the next word why is that ?

A: String s = "Hello,,hey,123";
String[] tokens = s.split(",", -1);


text:
Q: How to make sure that the column value is always added in Uppercase? I have an existing column host and want to make sure that the column value host is always added in Uppercase.
I am using Alter Table command as below:
ALTER TABLE `mydb`.`myTable`
CHANGE COLUMN `host` `host`
VARCHAR(255) GENERATED ALWAYS AS (UPPER()) STORED;

This is causing an error and I am not able to alter the column.

Operation failed: There was an error while applying the SQL script to the database.
ERROR 1582: Incorrect parameter count in the call to native function 'UPPER'
SQL Statement:
ALTER TABLE mydb.myTable
CHANGE COLUMN host host VARCHAR(255) GENERATED ALWAYS AS (UPPER()) VIRTUAL

I want to make sure that moving forward the value inserted in host is always in uppercase.
I want to achieve this by updating the value in uppercase at runtime.
I don't want to add any constraint as it will cause an error when the host value is entered in lowercase.

A: It is not entirely clear what you are trying to do.
If you want to set a constraint on the table that allows only upper case letters in host, use a check constraint:
alter table mytable
    add constraint chk_host_upper
    check (host rlike '^[A-Z]*$')
;

This prevents lower case character to be written to the column; an attempt to do so results in a runtime error.
If, on the other hand, you want to create a new column, that returns the upper case value of host, regardless of the actual column code:
alter table mytable
     add column host_upper varchar(50)  -- same as the original column
     as (upper(host))
;

With this set up at hand, you can query the new column host_upper when you want the upper case values.

Finally: if you want to convert input value to upper case on the fly on inserts, then you need a trigger:
delimiter //

create trigger mytrigger
before insert on mytable
for each row
begin
    set new.host = upper(new.host);
end
//

delimiter ;

A: You can just assign the host column to have a case insensitive collation:
ALTER TABLE mydb.myTable MODIFY host VARCHAR(255)
CHARACTER SET latin1
COLLATE latin1_swedish_ci;

Now the case of the host you use when inserting does not matter, and you may compare against this column using any case.  If you still need to view the host as uppercase, then just use UPPER():
SELECT UPPER(host) AS host_upper
FROM myTable;


text:
Q: EF: Login exception when binding custom object to User Identity
Unable to determine the principal end of an association between the types 'EntityFrameworkDatabase.Person' and 'EntityFrameworkDatabase.ApplicationUser'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

I know this questions is answered many times but I think I experience a different problem. ref
I have a relation (0-1 0-1) between User in Identity class and my own class Person. ref, ref
            modelBuilder.Entity<ApplicationUser>()
            .HasOptional(s => s.Person)
            .WithOptionalPrincipal()
            .Map(s => s.MapKey("ApplicationUserId"));

        modelBuilder.Entity<Person>()
            .HasOptional(s => s.ApplicationUser)
            .WithOptionalPrincipal()
            .Map(s => s.MapKey("PersonId"));

It works fine to migrate and I get two FK. But when I try to login a user I get an exception at
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

Why I get the exception when trying to login but not Updating the db and how to solve the problem?

A: The solution is to use the same context for the OwinContext as for the DataContext.


text:
Q: How to set password for PostgreSQL database with a script? In a bash script I'm writing, I need to create a database and set a password that is generated automatically by my script.
The problem is I can't find a way to set up the password without user interaction.
I need something like this:
$ createdb mydb -p $(cat password_file)

Any ideas?

A: From the documentation:

createdb is a wrapper around the SQL command CREATE DATABASE.
  There is no effective difference between creating databases via this
  utility and via other methods for accessing the server.

This means that you can write a script which issues a command like
psql -f createdb.sql -v passwd=$passwd -v user=$user

Where createdb.sql contains something like
CREATE ROLE :user WITH LOGIN PASSWORD :passwd;
CREATE DATABASE mydb OWNER :user;
GRANT {some privileges on the newly created database and/or its objects};

This means that you will have a user for every database created.
(At the same time I have a mild suspicion that your problem is what riouj answered.)

A: In order to connect to your PostgreSQL instance and run the createdb script, which is a client, you can use a password file. This file is generally located at ~/.pgpass and must contain theses information :
hostname:port:database:username:password

If you want to use a different path for your password file, you can set the PGPASSFILE environment variable.
For security concerns, you can change its rights :
chmod 600 ~/.pgpass

If you don't want createdb to prompt you for any password, you can use the -w switch (or --no-password) and use the password file.
You can take a look at the documentation for these features :

*

*http://www.postgresql.org/docs/9.2/static/app-createdb.html

*http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html


text:
Q: Contract requires Session, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it When i'm using SessionMode = SessionMode.Required in servicecontract then i get this error

Contract requires Session, but Binding 'BasicHttpBinding' doesn't
  support it or isn't configured properly to support it.

anyone tell me a solution?

A: This error message is seldom clear. Here the answer goes like this, basichttpbinding doesn't support session. So you have to use the below property if you want to use it.
[ServiceContract(SessionMode = SessionMode.Allowed)]
This means, If you are trying to configure multiple bindings like basichttp, wshttp, net.tcp, WCF will automatically enable session for other than basichttp binding. so if you put SessionMode.Required instead of Allowed, then you are forced not to use basichttpbinding.
That said, solving this issue usually would require something like this:
<system.serviceModel>
    <protocolMapping>
      <add scheme="http" binding="wsHttpBinding" bindingConfiguration="wsHttpBindingConfiguration" />
    </protocolMapping>
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpBindingConfiguration" transactionFlow="true" />
      </wsHttpBinding>
      .......

A: As it's listed here, choose wsHttpBinding or NetTcpBinding.WSHttpBinding binding.


text:
Q: Cannot declare class Google\Google_Client, because the name is already in use in vendor/google/apiclient/src/Google/Client.php Using this code to access google analytics data but keep on getting the above error

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/vendor/google/apiclient/src/Google/Client.php';
//require_once __DIR__.'/vendor/google/apiclient/src/Google/autoload.php';
$analytics = initializeAnalytics();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);
//use Google_Client;
function initializeAnalytics()
{
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);

return $analytics;
}


text:
Q: What's the meaning of $\mathcal O_S$-algebra? Let $(S,\mathcal O_S)$ be a scheme. What's the definition of $\mathcal O_S$-algebra?

A: It's a sheaf  $\mathcal{A}$ of $\mathcal{O}_S$-modules on $S$ which is also a sheaf of rings, such that the $\mathcal{O}_S$-module map $\mathcal{O}_S \to \mathcal{A}$ induced by $1 \mapsto 1$ is a ring map.
(Equivalently, a sheaf of rings $\mathcal{A}$ on $S$ together with a ring homomorphism $\mathcal{O}_S \to \mathcal{A}$.)


text:
Q: RuntimeException during maven build of Java 9 spring boot application The Java 9 application I am building compiles and works well from IntelliJ IDE. On IDE, I have tried configuring as both Spring Boot application as well as plain Application and both configuration work well.
While executing maven build, I encounter RuntimeException with below stacktrace.
Caused by: java.lang.RuntimeException
    at org.springframework.asm.ClassVisitor.visitModule(ClassVisitor.java:148)
    at org.springframework.asm.ClassReader.readModule(ClassReader.java:762)
    at org.springframework.asm.ClassReader.accept(ClassReader.java:663)
    at org.springframework.asm.ClassReader.accept(ClassReader.java:527)
    at org.springframework.boot.loader.tools.MainClassFinder.createClassDescriptor(MainClassFinder.java:267)
    at org.springframework.boot.loader.tools.MainClassFinder.doWithMainClasses(MainClassFinder.java:223)
    at org.springframework.boot.loader.tools.MainClassFinder.findSingleMainClass(MainClassFinder.java:203)
    at org.springframework.boot.loader.tools.Repackager.findMainMethod(Repackager.java:365)
    at org.springframework.boot.loader.tools.Repackager.findMainMethodWithTimeoutWarning(Repackager.java:354)
    at org.springframework.boot.loader.tools.Repackager.buildManifest(Repackager.java:325)
    at org.springframework.boot.loader.tools.Repackager.repackage(Repackager.java:255)
    at org.springframework.boot.loader.tools.Repackager.repackage(Repackager.java:248)
    at org.springframework.boot.loader.tools.Repackager.repackage(Repackager.java:193)
    at org.springframework.boot.maven.RepackageMojo.repackage(RepackageMojo.java:221)
    at org.springframework.boot.maven.RepackageMojo.execute(RepackageMojo.java:208)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    ... 22 more

On analyzing, its being caused because of the ASM api level provided. With direct execution, it is org.springframework.asm.Opcodes#ASM6, but when using maven build it is Opcodes#ASM4 which is causing the issue.
Further analysis reveals that the instances are created as below -
Maven Build - https://github.com/spring-projects/spring-boot/blob/d3c34ee3d1bfd3db4a98678c524e145ef9bca51c/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java#L301
IDE Execution - https://github.com/spring-projects/spring-framework/blob/43b5e21947f3ad9682ae39cd8b8b5ae4b8f72c14/spring-core/src/main/java/org/springframework/core/type/classreading/ClassMetadataReadingVisitor.java#L71
Let me know if I need to report this as an issue with Spring Framework or if any workarounds exist.
Maven Version: 3.5.0
Spring Boot: 2.0.0.M5
Its a modular build and POM files are here: https://gist.github.com/techpavan/faa81d46321004cd50e7403b03d70a2e
A simpler reproducer is available here - https://github.com/techpavan/java9-maven-spring-boot
With this reproducer, you can find that maven build fails readily. But when put a breakpoint at org.springframework.asm.ClassVisitor > line 78 (Constructor) and update the api value during execution to 393216 (ASM6), you'll find that the build completes successfully. By default the value is set to 262144 (ASM4) which fails at line 147.
Update: The issue is accepted as bug by Spring community and should be fixed in Milestone 6 release - https://github.com/spring-projects/spring-boot/issues/10647
Update: The issue is fixed in the spring-boot master branch on Oct 17, 2017. Should be a part of M6 release.

A: Your mvn dependency:tree describes it as follows:-
➜[main] [INFO] +- org.springframework.boot:spring-boot-starter-jetty:jar:2.0.0.M5:compile
 [main] [INFO] |  +- org.eclipse.jetty:jetty-servlets:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  +- org.eclipse.jetty:jetty-continuation:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  +- org.eclipse.jetty:jetty-http:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  +- org.eclipse.jetty:jetty-util:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  \- org.eclipse.jetty:jetty-io:jar:9.4.7.v20170914:compile
 [main] [INFO] |  +- org.eclipse.jetty:jetty-webapp:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  +- org.eclipse.jetty:jetty-xml:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  \- org.eclipse.jetty:jetty-servlet:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |     \- org.eclipse.jetty:jetty-security:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |        \- org.eclipse.jetty:jetty-server:jar:9.4.7.v20170914:compile
 [main] [INFO] |  +- org.eclipse.jetty.websocket:websocket-server:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  +- org.eclipse.jetty.websocket:websocket-common:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  |  \- org.eclipse.jetty.websocket:websocket-api:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  +- org.eclipse.jetty.websocket:websocket-client:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  |  \- org.eclipse.jetty:jetty-client:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  \- org.eclipse.jetty.websocket:websocket-servlet:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |     \- javax.servlet:javax.servlet-api:jar:3.1.0:compile
 [main] [INFO] |  +- org.eclipse.jetty.websocket:javax-websocket-server-impl:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  +- org.eclipse.jetty:jetty-annotations:jar:9.4.7.v20170914:compile
 [main] [INFO] |  |  |  +- org.eclipse.jetty:jetty-plus:jar:9.4.7.v20170914:compile
➜[main] [INFO] |  |  |  +- org.ow2.asm:asm:jar:5.1:compile
 [main] [INFO] |  |  |  \- org.ow2.asm:asm-commons:jar:5.1:compile
 [main] [INFO] |  |  |     \- org.ow2.asm:asm-tree:jar:5.1:compile

This clearly reflects that the dependency on spring-boot-starter-jetty for your project relies on asm:5.1 and the version of asm is not compatible with the latest Java release. You can try upgrading to 6.0_BETA version of it.

To what I got to know from this issue, jetty didn't upgrade to the latest version because of its incompatibility with OSGI version number. I'd faced that issue while trying to make vaadin8 application work with Java 9 wherein the solution I could achieve was to build jetty locally and then use a custom version in my project as stated in the answer -

This was attained after overcoming the #jetty.project/1758 by
  upgrading to the 6.0_BETA of asm and asm-commons libraries and using
  the custom 9.4.7-SNAPSHOT built on my local used in the project(commit
  - #e34415.)

Update: This indeed is a bug in spring-boot milestone as confirmed in the edited question as well.

A: Thanks to wilkinsona on GitHub whose workaround helped me on this issue. Just adding a spring-boot-maven-plugin configuration with mainClass entry can solve this problem on M5 release. Expected to have a proper fix on M6.
         <plugin>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
+            <configuration>
+                <mainClass>com.test.TestMain</mainClass>
+            </configuration>
         </plugin>