问:
Display projected event list from existing events
The more I think about this the more complex it seems, but what I am trying to get to is a workload planning report based on work that is underway.  As a job progresses, a row is added to a database (outside of my control) with the date of the last event.  The events happen in sequence and each has a timeframe in which activity should take place.

Example tables and data below:

```<code>CREATE TABLE [dbo].[Customers](
    [Cust_ID] [int] NOT NULL,
    [CustName] [varchar](50) NULL
)
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (1, N'ABC Corp')
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (2, N'Nuke')
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (3, N'ADUDAS')
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (4, N'POMA')

CREATE TABLE [dbo].[EventInfo](
    [Event_Name] [varchar](50) NOT NULL,
    [Sequence] [int] NOT NULL,
    [NextEvent] [varchar](50) NOT NULL,
    [NextEventDays] [int] NOT NULL
)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Received Request', 1, N'Draft Proposal', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Draft Proposal', 2, N'Proposal Accepted', 14)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Proposal Accepted', 3, N'Project Scheduled', 14)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Project Scheduled', 4, N'Project Start', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Project Start', 5, N'Project Complete', 30)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Project Complete', 6, N'Output Accepted', 14)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Proposal Rejected', 3, N'Draft Proposal', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Output Rejected', 6, N'Project Start', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Output Accepted', 7, N'Complete', 0)

CREATE TABLE [dbo].[Events](
    [Cust_ID] [int] NOT NULL,
    [EventName] [varchar](50) NOT NULL,
    [EventDate] [datetime] NOT NULL
)
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Received Request', CAST(N'2017-10-01T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Draft Proposal', CAST(N'2017-10-03T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Proposal Accepted', CAST(N'2017-10-23T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Project Scheduled', CAST(N'2017-10-23T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Project Start', CAST(N'2017-10-25T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (2, N'Received Request', CAST(N'2017-10-11T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Project Complete', CAST(N'2017-11-05T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Output Accepted', CAST(N'2017-11-07T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (2, N'Draft Proposal', CAST(N'2017-10-15T00:00:00.000' AS DateTime))
</code>```

I can get the actual events easily enough.

```<code>+---------+----------+-------------------+-------------------------+----------+-------------------+---------------+-------------------------+
| Cust_ID | CustName |     EventName     |        EventDate        | Sequence |     NextEvent     | NextEventDays |        NextEvent        |
+---------+----------+-------------------+-------------------------+----------+-------------------+---------------+-------------------------+
|       1 | ABC Corp | Received Request  | 2017-10-01 00:00:00.000 |        1 | Draft Proposal    |             5 | 2017-10-06 00:00:00.000 |
|       1 | ABC Corp | Draft Proposal    | 2017-10-03 00:00:00.000 |        2 | Proposal Accepted |            14 | 2017-10-17 00:00:00.000 |
|       1 | ABC Corp | Proposal Accepted | 2017-10-23 00:00:00.000 |        3 | Project Scheduled |            14 | 2017-11-06 00:00:00.000 |
|       1 | ABC Corp | Project Scheduled | 2017-10-23 00:00:00.000 |        4 | Project Start     |             5 | 2017-10-28 00:00:00.000 |
|       1 | ABC Corp | Project Start     | 2017-10-25 00:00:00.000 |        5 | Project Complete  |            30 | 2017-11-24 00:00:00.000 |
|       1 | ABC Corp | Project Complete  | 2017-11-05 00:00:00.000 |        6 | Output Accepted   |            14 | 2017-11-19 00:00:00.000 |
|       1 | ABC Corp | Output Accepted   | 2017-11-07 00:00:00.000 |        7 | Complete          |             0 | 2017-11-07 00:00:00.000 |
|       2 | Nuke     | Received Request  | 2017-10-11 00:00:00.000 |        1 | Draft Proposal    |             5 | 2017-10-16 00:00:00.000 |
|       2 | Nuke     | Draft Proposal    | 2017-10-15 00:00:00.000 |        2 | Proposal Accepted |            14 | 2017-10-29 00:00:00.000 |
+---------+----------+-------------------+-------------------------+----------+-------------------+---------------+-------------------------+
</code>```

... with this query:

```<code>SELECT        Customers.Cust_ID, Customers.CustName, Events.EventName, Events.EventDate, EventInfo.Sequence, EventInfo.NextEvent, EventInfo.NextEventDays, Events.EventDate + EventInfo.NextEventDays AS NextEvent
FROM            Events INNER JOIN
                         EventInfo ON Events.EventName = EventInfo.Event_Name INNER JOIN
                         Customers ON Events.Cust_ID = Customers.Cust_ID
ORDER BY Customers.Cust_ID, EventInfo.Sequence
</code>```

But what I am really after (with the available data) is more like this:

```<code>+---------+----------+-------------------+------------+-------------+
| Cust_ID | CustName |     EventName     | EventDate  | IsEstimated |
+---------+----------+-------------------+------------+-------------+
|       1 | ABC Corp | Received Request  | 1/10/2017  |           0 |
|       1 | ABC Corp | Draft Proposal    | 3/10/2017  |           0 |
|       1 | ABC Corp | Proposal Accepted | 23/10/2017 |           0 |
|       1 | ABC Corp | Project Scheduled | 23/10/2017 |           0 |
|       1 | ABC Corp | Project Start     | 25/10/2017 |           0 |
|       1 | ABC Corp | Project Complete  | 5/11/2017  |           0 |
|       1 | ABC Corp | Output Accepted   | 7/11/2017  |           0 |
|       1 | ABC Corp | Complete          | 7/11/2017  |           0 |
|       2 | Nuke     | Received Request  | 11/10/2017 |           0 |
|       2 | Nuke     | Draft Proposal    | 15/10/2017 |           0 |
|       2 | Nuke     | Proposal Accepted | 29/10/2017 |           1 |
|       2 | Nuke     | Project Scheduled | 12/11/2017 |           1 |
|       2 | Nuke     | Project Start     | 17/11/2017 |           1 |
|       2 | Nuke     | Project Complete  | 17/12/2017 |           1 |
|       2 | Nuke     | Output Accepted   | 22/12/2017 |           1 |
|       2 | Nuke     | Complete          | 22/12/2017 |           1 |
+---------+----------+-------------------+------------+-------------+
</code>```

The idea is that we can select a date range and see what was happening / will be happening during that time.  So each job will have a row for each stage through to completion with a flag to identify if the date displayed is real or projected.

In the table above, rows with 'IsEstimated' = 0 are pulled from the Events table, as per my example query.  Rows with 'IsEstimated' have been calculated based on the last actual event for that Customer, plus the value from [EventInfo].[extEventDays].

Perhaps it is clearer with this:

```<code>+---------+-------------------+------------+-----------+------------+
| Cust_ID |     EventName     |  RealDate  | EventDays |  EstDate   |
+---------+-------------------+------------+-----------+------------+
|       2 | Received Request  | 11/10/2017 |           |            |
|       2 | Draft Proposal    | 15/10/2017 | 5.00      |            |
|       2 | Proposal Accepted |            | 14.00     | 29/10/2017 |
|       2 | Project Scheduled |            | 14.00     | 12/11/2017 |
|       2 | Project Start     |            | 5.00      | 17/11/2017 |
|       2 | Project Complete  |            | 30.00     | 17/12/2017 |
|       2 | Output Accepted   |            | 14.00     | 22/12/2017 |
|       2 | Complete          |            | 0.00      | 22/12/2017 |
|      45 |                   |            |           |            |
+---------+-------------------+------------+-----------+------------+
</code>```

I'm trying to pull the real event records and add rows for events that do not yet exist, along with the cumulative dates of all previous events, based on the 'NextEventDays' of each event.

I should also note here that I do control the structure and content of the 'EventInfo' table, and am thinking that a stored procedure updating into an intermediate table might be preferable (am using this data for SSRS reporting).

Any ideas on how to progress with this would be greatly appreciated.

Thanks

EDIT:  How awesome is SQL Fiddle?

答:
What you need to do is to create a temp table (or table variable, whatever) with the data you need, and then fill it and report from it. I would do something like

Create a temp table with Cust_ID, EventName, EventDate,
IsEstimated

Fill this using the query you already have with the
real data (setting IsEstimated to 0 for these rows)

Create the future estimates (See below) with IsEstimated as yes

Report from this table

To create the estimated data, you need to find the rows that are missing, and figure out what date they should have. You could probably do this in one query with some thought, but doing it in two steps is easier to understand

To get the missing rows, you need a list of all the missing events. You need to figure out a way to specify which events are essential - if possible, I would add another column to the eventinfo table, called something like BestPath, and set it to 1 for the events that are the ideal path. You could then ignore all the others at this point. Cross joining the event info with the Customers table gets you a list of all the steps that should be taken on the ideal path.

However, you've already done some of these. You can't just say don't do anything that already exists, because you might have looped back and need to do some twice, so you need to get the latest valid SeqenceNo for each customer, and then for each customer get all the steps on the best path that come after that sequence number, and insert them in the temp table. Assuming your temp table is #FullData, you need something like this

```<code>--Get the future rows
With EventBase as (
    Select E.Cust_ID, EI.Sequence, E.EventDate, ROW_NUMBER () over (PARTITION BY E.Cust_ID  ORDER BY E.EventDate DESC) as RowNo
    From [Events] E
        INNER JOIN EventInfo EI on EI.Event_Name = E.EventName
), LastKnownEvent as
(
    SELECT Cust_ID, Sequence as LastSequence, EventDate
    FROM EventBase
    WHERE RowNo = 1
), AllEvents as
(
    SELECT EI.Event_Name, EI.Sequence, EI.NextEventDays, LE.Cust_ID, LE.LastSequence, LE.EventDate
    FROM EventInfo EI
        CROSS JOIN LastKnownEvent LE
    WHERE EI.BestPath = 1
)
INSERT INTO #FullData (Cust_ID, Event_Name, Sequence, IsEstimated, LastKnownDate)
SELECT Cust_ID, Event_Name, Sequence, 1, EventDate
FROM AllEvents AE
WHERE Sequence > LastSequence;
</code>```

Once you have that data, process the temp table and calculate the date required for each future row (get the sum of all NextEventDays for all future rows for the same customer with a lower sequence number, plus the nexteventdays for the last known event, then dateadd it to the LastknownDate), and store it in the temp table.

At that point, the temp table should have all the data you need for the report.

Body:
The more I think about this the more complex it seems, but what I am trying to get to is a workload planning report based on work that is underway.  As a job progresses, a row is added to a database (outside of my control) with the date of the last event.  The events happen in sequence and each has a timeframe in which activity should take place.

Example tables and data below:

CREATE TABLE [dbo].[Customers](
    [Cust_ID] [int] NOT NULL,
    [CustName] [varchar](50) NULL
)
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (1, N'ABC Corp')
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (2, N'Nuke')
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (3, N'ADUDAS')
INSERT [dbo].[Customers] ([Cust_ID], [CustName]) VALUES (4, N'POMA')

CREATE TABLE [dbo].[EventInfo](
    [Event_Name] [varchar](50) NOT NULL,
    [Sequence] [int] NOT NULL,
    [NextEvent] [varchar](50) NOT NULL,
    [NextEventDays] [int] NOT NULL
)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Received Request', 1, N'Draft Proposal', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Draft Proposal', 2, N'Proposal Accepted', 14)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Proposal Accepted', 3, N'Project Scheduled', 14)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Project Scheduled', 4, N'Project Start', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Project Start', 5, N'Project Complete', 30)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Project Complete', 6, N'Output Accepted', 14)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Proposal Rejected', 3, N'Draft Proposal', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Output Rejected', 6, N'Project Start', 5)
INSERT [dbo].[EventInfo] ([Event_Name], [Sequence], [NextEvent], [NextEventDays]) VALUES (N'Output Accepted', 7, N'Complete', 0)

CREATE TABLE [dbo].[Events](
    [Cust_ID] [int] NOT NULL,
    [EventName] [varchar](50) NOT NULL,
    [EventDate] [datetime] NOT NULL
)
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Received Request', CAST(N'2017-10-01T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Draft Proposal', CAST(N'2017-10-03T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Proposal Accepted', CAST(N'2017-10-23T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Project Scheduled', CAST(N'2017-10-23T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Project Start', CAST(N'2017-10-25T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (2, N'Received Request', CAST(N'2017-10-11T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Project Complete', CAST(N'2017-11-05T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (1, N'Output Accepted', CAST(N'2017-11-07T00:00:00.000' AS DateTime))
INSERT [dbo].[Events] ([Cust_ID], [EventName], [EventDate]) VALUES (2, N'Draft Proposal', CAST(N'2017-10-15T00:00:00.000' AS DateTime))

I can get the actual events easily enough.

+---------+----------+-------------------+-------------------------+----------+-------------------+---------------+-------------------------+
| Cust_ID | CustName |     EventName     |        EventDate        | Sequence |     NextEvent     | NextEventDays |        NextEvent        |
+---------+----------+-------------------+-------------------------+----------+-------------------+---------------+-------------------------+
|       1 | ABC Corp | Received Request  | 2017-10-01 00:00:00.000 |        1 | Draft Proposal    |             5 | 2017-10-06 00:00:00.000 |
|       1 | ABC Corp | Draft Proposal    | 2017-10-03 00:00:00.000 |        2 | Proposal Accepted |            14 | 2017-10-17 00:00:00.000 |
|       1 | ABC Corp | Proposal Accepted | 2017-10-23 00:00:00.000 |        3 | Project Scheduled |            14 | 2017-11-06 00:00:00.000 |
|       1 | ABC Corp | Project Scheduled | 2017-10-23 00:00:00.000 |        4 | Project Start     |             5 | 2017-10-28 00:00:00.000 |
|       1 | ABC Corp | Project Start     | 2017-10-25 00:00:00.000 |        5 | Project Complete  |            30 | 2017-11-24 00:00:00.000 |
|       1 | ABC Corp | Project Complete  | 2017-11-05 00:00:00.000 |        6 | Output Accepted   |            14 | 2017-11-19 00:00:00.000 |
|       1 | ABC Corp | Output Accepted   | 2017-11-07 00:00:00.000 |        7 | Complete          |             0 | 2017-11-07 00:00:00.000 |
|       2 | Nuke     | Received Request  | 2017-10-11 00:00:00.000 |        1 | Draft Proposal    |             5 | 2017-10-16 00:00:00.000 |
|       2 | Nuke     | Draft Proposal    | 2017-10-15 00:00:00.000 |        2 | Proposal Accepted |            14 | 2017-10-29 00:00:00.000 |
+---------+----------+-------------------+-------------------------+----------+-------------------+---------------+-------------------------+

... with this query:

SELECT        Customers.Cust_ID, Customers.CustName, Events.EventName, Events.EventDate, EventInfo.Sequence, EventInfo.NextEvent, EventInfo.NextEventDays, Events.EventDate + EventInfo.NextEventDays AS NextEvent
FROM            Events INNER JOIN
                         EventInfo ON Events.EventName = EventInfo.Event_Name INNER JOIN
                         Customers ON Events.Cust_ID = Customers.Cust_ID
ORDER BY Customers.Cust_ID, EventInfo.Sequence

But what I am really after (with the available data) is more like this:

+---------+----------+-------------------+------------+-------------+
| Cust_ID | CustName |     EventName     | EventDate  | IsEstimated |
+---------+----------+-------------------+------------+-------------+
|       1 | ABC Corp | Received Request  | 1/10/2017  |           0 |
|       1 | ABC Corp | Draft Proposal    | 3/10/2017  |           0 |
|       1 | ABC Corp | Proposal Accepted | 23/10/2017 |           0 |
|       1 | ABC Corp | Project Scheduled | 23/10/2017 |           0 |
|       1 | ABC Corp | Project Start     | 25/10/2017 |           0 |
|       1 | ABC Corp | Project Complete  | 5/11/2017  |           0 |
|       1 | ABC Corp | Output Accepted   | 7/11/2017  |           0 |
|       1 | ABC Corp | Complete          | 7/11/2017  |           0 |
|       2 | Nuke     | Received Request  | 11/10/2017 |           0 |
|       2 | Nuke     | Draft Proposal    | 15/10/2017 |           0 |
|       2 | Nuke     | Proposal Accepted | 29/10/2017 |           1 |
|       2 | Nuke     | Project Scheduled | 12/11/2017 |           1 |
|       2 | Nuke     | Project Start     | 17/11/2017 |           1 |
|       2 | Nuke     | Project Complete  | 17/12/2017 |           1 |
|       2 | Nuke     | Output Accepted   | 22/12/2017 |           1 |
|       2 | Nuke     | Complete          | 22/12/2017 |           1 |
+---------+----------+-------------------+------------+-------------+

The idea is that we can select a date range and see what was happening / will be happening during that time.  So each job will have a row for each stage through to completion with a flag to identify if the date displayed is real or projected.

In the table above, rows with 'IsEstimated' = 0 are pulled from the Events table, as per my example query.  Rows with 'IsEstimated' have been calculated based on the last actual event for that Customer, plus the value from [EventInfo].[extEventDays].

Perhaps it is clearer with this:

+---------+-------------------+------------+-----------+------------+
| Cust_ID |     EventName     |  RealDate  | EventDays |  EstDate   |
+---------+-------------------+------------+-----------+------------+
|       2 | Received Request  | 11/10/2017 |           |            |
|       2 | Draft Proposal    | 15/10/2017 | 5.00      |            |
|       2 | Proposal Accepted |            | 14.00     | 29/10/2017 |
|       2 | Project Scheduled |            | 14.00     | 12/11/2017 |
|       2 | Project Start     |            | 5.00      | 17/11/2017 |
|       2 | Project Complete  |            | 30.00     | 17/12/2017 |
|       2 | Output Accepted   |            | 14.00     | 22/12/2017 |
|       2 | Complete          |            | 0.00      | 22/12/2017 |
|      45 |                   |            |           |            |
+---------+-------------------+------------+-----------+------------+

I'm trying to pull the real event records and add rows for events that do not yet exist, along with the cumulative dates of all previous events, based on the 'NextEventDays' of each event.

I should also note here that I do control the structure and content of the 'EventInfo' table, and am thinking that a stored procedure updating into an intermediate table might be preferable (am using this data for SSRS reporting).

Any ideas on how to progress with this would be greatly appreciated.

Thanks

EDIT:  How awesome is SQL Fiddle?

Body:
What you need to do is to create a temp table (or table variable, whatever) with the data you need, and then fill it and report from it. I would do something like

Create a temp table with Cust_ID, EventName, EventDate,
IsEstimated

Fill this using the query you already have with the
real data (setting IsEstimated to 0 for these rows)

Create the future estimates (See below) with IsEstimated as yes

Report from this table

To create the estimated data, you need to find the rows that are missing, and figure out what date they should have. You could probably do this in one query with some thought, but doing it in two steps is easier to understand

To get the missing rows, you need a list of all the missing events. You need to figure out a way to specify which events are essential - if possible, I would add another column to the eventinfo table, called something like BestPath, and set it to 1 for the events that are the ideal path. You could then ignore all the others at this point. Cross joining the event info with the Customers table gets you a list of all the steps that should be taken on the ideal path.

However, you've already done some of these. You can't just say don't do anything that already exists, because you might have looped back and need to do some twice, so you need to get the latest valid SeqenceNo for each customer, and then for each customer get all the steps on the best path that come after that sequence number, and insert them in the temp table. Assuming your temp table is #FullData, you need something like this

--Get the future rows
With EventBase as (
    Select E.Cust_ID, EI.Sequence, E.EventDate, ROW_NUMBER () over (PARTITION BY E.Cust_ID  ORDER BY E.EventDate DESC) as RowNo
    From [Events] E
        INNER JOIN EventInfo EI on EI.Event_Name = E.EventName
), LastKnownEvent as
(
    SELECT Cust_ID, Sequence as LastSequence, EventDate
    FROM EventBase
    WHERE RowNo = 1
), AllEvents as
(
    SELECT EI.Event_Name, EI.Sequence, EI.NextEventDays, LE.Cust_ID, LE.LastSequence, LE.EventDate
    FROM EventInfo EI
        CROSS JOIN LastKnownEvent LE
    WHERE EI.BestPath = 1
)
INSERT INTO #FullData (Cust_ID, Event_Name, Sequence, IsEstimated, LastKnownDate)
SELECT Cust_ID, Event_Name, Sequence, 1, EventDate
FROM AllEvents AE
WHERE Sequence > LastSequence;

Once you have that data, process the temp table and calculate the date required for each future row (get the sum of all NextEventDays for all future rows for the same customer with a lower sequence number, plus the nexteventdays for the last known event, then dateadd it to the LastknownDate), and store it in the temp table.

At that point, the temp table should have all the data you need for the report.


来源: stackexchange

问:
App Deployment: Django not installing on server- AttributeError: 'module' object has no attribute 'lru_cache'
I am trying to deploy a Django App and for some reason, I keep getting this error. It seems to me that Django is not installed but it also errors when installing. Thank you for the help on this. I am deploying on Amazon EC2

```(venv) ubuntu@ip----:~/quotes$ pip install Django
Collecting Django
  Using cached Django-2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "", line 1, in
      File "/tmp/pip-build-ceP6se/Django/setup.py", line 32, in
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ceP6se/Django/```

答:
Django has stopped its support for Python 2 version, still you can try installing 1.11 version by using the below code.</p>

```<code>pip install Django==1.11
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to deploy a Django App and for some reason, I keep getting this error. It seems to me that Django is not installed but it also errors when installing. Thank you for the help on this. I am deploying on Amazon EC2

(venv) ubuntu@ip----:~/quotes$ pip install Django
Collecting Django
  Using cached Django-2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "", line 1, in
      File "/tmp/pip-build-ceP6se/Django/setup.py", line 32, in
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ceP6se/Django/

Body:
Django has stopped its support for Python 2 version, still you can try installing 1.11 version by using the below code.

pip install Django==1.11


问:
Do calling a ColdFusion web service using <s:RemoteObject> and <s:WebService> have a difference in performance?
Assuming calling the same ColdFusion web service and all other factors are identical, is there a difference in performance/speed between using the following two tags?

```<code> <s:RemoteObject id="MyService" destination="ColdFusion" source="MyWSFolder.MyService"/>
</code>```

and

```<code><s:WebService id="MyService" wsdl="http://www.myDomain.com/MyWSFolder/MyService.cfc?wsdl"/>
</code>```

Thanks in advance,

Monte

答:
If I remember correctly (and you'll want to confirm this, because I may be wrong) a WebService is specifically designed to work over HTTP with SOAP. It's like a strictly-typed HTTPRequest.

RemoteObject, however, uses AMF for its transfer - meaning you're not sending headers back and forth, you're essentially creating a binary stream of whatever you're transferring. This is supposed to be much faster, if I remember correctly. I tend to work with RemoteObject over WebService whenever I can because then I don't need to mess with SOAP. Plus with RemoteObject you can do Class mapping, so for instance you have strongly typed value objects coming back from PHP and your application can know exactly what time your data conforms to.

ContentLicense: CC BY-SA 2.5

Body:
Assuming calling the same ColdFusion web service and all other factors are identical, is there a difference in performance/speed between using the following two tags?

 <s:RemoteObject id="MyService" destination="ColdFusion" source="MyWSFolder.MyService"/>

and

<s:WebService id="MyService" wsdl="http://www.myDomain.com/MyWSFolder/MyService.cfc?wsdl"/>

Thanks in advance,

Monte


问:
How to filter date field in yii2
I want to filter Date column like 3 months ago, 6 months ago, 1 year ago.
I have created a dropdown in search field of gridview as given below.

```<code>[
    'attribute' => 'modified',
    'value'     => 'name',
    'filter'    => array("ID1" => "Before Three months",
                         "ID2" => "Before six months",
                         "ID"  => "Before Twelve months",),
],
</code>```

and in modelsearch I want to search like...

```<code>if (($this->modified) == "ID1"){
    $query->andFilterWhere(['between', $this->modified, 'today', '3monthsago']);
}
</code>```

but I can't understand what should be there in place of today 3monthsago ?
how to calculate and pass this variables in query??

答:
Add this to your modelsearch</p>

```<code>$today = date('Y-m-d H:i:s',time());
if (($this->modified)=="ID1"){
    $endDate = date('Y-m-d H:i:s', strtotime('-3 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}elseif (($this->modified)=="ID2") {
    $endDate = date('Y-m-d H:i:s', strtotime('-6 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}elseif (($this->modified)=="ID") {
    $endDate = date('Y-m-d H:i:s', strtotime('-12 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to filter date field in yii2

Body:
I want to filter Date column like 3 months ago, 6 months ago, 1 year ago.
I have created a dropdown in search field of gridview as given below.

[
    'attribute' => 'modified',
    'value'     => 'name',
    'filter'    => array("ID1" => "Before Three months",
                         "ID2" => "Before six months",
                         "ID"  => "Before Twelve months",),
],

and in modelsearch I want to search like...

if (($this->modified) == "ID1"){
    $query->andFilterWhere(['between', $this->modified, 'today', '3monthsago']);
}

but I can't understand what should be there in place of today 3monthsago ?
how to calculate and pass this variables in query??

Body:
Add this to your modelsearch

$today = date('Y-m-d H:i:s',time());
if (($this->modified)=="ID1"){
    $endDate = date('Y-m-d H:i:s', strtotime('-3 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}elseif (($this->modified)=="ID2") {
    $endDate = date('Y-m-d H:i:s', strtotime('-6 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}elseif (($this->modified)=="ID") {
    $endDate = date('Y-m-d H:i:s', strtotime('-12 months'));
    $query->andFilterWhere(['between', 'contacts.modified', $today, $endDate]);
}


问:
Android Studio - Canary 8: Can't access the resources in feature modules and library modules
I can't access to the feature module resources and the resources from another library which is included as an API in InstantApp. The only place where it recognises to get resources is the base feature class. I have the following sample: when I run the application there are several Fragment classes in the feature module which have to be loaded along with the layouts also located in that module, but it always fails with

```<code>Caused by: android.content.res.Resources$NotFoundException:
</code>```

Tried to exclude Multi-Dexing, other modules, also disabled the aapt2, after which it has started to complain about not found views.

What could be the reason of this?

A bug is reported here.

答:
With reference to Google issue tracker, it has been fixed with Android SDK Built-Tools to 27.0.2

Please update your Android SDK Built-Tools to 27.0.2 And ensure you are on Android Studio 3.0.1 or newer.

If any issue persists, please report at Google issue tracker they will re-open to examine.

Body:
I can't access to the feature module resources and the resources from another library which is included as an API in InstantApp. The only place where it recognises to get resources is the base feature class. I have the following sample: when I run the application there are several Fragment classes in the feature module which have to be loaded along with the layouts also located in that module, but it always fails with

Caused by: android.content.res.Resources$NotFoundException:

Tried to exclude Multi-Dexing, other modules, also disabled the aapt2, after which it has started to complain about not found views.

What could be the reason of this?

A bug is reported here.


问:
Liferay Service is not overriding journalArticle is not calling restoreArticleFromTrash?
This method is not calling while restore article from recycle bin.</p>

```<code>@Override
public void restoreArticleFromTrash(long groupId, String articleId) throws PortalException {
    // TODO Auto-generated method stub
    System.out.println(":::::::::::::restote article from the trash::::::::::::");
    super.restoreArticleFromTrash(groupId, articleId);
}
</code>```

答:
Every method is  calling except restoreArticleFromTrash.
Is any other way.

Below added the full class file

@Component(service = ServiceWrapper.class)

public class CustomJournalArticleServiceWrapper extends JournalArticleServiceWrapper {

```<code>public CustomJournalArticleServiceWrapper() {
    super(null);
}

    @Override
public JournalArticle addArticle(long groupId, long folderId, long classNameId, long classPK, String articleId,
        boolean autoArticleId, Map<Locale, String> titleMap, Map<Locale, String> descriptionMap, String content,
        String ddmStructureKey, String ddmTemplateKey, String layoutUuid, int displayDateMonth, int displayDateDay,
        int displayDateYear, int displayDateHour, int displayDateMinute, int expirationDateMonth,
        int expirationDateDay, int expirationDateYear, int expirationDateHour, int expirationDateMinute,
        boolean neverExpire, int reviewDateMonth, int reviewDateDay, int reviewDateYear, int reviewDateHour,
        int reviewDateMinute, boolean neverReview, boolean indexable, boolean smallImage, String smallImageURL,
        File smallFile, Map<String, byte[]> images, String articleURL, ServiceContext serviceContext)
        throws PortalException {

    return super.addArticle(groupId, folderId, classNameId, classPK, articleId,
            autoArticleId, titleMap, descriptionMap, content, ddmStructureKey, ddmTemplateKey, layoutUuid,
            displayDateMonth, displayDateDay, displayDateYear, displayDateHour, displayDateMinute,
            expirationDateMonth, expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute,
            neverExpire, reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute,
            neverReview, indexable, smallImage, smallImageURL, smallFile, images, articleURL, serviceContext);
            }

            @Override
public JournalArticle updateArticle(long groupId, long folderId, String articleId, double version,
        Map<Locale, String> titleMap, Map<Locale, String> descriptionMap, String content, String ddmStructureKey,
        String ddmTemplateKey, String layoutUuid, int displayDateMonth, int displayDateDay, int displayDateYear,
        int displayDateHour, int displayDateMinute, int expirationDateMonth, int expirationDateDay,
        int expirationDateYear, int expirationDateHour, int expirationDateMinute, boolean neverExpire,
        int reviewDateMonth, int reviewDateDay, int reviewDateYear, int reviewDateHour, int reviewDateMinute,
        boolean neverReview, boolean indexable, boolean smallImage, String smallImageURL, File smallFile,
        Map<String, byte[]> images, String articleURL, ServiceContext serviceContext) throws PortalException {

        return super.updateArticle(groupId, folderId, articleId, version, titleMap,
            descriptionMap, content, ddmStructureKey, ddmTemplateKey, layoutUuid, displayDateMonth, displayDateDay,
            displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
            expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
            reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview, indexable, smallImage,
            smallImageURL, smallFile, images, articleURL, serviceContext);
            }

@Override
public JournalArticle moveArticleToTrash(long groupId, String articleId) throws PortalException {
    // TODO Auto-generated method stub
    System.out.println("::::::::::move article to the trash:::::::::::::");
    return super.moveArticleToTrash(groupId, articleId);
}

@Override
public void restoreArticleFromTrash(long groupId, String articleId) throws PortalException {
    // TODO Auto-generated method stub
    System.out.println(":::::::::::::restote article from the trash::::::::::::");
    super.restoreArticleFromTrash(groupId, articleId);
}

}
</code>```

Body:
This method is not calling while restore article from recycle bin.

@Override
public void restoreArticleFromTrash(long groupId, String articleId) throws PortalException {
    // TODO Auto-generated method stub
    System.out.println(":::::::::::::restote article from the trash::::::::::::");
    super.restoreArticleFromTrash(groupId, articleId);
}

Body:
Every method is  calling except restoreArticleFromTrash.
Is any other way.

Below added the full class file

@Component(service = ServiceWrapper.class)

public class CustomJournalArticleServiceWrapper extends JournalArticleServiceWrapper {

public CustomJournalArticleServiceWrapper() {
    super(null);
}

    @Override
public JournalArticle addArticle(long groupId, long folderId, long classNameId, long classPK, String articleId,
        boolean autoArticleId, Map<Locale, String> titleMap, Map<Locale, String> descriptionMap, String content,
        String ddmStructureKey, String ddmTemplateKey, String layoutUuid, int displayDateMonth, int displayDateDay,
        int displayDateYear, int displayDateHour, int displayDateMinute, int expirationDateMonth,
        int expirationDateDay, int expirationDateYear, int expirationDateHour, int expirationDateMinute,
        boolean neverExpire, int reviewDateMonth, int reviewDateDay, int reviewDateYear, int reviewDateHour,
        int reviewDateMinute, boolean neverReview, boolean indexable, boolean smallImage, String smallImageURL,
        File smallFile, Map<String, byte[]> images, String articleURL, ServiceContext serviceContext)
        throws PortalException {

    return super.addArticle(groupId, folderId, classNameId, classPK, articleId,
            autoArticleId, titleMap, descriptionMap, content, ddmStructureKey, ddmTemplateKey, layoutUuid,
            displayDateMonth, displayDateDay, displayDateYear, displayDateHour, displayDateMinute,
            expirationDateMonth, expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute,
            neverExpire, reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute,
            neverReview, indexable, smallImage, smallImageURL, smallFile, images, articleURL, serviceContext);
            }

            @Override
public JournalArticle updateArticle(long groupId, long folderId, String articleId, double version,
        Map<Locale, String> titleMap, Map<Locale, String> descriptionMap, String content, String ddmStructureKey,
        String ddmTemplateKey, String layoutUuid, int displayDateMonth, int displayDateDay, int displayDateYear,
        int displayDateHour, int displayDateMinute, int expirationDateMonth, int expirationDateDay,
        int expirationDateYear, int expirationDateHour, int expirationDateMinute, boolean neverExpire,
        int reviewDateMonth, int reviewDateDay, int reviewDateYear, int reviewDateHour, int reviewDateMinute,
        boolean neverReview, boolean indexable, boolean smallImage, String smallImageURL, File smallFile,
        Map<String, byte[]> images, String articleURL, ServiceContext serviceContext) throws PortalException {

        return super.updateArticle(groupId, folderId, articleId, version, titleMap,
            descriptionMap, content, ddmStructureKey, ddmTemplateKey, layoutUuid, displayDateMonth, displayDateDay,
            displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
            expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
            reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview, indexable, smallImage,
            smallImageURL, smallFile, images, articleURL, serviceContext);
            }

@Override
public JournalArticle moveArticleToTrash(long groupId, String articleId) throws PortalException {
    // TODO Auto-generated method stub
    System.out.println("::::::::::move article to the trash:::::::::::::");
    return super.moveArticleToTrash(groupId, articleId);
}

@Override
public void restoreArticleFromTrash(long groupId, String articleId) throws PortalException {
    // TODO Auto-generated method stub
    System.out.println(":::::::::::::restote article from the trash::::::::::::");
    super.restoreArticleFromTrash(groupId, articleId);
}

}


问:
how to extract image from word file and save image in another location in php
I want the images form word file and save those picture in another folder. </p>

```<code>$document = 'hindiquestion.docx';
function readZippedImages($filename) {

    /*Create a new ZIP archive object*/
    $zip = new ZipArchive;
    /*Open the received archive file*/
    if (true === $zip->open($filename)) {
         for ($i=0; $i<$zip->numFiles;$i++) {
            /*Loop via all the files to check for image files*/
            $zip_element = $zip->statIndex($i);

           /*Check for images*/
           if(preg_match("([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)",$zip_element['name'])) {
              saveImage('display.php?filename=".$filename."&index=".$i."');/* here this function save file in folder but not with image only corrupt file save in folder*/
              echo "<image src='display.php?filename=".$filename."&index=".$i."' /><hr />";/*Display images if present by using display.php*/
           }//image serach
        }
    }
}

function saveImage($path)
{
    copy($path, rand().'-img.jpg');
}

readZippedImages($document);
?>
</code>```

答:
Note : first you need to create folder "docimages"   </p>

```<code> <?php

    class DImages {
        private $file;
        private $indexes = [ ];
        /** Local directory name where images will be saved */
        private $savepath = 'docimages';
        public function __construct( $filePath ) {
            $this->file = $filePath;
            $this->extractImages();
        }
        function extractImages() {
            $ZipArchive = new ZipArchive;
            if ( true === $ZipArchive->open( $this->file ) ) {
                for ( $i = 0; $i < $ZipArchive->numFiles; $i ++ ) {
                    $zip_element = $ZipArchive->statIndex( $i );
                    if ( preg_match( "([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)", $zip_element['name'] ) ) {
                        $imagename                   = explode( '/', $zip_element['name'] );
                        $imagename                   = end( $imagename );
                        $this->indexes[ $imagename ] = $i;
                    }
                }
            }
        }
        function saveAllImages() {
            if ( count( $this->indexes ) == 0 ) {
                echo 'No images found';
            }
            foreach ( $this->indexes as $key => $index ) {
                $zip = new ZipArchive;
                if ( true === $zip->open( $this->file ) ) {
                    file_put_contents( dirname( __FILE__ ) . '/' . $this->savepath . '/' . $key, $zip->getFromIndex( $index ) );
                }
                $zip->close();
            }
        }

    }
    $DImages = new DImages("testdoc.docx");

    ?>
</code>```

Body:
I want the images form word file and save those picture in another folder.

$document = 'hindiquestion.docx';
function readZippedImages($filename) {

    /*Create a new ZIP archive object*/
    $zip = new ZipArchive;
    /*Open the received archive file*/
    if (true === $zip->open($filename)) {
         for ($i=0; $i<$zip->numFiles;$i++) {
            /*Loop via all the files to check for image files*/
            $zip_element = $zip->statIndex($i);

           /*Check for images*/
           if(preg_match("([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)",$zip_element['name'])) {
              saveImage('display.php?filename=".$filename."&index=".$i."');/* here this function save file in folder but not with image only corrupt file save in folder*/
              echo "<image src='display.php?filename=".$filename."&index=".$i."' />
";/*Display images if present by using display.php*/
           }//image serach
        }
    }
}

function saveImage($path)
{
    copy($path, rand().'-img.jpg');
}

readZippedImages($document);
?>

Body:
Note : first you need to create folder "docimages"

 <?php

    class DImages {
        private $file;
        private $indexes = [ ];
        /** Local directory name where images will be saved */
        private $savepath = 'docimages';
        public function __construct( $filePath ) {
            $this->file = $filePath;
            $this->extractImages();
        }
        function extractImages() {
            $ZipArchive = new ZipArchive;
            if ( true === $ZipArchive->open( $this->file ) ) {
                for ( $i = 0; $i < $ZipArchive->numFiles; $i ++ ) {
                    $zip_element = $ZipArchive->statIndex( $i );
                    if ( preg_match( "([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)", $zip_element['name'] ) ) {
                        $imagename                   = explode( '/', $zip_element['name'] );
                        $imagename                   = end( $imagename );
                        $this->indexes[ $imagename ] = $i;
                    }
                }
            }
        }
        function saveAllImages() {
            if ( count( $this->indexes ) == 0 ) {
                echo 'No images found';
            }
            foreach ( $this->indexes as $key => $index ) {
                $zip = new ZipArchive;
                if ( true === $zip->open( $this->file ) ) {
                    file_put_contents( dirname( __FILE__ ) . '/' . $this->savepath . '/' . $key, $zip->getFromIndex( $index ) );
                }
                $zip->close();
            }
        }

    }
    $DImages = new DImages("testdoc.docx");

    ?>


问:
JQuery Default text on empty text box
I have a email form text box that while it is empty I would like it to have the value "E-Mail" And when you click on it the text goes away. If someone clicks on it and doesn't enter text. on Blur I would like for it to return to having the default text.

I have been trying a few things but nothing is working. Could someone please point me in the right direction?

答:
You could use one of the watermark plugins of jquery that do just that. I use a watermark plugin that has the following code

```<code>$.fn.watermark = function (c, t) {
var e = function (e) {
    var i = $(this);
    if (!i.val()) {
        var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
        i.replaceWith($c);
        $c.focus(function () {
            $c.replaceWith(i); setTimeout(function () { i.focus(); }, 1);
        })
            .change(function (e) {
                i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
            })
            .closest('form').submit(function () {
                $c.replaceWith(i);
            });
    }
};
return $(this).live('blur change', e).change();
</code>```

};

Callable in jquery by setting the class of the input textbox to watermark like this

```<code><input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px"
    title="Type keyword here" />
</code>```

The title is what will be displayed in the watermark.

Title: JQuery Default text on empty text box

Body:
You could use one of the watermark plugins of jquery that do just that. I use a watermark plugin that has the following code

$.fn.watermark = function (c, t) {
var e = function (e) {
    var i = $(this);
    if (!i.val()) {
        var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
        i.replaceWith($c);
        $c.focus(function () {
            $c.replaceWith(i); setTimeout(function () { i.focus(); }, 1);
        })
            .change(function (e) {
                i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
            })
            .closest('form').submit(function () {
                $c.replaceWith(i);
            });
    }
};
return $(this).live('blur change', e).change();

};

Callable in jquery by setting the class of the input textbox to watermark like this

<input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px"
    title="Type keyword here" />

The title is what will be displayed in the watermark.


问:
Unable to Convert Linq to Lambda Notation
```<code> public ActionResult EditArticle(int id)
    {
      if (id == null)
      {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      var typeId = 0;
      var catId = 0;
      var subCatId = 0;
      var viewModel = (from sa in ems.SupportArticles
                       join ssc in ems.SupportSubCategories on sa.SubCatID equals ssc.SubCatID
                       join sc in ems.SupportCategories on ssc.CatID equals sc.CatID
                       join st in ems.SupportTypes on sc.TypeID equals st.TypeID
                       where sa.ArcticleId == id
                       select new SupportArticleViewModel { supportArticle = sa, supportSubCat = ssc, supportCat = sc, supportType = st });
      foreach (var vm in viewModel)
      {
        typeId = vm.supportType.TypeID;
        catId = vm.supportCat.CatID;
        subCatId = vm.supportSubCat.SubCatID;
      }
</code>```

I want to convert it into Lambda Notation.But, I am unable to do it.Please help.I am using SupportViewModel which contains property of SupportType,SupportCategory ,SupportSubCategoryand SupportArticle.

答:
Following is functional way do query , you have to make use of join function and than you get data </p>

```<code> var filteredArtciles = SupportArticles.Where(sa=> sa.ArcticleId == id);
 var query =
        SupportArticles.
         Join(SupportSubCategories,sa  =>  sa.SubCatID ,ssc => ssc.SubCatID,(sa, ssc) => new {sa,ssc}).
         Join(SupportCategories,sassc  =>  sassc.ssc.CatID ,sc=>sc.CatID ,(sassc, sc) => new {sassc,sc}).;
         Join(SupportTypes,sasscsc  => sasscsc.sc.TypeID  ,st=>st.TypeID ,(sc, st) => new {sasscsc,st}).
         Select(j=>
             new  SupportArticleViewModel
               {
                  supportArticle = j.sasscsc.sassc.sa,
                  supportSubCat = j.sasscsc.sassc.ssc,
                  supportCat = j.sasscsc.sc,
                  supportType = j.st
               }
        ));
</code>```

Body:
 public ActionResult EditArticle(int id)
    {
      if (id == null)
      {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      var typeId = 0;
      var catId = 0;
      var subCatId = 0;
      var viewModel = (from sa in ems.SupportArticles
                       join ssc in ems.SupportSubCategories on sa.SubCatID equals ssc.SubCatID
                       join sc in ems.SupportCategories on ssc.CatID equals sc.CatID
                       join st in ems.SupportTypes on sc.TypeID equals st.TypeID
                       where sa.ArcticleId == id
                       select new SupportArticleViewModel { supportArticle = sa, supportSubCat = ssc, supportCat = sc, supportType = st });
      foreach (var vm in viewModel)
      {
        typeId = vm.supportType.TypeID;
        catId = vm.supportCat.CatID;
        subCatId = vm.supportSubCat.SubCatID;
      }

I want to convert it into Lambda Notation.But, I am unable to do it.Please help.I am using SupportViewModel which contains property of SupportType,SupportCategory ,SupportSubCategoryand SupportArticle.

Body:
Following is functional way do query , you have to make use of join function and than you get data

 var filteredArtciles = SupportArticles.Where(sa=> sa.ArcticleId == id);
 var query =
        SupportArticles.
         Join(SupportSubCategories,sa  =>  sa.SubCatID ,ssc => ssc.SubCatID,(sa, ssc) => new {sa,ssc}).
         Join(SupportCategories,sassc  =>  sassc.ssc.CatID ,sc=>sc.CatID ,(sassc, sc) => new {sassc,sc}).;
         Join(SupportTypes,sasscsc  => sasscsc.sc.TypeID  ,st=>st.TypeID ,(sc, st) => new {sasscsc,st}).
         Select(j=>
             new  SupportArticleViewModel
               {
                  supportArticle = j.sasscsc.sassc.sa,
                  supportSubCat = j.sasscsc.sassc.ssc,
                  supportCat = j.sasscsc.sc,
                  supportType = j.st
               }
        ));


问:
Properly using Facets for Algolia Search Results
I have an indice with the following JSON key and can have either two values:

ApprovalFL: true OR ApprovalFL: null

I’d like my search result to display only the results that have ApprovalFL: true meaning that they have been approved to display on the site.

I tried looking into the Algolia Facet method ( https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values ), but I’m honestly not too sure where to put it in my code, (dev initially set up Algolia…I’m still learning) here’s my relevant javascript: https://jsfiddle.net/vpnvt9vv/1

Here's a snippet of my code, the rest is found in the link above:

```<code>var searchSong = instantsearch
    ({
        appId: "---",
        apiKey: "---",
        indexName: "Song",
        searchFunction: function (helper) {
            var query = searchArtist.helper.state.query;

            helper.state.index = "Song";
            helper.state.hitsPerPage = 30;
            helper.setQuery(query);
            helper.search();
        },
        searchParameters:
        {
            hitsPerPage: 30
        }
    });
</code>```

I’ve already added the key to “attributesforFaceting” in the Algolia Dashboard page.

If you'd like to see a live example, go https://unearthapp.io and type in the search bar the letter "a" you'll see two results from an artist called "Turbo" that have an ApprovalFL of null when I only want songs with ApprovalFL of true to display

Let me know if you need any more info, thanks!

答:
You can use facetFilters and set it to ["ApprovalFL:true"]

FACET FILTERS

From your code structure, you can add it either in the searchFunction OR in the searchParameters something like below. Ideally, you would want to add search filters once in your code otherwise the code could get unpredicatable due to the declaration at many places.

```<code>var searchSong = instantsearch ({
    appId: "---",
    apiKey: "---",
    indexName: "Song",
    searchFunction: function (helper) {
        .
        .
        .
        helper.state.facetFilters = ["ApprovalFL:true"];
        .
        .
        .
    },
    searchParameters: {
        hitsPerPage: 30,
        facetFilters: ["ApprovalFL:true"]
    }
});
</code>```

Body:
I have an indice with the following JSON key and can have either two values:

ApprovalFL: true OR ApprovalFL: null

I’d like my search result to display only the results that have ApprovalFL: true meaning that they have been approved to display on the site.

I tried looking into the Algolia Facet method ( https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values ), but I’m honestly not too sure where to put it in my code, (dev initially set up Algolia…I’m still learning) here’s my relevant javascript: https://jsfiddle.net/vpnvt9vv/1

Here's a snippet of my code, the rest is found in the link above:

var searchSong = instantsearch
    ({
        appId: "---",
        apiKey: "---",
        indexName: "Song",
        searchFunction: function (helper) {
            var query = searchArtist.helper.state.query;

            helper.state.index = "Song";
            helper.state.hitsPerPage = 30;
            helper.setQuery(query);
            helper.search();
        },
        searchParameters:
        {
            hitsPerPage: 30
        }
    });

I’ve already added the key to “attributesforFaceting” in the Algolia Dashboard page.

If you'd like to see a live example, go https://unearthapp.io and type in the search bar the letter "a" you'll see two results from an artist called "Turbo" that have an ApprovalFL of null when I only want songs with ApprovalFL of true to display

Let me know if you need any more info, thanks!

Body:
You can use facetFilters and set it to ["ApprovalFL:true"]

FACET FILTERS

From your code structure, you can add it either in the searchFunction OR in the searchParameters something like below. Ideally, you would want to add search filters once in your code otherwise the code could get unpredicatable due to the declaration at many places.

var searchSong = instantsearch ({
    appId: "---",
    apiKey: "---",
    indexName: "Song",
    searchFunction: function (helper) {
        .
        .
        .
        helper.state.facetFilters = ["ApprovalFL:true"];
        .
        .
        .
    },
    searchParameters: {
        hitsPerPage: 30,
        facetFilters: ["ApprovalFL:true"]
    }
});


问:
font face not working in local not in server
I used font-face, and it is not working. I used the following code in internal CSS:

```<code>@font-face {
font-family: acme;
src: url(https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf);
}
</code>```

My html code is below:

```<code><p style="text-align:center; font-family: acme; font-size:28px; color: #4D4B4B;">TYPICAL MEETING ROOM</p>
</code>```

When I use this in local it works fine, but when upload the fonts to the server and when I get the fonts from the server it won't work. Please anyone give a solution for this.

答:
Use this code. It should work perfectly

@font-face {
  font-family: 'acme';
  src: url('https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p style="text-align:center; font-family: 'acme', arial; font-size:28px; color: #4D4B4B;">TYPICAL MEETING ROOM</p></code>```

Body:
I used font-face, and it is not working. I used the following code in internal CSS:

@font-face {
font-family: acme;
src: url(https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf);
}

My html code is below:

TYPICAL MEETING ROOM

When I use this in local it works fine, but when upload the fonts to the server and when I get the fonts from the server it won't work. Please anyone give a solution for this.

Body:
Use this code. It should work perfectly

@font-face {
  font-family: 'acme';
  src: url('https://s3.ap-south-1.amazonaws.com/mailer-reach-on-time/ACMESecretAgentBB_BoldItal.otf');
}

<p style="text-align:center; font-family: 'acme', arial; font-size:28px; color: #4D4B4B;">TYPICAL MEETING ROOM</p>


问:
How to reuse the code Intent intent=new Intent(context,Activity.class) from a superclass to a subclass?

How the code Intent intent=new Intent(context,Activity.class) which is in the superclass can be reused by its subclasses given that the subclasses have different context and different activities to start after on click listener is called. Is it possible?

This is the superclass:

```<code>public class CommonPost extends AppCompatActivity {

    public void on_create(final Context context, final Class aclass) {
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonPost commonPost = new CommonPost();
                MyTask task = commonPost.new MyTask(context, aclass);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                else
                    task.execute();
            }
        });
    }

class MyTask extends AsyncTask<Void,Void,Void> {
          Context context;
          Class aclass;

        public MyTask(Context context,Class aclass){
             this.context=context;
             this.aclass=aclass;
        }

        @Override
        protected void onPreExecute() {
            // do something
        }

        @Override
        protected Void doInBackground(Void... voids) {
            // do something
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent intent = new Intent(context, aclass);
            startActivity(intent);
        }
}
</code>```

One of the subclass:

```<code>public class PlacementPost extends CommonPost {
            Context context=PlacementPost.this;
            Class aclass=Placements.class;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                on_create(context,aclass);
            }
        }
</code>```

I am getting the following error when I try the above code:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
       at android.app.Activity.startActivityForResult(Activity.java:4266)
       at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)

at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
   at android.app.Activity.startActivityForResult(Activity.java:4224)
   at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
   at android.app.Activity.startActivity(Activity.java:4548)
   at android.app.Activity.startActivity(Activity.java:4516)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:240)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:177)
   at android.os.AsyncTask.finish(AsyncTask.java:660)
   at android.os.AsyncTask.-wrap1(AsyncTask.java)
   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6077)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

I am not sure where I am wrong or what I am missing. I just tried out whatever logically I felt correct. Please do correct me out where I am wrong!

答:
for the starters you should never initialize your Activity using new, it has it's own life cycle and context should be of the class where you are actually starting intent, change you code to

on_create

```<code> public void on_create(final Context context, final Class aclass) {
            post.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MyTask task = new MyTask(stor_root, mProgress, editTextplace, post, ninfo, imageUri,
                            mstorage, mDatabase, context, aclass);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    else
                        task.execute();
                }
            });
        }
</code>```

MyTask - Stop passing context from child

```<code>class MyTask extends AsyncTask<Void,Void,Void> {
        Class aclass;

        public MyTask(Class aclass){
             this.aclass=aclass;
        }

        @Override
        protected void onPreExecute() {
            // do something
        }

        @Override
        protected Void doInBackground(Void... voids) {
            // do something
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent intent = new Intent(CommonPost.this, aclass);
            startActivity(intent);
        }
}
</code>```

SubClass

```<code>public class PlacementPost extends CommonPost {
            Context context=PlacementPost.this;
            Class aclass=Placements.class;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                on_create(aclass);
            }
        }
</code>```

Body:
How the code Intent intent=new Intent(context,Activity.class) which is in the superclass can be reused by its subclasses given that the subclasses have different context and different activities to start after on click listener is called. Is it possible?

This is the superclass:

public class CommonPost extends AppCompatActivity {

    public void on_create(final Context context, final Class aclass) {
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonPost commonPost = new CommonPost();
                MyTask task = commonPost.new MyTask(context, aclass);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                else
                    task.execute();
            }
        });
    }

class MyTask extends AsyncTask<Void,Void,Void> {
          Context context;
          Class aclass;

        public MyTask(Context context,Class aclass){
             this.context=context;
             this.aclass=aclass;
        }

        @Override
        protected void onPreExecute() {
            // do something
        }

        @Override
        protected Void doInBackground(Void... voids) {
            // do something
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent intent = new Intent(context, aclass);
            startActivity(intent);
        }
}

One of the subclass:

public class PlacementPost extends CommonPost {
            Context context=PlacementPost.this;
            Class aclass=Placements.class;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                on_create(context,aclass);
            }
        }

I am getting the following error when I try the above code:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
       at android.app.Activity.startActivityForResult(Activity.java:4266)
       at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)

at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
   at android.app.Activity.startActivityForResult(Activity.java:4224)
   at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
   at android.app.Activity.startActivity(Activity.java:4548)
   at android.app.Activity.startActivity(Activity.java:4516)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:240)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:177)
   at android.os.AsyncTask.finish(AsyncTask.java:660)
   at android.os.AsyncTask.-wrap1(AsyncTask.java)
   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6077)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I am not sure where I am wrong or what I am missing. I just tried out whatever logically I felt correct. Please do correct me out where I am wrong!

Body:
for the starters you should never initialize your Activity using new, it has it's own life cycle and context should be of the class where you are actually starting intent, change you code to

on_create

 public void on_create(final Context context, final Class aclass) {
            post.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MyTask task = new MyTask(stor_root, mProgress, editTextplace, post, ninfo, imageUri,
                            mstorage, mDatabase, context, aclass);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    else
                        task.execute();
                }
            });
        }

MyTask - Stop passing context from child

class MyTask extends AsyncTask<Void,Void,Void> {
        Class aclass;

        public MyTask(Class aclass){
             this.aclass=aclass;
        }

        @Override
        protected void onPreExecute() {
            // do something
        }

        @Override
        protected Void doInBackground(Void... voids) {
            // do something
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent intent = new Intent(CommonPost.this, aclass);
            startActivity(intent);
        }
}

SubClass

public class PlacementPost extends CommonPost {
            Context context=PlacementPost.this;
            Class aclass=Placements.class;

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


问:
Why is <select> different on my tablet and mobile phone?
The tablet shows the drop-down list with a tap, just like on desktop.

The phone shows a list of options at the center of screen (it looks like a modal dialog).

For example, I tried this page. I have Chrome 63.0.3239.83 on both devices. The tablet OS is Android 5.1.0 and the phone OS is Android 6.0.1.

What determines the difference? Could it be screen size or Android version?

Can I make the tablet show the options in the same way of my phone?

What about Android WebView? Do iOS tablet and phone also differ in a similar way?

答: select tag has user agent stylesheet for each browser. So it includes device and browser dependent styles and modes of operation</p>


问:
Batch file - restart program every day at fix time
In windows environment ,

I have to restart some program forcefully .

1  > How to create batch or exe file for this.

2 > should I run particular batch  in task scheduler .

HELP NEEDED**

答:
A batch file that springs to life once a day.

```<code>:Loop
rem 86400 secs is 24 hours
timeout /t 86400
Taskkill /f /Im notepad.exe
start "" notepad
Goto Loop
</code>```

A VBS file to start a hidden batch file.

```<code>CreateObject("WScript.Shell").Run """c:\windows\system32\Mybat.bat""", 0, false
</code>```

Body:
A batch file that springs to life once a day.

:Loop
rem 86400 secs is 24 hours
timeout /t 86400
Taskkill /f /Im notepad.exe
start "" notepad
Goto Loop

A VBS file to start a hidden batch file.

CreateObject("WScript.Shell").Run """c:\windows\system32\Mybat.bat""", 0, false


问:
assigned objects using spread syntax `...` and equals `=`
Is there a difference if I assign an object using = or ...

```<code>var o1 = {
    a:1,
    b:2
}

var o2 = o1; //say style 1
var o3 = {...o1} //say style 2
</code>```

Does it matter whether I use style 1 or style 2?

答:
Yes,There is a difference

```<code>var o2 = o1; //say style 1
</code>```

In style1 o2 will be pointing to o1 and changing anything in one reflect changes in another. So it is like 02 is referring same object.

```<code>var o3 = {...o1} //say style 2
</code>```

In style2 o3 is new variable which will have same value but will not be referring o1. on changing o1 nothing will change in o3 and vice versa

Body:
Is there a difference if I assign an object using = or ...

var o1 = {
    a:1,
    b:2
}

var o2 = o1; //say style 1
var o3 = {...o1} //say style 2

Does it matter whether I use style 1 or style 2?

Body:
Yes,There is a difference

var o2 = o1; //say style 1

In style1 o2 will be pointing to o1 and changing anything in one reflect changes in another. So it is like 02 is referring same object.

var o3 = {...o1} //say style 2

In style2 o3 is new variable which will have same value but will not be referring o1. on changing o1 nothing will change in o3 and vice versa


问:
CSS Absolute Positioning
I have a div inside a field set that looks like this:

```<code>        <fieldset>
            <legend>Device</legend>
            <label id="select-6-container">
                <select id="select-6" name="device_select" style="display:none"></select>
            </label>
        </fieldset>

        <div id="ctrl">
        <button type="button" id="restart1" name="button1" onclick="window.location.reload()" value="Restart Wizard">Restart Wizard</button>
        <button type="button" id="gotostep2" class="gotostep2" name="button1" value="Next Step">Next Step</button>
        </div>
</code>```

My select box is populated with YUI and then shown (notice that its hidden on load). My CSS for the box looks like this:

```<code>#ctrl {
margin-top: 102px;
margin-left: -200px;
position: absolute;
width:100px;
  }
</code>```

But when My select box is generated, the ctrl box moves down everytime! Do I have my CSS wrong? Or is it because the select box is generated by Javascript after the page has loaded?

I should mention that when YUI renders the select box as a menu button it changes it's markup to be a button, I didn't think this should matter because the positioning of ctrl is what I'm trying to change.

Any advice would help!
Thanks!

答:
Your div doesn't seem to be inside the fieldset, as you had mentioned.
Try to assign a position to the div using top, right, bottom and/or left. The div's position will be then depending on the next positioned parent element, so have an eye on that as well.

If all of this doesn't work — please post as well the surrounding mark–up and CSS.

Title: CSS Absolute Positioning

Body:
I have a div inside a field set that looks like this:

        <fieldset>
            <legend>Device</legend>

                <select id="select-6" name="device_select" style="display:none"></select>

        </fieldset>

        <button type="button" id="restart1" name="button1" onclick="window.location.reload()" value="Restart Wizard">Restart Wizard</button>
        <button type="button" id="gotostep2" class="gotostep2" name="button1" value="Next Step">Next Step</button>

My select box is populated with YUI and then shown (notice that its hidden on load). My CSS for the box looks like this:

#ctrl {
margin-top: 102px;
margin-left: -200px;
position: absolute;
width:100px;
  }

But when My select box is generated, the ctrl box moves down everytime! Do I have my CSS wrong? Or is it because the select box is generated by Javascript after the page has loaded?

I should mention that when YUI renders the select box as a menu button it changes it's markup to be a button, I didn't think this should matter because the positioning of ctrl is what I'm trying to change.

Any advice would help!
Thanks!


问:
"Index out of range" with Firebase and populating cell
I'm trying to post a dictionary to firebase that has the username as the key and the text as the value. I'm posting it like this:

```<code> let dict = ["\(currentUser!)":"\(text)"]
Database.database().reference().child("posts/\(ourID!)/comment").setValue(dict)
</code>```

What I'm trying to do her his populate a tableview with .subtitle cells populate it using the posts' text and user values so that way you can see the user's username and their post. Note: the problem is when I try to add a comment. This populates the tableview fine by itself when I'm reading the data. The problem is when I click a button to add another comment. For some reason I can't get the array to populate with the second post. The reason I have two arrays is because on is for the users, and one is for the text. Consequently, in the table view, each cell is populated with the corresponding post and matching user.

Here is how I'm reading the post(s):

```<code>let myTopPostsQuery = (Database.database().reference().child("posts").child("\(ourID!)/comment")).queryOrdered(byChild: "comment")

        myTopPostsQuery.observe(DataEventType.childAdded, with: { (snapshot) in

            print(snapshot)
            print("User: \(snapshot.key)")
            if let item = snapshot.value as? String {
                self.comments.append(item)
                print("Comments so far: \(self.comments)")
            }
            if let item2 = snapshot.key as? String {
                self.keyUsers.append(item2)
                print("Our users \(self.keyUsers)")
            }
            self.tableView.reloadData()

        })
 tableView.reloadData()
</code>```

The post is going to the Firebase Database successfully although I'm getting an error reading the username when I try to populate the tableview cell. I don't know why keyUsers won't work properly.

```<code>cell.textLabel?.text = comments[indexPath.row]
cell.detailTextLabel?.text = keyUsers[indexPath.row]**Thread 1: Fatal error: Index out of range
</code>```

答:
Did you update your row count in numberOfRowsInSection for your tableView?</p>

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return keyUsers.count  //keyUsers should always be updated whenever there is changes in your items
}
</code>```

Body:
I'm trying to post a dictionary to firebase that has the username as the key and the text as the value. I'm posting it like this:

 let dict = ["\(currentUser!)":"\(text)"]
Database.database().reference().child("posts/\(ourID!)/comment").setValue(dict)

What I'm trying to do her his populate a tableview with .subtitle cells populate it using the posts' text and user values so that way you can see the user's username and their post. Note: the problem is when I try to add a comment. This populates the tableview fine by itself when I'm reading the data. The problem is when I click a button to add another comment. For some reason I can't get the array to populate with the second post. The reason I have two arrays is because on is for the users, and one is for the text. Consequently, in the table view, each cell is populated with the corresponding post and matching user.

Here is how I'm reading the post(s):

let myTopPostsQuery = (Database.database().reference().child("posts").child("\(ourID!)/comment")).queryOrdered(byChild: "comment")

        myTopPostsQuery.observe(DataEventType.childAdded, with: { (snapshot) in

            print(snapshot)
            print("User: \(snapshot.key)")
            if let item = snapshot.value as? String {
                self.comments.append(item)
                print("Comments so far: \(self.comments)")
            }
            if let item2 = snapshot.key as? String {
                self.keyUsers.append(item2)
                print("Our users \(self.keyUsers)")
            }
            self.tableView.reloadData()

        })
 tableView.reloadData()

The post is going to the Firebase Database successfully although I'm getting an error reading the username when I try to populate the tableview cell. I don't know why keyUsers won't work properly.

cell.textLabel?.text = comments[indexPath.row]
cell.detailTextLabel?.text = keyUsers[indexPath.row]**Thread 1: Fatal error: Index out of range

Body:
Did you update your row count in numberOfRowsInSection for your tableView?

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return keyUsers.count  //keyUsers should always be updated whenever there is changes in your items
}


问:
How to Send an Email on Oracle Apex
I'm building a little application using Oracle Application Express Online. I'd like to send automatically email when an user inserts into the database a row.
I created an Item, called Email, in which I put the address of the user of the application:

```<code>Select User.Email from Users wher Users.Username=:APP_USER
</code>```

Query works, because in the application I see right email.
Then I create a process in the way you see in the screen I'll post here. But nothing happens. Can you help me, please?

As you see, in the centre of the photo there are 2 items: one has to go into the database to store a new row, the second one is the email that is in the process. But, as I said early, nothing happens.

答:
If you click on any attribute in APEX, and click the "Help" tab, you get some very useful information - in this case, that the field expects a substitution syntax for this scenario.

To

Enter the email recipients by specifying one or more email addresses.
  For multiple email addresses, use a comma-separated list. Use
  substitution syntax if you want to use a dynamic value.

Examples

```<code>john.doe@test.com, jane.doe@test.com
John Doe <john.doe@test.com>, Jane Doe <jane.doe@test.com>
&P6_TO.
</code>```

Title: How to Send an Email on Oracle Apex

Body:
I'm building a little application using Oracle Application Express Online. I'd like to send automatically email when an user inserts into the database a row.
I created an Item, called Email, in which I put the address of the user of the application:

Select User.Email from Users wher Users.Username=:APP_USER

Query works, because in the application I see right email.
Then I create a process in the way you see in the screen I'll post here. But nothing happens. Can you help me, please?

As you see, in the centre of the photo there are 2 items: one has to go into the database to store a new row, the second one is the email that is in the process. But, as I said early, nothing happens.

Body:
If you click on any attribute in APEX, and click the "Help" tab, you get some very useful information - in this case, that the field expects a substitution syntax for this scenario.

To

Enter the email recipients by specifying one or more email addresses.
  For multiple email addresses, use a comma-separated list. Use
  substitution syntax if you want to use a dynamic value.

Examples

john.doe@test.com, jane.doe@test.com
John Doe <john.doe@test.com>, Jane Doe <jane.doe@test.com>
&P6_TO.


问:
Jump to next sql query if one query fails
I want to know that is it possible to create package of queries such that if any query fails then plsql developer should jump to next query and should not stop until all queries run and at the end it should display that which query failed.

For example I have set of 5 queries.

I created one package contains these 5 queries. Now I want to create that package such that if 3rd query fails while running, plsql developer shouldn't stop and should jump to 4th query and run all remaining queries. At the end of all queries result it should show '3rd query failed'

答:
you can use try catch.

here's the syntax

BEGIN TRY

     { sql_statement | statement_block }

END TRY

BEGIN CATCH

     [ { sql_statement | statement_block } ]

END CATCH

[ ; ]


问:
replace substring for particular position in postgres
I have a table and want update query to update dob

```<code>------------
dob
------------
19101984
19111984
19071985
19081985
19101985
19121985
</code>```

I want to remove sub string from position 5 to character length of 2 means in the result table will be  :

```<code>------------
dob
------------
191084
191184
190785
190885
191085
191285
</code>```

答:
Use regex_replace:

```<code>select regexp_replace(dob::text, '(\d{4})\d{2}(\d{2})', E'\\1\\2')
from your_table;
</code>```

For updating:

```<code>update your_table
set dob = regexp_replace(dob, '(\d{4})\d{2}(\d{2})', E'\\1\\2');
</code>```

The regex pattern being used here is:

```<code>(\d{4})\d{2}(\d{2})
 ^^^^        ^^^^     <-- capture groups
</code>```

The first four and last two digits are captured in groups 1 and 2, respectively.  Then, we simply replace with the first and second capture group.

It is not clear whether the dob column is text or not.  If it is numeric, then you should be able to cast to text and run the above query.

Demo

Body:
I have a table and want update query to update dob

------------
dob
------------
19101984
19111984
19071985
19081985
19101985
19121985

I want to remove sub string from position 5 to character length of 2 means in the result table will be  :

------------
dob
------------
191084
191184
190785
190885
191085
191285

Body:
Use regex_replace:

select regexp_replace(dob::text, '(\d{4})\d{2}(\d{2})', E'\\1\\2')
from your_table;

For updating:

update your_table
set dob = regexp_replace(dob, '(\d{4})\d{2}(\d{2})', E'\\1\\2');

The regex pattern being used here is:

(\d{4})\d{2}(\d{2})
 ^^^^        ^^^^     <-- capture groups

The first four and last two digits are captured in groups 1 and 2, respectively.  Then, we simply replace with the first and second capture group.

It is not clear whether the dob column is text or not.  If it is numeric, then you should be able to cast to text and run the above query.

Demo


问:
How to read Unicode input and compare Unicode strings in Python?
I work in Python and would like to read user input (from command line) in Unicode format, ie a Unicode equivalent of raw_input?

Also, I would like to test Unicode strings for equality and it looks like a standard == does not work.

答:
I'm not really sure, which format you mean by "Unicode format", there are several. UTF-8? UTF-16? In any case you should be able to read a normal string with raw_input and then decode it using the strings decode method:

```<code>raw = raw_input("Please input some funny characters: ")
decoded = raw.decode("utf-8")
</code>```

If you have a different input encoding just use "utf-16" or whatever instead of "utf-8". Also see the codecs modules docs for different kinds of encodings.

Comparing then should work just fine with ==. If you have string literals containing special characters you should prefix them with "u" to mark them as unicode:

```<code>if decoded == u"äöü":
  print "Do you speak German?"
</code>```

And if you want to output these strings again, you probably want to encode them again in the desired encoding:

```<code>print decoded.encode("utf-8")
</code>```

Body:
I'm not really sure, which format you mean by "Unicode format", there are several. UTF-8? UTF-16? In any case you should be able to read a normal string with raw_input and then decode it using the strings decode method:

raw = raw_input("Please input some funny characters: ")
decoded = raw.decode("utf-8")

If you have a different input encoding just use "utf-16" or whatever instead of "utf-8". Also see the codecs modules docs for different kinds of encodings.

Comparing then should work just fine with ==. If you have string literals containing special characters you should prefix them with "u" to mark them as unicode:

if decoded == u"äöü":
  print "Do you speak German?"

And if you want to output these strings again, you probably want to encode them again in the desired encoding:

print decoded.encode("utf-8")

OwnerDisplayName: sth


问:
How to Expand/Collapse android component in Material Design
How to Expand/Collapse android component like ImageView, GoogleMap .. etc
I am using Design support library to provide android.support.design.widget.CollapsingToolbarLayout to Collapse ToolBar.

But how to Collapse other component.
Also I Haven't depth knowledge of Design support library, If it is possible to Collapse component using CollapsingToolbarLayout then give me some sample or Example.
Thanks in advance.

答:
Views inside a CoordinatorLayout negotiate with others in order to work together effectively by specifying these Behaviors

A CoordinatorLayout is a super cool feature of Material Design that helps to create attractive and harmonized layouts.

All you have to do is wrap your child views inside the CoordinatorLayout.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:fitsSystemWindows="true"
 tools:context="com.byte64.coordinatorlayoutexample.ScollingActivity">

 <android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/app_bar_height"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_scolling" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchor="@id/app_bar"
    app:layout_anchorGravity="bottom|end"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>
</code>```

and content_scrolling:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 app:layout_behavior="@string/appbar_scrolling_view_behavior"
 tools:context="com.byte64.coordinatorlayoutexample.ScollingActivity"
 tools:showIn="@layout/activity_scolling">

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/text_margin"
    android:text="@string/large_text" />

 </android.support.v4.widget.NestedScrollView>
</code>```

What this gives us is a layout that can be scrolled to collapse the Toolbar and hide the FloatingActionButton

Open:

Closed:

Body:
Views inside a CoordinatorLayout negotiate with others in order to work together effectively by specifying these Behaviors

A CoordinatorLayout is a super cool feature of Material Design that helps to create attractive and harmonized layouts.

All you have to do is wrap your child views inside the CoordinatorLayout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:fitsSystemWindows="true"
 tools:context="com.byte64.coordinatorlayoutexample.ScollingActivity">

 <android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/app_bar_height"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_scolling" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchor="@id/app_bar"
    app:layout_anchorGravity="bottom|end"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>

and content_scrolling:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 app:layout_behavior="@string/appbar_scrolling_view_behavior"
 tools:context="com.byte64.coordinatorlayoutexample.ScollingActivity"
 tools:showIn="@layout/activity_scolling">

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/text_margin"
    android:text="@string/large_text" />

 </android.support.v4.widget.NestedScrollView>

What this gives us is a layout that can be scrolled to collapse the Toolbar and hide the FloatingActionButton

Open:

Closed:


答:
Does it matter whether I use style 1 or style 2?

Yes, your style1 and style2 are essentially doing two different things.

style1 is assigning the reference of o1 to o2, so

```<code>o1 == o2 // true
</code>```

style2, on the other hand, is assigning the values of o1 to o3 and a new object is created, so

```<code>o1 == o3 // false
</code>```

Title: assigned objects using spread syntax `...` and equals `=`

Body:
Does it matter whether I use style 1 or style 2?

Yes, your style1 and style2 are essentially doing two different things.

style1 is assigning the reference of o1 to o2, so

o1 == o2 // true

style2, on the other hand, is assigning the values of o1 to o3 and a new object is created, so

o1 == o3 // false


问:
htaccess replacing PHP file.php?id=dynamic_id with file/id
I am wanting to use htaccess to make a url such as http://example.com/news/news_post.php?id=dynamic_id with a URL that looks like http://example.com/news/news_post/dynamic_id. So basically remove the .php file extension, as well as make ?id=dynamic_id to /dynamic_id for my news_post.php page.

I have searched around at other examples to find something that may help, but I haven't been able to find anything that helps.

If someone can help me with this, it would be much appreciated!

答:
Quickly Googling this and trying something out I came up with this...

.htaccess

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^news/news_post/(\d+)*$ ./news_post.php/$1
</code>```

news_post.php

```<code><?php

//var_dump($_SERVER);

//var_dump(explode('/',$_SERVER['REQUEST_URI']));

$url_segments = explode('/',$_SERVER['REQUEST_URI']);
//var_dump($url_segments);

$id = $url_segments[3];

//var_dump($id);
echo __FILE__;
echo '<br>';
echo 'The Dynamic Id is '. $id;
</code>```

So you can use whatever you like to get at the rest of the URL Parameters and do with them as you please...

Note: The var_dumps in news_post.php were used to quickly see what was going on and what was what...I left them there for you to play with if you so desire.

Of course you will change this to suit - I just guessed at what you may or may not have done or want.

Example:

```<code>http://phptutorials.com/news/news_post/1
</code>```

Result:

```<code>/home/phptutorials/public_html/news_post.php
The Dynamic Id is 1
</code>```

Using a Central file to handle all requests.
Going back to .htaccess

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

You can now use index.php as the central "policeman" to show your pages for anything you like using the code above as shown in news_post.php. But that is outside of your question and something you might want to look into.

Body:
Quickly Googling this and trying something out I came up with this...

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^news/news_post/(\d+)*$ ./news_post.php/$1

news_post.php

<?php

//var_dump($_SERVER);

//var_dump(explode('/',$_SERVER['REQUEST_URI']));

$url_segments = explode('/',$_SERVER['REQUEST_URI']);
//var_dump($url_segments);

$id = $url_segments[3];

//var_dump($id);
echo __FILE__;
echo '<br>';
echo 'The Dynamic Id is '. $id;

So you can use whatever you like to get at the rest of the URL Parameters and do with them as you please...

Note: The var_dumps in news_post.php were used to quickly see what was going on and what was what...I left them there for you to play with if you so desire.

Of course you will change this to suit - I just guessed at what you may or may not have done or want.

Example:

http://phptutorials.com/news/news_post/1

Result:

/home/phptutorials/public_html/news_post.php
The Dynamic Id is 1

Using a Central file to handle all requests.
Going back to .htaccess

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

You can now use index.php as the central "policeman" to show your pages for anything you like using the code above as shown in news_post.php. But that is outside of your question and something you might want to look into.