问:
Find a string within an array column in PostgreSQL
I have built a series of views in a PostgreSQL database that includes a couple of array columns.  The view definition is as follows:

```<code>create view articles_view as
  (select articles.*,
   array(select row(people.*)::people
     from people
     where articles.spubid=people.spubid and
       people.stype='Author' and
       bactive='t'
     order by people.iorder) as authors,
   array(select row(people.*)::people
     from people
     where articles.spubid=people.spubid and
       people.stype='Editor' and
       bactive='t'
     order by people.iorder) as editors,
   array(select row(people.*)::people
     from people
     where articles.spubid=people.spubid and
       people.stype='Reviewer' and
       bactive='t'
     order by people.iorder) as reviewers,
   array(select row(status.*)::status
     from status
     where articles.spubid=status.spubid and
       bactive='t') as status
  from articles
  where articles.bactive='t');
</code>```

Essentially what I want to do is an iLike on the 'author' column to determine if a specific user id exists in that array.  Obviously I can't use iLike on that datatype so I need to find another approach.

Here is an example of data in the 'authors' array:

{"(2373,t,f,f,\"2011-08-01
  11:57:40.696496\",/Pubs/pubs_edit_article.php,\"2011-08-09
  15:36:29.281833\",000128343,A00592,Author,1,Nicholas,K.,Kreidberg,\"\",123456789,t,Admin,A,A,A,0,\"\")","(2374,t,f,f,\"2011-08-01
  11:57:40.706617\",/Pubs/pubs_edit_article.php,\"2011-08-09
  15:36:29.285428\",000128343,A00592,Author,2,John,D.,Doe,\"\",234567890,t,IT,A,A,A,0,\"\")","(2381,t,f,f,\"2011-08-09
  14:45:14.870418\",000128343,\"2011-08-09
  15:36:29.28854\",000128343,A00592,Author,3,Jane,E,Doe,\"\",345678901,t,Admin,A,A,A,,\"\")","(2383,t,f,f,\"2011-08-09
  15:35:11.845283\",567890123,\"2011-08-09
  15:36:29.291388\",000128343,A00592,Author,4,Test,T,Testerton,\"\",TestTesterton,f,N/A,A,A,A,,\"\")"}

What I want to be able to do is a query the view and find out if the string '123456789' (that is the user id assigned to Nicholas Kreidberg in the array) exists in the array.  I don't care which user it is assigned to or where it appears in the array, all I need to know is if '123456789' shows up anywhere in the array.

Once I know how to write a query that determines if the condition above is true then my application will simply execute that query and if rows are returned it will know that the user id passed to the query is an author for that publication and proceed accordingly.

Thanks in advance for any insight that can be provided on this topic.

答:
The ANY() function can do the job for you:

```<code>SELECT * FROM people WHERE '123456789' = ANY(authors);
</code>```

Given people.authors is of type text[].

Body:
I have built a series of views in a PostgreSQL database that includes a couple of array columns.  The view definition is as follows:

create view articles_view as
  (select articles.*,
   array(select row(people.*)::people
     from people
     where articles.spubid=people.spubid and
       people.stype='Author' and
       bactive='t'
     order by people.iorder) as authors,
   array(select row(people.*)::people
     from people
     where articles.spubid=people.spubid and
       people.stype='Editor' and
       bactive='t'
     order by people.iorder) as editors,
   array(select row(people.*)::people
     from people
     where articles.spubid=people.spubid and
       people.stype='Reviewer' and
       bactive='t'
     order by people.iorder) as reviewers,
   array(select row(status.*)::status
     from status
     where articles.spubid=status.spubid and
       bactive='t') as status
  from articles
  where articles.bactive='t');

Essentially what I want to do is an iLike on the 'author' column to determine if a specific user id exists in that array.  Obviously I can't use iLike on that datatype so I need to find another approach.

Here is an example of data in the 'authors' array:

{"(2373,t,f,f,\"2011-08-01
  11:57:40.696496\",/Pubs/pubs_edit_article.php,\"2011-08-09
  15:36:29.281833\",000128343,A00592,Author,1,Nicholas,K.,Kreidberg,\"\",123456789,t,Admin,A,A,A,0,\"\")","(2374,t,f,f,\"2011-08-01
  11:57:40.706617\",/Pubs/pubs_edit_article.php,\"2011-08-09
  15:36:29.285428\",000128343,A00592,Author,2,John,D.,Doe,\"\",234567890,t,IT,A,A,A,0,\"\")","(2381,t,f,f,\"2011-08-09
  14:45:14.870418\",000128343,\"2011-08-09
  15:36:29.28854\",000128343,A00592,Author,3,Jane,E,Doe,\"\",345678901,t,Admin,A,A,A,,\"\")","(2383,t,f,f,\"2011-08-09
  15:35:11.845283\",567890123,\"2011-08-09
  15:36:29.291388\",000128343,A00592,Author,4,Test,T,Testerton,\"\",TestTesterton,f,N/A,A,A,A,,\"\")"}

What I want to be able to do is a query the view and find out if the string '123456789' (that is the user id assigned to Nicholas Kreidberg in the array) exists in the array.  I don't care which user it is assigned to or where it appears in the array, all I need to know is if '123456789' shows up anywhere in the array.

Once I know how to write a query that determines if the condition above is true then my application will simply execute that query and if rows are returned it will know that the user id passed to the query is an author for that publication and proceed accordingly.

Thanks in advance for any insight that can be provided on this topic.

Body:
The ANY() function can do the job for you:

SELECT * FROM people WHERE '123456789' = ANY(authors);

Given people.authors is of type text[].


来源: stackexchange

问:
Help with a SQL Query
I have a question on a SQL query and im wondering where to start. Thoughts so far include creating a table in memory with a range of dates, and joining on to it to get the sum of hours entered for a particular day.

Just to give an idea of the background of this question here is a little information.

The database is structured like so:

The result im trying to achieve with the query im currently writing needs to look like this:

The Query I have written so far:

```<code>DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2011/05/01 00:00'
SET @WeekEndDate = '2011/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
'???' AS 'Mon',
'???' AS 'Tue',
'???' AS 'Wed',
'???' AS 'Thu',
'???' AS 'Fri',
'???' AS 'Sat',
'???' AS 'Sun'

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]
</code>```

And this outputs the result set below:

As you can see the result set is almost there, I just need to total the number of hours worked on that particular day, grouping on ContractID, JobID, ProjectID, CostRateCode so I can get the number of hours for each cost rate on each unique project.

Is this possible with the current table design? or by using a temporary calendar table for the dates between the two passed in to the query?

EDIT:
Updated Query:

```<code>SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @RequestedByID AS BIGINT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME
DECLARE @WaitingForUserID AS BIGINT
DECLARE @WaitingForUserTypeID AS BIGINT
DECLARE @WaitingForTypeUser AS VARCHAR(50)
DECLARE @WaitingForTypeUserType AS VARCHAR(50)

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN SUM(JobSheetLineHours.Hours )
END
AS MON,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN SUM(JobSheetLineHours.Hours )
END
AS TUE,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN SUM(JobSheetLineHours.Hours )
END
AS WED,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN SUM(JobSheetLineHours.Hours )
END
AS THU,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN SUM(JobSheetLineHours.Hours )
END
AS FRI,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN SUM(JobSheetLineHours.Hours )
END
AS SAT,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN SUM(JobSheetLineHours.Hours )
END
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END
</code>```

Updated Result Set:

What I'm trying to do now is remove the JobSheetDate from the result set so the Total hours for each day are not all on seperate rows eg. The values for the same contract, project etc are put in the same row, but in the Mon, Tues, Wed etc column, rather than on multiple rows with the hours for one day populated, and the rest of the days null (see screenshot)

EDIT 2:
Updated Query:

```<code>SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
--[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN JobSheetLineHours.Hours
END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN JobSheetLineHours.Hours
END )
AS TUE,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN JobSheetLineHours.Hours
END)
AS WED,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN JobSheetLineHours.Hours
END)
AS THU,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN JobSheetLineHours.Hours
END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN JobSheetLineHours.Hours
END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN JobSheetLineHours.Hours
END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    --[JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END
</code>```

Results:

FINAL Update with finished Query:

```<code>SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Monday
     WHEN 1
     THEN [JobSheetLineHours].[Hours]
     END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Tuesday
     WHEN 2
     THEN [JobSheetLineHours].[Hours]
     END )
AS TUE,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Wednesday
     WHEN 3
     THEN [JobSheetLineHours].[Hours]
     END )
AS WED,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Thursday
     WHEN 4
     THEN [JobSheetLineHours].[Hours]
     END )
AS THU,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Friday
     WHEN 5
     THEN [JobSheetLineHours].[Hours]
     END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Saturday
     WHEN 6
     THEN [JobSheetLineHours].[Hours]
     END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Sunday
     WHEN 7
     THEN [JobSheetLineHours].[Hours]
     END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]
</code>```

答:
If I understand correctly you'll need to add this to your SELECT

EDIT Since you want sums you'll need to ADD SUMs around the case

```<code>SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 1 THEN
    JobSheetLineHours.Hours
END) AS MON,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 2 THEN
    JobSheetLineHours.Hours
END) AS TUE,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 3 THEN
    JobSheetLineHours.Hours
END) AS WED,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 4 THEN
    JobSheetLineHours.Hours
END) AS THU,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 5 THEN
    JobSheetLineHours.Hours
END) AS FRI,
</code>```

You'll also need to remove any [JobSheet].[JobSheetDate] from the SELECT and GROUP BY to get the days all on one line

As noted in the comments this depends on how SET DATEFIRST is set

Also it should be noted that whenever you have a SUM(CASE there's definitely a PIVOT alternative

ContentLicense: CC BY-SA 3.0

Title: Help with a SQL Query

Body:
I have a question on a SQL query and im wondering where to start. Thoughts so far include creating a table in memory with a range of dates, and joining on to it to get the sum of hours entered for a particular day.

Just to give an idea of the background of this question here is a little information.

The database is structured like so:

The result im trying to achieve with the query im currently writing needs to look like this:

The Query I have written so far:

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2011/05/01 00:00'
SET @WeekEndDate = '2011/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
'???' AS 'Mon',
'???' AS 'Tue',
'???' AS 'Wed',
'???' AS 'Thu',
'???' AS 'Fri',
'???' AS 'Sat',
'???' AS 'Sun'

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]

And this outputs the result set below:

As you can see the result set is almost there, I just need to total the number of hours worked on that particular day, grouping on ContractID, JobID, ProjectID, CostRateCode so I can get the number of hours for each cost rate on each unique project.

Is this possible with the current table design? or by using a temporary calendar table for the dates between the two passed in to the query?

EDIT:
Updated Query:

SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @RequestedByID AS BIGINT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME
DECLARE @WaitingForUserID AS BIGINT
DECLARE @WaitingForUserTypeID AS BIGINT
DECLARE @WaitingForTypeUser AS VARCHAR(50)
DECLARE @WaitingForTypeUserType AS VARCHAR(50)

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN SUM(JobSheetLineHours.Hours )
END
AS MON,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN SUM(JobSheetLineHours.Hours )
END
AS TUE,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN SUM(JobSheetLineHours.Hours )
END
AS WED,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN SUM(JobSheetLineHours.Hours )
END
AS THU,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN SUM(JobSheetLineHours.Hours )
END
AS FRI,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN SUM(JobSheetLineHours.Hours )
END
AS SAT,
CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN SUM(JobSheetLineHours.Hours )
END
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END

Updated Result Set:

What I'm trying to do now is remove the JobSheetDate from the result set so the Total hours for each day are not all on seperate rows eg. The values for the same contract, project etc are put in the same row, but in the Mon, Tues, Wed etc column, rather than on multiple rows with the hours for one day populated, and the rest of the days null (see screenshot)

EDIT 2:
Updated Query:

SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
--[JobSheet].[JobSheetDate],
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 1
THEN JobSheetLineHours.Hours
END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 2
THEN JobSheetLineHours.Hours
END )
AS TUE,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 3
THEN JobSheetLineHours.Hours
END)
AS WED,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 4
THEN JobSheetLineHours.Hours
END)
AS THU,
SUM(CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 5
THEN JobSheetLineHours.Hours
END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 6
THEN JobSheetLineHours.Hours
END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
WHEN 7
THEN JobSheetLineHours.Hours
END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    --[JobSheet].[JobSheetDate],
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode],
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate)
    WHEN 1
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 2
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 3
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 4
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 5
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 6
    THEN     JobSheetLineHours.Hours
    END,
    CASE DATEPART(WEEKDAY, JobSheet.JobSheetDate) WHEN 7
    THEN     JobSheetLineHours.Hours
    END

Results:

FINAL Update with finished Query:

SET DATEFIRST 1 -- Set the first day of week to monday
GO

DECLARE @Deleted AS BIT
DECLARE @WeekStartDate AS DATETIME
DECLARE @WeekEndDate AS DATETIME

SET @Deleted = 0
SET @WeekStartDate = '2009/05/01 00:00'
SET @WeekEndDate = '2012/05/07 00:00'

SELECT
[JobSheet].[ContractID],
[JobSheet].[ContractCode],
[JobSheet].[ContractTitle],
[JobSheet].[ProjectID],
[JobSheet].[ProjectCode],
[JobSheet].[ProjectTitle],
[JobSheet].[JobID],
[JobSheet].[JobCode],
[JobSheet].[JobTitle],
[JobSheet].[SageDatabaseID],
[JobSheetLineHours].[CostRateCode],
SUM([JobSheetLineHours].[Hours]) AS TotalCostRateHours,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Monday
     WHEN 1
     THEN [JobSheetLineHours].[Hours]
     END )
AS MON,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Tuesday
     WHEN 2
     THEN [JobSheetLineHours].[Hours]
     END )
AS TUE,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Wednesday
     WHEN 3
     THEN [JobSheetLineHours].[Hours]
     END )
AS WED,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Thursday
     WHEN 4
     THEN [JobSheetLineHours].[Hours]
     END )
AS THU,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Friday
     WHEN 5
     THEN [JobSheetLineHours].[Hours]
     END )
AS FRI,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Saturday
     WHEN 6
     THEN [JobSheetLineHours].[Hours]
     END )
AS SAT,
SUM( CASE DATEPART(WEEKDAY, [JobSheet].[JobSheetDate]) -- Get Total Value for Sunday
     WHEN 7
     THEN [JobSheetLineHours].[Hours]
     END )
AS SUN

FROM [JobSheet]

INNER JOIN [JobSheetLine]
ON  [JobSheetLine].[JobSheetID]
=   [JobSheet].[JobSheetID]

INNER JOIN [JobSheetLineHours]
ON  [JobSheetLineHours].[JobSheetLineID]
=   [JobSheetLine].[JobSheetLineID]

WHERE
    [JobSheet].[Deleted]=@Deleted
AND [JobSheet].[JobSheetDate] >= @WeekStartDate
AND [JobSheet].[JobSheetDate] <= @WeekEndDate
AND [JobSheetLine].[Deleted]=@Deleted
AND [JobSheetLineHours].[Deleted]=@Deleted

GROUP BY
    [JobSheet].[ContractID],
    [JobSheet].[ContractCode],
    [JobSheet].[ContractTitle],
    [JobSheet].[ProjectID],
    [JobSheet].[ProjectCode],
    [JobSheet].[ProjectTitle],
    [JobSheet].[JobID],
    [JobSheet].[JobCode],
    [JobSheet].[JobTitle],
    [JobSheet].[SageDatabaseID],
    [JobSheetLineHours].[CostRateCode]

Body:
If I understand correctly you'll need to add this to your SELECT

EDIT Since you want sums you'll need to ADD SUMs around the case

SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 1 THEN
    JobSheetLineHours.Hours
END) AS MON,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 2 THEN
    JobSheetLineHours.Hours
END) AS TUE,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 3 THEN
    JobSheetLineHours.Hours
END) AS WED,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 4 THEN
    JobSheetLineHours.Hours
END) AS THU,
SUM(CASE WHEN DATEPART(WEEKDAY, JobSheet.JobSheetDate) = 5 THEN
    JobSheetLineHours.Hours
END) AS FRI,

You'll also need to remove any [JobSheet].[JobSheetDate] from the SELECT and GROUP BY to get the days all on one line

As noted in the comments this depends on how SET DATEFIRST is set

Also it should be noted that whenever you have a SUM(CASE there's definitely a PIVOT alternative


问:
Which linux kernel version I'm using with yocto poky SUMO branch?
I am using yocto project to build linux kernel for my board.
I used yocto project version 2.5 SUMO branch and 19.0 poky version.
I am going to use MUSL-LibC and this is dependent to Linux 2.6 or later versions as it's shown here :
https://www.musl-libc.org/faq.html

I want to know how can I find out which linux kernel version I'm using now ?

答:
https://wiki.yoctoproject.org/wiki/Linux_Yocto

Yocto Project Release =
Yocto Project 2.5

LTSI Kernel Version =

linux-yocto_4.9

LTS Kernel Version =
linux-yocto_4.14

Released Kernel Version =
linux-yocto_4.15

ContentLicense: CC BY-SA 4.0


问:
502 Bad Gateway when installing PHP7.2 on nginx
So i installed LEMP (nginx, mysql, php..) by following the digital ocean guide. But ubuntu 16.04 only comes with php7 by default and i need greater then 7.1 to run Laravel. I am confused on why every time i replace php 7 with php 7.2-fpm from ondrej

sudo add-apt-repository ppa:ondrej/php

Why does the default php-fpm work and load the info.php page.. but when i install php 7.2-fpm from ondrej it shows up 502 bad gateway. Any help is appreciated so i can start Laravel! :D

答:
CentOS8 nginx Mariadb PHP7.2  on a free one year trial cloud server:

CentOS-8.1_64bit
Plan: G2.1GB
CPU: 1 vCPU
RAM: 1 GB
Disk: 40 GB

After many struggles, tearouts and reinstalls, I can confirm that in:

```<code>/usr/share/nginx/html/*.php
</code>```

You need:

```<code>echo <?php phpinfo(); ?>
</code>```

But, you also need to change file ownership:

```<code>sudo chown nginx:nginx usr/share/nginx/html/ -R
</code>```

Now I can drink to enjoy and not to forget about nights of tail chasing!

Body:
CentOS8 nginx Mariadb PHP7.2  on a free one year trial cloud server:

CentOS-8.1_64bit
Plan: G2.1GB
CPU: 1 vCPU
RAM: 1 GB
Disk: 40 GB

After many struggles, tearouts and reinstalls, I can confirm that in:

/usr/share/nginx/html/*.php

You need:

echo <?php phpinfo(); ?>

But, you also need to change file ownership:

sudo chown nginx:nginx usr/share/nginx/html/ -R

Now I can drink to enjoy and not to forget about nights of tail chasing!


问:
Vessel segmentation in retina image
I am trying to trace the vessels in a retina image. Currently I am using cv2's threshold functions to make the vessels contrast more with the surrounding retina:

```<code>from matplotlib import pyplot as plt
import cv2

img = cv2.imread('misc images/eye.jpeg',0)
img = cv2.medianBlur(img,5)

ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            cv2.THRESH_BINARY,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,11,2)

titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]

for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()
</code>```

And this is the result:

All 3 methods still have a lot of background noise from the rest of the retina. What can I do to improve the accuracy of vessel tracing?

答:
Here is another way to threshold your image using division normalization followed by filtering on contour area.

Read the input

Convert to gray

Apply morphology dilate (or apply gaussianBlur)

Divide input by dilated result

Threshold

Invert so vessels are white on black background

Find all contours

Filter contours to discard ones that are too small

Draw remaining contours in white on black image as mask

Apply mask to threshold image as first result

Apply mask to input as second result

Save results

Input

```<code>import cv2
import numpy as np

# read the image
img = cv2.imread('retina_eye.jpg')

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (5,5))
morph = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel)

# divide gray by morphology image
division = cv2.divide(gray, morph, scale=255)

# threshold
thresh = cv2.threshold(division, 0, 255, cv2.THRESH_OTSU )[1]

# invert
thresh = 255 - thresh

# find contours and discard contours with small areas
mask = np.zeros_like(thresh)
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

area_thresh = 10000
for cntr in contours:
    area = cv2.contourArea(cntr)
    if area > area_thresh:
        cv2.drawContours(mask, [cntr], -1, 255, 2)

# apply mask to thresh
result1 = cv2.bitwise_and(thresh, mask)
mask = cv2.merge([mask,mask,mask])
result2 = cv2.bitwise_and(img, mask)

# save results
cv2.imwrite('retina_eye_division.jpg',division)
cv2.imwrite('retina_eye_thresh.jpg',thresh)
cv2.imwrite('retina_eye_mask.jpg',mask)
cv2.imwrite('retina_eye_result1.jpg',result1)
cv2.imwrite('retina_eye_result2.jpg',result2)

# show results
cv2.imshow('morph', morph)
cv2.imshow('division', division)
cv2.imshow('thresh', thresh)
cv2.imshow('mask', mask)
cv2.imshow('result1', result1)
cv2.imshow('result2', result2)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Division image:

Threshold image:

Mask image:

Result 1:

Result 2:

Title: Vessel segmentation in retina image

Body:
I am trying to trace the vessels in a retina image. Currently I am using cv2's threshold functions to make the vessels contrast more with the surrounding retina:

from matplotlib import pyplot as plt
import cv2

img = cv2.imread('misc images/eye.jpeg',0)
img = cv2.medianBlur(img,5)

ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            cv2.THRESH_BINARY,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,11,2)

titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]

for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

And this is the result:

All 3 methods still have a lot of background noise from the rest of the retina. What can I do to improve the accuracy of vessel tracing?

Body:
Here is another way to threshold your image using division normalization followed by filtering on contour area.

Read the input

Convert to gray

Apply morphology dilate (or apply gaussianBlur)

Divide input by dilated result

Threshold

Invert so vessels are white on black background

Find all contours

Filter contours to discard ones that are too small

Draw remaining contours in white on black image as mask

Apply mask to threshold image as first result

Apply mask to input as second result

Save results

Input

import cv2
import numpy as np

# read the image
img = cv2.imread('retina_eye.jpg')

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (5,5))
morph = cv2.morphologyEx(gray, cv2.MORPH_DILATE, kernel)

# divide gray by morphology image
division = cv2.divide(gray, morph, scale=255)

# threshold
thresh = cv2.threshold(division, 0, 255, cv2.THRESH_OTSU )[1]

# invert
thresh = 255 - thresh

# find contours and discard contours with small areas
mask = np.zeros_like(thresh)
contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

area_thresh = 10000
for cntr in contours:
    area = cv2.contourArea(cntr)
    if area > area_thresh:
        cv2.drawContours(mask, [cntr], -1, 255, 2)

# apply mask to thresh
result1 = cv2.bitwise_and(thresh, mask)
mask = cv2.merge([mask,mask,mask])
result2 = cv2.bitwise_and(img, mask)

# save results
cv2.imwrite('retina_eye_division.jpg',division)
cv2.imwrite('retina_eye_thresh.jpg',thresh)
cv2.imwrite('retina_eye_mask.jpg',mask)
cv2.imwrite('retina_eye_result1.jpg',result1)
cv2.imwrite('retina_eye_result2.jpg',result2)

# show results
cv2.imshow('morph', morph)
cv2.imshow('division', division)
cv2.imshow('thresh', thresh)
cv2.imshow('mask', mask)
cv2.imshow('result1', result1)
cv2.imshow('result2', result2)
cv2.waitKey(0)
cv2.destroyAllWindows()

Division image:

Threshold image:

Mask image:

Result 1:

Result 2:


问:
Do Timers run on their Own threads in Node.js?
I am a bit confused here I know Javascript is a single-threaded language but while reading about the event loop. I got to know that in case of setTimeout or setInterval javascript calls web API provided by the browser which spawns a new thread to execute timer on that thread. but what happens in the case of node.js environment with timers how do they execute/work?</p>

答:
Node runs on a single thread but asynchronous work happens elsewhere. For example, libuv provides a pool of 4 threads that it may use, but wont if there's a better option.

The node documentation says

Node.js runs JavaScript code in the Event Loop (initialization and callbacks), and offers a Worker Pool to handle expensive tasks like file I/O. Node.js scales well, sometimes better than more heavyweight approaches like Apache. The secret to the scalability of Node.js is that it uses a small number of threads to handle many clients. If Node.js can make do with fewer threads, then it can spend more of your system's time and memory working on clients rather than on paying space and time overheads for threads (memory, context-switching). But because Node.js has only a few threads, you must structure your application to use them wisely.

A more detailed look at the event loop


问:
Unable to get IAM security credentials for AWS S3
This error is driving me crazy, had the same issue with a lambda web api, but that worked when uploaded, so that will do for now

This project however will be a NuGet package, and i need to be able to simply upload a file to S3

I have the code in place using the following : "https://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileDotNet.html"

im trying to run this local, but getting the Unable to get IAM security credentials from EC2 Instance Metadata Service." error

within visual studio, i can see the AWS Explorer, and i can create a bucket from here... so i have my user setup... but when i run local... there is no user???

i know its going to be a one line missing value somewhere :(

答:
This is due to missing credentials in your local machine. Setting up the AWS Explorer will not provide the credentials to running your code.

One way to setup the credentials is to use a Credentials File in C:\users\awsuser\.aws\credentials (asuming you are using windows).

The following is an example of a profile in the credentials file.

```<code>[default]
aws_access_key_id = {accessKey}
aws_secret_access_key = {secretKey}
</code>```

Here you can read more about managing credentials for .Net

Body:
This is due to missing credentials in your local machine. Setting up the AWS Explorer will not provide the credentials to running your code.

One way to setup the credentials is to use a Credentials File in C:\users\awsuser\.aws\credentials (asuming you are using windows).

The following is an example of a profile in the credentials file.

[default]
aws_access_key_id = {accessKey}
aws_secret_access_key = {secretKey}

Here you can read more about managing credentials for .Net


问:
I just want to use time in this colum (novice)
```<code>CREATE TABLE Vitals
(
    Record_No   int NOT NULL PRIMARY KEY,
    Patient_ID  int,
    Date_Taken  DATE NOT NULL,
    Time_Taken  time(7) NOT NULL,
    Systolic    int,
    CHECK       (Systolic > Diastolic),
    Diastolic   int,
    Heart_Rate  int CHECK (Heart_Rate > 30),
    CONSTRAINT fk_Patient_ID FOREIGN KEY (Patient_ID) REFERENCES Patients(Patient_ID)
);
</code>```

But, I get an error

```<code>Time_Taken time(7) NOT NULL,
               *
ERROR at line 6:
ORA-00907: missing right parenthesis
</code>```

When I use timestamp default systimestamp
it works. All I need is the time for Time_Taken column.
enter image description here

答:
You can not use the TIME data type as it is not the oracle defined datatype.

You can use the DATE or TIMESTAMP data type to store time with date.

Supported data types in oracle are documented here.

Body:
CREATE TABLE Vitals
(
    Record_No   int NOT NULL PRIMARY KEY,
    Patient_ID  int,
    Date_Taken  DATE NOT NULL,
    Time_Taken  time(7) NOT NULL,
    Systolic    int,
    CHECK       (Systolic > Diastolic),
    Diastolic   int,
    Heart_Rate  int CHECK (Heart_Rate > 30),
    CONSTRAINT fk_Patient_ID FOREIGN KEY (Patient_ID) REFERENCES Patients(Patient_ID)
);

But, I get an error

Time_Taken time(7) NOT NULL,
               *
ERROR at line 6:
ORA-00907: missing right parenthesis

When I use timestamp default systimestamp
it works. All I need is the time for Time_Taken column.
enter image description here


问:
Avoid bash command output to logged
I'm searching for a way to avoid that some bash command executed from within a Node-Red process (running on my Raspberry Pi 3B+ device) will go into the /var/log/system log file of the Raspeberry OS (Stretch).

In particular I've got a node (within  node-red) that each 30 seconds execute a bash command in order to kill any eventual process running on a serial device (connected to the Raspberry through a FTDI USB converter).

The command that I execute from within node-red is the following:

sudo fuser /dev/ttyFTDI_GAS -k

Most of the time there is no running process on the FTDI serial connected device so the command results in an error. In this case this error fill my system log file making it
really "crowded" and difficult to read.

Below how my system file looks like.

May 27 07:30:59 raspberrypi Node-RED[349]: 27 May 07:30:59 - [info] [exec:96ba9b5a.d097b8] error:Error: Command failed: sudo fuser /dev/ttyFTDI_GAS -k

May 27 07:30:59 raspberrypi Node-RED[349]: 27 May 07:31:29 - [info] [exec:96ba9b5a.d097b8] error:Error: Command failed: sudo fuser /dev/ttyFTDI_GAS -k

May 27 07:30:59 raspberrypi Node-RED[349]: 27 May 07:31:59 - [info] [exec:96ba9b5a.d097b8] error:Error: Command failed: sudo fuser /dev/ttyFTDI_GAS -k

May 27 07:30:59 raspberrypi Node-RED[349]: 27 May 07:32:29 - [info] [exec:96ba9b5a.d097b8] error:Error: Command failed: sudo fuser /dev/ttyFTDI_GAS -k

When instead there is one or mode processes using the connected device this command (that's the reason for having used the "-k" option) will kill them and "free" the connected device so preparing it to be ready to accept a new serial communication with the Raspberry.

Is there a way to avoid showing in the system log all the outcome of the sudo fuser /dev/ttyFTDI_GAS -k command?

答: The solution I've found in order to suppress each and every entry of the command in the system log is to add > /dev/null 2>&1 & at the end of the command, so in my example sudo fuser /dev/ttyFTDI_GAS -k > /dev/null 2>&1 &

Title: Avoid bash command output to logged


问:
Xamarin Forms Center Grid horizontal
I have a problem. I am trying to achieve the following Grid:

To do that, I thought that I should set both the ColumnWidth to Auto and set the HorizontalOptions of the Grid to Center, so the Grid is centred in the middle of the screen creating equal spaces at the left and right side, but no matter what I try, I can't seem to move the columns from the right side. Here is what I have now:

And here is my code:

```<code><Frame BorderColor="#00D8FF" Padding="0" HorizontalOptions="FillAndExpand" BackgroundColor="Transparent">
    <StackLayout Orientation="Vertical">
        <CarouselView ItemsSource="{Binding coinDataList}" HeightRequest="50">
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <Grid RowSpacing="0" HorizontalOptions="Center">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="25" />
                            <RowDefinition Height="25" />
                        </Grid.RowDefinitions>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>

                        <Label Grid.Row="0" Grid.Column="1" Text="BTC-USDT" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>
                        <Label Grid.Row="1" Grid.Column="1" Text="9762.33" TextColor="White" FontSize="18"/>
                        <Label Grid.RowSpan="2" Grid.Column="2" Text="-$476.22  (-4.77%)" VerticalOptions="CenterAndExpand" FontAttributes="Bold" TextColor="Red" FontSize="18" Margin="15,0,0,0"/>
                    </Grid>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>
    </StackLayout>
</Frame>
</code>```

How can I create my wanted result?

答:
Can you try this?</p>

```<code><Frame BorderColor="#00D8FF" Padding="0" HorizontalOptions="FillAndExpand" BackgroundColor="Transparent">
    <StackLayout Orientation="Vertical">
        <CarouselView ItemsSource="{Binding coinDataList}" HeightRequest="50">
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <Grid >
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Label Grid.Row="0" Grid.Column="1" Text="BTC-USDT" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>
                        <Label Grid.Row="1" Grid.Column="1" Text="9762.33" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>
                        <Label Grid.Row="0" Grid.Column="2" VerticalTextAlignment="Center" Text="-$476.22  (-4.77%)" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>

                    </Grid>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>
    </StackLayout>
</Frame>
</code>```

Title: Xamarin Forms Center Grid horizontal

Body:
I have a problem. I am trying to achieve the following Grid:

To do that, I thought that I should set both the ColumnWidth to Auto and set the HorizontalOptions of the Grid to Center, so the Grid is centred in the middle of the screen creating equal spaces at the left and right side, but no matter what I try, I can't seem to move the columns from the right side. Here is what I have now:

And here is my code:

<Frame BorderColor="#00D8FF" Padding="0" HorizontalOptions="FillAndExpand" BackgroundColor="Transparent">
    <StackLayout Orientation="Vertical">
        <CarouselView ItemsSource="{Binding coinDataList}" HeightRequest="50">
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <Grid RowSpacing="0" HorizontalOptions="Center">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="25" />
                            <RowDefinition Height="25" />
                        </Grid.RowDefinitions>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>

                    </Grid>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>
    </StackLayout>
</Frame>

How can I create my wanted result?

Body:
Can you try this?

<Frame BorderColor="#00D8FF" Padding="0" HorizontalOptions="FillAndExpand" BackgroundColor="Transparent">
    <StackLayout Orientation="Vertical">
        <CarouselView ItemsSource="{Binding coinDataList}" HeightRequest="50">
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <Grid >
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Label Grid.Row="0" Grid.Column="1" Text="BTC-USDT" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>
                        <Label Grid.Row="1" Grid.Column="1" Text="9762.33" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>
                        <Label Grid.Row="0" Grid.Column="2" VerticalTextAlignment="Center" Text="-$476.22  (-4.77%)" FontAttributes="Bold" TextColor="#00D8FF" FontSize="18"/>

                    </Grid>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>
    </StackLayout>
</Frame>


问:
I am getting a different maximum and minimum value here
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done
```

<p>Output: </p>

<p>Invalid Input</p>

<p>Maximum is 10</p>

<p>Minimum is 4</p>

<p><strong>Expected Output:</strong></p>

<p><strong>Invalid Input</strong></p>

<p><strong>Maximum is 11</strong></p>

<p><strong>Minimum is 2</strong></p>

```a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()
```

答:
Problems with your code

Why your functions are in while loop

Every time while finding small and large you are comparing with first value only

Solution

Below is smallest possible changed answer from your code.

a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

def sml():
    smalles=a[0]
    for i in range(len(a)):
        if a[i]<smalles:
            smalles=a[i]
    print("Minimum is",smalles)

def lge():
    larges=a[0]
    for i in range(len(a)):
        if a[i]>larges:
            larges=a[i]
    print("Maximum is",larges)

lge()
sml()
```

Body:
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done

Output:

Invalid Input

Maximum is 10

Minimum is 4

Expected Output:

Invalid Input

Maximum is 11

Minimum is 2

a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()


问:
How to access a list of json in flutter
I am trying to access a son that is sent through API. But the JSON contains a list. I couldn't access it. please help me.

This is my JSON which I receive from the API.

```<code>{
  "message": "success",
  "events": [
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6acc6836b3263e4f50662",
      "eventid": "01",
      "schoolname": "abc school",
      "teacherid": "0015",
      "teachername": "Malar",
      "eventdate": "2000-03-05T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6ad38836b3263e4f50665",
      "eventid": "02",
      "schoolname": "abc school",
      "teacherid": "0016",
      "teachername": "Malaring",
      "eventdate": "2000-06-02T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
  ]
}
</code>```

My PODO class is

```<code>// To parse this JSON data, do
//
//     final allEvents = allEventsFromJson(jsonString);

import 'dart:convert';

GetAllEvents allEventsFromJson(String str) => GetAllEvents.fromJson(json.decode(str));

String allEventsToJson(GetAllEvents data) => json.encode(data.toJson());

class GetAllEvents {
  GetAllEvents({
    this.message,
    this.events,
  });

  String message;
  List<Event> events;

  factory GetAllEvents.fromJson(Map<String, dynamic> json) => GetAllEvents(
    message: json["message"],
    events: List<Event>.from(json["events"].map((x) => Event.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "message": message,
    "events": List<dynamic>.from(events.map((x) => x.toJson())),
  };
}

class Event {
  Event({
    this.schools,
    this.participants,
    this.id,
    this.eventid,
    this.schoolname,
    this.teacherid,
    this.teachername,
    this.eventdate,
    this.eventname,
    this.eventdescription,
    this.eventtype,
    this.eventimage,
    this.v,
  });

  int schools;
  int participants;
  String id;
  String eventid;
  String schoolname;
  String teacherid;
  String teachername;
  DateTime eventdate;
  String eventname;
  String eventdescription;
  String eventtype;
  String eventimage;
  int v;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
    schools: json["schools"],
    participants: json["participants"],
    id: json["_id"],
    eventid: json["eventid"],
    schoolname: json["schoolname"],
    teacherid: json["teacherid"],
    teachername: json["teachername"],
    eventdate: DateTime.parse(json["eventdate"]),
    eventname: json["eventname"],
    eventdescription: json["eventdescription"],
    eventtype: json["eventtype"],
    eventimage: json["eventimage"],
    v: json["__v"],
  );

  Map<String, dynamic> toJson() => {
    "schools": schools,
    "participants": participants,
    "_id": id,
    "eventid": eventid,
    "schoolname": schoolname,
    "teacherid": teacherid,
    "teachername": teachername,
    "eventdate": eventdate.toIso8601String(),
    "eventname": eventname,
    "eventdescription": eventdescription,
    "eventtype": eventtype,
    "eventimage": eventimage,
    "__v": v,
  };
}
</code>```

And my future function is:

```<code>final String getAllEventsUrl = "http://192.168.1.5:8080/api/events/getall";

  Future getAllEvents() async {
    Response response = await post(getAllEventsUrl);
    var result = response.body;
    var body = jsonDecode(result);
    return GetAllEvents.fromJson(body);
  }
</code>```

And my code is:

```<code>Container(
      margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
      child: FutureBuilder(
        future: eventsApi.getAllEvents(),
        builder: (context, snapshot) {
          if(snapshot.hasData){
            print(snapshot.data);
            List<GetAllEvents> events = snapshot.data;
            ListView(
              children: events.map((e) => ListTile(title: Text(e.events[0].eventdescription),)).toList(),
            );
          }
          return Center(child: CircularProgressIndicator());
        },
      ),
    );
</code>```

I get this error

type 'GetAllEvents' is not a subtype of type 'List' what should I do now. Please help.

答:
You can copy paste run full code below

Step 1 : You can provide type GetAllEvents to Future and AsyncSnapshot<GetAllEvents>

Step 2 : You need to check connectionState

```<code>Future<GetAllEvents> _future;
...
@override
void initState() {
_future = getAllEvents();
...
Future<GetAllEvents> getAllEvents() async {
...
FutureBuilder(
        future: _future,
        builder: (context, AsyncSnapshot<GetAllEvents> snapshot) {
          switch (snapshot.connectionState) {
            ...
            case ConnectionState.waiting:
              return Center(child: CircularProgressIndicator());
            case ConnectionState.active:
              return Text('');
            case ConnectionState.done:
              if (snapshot.hasError) {
                ...
              } else {
                return ListView.builder(
                    itemCount: snapshot.data.events.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                          title: Text(snapshot
                              .data.events[index].eventdescription))
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

GetAllEvents allEventsFromJson(String str) =>
    GetAllEvents.fromJson(json.decode(str));

String allEventsToJson(GetAllEvents data) => json.encode(data.toJson());

class GetAllEvents {
  GetAllEvents({
    this.message,
    this.events,
  });

  String message;
  List<Event> events;

  factory GetAllEvents.fromJson(Map<String, dynamic> json) => GetAllEvents(
        message: json["message"],
        events: List<Event>.from(json["events"].map((x) => Event.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "message": message,
        "events": List<dynamic>.from(events.map((x) => x.toJson())),
      };
}

class Event {
  Event({
    this.schools,
    this.participants,
    this.id,
    this.eventid,
    this.schoolname,
    this.teacherid,
    this.teachername,
    this.eventdate,
    this.eventname,
    this.eventdescription,
    this.eventtype,
    this.eventimage,
    this.v,
  });

  int schools;
  int participants;
  String id;
  String eventid;
  String schoolname;
  String teacherid;
  String teachername;
  DateTime eventdate;
  String eventname;
  String eventdescription;
  String eventtype;
  String eventimage;
  int v;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
        schools: json["schools"],
        participants: json["participants"],
        id: json["_id"],
        eventid: json["eventid"],
        schoolname: json["schoolname"],
        teacherid: json["teacherid"],
        teachername: json["teachername"],
        eventdate: DateTime.parse(json["eventdate"]),
        eventname: json["eventname"],
        eventdescription: json["eventdescription"],
        eventtype: json["eventtype"],
        eventimage: json["eventimage"],
        v: json["__v"],
      );

  Map<String, dynamic> toJson() => {
        "schools": schools,
        "participants": participants,
        "_id": id,
        "eventid": eventid,
        "schoolname": schoolname,
        "teacherid": teacherid,
        "teachername": teachername,
        "eventdate": eventdate.toIso8601String(),
        "eventname": eventname,
        "eventdescription": eventdescription,
        "eventtype": eventtype,
        "eventimage": eventimage,
        "__v": v,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<GetAllEvents> _future;

  Future<GetAllEvents> getAllEvents() async {
    String jsonString = '''
    {
  "message": "success",
  "events": [
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6acc6836b3263e4f50662",
      "eventid": "01",
      "schoolname": "abc school",
      "teacherid": "0015",
      "teachername": "Malar",
      "eventdate": "2000-03-05T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6ad38836b3263e4f50665",
      "eventid": "02",
      "schoolname": "abc school",
      "teacherid": "0016",
      "teachername": "Malaring",
      "eventdate": "2000-06-02T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    }
  ]
}
    ''';
    //Response response = await post(getAllEventsUrl);
    http.Response response = http.Response(jsonString, 200);
    var result = response.body;
    var body = jsonDecode(result);
    return GetAllEvents.fromJson(body);
  }

  @override
  void initState() {
    _future = getAllEvents();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<GetAllEvents> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.events.length,
                        itemBuilder: (context, index) {
                          return ListTile(
                              title: Text(snapshot
                                  .data.events[index].eventdescription));
                        });
                  }
              }
            }));
  }
}
</code>```

Title: How to access a list of json in flutter

Body:
I am trying to access a son that is sent through API. But the JSON contains a list. I couldn't access it. please help me.

This is my JSON which I receive from the API.

{
  "message": "success",
  "events": [
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6acc6836b3263e4f50662",
      "eventid": "01",
      "schoolname": "abc school",
      "teacherid": "0015",
      "teachername": "Malar",
      "eventdate": "2000-03-05T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6ad38836b3263e4f50665",
      "eventid": "02",
      "schoolname": "abc school",
      "teacherid": "0016",
      "teachername": "Malaring",
      "eventdate": "2000-06-02T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
  ]
}

My PODO class is

// To parse this JSON data, do
//
//     final allEvents = allEventsFromJson(jsonString);

import 'dart:convert';

GetAllEvents allEventsFromJson(String str) => GetAllEvents.fromJson(json.decode(str));

String allEventsToJson(GetAllEvents data) => json.encode(data.toJson());

class GetAllEvents {
  GetAllEvents({
    this.message,
    this.events,
  });

  String message;
  List<Event> events;

  factory GetAllEvents.fromJson(Map<String, dynamic> json) => GetAllEvents(
    message: json["message"],
    events: List<Event>.from(json["events"].map((x) => Event.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "message": message,
    "events": List<dynamic>.from(events.map((x) => x.toJson())),
  };
}

class Event {
  Event({
    this.schools,
    this.participants,
    this.id,
    this.eventid,
    this.schoolname,
    this.teacherid,
    this.teachername,
    this.eventdate,
    this.eventname,
    this.eventdescription,
    this.eventtype,
    this.eventimage,
    this.v,
  });

  int schools;
  int participants;
  String id;
  String eventid;
  String schoolname;
  String teacherid;
  String teachername;
  DateTime eventdate;
  String eventname;
  String eventdescription;
  String eventtype;
  String eventimage;
  int v;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
    schools: json["schools"],
    participants: json["participants"],
    id: json["_id"],
    eventid: json["eventid"],
    schoolname: json["schoolname"],
    teacherid: json["teacherid"],
    teachername: json["teachername"],
    eventdate: DateTime.parse(json["eventdate"]),
    eventname: json["eventname"],
    eventdescription: json["eventdescription"],
    eventtype: json["eventtype"],
    eventimage: json["eventimage"],
    v: json["__v"],
  );

  Map<String, dynamic> toJson() => {
    "schools": schools,
    "participants": participants,
    "_id": id,
    "eventid": eventid,
    "schoolname": schoolname,
    "teacherid": teacherid,
    "teachername": teachername,
    "eventdate": eventdate.toIso8601String(),
    "eventname": eventname,
    "eventdescription": eventdescription,
    "eventtype": eventtype,
    "eventimage": eventimage,
    "__v": v,
  };
}

And my future function is:

final String getAllEventsUrl = "http://192.168.1.5:8080/api/events/getall";

  Future getAllEvents() async {
    Response response = await post(getAllEventsUrl);
    var result = response.body;
    var body = jsonDecode(result);
    return GetAllEvents.fromJson(body);
  }

And my code is:

Container(
      margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
      child: FutureBuilder(
        future: eventsApi.getAllEvents(),
        builder: (context, snapshot) {
          if(snapshot.hasData){
            print(snapshot.data);
            List<GetAllEvents> events = snapshot.data;
            ListView(
              children: events.map((e) => ListTile(title: Text(e.events[0].eventdescription),)).toList(),
            );
          }
          return Center(child: CircularProgressIndicator());
        },
      ),
    );

I get this error

type 'GetAllEvents' is not a subtype of type 'List' what should I do now. Please help.

Body:
You can copy paste run full code below

Step 1 : You can provide type GetAllEvents to Future and AsyncSnapshot<GetAllEvents>

Step 2 : You need to check connectionState

Future<GetAllEvents> _future;
...
@override
void initState() {
_future = getAllEvents();
...
Future<GetAllEvents> getAllEvents() async {
...
FutureBuilder(
        future: _future,
        builder: (context, AsyncSnapshot<GetAllEvents> snapshot) {
          switch (snapshot.connectionState) {
            ...
            case ConnectionState.waiting:
              return Center(child: CircularProgressIndicator());
            case ConnectionState.active:
              return Text('');
            case ConnectionState.done:
              if (snapshot.hasError) {
                ...
              } else {
                return ListView.builder(
                    itemCount: snapshot.data.events.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                          title: Text(snapshot
                              .data.events[index].eventdescription))

working demo

full code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

GetAllEvents allEventsFromJson(String str) =>
    GetAllEvents.fromJson(json.decode(str));

String allEventsToJson(GetAllEvents data) => json.encode(data.toJson());

class GetAllEvents {
  GetAllEvents({
    this.message,
    this.events,
  });

  String message;
  List<Event> events;

  factory GetAllEvents.fromJson(Map<String, dynamic> json) => GetAllEvents(
        message: json["message"],
        events: List<Event>.from(json["events"].map((x) => Event.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "message": message,
        "events": List<dynamic>.from(events.map((x) => x.toJson())),
      };
}

class Event {
  Event({
    this.schools,
    this.participants,
    this.id,
    this.eventid,
    this.schoolname,
    this.teacherid,
    this.teachername,
    this.eventdate,
    this.eventname,
    this.eventdescription,
    this.eventtype,
    this.eventimage,
    this.v,
  });

  int schools;
  int participants;
  String id;
  String eventid;
  String schoolname;
  String teacherid;
  String teachername;
  DateTime eventdate;
  String eventname;
  String eventdescription;
  String eventtype;
  String eventimage;
  int v;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
        schools: json["schools"],
        participants: json["participants"],
        id: json["_id"],
        eventid: json["eventid"],
        schoolname: json["schoolname"],
        teacherid: json["teacherid"],
        teachername: json["teachername"],
        eventdate: DateTime.parse(json["eventdate"]),
        eventname: json["eventname"],
        eventdescription: json["eventdescription"],
        eventtype: json["eventtype"],
        eventimage: json["eventimage"],
        v: json["__v"],
      );

  Map<String, dynamic> toJson() => {
        "schools": schools,
        "participants": participants,
        "_id": id,
        "eventid": eventid,
        "schoolname": schoolname,
        "teacherid": teacherid,
        "teachername": teachername,
        "eventdate": eventdate.toIso8601String(),
        "eventname": eventname,
        "eventdescription": eventdescription,
        "eventtype": eventtype,
        "eventimage": eventimage,
        "__v": v,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<GetAllEvents> _future;

  Future<GetAllEvents> getAllEvents() async {
    String jsonString = '''
    {
  "message": "success",
  "events": [
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6acc6836b3263e4f50662",
      "eventid": "01",
      "schoolname": "abc school",
      "teacherid": "0015",
      "teachername": "Malar",
      "eventdate": "2000-03-05T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6ad38836b3263e4f50665",
      "eventid": "02",
      "schoolname": "abc school",
      "teacherid": "0016",
      "teachername": "Malaring",
      "eventdate": "2000-06-02T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    }
  ]
}
    ''';
    //Response response = await post(getAllEventsUrl);
    http.Response response = http.Response(jsonString, 200);
    var result = response.body;
    var body = jsonDecode(result);
    return GetAllEvents.fromJson(body);
  }

  @override
  void initState() {
    _future = getAllEvents();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<GetAllEvents> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.events.length,
                        itemBuilder: (context, index) {
                          return ListTile(
                              title: Text(snapshot
                                  .data.events[index].eventdescription));
                        });
                  }
              }
            }));
  }
}


问:
Pandas splitting Columns and creating Columns of tuples
I have a dataframe which looks as follows:

```<code># df

colA     colB          colC

rqp      129            a
pot      217;345        u
ghay     716            b
rbba     217;345        d
tary     612;811;760    a
kals     716            t
</code>```

The ColB (any component out of two shown) & ColC combination make a unique combination.
I want to create a dataframe from this dataframe which will look like the following

```<code># newdf:

colAA      coLBB

(129,a)    (a,rqp)
(217,u)    (u,pot)
(345,u)    (u,pot)
(716,b)    (b,ghay)
(217,d)    (d,rbba)
(345,d)    (d,rbba)
(612,a)    (a,tary)
(811,a)    (a,tary)
(760,a)    (a,tary)
(716,t)    (t,kals)
</code>```

I have tried creating new columns if there is a single element in colB, but cannot get how to do using the semicolon splitter and then how to create columns of tuples.

If I do not have any semicolon in ColB, then I can use

```<code>df['AA'] = list(zip(df[colB], df[colC]))
df['AB'] = list(zip(df[colC], df[colA]))
</code>```

However the presence of semicolon in ColB I am getting issues, as how to split that string into multiple ones and assign the tuples.
Any help will be very much appreciated.

答:
Use, Series.str.split to split the strings of column colB around the delimiter ; then using DataFrame.explode transform each element of a column colB to a row, replicating index values. Then use DataFrame.agg to aggregate the required columns as tuple along axis=1:

```<code>df['colB'] = df['colB'].str.split(';')
df = df.explode('colB')
df['ColAA'] = df[['colB', 'colC']].agg(tuple, axis=1)
df['ColBB'] = df[['colC', 'colA']].agg(tuple, axis=1)
df = df[['ColAA', 'ColBB']].reset_index(drop=True)
</code>```

Result:

```<code># print(df)
     ColAA      ColBB
0  (129, a)   (a, rqp)
1  (217, u)   (u, pot)
2  (345, u)   (u, pot)
3  (716, b)  (b, ghay)
4  (217, d)  (d, rbba)
5  (345, d)  (d, rbba)
6  (612, a)  (a, tary)
7  (811, a)  (a, tary)
8  (760, a)  (a, tary)
9  (716, t)  (t, kals)
</code>```

Body:
I have a dataframe which looks as follows:

# df

colA     colB          colC

rqp      129            a
pot      217;345        u
ghay     716            b
rbba     217;345        d
tary     612;811;760    a
kals     716            t

The ColB (any component out of two shown) & ColC combination make a unique combination.
I want to create a dataframe from this dataframe which will look like the following

# newdf:

colAA      coLBB

(129,a)    (a,rqp)
(217,u)    (u,pot)
(345,u)    (u,pot)
(716,b)    (b,ghay)
(217,d)    (d,rbba)
(345,d)    (d,rbba)
(612,a)    (a,tary)
(811,a)    (a,tary)
(760,a)    (a,tary)
(716,t)    (t,kals)

I have tried creating new columns if there is a single element in colB, but cannot get how to do using the semicolon splitter and then how to create columns of tuples.

If I do not have any semicolon in ColB, then I can use

df['AA'] = list(zip(df[colB], df[colC]))
df['AB'] = list(zip(df[colC], df[colA]))

However the presence of semicolon in ColB I am getting issues, as how to split that string into multiple ones and assign the tuples.
Any help will be very much appreciated.

Body:
Use, Series.str.split to split the strings of column colB around the delimiter ; then using DataFrame.explode transform each element of a column colB to a row, replicating index values. Then use DataFrame.agg to aggregate the required columns as tuple along axis=1:

df['colB'] = df['colB'].str.split(';')
df = df.explode('colB')
df['ColAA'] = df[['colB', 'colC']].agg(tuple, axis=1)
df['ColBB'] = df[['colC', 'colA']].agg(tuple, axis=1)
df = df[['ColAA', 'ColBB']].reset_index(drop=True)

Result:

# print(df)
     ColAA      ColBB
0  (129, a)   (a, rqp)
1  (217, u)   (u, pot)
2  (345, u)   (u, pot)
3  (716, b)  (b, ghay)
4  (217, d)  (d, rbba)
5  (345, d)  (d, rbba)
6  (612, a)  (a, tary)
7  (811, a)  (a, tary)
8  (760, a)  (a, tary)
9  (716, t)  (t, kals)


问:
How to put initial snapshot data with the phone sign in method
I am trying to figure out how to put initial data into Firestore when the user signs in using their phone #(And keep their data stored when they log out and sign in again). If anyone has worked with the email sign-in method you will know that createUserWithEmailAndPassword runs only once when the user registers a new account.

But for the google sign-in method and phone sign-in method, it has only one function that runs every time when they sign up, so every time when they log out and sign back in, their data gets overwritten with the initial data I have implemented.
The Issue is that I am calling a function that puts initial data into Firestore every time they sign in with the phone auth, as seen below. I have tried many ways to get around this, but no luck.

```<code>AuthCredential credential = PhoneAuthProvider.getCredential(verificationId: widget.verificationId, smsCode: smsCode);
                    AuthResult result = await _auth.signInWithCredential(credential);
                    FirebaseUser user = result.user;
                    await DatabaseService(uid: user.uid).updatingProfile( // How I put the initialData into Firestore
                      "",
                      "https://www.nacdnet.org/wp-content/uploads/2016/06/person-placeholder.jpg",
                      user.phoneNumber
                    );
                    await DatabaseService(uid: user.uid).updatingStat(""); // How I put the initialData into Firestore
                    return user;
</code>```

DatabaseService

```<code>// Create instance for Firestore collection
  final CollectionReference _profileCollection = Firestore.instance.collection("profile");
  final CollectionReference _statCollection = Firestore.instance.collection("stat");

  // Updating user profile
  Future updatingProfile(String name, String image, String phoneNumber) async {
  return await _profileCollection.document(uid).setData({
    "name": name,
    "image": image,
    "phoneNumber": phoneNumber,
    });
  }

  // Updating user Stat
  Future updatingStat(String stat) async {
    return await _statCollection.document(uid).setData({
      "stat": stat,
      "lastUpdate": DateTime.now()
    });
  }
</code>```

答:
One way that worked was by using the where method for filtering. I first query all the documents and filter with the phone number field, then go through each document individually to check if they have any documents in firestore, if not, then a new account gets created.

```<code>    AuthCredential credential = PhoneAuthProvider.getCredential(verificationId: widget.verificationId, smsCode: smsCode);
    AuthResult result = await _auth.signInWithCredential(credential);
    FirebaseUser user = result.user;
    QuerySnapshot resultFromDb = await _db
      .where("phoneNumber", isEqualTo: user.phoneNumber)
      .getDocuments();
       final List<DocumentSnapshot> docsFromDb = resultFromDb.documents;
        if (docsFromDb.length == 0) {
         await DatabaseService(uid: user.uid).updatingProfile(
          "",
          "https://www.nacdnet.org/wp-content/uploads/2016/06/person-placeholder.jpg",
           user.phoneNumber
         );
         await DatabaseService(uid: user.uid).updatingStat("");
         return user;
        }
</code>```

Body:
I am trying to figure out how to put initial data into Firestore when the user signs in using their phone #(And keep their data stored when they log out and sign in again). If anyone has worked with the email sign-in method you will know that createUserWithEmailAndPassword runs only once when the user registers a new account.

But for the google sign-in method and phone sign-in method, it has only one function that runs every time when they sign up, so every time when they log out and sign back in, their data gets overwritten with the initial data I have implemented.
The Issue is that I am calling a function that puts initial data into Firestore every time they sign in with the phone auth, as seen below. I have tried many ways to get around this, but no luck.

AuthCredential credential = PhoneAuthProvider.getCredential(verificationId: widget.verificationId, smsCode: smsCode);
                    AuthResult result = await _auth.signInWithCredential(credential);
                    FirebaseUser user = result.user;
                    await DatabaseService(uid: user.uid).updatingProfile( // How I put the initialData into Firestore
                      "",
                      "https://www.nacdnet.org/wp-content/uploads/2016/06/person-placeholder.jpg",
                      user.phoneNumber
                    );
                    await DatabaseService(uid: user.uid).updatingStat(""); // How I put the initialData into Firestore
                    return user;

DatabaseService

// Create instance for Firestore collection
  final CollectionReference _profileCollection = Firestore.instance.collection("profile");
  final CollectionReference _statCollection = Firestore.instance.collection("stat");

  // Updating user profile
  Future updatingProfile(String name, String image, String phoneNumber) async {
  return await _profileCollection.document(uid).setData({
    "name": name,
    "image": image,
    "phoneNumber": phoneNumber,
    });
  }

  // Updating user Stat
  Future updatingStat(String stat) async {
    return await _statCollection.document(uid).setData({
      "stat": stat,
      "lastUpdate": DateTime.now()
    });
  }

Body:
One way that worked was by using the where method for filtering. I first query all the documents and filter with the phone number field, then go through each document individually to check if they have any documents in firestore, if not, then a new account gets created.

    AuthCredential credential = PhoneAuthProvider.getCredential(verificationId: widget.verificationId, smsCode: smsCode);
    AuthResult result = await _auth.signInWithCredential(credential);
    FirebaseUser user = result.user;
    QuerySnapshot resultFromDb = await _db
      .where("phoneNumber", isEqualTo: user.phoneNumber)
      .getDocuments();
       final List<DocumentSnapshot> docsFromDb = resultFromDb.documents;
        if (docsFromDb.length == 0) {
         await DatabaseService(uid: user.uid).updatingProfile(
          "",
          "https://www.nacdnet.org/wp-content/uploads/2016/06/person-placeholder.jpg",
           user.phoneNumber
         );
         await DatabaseService(uid: user.uid).updatingStat("");
         return user;
        }


问:
How to customize whether a request follow the 302 by one okhttpclient
Currently, we only have one okhttpclient in our app, by some of our request need to intercept the original reponse and some want to follow the redirect.

we can identify the request whether it needs to redirect, but a okhttp client only has a global param to control this, how can we customize for each request?

答: You could use a network Interceptor to remove the server response’s Location header. If you need that data you can put it into another header like Rewritten-Location. Either way if the location header is absent the response will not be redirected.


问:
Swapping the variables using pointers. What is the difference? (C Programming)
What is the difference between the two functions? Can you show that through an example? Thank you in advance.

One is swapping variables using variables, the other one is doing the same thing just with pointers. I am given that one of them is wrong, but which one and why?

void swap1(int x, int y) {
  int temp;

  temp = x;
  x = y;
  y = temp;
}

void swap2(int *p1, int *p2) {
  int temp;

  temp = *p1;
  *p1 = *p2;
  *p2 = temp;
}```

答:
It has to do with the concepts of pointers. Consider the program below (just added some informative code):

```<code>#include <stdio.h>

void swap1(int x, int y) {
    printf("swap1 : xaddr = %p yaddr = %p\n", &x, &y);

    printf("swap1: %d %d\n", x, y);

    int temp;
    temp = x;
    x = y;
    y = temp;

    printf("swap1: %d %d\n", x, y);
}

void swap2(int *p1, int *p2) {
    printf("swap2 : xaddr = %p yaddr = %p\n", p1, p2);

    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

int main()
{
    int x = 10, y = 20;

    printf("main: xaddr = %p yaddr = %p\n", &x, &y);

    swap1(x, y);

    printf("main after swap1 : %d %d\n", x, y);

    swap2(&x, &y);

    printf("main after swap2: %d %d\n", x, y);

    return 0;
}
</code>```

The variables x and y in the main are residing in the local function stack of the main(), when swap1 is called just the copy of the values are passed not the actual address where x and y are residing. So, swap operation just takes place between the values which are local to swap1. Whereas in the case of swap2, the actual address is being passed. So any operations you perform on that address is reflected in main() also.

Output:

```<code>main: xaddr = 0x7ffda2efc05c yaddr = 0x7ffda2efc058
swap1 : xaddr = 0x7ffda2efc02c yaddr = 0x7ffda2efc028
swap1: 10 20
swap1: 20 10
main after swap1 : 10 20
swap2 : xaddr = 0x7ffda2efc05c yaddr = 0x7ffda2efc058
main after swap2: 20 10
</code>```

It is evident from the output that the address of x and y in the main are different from the swap1, and the swap operation indeed took place in swap1, but it is just local to swap1. Whereas in swap2, we are operating on the same address, which main treats as x and y, so operations are permanent.

Body:
It has to do with the concepts of pointers. Consider the program below (just added some informative code):

#include <stdio.h>

void swap1(int x, int y) {
    printf("swap1 : xaddr = %p yaddr = %p\n", &x, &y);

    printf("swap1: %d %d\n", x, y);

    int temp;
    temp = x;
    x = y;
    y = temp;

    printf("swap1: %d %d\n", x, y);
}

void swap2(int *p1, int *p2) {
    printf("swap2 : xaddr = %p yaddr = %p\n", p1, p2);

    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

int main()
{
    int x = 10, y = 20;

    printf("main: xaddr = %p yaddr = %p\n", &x, &y);

    swap1(x, y);

    printf("main after swap1 : %d %d\n", x, y);

    swap2(&x, &y);

    printf("main after swap2: %d %d\n", x, y);

    return 0;
}

The variables x and y in the main are residing in the local function stack of the main(), when swap1 is called just the copy of the values are passed not the actual address where x and y are residing. So, swap operation just takes place between the values which are local to swap1. Whereas in the case of swap2, the actual address is being passed. So any operations you perform on that address is reflected in main() also.

Output:

main: xaddr = 0x7ffda2efc05c yaddr = 0x7ffda2efc058
swap1 : xaddr = 0x7ffda2efc02c yaddr = 0x7ffda2efc028
swap1: 10 20
swap1: 20 10
main after swap1 : 10 20
swap2 : xaddr = 0x7ffda2efc05c yaddr = 0x7ffda2efc058
main after swap2: 20 10

It is evident from the output that the address of x and y in the main are different from the swap1, and the swap operation indeed took place in swap1, but it is just local to swap1. Whereas in swap2, we are operating on the same address, which main treats as x and y, so operations are permanent.


问:
Does C++0x support std::wstring conversion to/from UTF-8 byte sequence?
I saw that C++0x will add support for UTF-8, UTF-16 and UTF-32 literals. But what about conversions between the three representations ?

I plan to use std::wstring everywhere in my code. But I also need to manipulate UTF-8 encoded data when dealing with files and network. Will C++0x provide also support for these operations ?

答:
In C++0x, char16_t and char32_t will be used to store UTF-16 and UTF-32 and not wchar_t.

From the draft n2798:

22.2.1.4 Class template codecvt

2 The class codecvt is for use when converting from one codeset to another, such as from wide characters to multibyte characters or between wide character encodings such as Unicode and
  EUC.

3 The specializations required in Table 76 (22.1.1.1.1) convert the implementation-
  defined native character set. codecvt implements a degenerate
  conversion; it does not convert at all. The specialization codecvt<char16_t, char,
  mbstate_t> converts between the UTF-16 and UTF-8 encodings schemes, and the
  specialization codecvt <char32_t, char, mbstate_t> converts between the UTF-32 and
  UTF-8 encodings schemes. codecvt<wchar_t,char,mbstate_t> converts between the native
  character sets for narrow and wide characters. Specializations on mbstate_t perform
  conversion between encodings known to the library implementor.

Other encodings can be converted by specializing on a user-defined stateT type. The stateT object can contain any state that is useful to communicate to or from the specialized do_in or
  do_out members.

The thing about wchar_t is that it does not give you any guarantees about the encoding used. It is a type that can hold a multibyte character. Period. If you are going to write software now, you have to live with this compromise. C++0x compliant compilers are yet a far cry. You can always give the VC2010 CTP and g++ compilers a try for what it is worth. Moreover, wchar_t has different sizes on different platforms which is another thing to watch out for (2 bytes on VS/Windows, 4 bytes on GCC/Mac and so on). There is then options like -fshort-wchar for GCC to further complicate the issue.

The best solution therefore is to use an existing library. Chasing UNICODE bugs around isn't the best possible use of effort/time. I'd suggest you take a look at:

GNU libiconv

IBM's libicu

More on C++0x Unicode string literals here

OwnerDisplayName: chmike

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dirkgently

LastEditorDisplayName: dirkgently


问:
how to test MFMessageComposeViewController on iPhone simulator?
Is there anyway or I must get a iPhone?
Can I inherit form MFMessageComposeViewController to add some function in it?</p>

答: No, You can't inherit MFMessageComposeViewController, you could present the view controller modally using the presentModalViewController, More


问:
Installing TensorFlow with Pip Python on Windows
Last month they released tensor-flow comparability with windows. Looking at the docs I've installed python 3.6 and run

```<code>pip install tensorflow-gpu
</code>```

but it doesn't find it and therefore doesn't install it.

```<code>could not find a version that satisfies the requirements tensorflow-gpu(from versions)
</code>```

Am I missing something basic? How can I fix or circumvent this?

Body:
Last month they released tensor-flow comparability with windows. Looking at the docs I've installed python 3.6 and run

pip install tensorflow-gpu

but it doesn't find it and therefore doesn't install it.

could not find a version that satisfies the requirements tensorflow-gpu(from versions)

Am I missing something basic? How can I fix or circumvent this?

Body:
pip3 install tensorflow==tensorflow_version

Available tensorflow versions: (0.12.1, 1.0.0, 1.0.1, 1.1.0rc0, 1.1.0rc1, 1.1.0rc2, 1.1.0, 1.2.0rc0, 1.2.0rc1, 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.4.1, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0, 1.7.1, 1.8.0rc0, 1.8.0rc1, 1.8.0, 1.9.0rc0, 1.9.0rc1, 1.9.0rc2, 1.9.0, 1.10.0rc0, 1.10.0rc1, 1.10.0, 1.10.1, 1.11.0rc0, 1.11.0rc1, 1.11.0rc2, 1.11.0, 1.12.0rc0, 1.12.0rc1, 1.12.0rc2, 1.12.0, 1.12.2, 1.12.3, 1.13.0rc0, 1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 2.0.0a0, 2.0.0b0, 2.0.0b1)