问:
Script to downsize SYSTEM_TIME column from DATETIME2(7) to DATETIME2(3)
For all temporal tables within a database, I seek a script which generates T-SQL to downsize their SYSTEM_TIME columns from DATETIME2(7) to DATETIME2(3).

My rationale: I want to be able to update such tables from within an MS Access database when the tables are linked via an ODBC connection. Access doesn't support DATETIME2(7) for updates when linked via the ODBC driver (The field is too large). Conversely, the SQL Server Native Client driver works (supposedly, I haven't tried it); but it doesn't support Active Directory - Integrated connections. Moreover my application doesn't require the extra precision for these fields.

The generated code will be something like the following. Just curious if someone might have such a script?

```<code>CREATE TABLE [dbo].[Tasks] (
    [Id]           INT                                                IDENTITY (1, 1) NOT NULL,
    [Task]         NVARCHAR(50)                                       NOT NULL,
    [ValidFrom]    DATETIME2(7) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
    [ValidTo]      DATETIME2 (7) GENERATED ALWAYS AS ROW END HIDDEN   NOT NULL,
    [Who]          NVARCHAR (128)                                     CONSTRAINT [DF_dbo_Tasks_Who] DEFAULT (SUSER_SNAME()) NOT NULL,
    CONSTRAINT [PK_dbo_Tasks] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_Tasks_Task] UNIQUE NONCLUSTERED ([Task] ASC),
    PERIOD FOR SYSTEM_TIME ([ValidFrom], [ValidTo])
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[History_Tasks], DATA_CONSISTENCY_CHECK=ON));
GO

INSERT INTO dbo.Tasks (Task)
VALUES (N'Task 1'), (N'Task 2'), (N'Task 3'), (N'Task 4'), (N'Task 5');
GO

UPDATE dbo.Tasks SET Task = N'Task 1.1' WHERE Id = 1;
DELETE FROM dbo.Tasks WHERE Id = 3;
INSERT INTO dbo.Tasks (Task) VALUES (N'Task 6');
GO

SELECT * FROM dbo.Tasks
SELECT * FROM dbo.History_Tasks
GO
---------------------------------------------------------------------------------------------------
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = OFF);
ALTER TABLE dbo.Tasks DROP PERIOD FOR SYSTEM_TIME;
GO
ALTER TABLE dbo.Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ALTER COLUMN ValidTo   DATETIME2(3) NOT NULL;
DROP INDEX ix_History_Tasks ON dbo.History_Tasks;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidTo DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ADD PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=dbo.History_Tasks));
CREATE CLUSTERED INDEX ix_History_Tasks ON dbo.History_Tasks(ValidTo ASC, ValidFrom ASC);
GO
---------------------------------------------------------------------------------------------------
-- ... Next table ...
</code>```

答:
The following code does the trick:</p>

```<code>WITH a AS (
    SELECT
          SCHEMA_NAME(t.schema_id) AS PrimarySchema
        , t.name AS PrimaryTable
        , OBJECT_SCHEMA_NAME(t.history_table_id) AS HistorySchema
        , OBJECT_NAME(t.history_table_id) AS HistoryTable
        , i.name AS HistoryIndexName
    FROM sys.tables AS t
    JOIN sys.indexes AS i ON t.history_table_id = i.object_id -- There should only be one index on each history table
    WHERE t.temporal_type = 2 -- SYSTEM_VERSIONED_TEMPORAL_TABLE
), b AS (
    SELECT a.PrimarySchema
         , a.PrimaryTable
         , CONCAT(a.PrimarySchema, N'.', a.PrimaryTable) AS PrimarySchemaTable
         , a.HistorySchema
         , a.HistoryTable
         , CONCAT(a.HistorySchema, N'.', a.HistoryTable) AS HistorySchemaTable
         , a.HistoryIndexName
    FROM a
), c AS (
    SELECT b.PrimarySchema, b.PrimaryTable
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' SET (SYSTEM_VERSIONING = OFF);')                                             AS L1
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' DROP PERIOD FOR SYSTEM_TIME;')                                               AS L2
         , N'GO'                                                                                AS L3
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;')                              AS L4
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' ALTER COLUMN ValidTo   DATETIME2(3) NOT NULL;')                              AS L5
         , CONCAT(N'DROP INDEX ', b.HistoryIndexName, N' ON ', b.HistorySchemaTable , N';')                                               AS L6
         , CONCAT(N'ALTER TABLE ', b.HistorySchemaTable, N' ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;')                               AS L7
         , CONCAT(N'ALTER TABLE ', b.HistorySchemaTable, N' ALTER COLUMN ValidTo DATETIME2(3) NOT NULL;')                                 AS L8
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' ADD PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);')                           AS L9
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=', b.HistorySchemaTable, N'));')  AS L10
         , CONCAT(N'CREATE CLUSTERED INDEX ', b.HistoryIndexName, N' ON ', b.HistorySchemaTable, N'(ValidTo ASC, ValidFrom ASC);')        AS L11
         , N'GO'                                                                                AS L12
         , N'-------------------------------------------------------------------------------------------------------------------------'   AS L13
    FROM b
)
SELECT CONCAT(c.L1, CHAR(10), c.L2, CHAR(10), c.L3, CHAR(10), c.L4, CHAR(10), c.L5, CHAR(10), c.L6, CHAR(10), c.L7, CHAR(10), c.L8, CHAR(10), c.L9, CHAR(10), c.L10, CHAR(10), c.L11, CHAR(10), c.L12, CHAR(10), c.L13, CHAR(10)) AS Statements
FROM c
ORDER BY c.PrimarySchema, c.PrimaryTable
</code>```

Body:
For all temporal tables within a database, I seek a script which generates T-SQL to downsize their SYSTEM_TIME columns from DATETIME2(7) to DATETIME2(3).

My rationale: I want to be able to update such tables from within an MS Access database when the tables are linked via an ODBC connection. Access doesn't support DATETIME2(7) for updates when linked via the ODBC driver (The field is too large). Conversely, the SQL Server Native Client driver works (supposedly, I haven't tried it); but it doesn't support Active Directory - Integrated connections. Moreover my application doesn't require the extra precision for these fields.

The generated code will be something like the following. Just curious if someone might have such a script?

CREATE TABLE [dbo].[Tasks] (
    [Id]           INT                                                IDENTITY (1, 1) NOT NULL,
    [Task]         NVARCHAR(50)                                       NOT NULL,
    [ValidFrom]    DATETIME2(7) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
    [ValidTo]      DATETIME2 (7) GENERATED ALWAYS AS ROW END HIDDEN   NOT NULL,
    [Who]          NVARCHAR (128)                                     CONSTRAINT [DF_dbo_Tasks_Who] DEFAULT (SUSER_SNAME()) NOT NULL,
    CONSTRAINT [PK_dbo_Tasks] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_Tasks_Task] UNIQUE NONCLUSTERED ([Task] ASC),
    PERIOD FOR SYSTEM_TIME ([ValidFrom], [ValidTo])
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[History_Tasks], DATA_CONSISTENCY_CHECK=ON));
GO

INSERT INTO dbo.Tasks (Task)
VALUES (N'Task 1'), (N'Task 2'), (N'Task 3'), (N'Task 4'), (N'Task 5');
GO

UPDATE dbo.Tasks SET Task = N'Task 1.1' WHERE Id = 1;
DELETE FROM dbo.Tasks WHERE Id = 3;
INSERT INTO dbo.Tasks (Task) VALUES (N'Task 6');
GO

SELECT * FROM dbo.Tasks
SELECT * FROM dbo.History_Tasks
GO
---------------------------------------------------------------------------------------------------
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = OFF);
ALTER TABLE dbo.Tasks DROP PERIOD FOR SYSTEM_TIME;
GO
ALTER TABLE dbo.Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ALTER COLUMN ValidTo   DATETIME2(3) NOT NULL;
DROP INDEX ix_History_Tasks ON dbo.History_Tasks;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidTo DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ADD PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=dbo.History_Tasks));
CREATE CLUSTERED INDEX ix_History_Tasks ON dbo.History_Tasks(ValidTo ASC, ValidFrom ASC);
GO
---------------------------------------------------------------------------------------------------
-- ... Next table ...

Body:
The following code does the trick:

WITH a AS (
    SELECT
          SCHEMA_NAME(t.schema_id) AS PrimarySchema
        , t.name AS PrimaryTable
        , OBJECT_SCHEMA_NAME(t.history_table_id) AS HistorySchema
        , OBJECT_NAME(t.history_table_id) AS HistoryTable
        , i.name AS HistoryIndexName
    FROM sys.tables AS t
    JOIN sys.indexes AS i ON t.history_table_id = i.object_id -- There should only be one index on each history table
    WHERE t.temporal_type = 2 -- SYSTEM_VERSIONED_TEMPORAL_TABLE
), b AS (
    SELECT a.PrimarySchema
         , a.PrimaryTable
         , CONCAT(a.PrimarySchema, N'.', a.PrimaryTable) AS PrimarySchemaTable
         , a.HistorySchema
         , a.HistoryTable
         , CONCAT(a.HistorySchema, N'.', a.HistoryTable) AS HistorySchemaTable
         , a.HistoryIndexName
    FROM a
), c AS (
    SELECT b.PrimarySchema, b.PrimaryTable
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' SET (SYSTEM_VERSIONING = OFF);')                                             AS L1
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' DROP PERIOD FOR SYSTEM_TIME;')                                               AS L2
         , N'GO'                                                                                AS L3
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;')                              AS L4
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' ALTER COLUMN ValidTo   DATETIME2(3) NOT NULL;')                              AS L5
         , CONCAT(N'DROP INDEX ', b.HistoryIndexName, N' ON ', b.HistorySchemaTable , N';')                                               AS L6
         , CONCAT(N'ALTER TABLE ', b.HistorySchemaTable, N' ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;')                               AS L7
         , CONCAT(N'ALTER TABLE ', b.HistorySchemaTable, N' ALTER COLUMN ValidTo DATETIME2(3) NOT NULL;')                                 AS L8
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' ADD PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);')                           AS L9
         , CONCAT(N'ALTER TABLE ', b.PrimarySchemaTable , N' SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=', b.HistorySchemaTable, N'));')  AS L10
         , CONCAT(N'CREATE CLUSTERED INDEX ', b.HistoryIndexName, N' ON ', b.HistorySchemaTable, N'(ValidTo ASC, ValidFrom ASC);')        AS L11
         , N'GO'                                                                                AS L12
         , N'-------------------------------------------------------------------------------------------------------------------------'   AS L13
    FROM b
)
SELECT CONCAT(c.L1, CHAR(10), c.L2, CHAR(10), c.L3, CHAR(10), c.L4, CHAR(10), c.L5, CHAR(10), c.L6, CHAR(10), c.L7, CHAR(10), c.L8, CHAR(10), c.L9, CHAR(10), c.L10, CHAR(10), c.L11, CHAR(10), c.L12, CHAR(10), c.L13, CHAR(10)) AS Statements
FROM c
ORDER BY c.PrimarySchema, c.PrimaryTable


来源: stackexchange

问:
Need a macro that searches for values, and if true it selects the row with the value and the row above
I hope I don't confuse you but here's what I'm trying to do.

Here's an example of what some of the data in the sheet looks like:

Excel Screenshot

Basically I have a criteria of 6 four-digit numbers e.g. (3413, 3414, 3417 etc.) and I need the macro to search for any rows that have a number that begins with any of these numbers, and copy both the row the value is in and the row above to a new sheet. I need the row above because it has the customer's name in it.

In this case the macro would find the value in row 2 and copy both row 2 and row 1.

I can't seem to find anyone that has the same issue as me, can anyone help? Thanks!

Edit - this would likely be my starting code:

```<code>Sub Test()
For Each Cell In Sheets(1).Range("J:J")
    If Cell.Value = "131125" Then
        matchRow = Cell.Row
        Rows(matchRow & ":" & matchRow).Select
        Selection.Copy

        Sheets("Sheet2").Select
        ActiveSheet.Rows(matchRow).Select
        ActiveSheet.Paste
        Sheets("Sheet1").Select
    End If
Next
End Sub
</code>```

答:
Something like this:</p>

```<code>Sub Test()
    Dim c As Range, shtSrc As Worksheet, shtDest As Worksheet
    Dim arr, v, txt, destRow As Long

    arr = Array(3413, 3414, 3417) '<< array of values to look for

    Set shtSrc = Sheets("Sheet1")
    Set shtDest = Sheets("Sheet2")
    destRow = 2 'start copying to here

    'ignore empty ranges
    For Each c In Application.Intersect(shtSrc.Range("J:J"), _
                                        shtSrc.UsedRange).Cells
        txt = c.Value
        For Each v In arr
            'does the cell contain the search number ?
            If txt Like "*" & v & "*" Then
                'copy to same row on sheet2
                c.EntireRow.Resize(2).Copy shtDest.Cells(c.Row, 1)

                '...or copy below previous hit
                'c.EntireRow.Resize(2).Copy shtDest.Cells(destRow, 1)
                'destRow = destRow + 2

                Exit For '<< stop checking this row
            End If
        Next v
    Next

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I hope I don't confuse you but here's what I'm trying to do.

Here's an example of what some of the data in the sheet looks like:

Excel Screenshot

Basically I have a criteria of 6 four-digit numbers e.g. (3413, 3414, 3417 etc.) and I need the macro to search for any rows that have a number that begins with any of these numbers, and copy both the row the value is in and the row above to a new sheet. I need the row above because it has the customer's name in it.

In this case the macro would find the value in row 2 and copy both row 2 and row 1.

I can't seem to find anyone that has the same issue as me, can anyone help? Thanks!

Edit - this would likely be my starting code:

Sub Test()
For Each Cell In Sheets(1).Range("J:J")
    If Cell.Value = "131125" Then
        matchRow = Cell.Row
        Rows(matchRow & ":" & matchRow).Select
        Selection.Copy

        Sheets("Sheet2").Select
        ActiveSheet.Rows(matchRow).Select
        ActiveSheet.Paste
        Sheets("Sheet1").Select
    End If
Next
End Sub

Body:
Something like this:

Sub Test()
    Dim c As Range, shtSrc As Worksheet, shtDest As Worksheet
    Dim arr, v, txt, destRow As Long

    arr = Array(3413, 3414, 3417) '<< array of values to look for

    Set shtSrc = Sheets("Sheet1")
    Set shtDest = Sheets("Sheet2")
    destRow = 2 'start copying to here

    'ignore empty ranges
    For Each c In Application.Intersect(shtSrc.Range("J:J"), _
                                        shtSrc.UsedRange).Cells
        txt = c.Value
        For Each v In arr
            'does the cell contain the search number ?
            If txt Like "*" & v & "*" Then
                'copy to same row on sheet2
                c.EntireRow.Resize(2).Copy shtDest.Cells(c.Row, 1)

                '...or copy below previous hit
                'c.EntireRow.Resize(2).Copy shtDest.Cells(destRow, 1)
                'destRow = destRow + 2

                Exit For '<< stop checking this row
            End If
        Next v
    Next

End Sub

ContentLicense: CC BY-SA 3.0


问:
How to auto create database on first run?
My application being ported to .NET Core will use EF Core with SQLite. I want to automatically create the database and tables when the app is first run. According to documentation this is done using manual commands :

```<code>dotnet ef migrations add MyFirstMigration

dotnet ef database update
</code>```

I don't want end user to enter these but prefer the app to create and setup the database on first use. For EF 6 there is :

```<code>Database.SetInitializer(new CreateDatabaseIfNotExists<MyContext>());
</code>```

But I can't find any equivalent for EF Core. I have the model classes already so I could write code to initialize the database based on the models but it would be easier if the framework did this automatically. I don't want to auto build the model or migrate, just create the tables in a new database.

Is an auto create table function missing from EF Core?

答:
If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:</p>

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env,  LoggerFactory loggerFactory,
    ApplicationDbContext context)
 {
      context.Database.Migrate();
      ...
</code>```

Body:
My application being ported to .NET Core will use EF Core with SQLite. I want to automatically create the database and tables when the app is first run. According to documentation this is done using manual commands :

dotnet ef migrations add MyFirstMigration

dotnet ef database update

I don't want end user to enter these but prefer the app to create and setup the database on first use. For EF 6 there is :

Database.SetInitializer(new CreateDatabaseIfNotExists<MyContext>());

But I can't find any equivalent for EF Core. I have the model classes already so I could write code to initialize the database based on the models but it would be easier if the framework did this automatically. I don't want to auto build the model or migrate, just create the tables in a new database.

Is an auto create table function missing from EF Core?

Body:
If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  LoggerFactory loggerFactory,
    ApplicationDbContext context)
 {
      context.Database.Migrate();
      ...


问:
Trigger an API automatically based on user specified time using nodejs
I am working on an application which will trigger a http api based on user specified time. Basically it is a message scheduling app on Nodejs that will call different web-services to communicate and post data on user specified time. I am using AWS dynamo db to store user messages and date & time when they want to publish.
What will be the best solution to achieve this?

Thanks in advance.

答:
While there are tons of ways to solve this problem, I think the cleaner solution would be with

Dynamodb (Table with TTL field) --> DynamoDBStreams (Old Image) -->  (Check for Remove Record) Lambda (do whatever you want with the event here)

Create a record in DynamoDB with a TTL field that you want to trigger your record. Stream will deliver a record removed stream message which can be received by the lambda and you can take any action from there.

Hope it helps.


问:
Make OCaml function polymorphic for int lists and float lists
Is there a way to create a polymorphic add function in OCaml that works equally well for ints and floats?  So for example if I have a function like:

partialsums [1; 2; 3; 4; 5] I should get [1; 3; 6; 10; 15] but this function won't work on [1.; 2.; 3.; 4.; 5.] because in OCaml ints and floats absolutely cannot be mixed.  But what if I want my function to work equally well for int lists and float lists?  Is there a general type of which int and float are sub-types?  If so, what is it?  I'm a little lost on this one.  Thanks for the help?

答:
You can also try first-class modules as Base does (https://github.com/janestreet/base/blob/57240d0d8403031f37e105351d7d928a6aea1524/src/container.ml#L17), e.g.:

```<code>let sum (type a) ~fold (module M : Commutative_group.S with type t = a) t ~f =
  fold t ~init:M.zero ~f:(fun n a -> M.(+) n (f a))
;;
</code>```

That gives you a pretty light-weight syntax:

```<code>List.sum (module Int) [1; 2; 3; 4; 5] ~f:Fn.id
</code>```

Body:
You can also try first-class modules as Base does (https://github.com/janestreet/base/blob/57240d0d8403031f37e105351d7d928a6aea1524/src/container.ml#L17), e.g.:

let sum (type a) ~fold (module M : Commutative_group.S with type t = a) t ~f =
  fold t ~init:M.zero ~f:(fun n a -> M.(+) n (f a))
;;

That gives you a pretty light-weight syntax:

List.sum (module Int) [1; 2; 3; 4; 5] ~f:Fn.id


问:
css is hover not working on class
I'm trying to get a bar to transition in when the li is hovered over however the hover seems to be ignored and nothing happens. If I instead put 'nav ul:hover', it works but the bar pops in under all the li's.

```<code><nav>
  <ul>
    <li class="nav-li">All Departments</li>
    <li class="nav-li">Shop by Room</li>
    <li class="nav-li">DIY Projects & Ideas</li>
    <li class="nav-li">Home Services</li>
    <li class="nav-li">Speacials & Offers</li>
    <li class="nav-li">Local Ad</li>
  </ul>
</nav>
</code>```

CSS

```<code>.nav-li {
margin-right: 40px;
display: inline-block;
padding-bottom: 2em;
transition: all .5s ease;
cursor: pointer;
position: relative;
}

.nav-li::after {
content: "";
display: block;
position: absolute;
left: 0;
bottom: 0;
height: 3px;
width: 0;
transition: width .5s ease;
}

.nav-li:hover .nav-li::after {
background-color: #f96302;
width: 100%;
}
</code>```

答:
Try combining the two.

```<code>.nav-li:hover::after
</code>```

Example: https://jsfiddle.net/pc26LnLz/1/

Title: css is hover not working on class

Body:
I'm trying to get a bar to transition in when the li is hovered over however the hover seems to be ignored and nothing happens. If I instead put 'nav ul:hover', it works but the bar pops in under all the li's.

All Departments

Shop by Room

DIY Projects & Ideas

Home Services

Speacials & Offers

Local Ad

CSS

.nav-li {
margin-right: 40px;
display: inline-block;
padding-bottom: 2em;
transition: all .5s ease;
cursor: pointer;
position: relative;
}

.nav-li::after {
content: "";
display: block;
position: absolute;
left: 0;
bottom: 0;
height: 3px;
width: 0;
transition: width .5s ease;
}

.nav-li:hover .nav-li::after {
background-color: #f96302;
width: 100%;
}

Body:
Try combining the two.

.nav-li:hover::after

Example: https://jsfiddle.net/pc26LnLz/1/


问:
Getting the last revision number in SVN?
Using PHP, Perl, or Python (preferably PHP), I need a way to query an SVN database and find out the last revision number sent to SVN. I don't need anything other than that. It needs to be non-intensive (so I do it every 5 minutes as a cron job; SVN's performance should not be affected).

SVN is located on my Intranet, but not my specific computer.

I have SVN installed, but no bindings installed for PHP/Perl/Python. I'm running Windows XP, but I would prefer a platform-independent solution that can also work in Linux. If you have a Linux-only (or XP-only) solution, that would also be helpful.

答:
You can use the XML out format, for example:

```<code>  svn info --xml | grep 'revision' | head -1 | grep -Eo "[0-9]+" | xargs expr -1 +
</code>```

Example: using the revision number

```<code>working=`svn info --xml | grep 'revision' | head -1 | grep -Eo "[0-9]+" | xargs expr -1 +`
svn diff -r $working:HEAD --summarize --xml
</code>```

OwnerDisplayName: Coltin

LastEditorDisplayName: brian d foy

Body:
You can use the XML out format, for example:

  svn info --xml | grep 'revision' | head -1 | grep -Eo "[0-9]+" | xargs expr -1 +

Example: using the revision number

working=`svn info --xml | grep 'revision' | head -1 | grep -Eo "[0-9]+" | xargs expr -1 +`
svn diff -r $working:HEAD --summarize --xml


问:
Is this React app far too simple to use Redux?
While using ReactJS, I have a parent component, which contains two children components:

```<code>- Main
    - NewReminder
    - ExistingReminders
</code>```

Main passes information to NewReminder as well as ExistingReminders through props. When a NewReminder is created, it must update the list that the user sees of ExistingReminders. This seems like a great use of redux, where the state can be updated from NewReminder, and will update this list, but I don't know if there are alternatives as this might be far too simple to set up an entire redux environment?

Should I go ahead and begin implementing Redux, or do you have any suggestions for alternatives?

答:
It's really quite a broad question, but I'll give it a crack: you should consider taking the advice of the author:

Seriously, it bears repeating.

Local state is fine.

The tradeoff that Redux offers is to add indirection to decouple “what happened” from “how things change”.

Is it always a good thing to do? No. It’s a tradeoff.

Redux doesn't have to be complicated (in fact, you could argue it goes out of its way to stay fairly light and simple). Once you've set up the basics a few times it's not intimidating. However, if you can write a simple application without Redux in a way that's clear and maintainable, sounds like a win to me!

Body:
While using ReactJS, I have a parent component, which contains two children components:

- Main
    - NewReminder
    - ExistingReminders

Main passes information to NewReminder as well as ExistingReminders through props. When a NewReminder is created, it must update the list that the user sees of ExistingReminders. This seems like a great use of redux, where the state can be updated from NewReminder, and will update this list, but I don't know if there are alternatives as this might be far too simple to set up an entire redux environment?

Should I go ahead and begin implementing Redux, or do you have any suggestions for alternatives?


问:
Any idea where the additional printed None is coming from?
Hello am trying between local vs global variables and got the below code. When I run this code the following outputs are given. I thought the below code only asks for 2 outputs from the various print statements but am getting a "None" as well. Please can you let me know where this "None" is coming from? Thanks!

CODE:

```<code>x = 'global X'

def test():
    global x
    x = 'local x'
    print (x)

print (test())
print (x)
</code>```

Output:

```<code>local x
None
local x
</code>```

答:
In your test() function, you have a print.

The 1st local x of you output is the one in the test function,
then it tries to print the return of the test function, which is nothing, so it prints none. You could simply return x instead of printing it, like this:

```<code>def test():
    global x
    x = 'local x'
    return x
</code>```

This way it won't print none.

Body:
Hello am trying between local vs global variables and got the below code. When I run this code the following outputs are given. I thought the below code only asks for 2 outputs from the various print statements but am getting a "None" as well. Please can you let me know where this "None" is coming from? Thanks!

CODE:

x = 'global X'

def test():
    global x
    x = 'local x'
    print (x)

print (test())
print (x)

Output:

local x
None
local x

Body:
In your test() function, you have a print.

The 1st local x of you output is the one in the test function,
then it tries to print the return of the test function, which is nothing, so it prints none. You could simply return x instead of printing it, like this:

def test():
    global x
    x = 'local x'
    return x

This way it won't print none.


问:
Checking a private value in another class [C#]
I'm making a simple dart game in the console for an assignment where I am to practice using private lists and variables everywhere. The basic flow of the program for some context is as follows:

User lands in a menu

User chooses from 1-4. (1 = Add player, 2 = Add CPU, 3 = Start game, 4 = Quit)

Game starts. Players manually add their 3 throws per turn, and CPU gets theirs randomly.

When a player or CPU reaches 301 score, the loop ends and you now see every throw made by the winner.

UML diagram for class structure context: https://i.imgur.com/bL5pZV5.png

Everything is pretty much complete. I've made the program to such an extent that both players and CPUs are getting random values (are treated as CPU players), it prints out everything correctly and follows the flow to the end.

My issue now is that I want to be able to reach the is_CPU variable which is private in the Player class from the Game class and use it in an IF check, directing whether or not the values are manually added or randomly generated.

Pseudo-code:

```<code>FOREACH (var player in player_list)
  IF (is_CPU == TRUE)
    THEN Assign random values
  ELSE
    THEN Manually enter values
</code>```

I tried messing around with the get-set stuff, but I don't fully understand how to use them and how they work. I have looked around on here and still don't see how I should be using them in this case, if at all.

I can think of one way to work around this and that is by making a method just for this where it checks that value and returns true/false, but that seems like a 'lazy' or improper way to do this, and comes with several downsides. I feel like there should be a better way to do this, one that won't come back to bite me in the ass later. Hopefully there is, and I can learn it by asking here.

EDIT: The variables and lists HAVE to be private. It is part of the exercise where we learn how to handle these.

答:
In order to access private members of a class instance, you either have to define properties on that class with a public getter, as follows:

```<code>public class Player
{
    private Boolean m_IsCPU;

    public Boolean IsCPU
    {
        get { return m_IsCPU; }
    }

    // ...
}
</code>```

or to change these members in order to make them public, as follows:

```<code>public class Player
{
    public Boolean IsCPU;

    // ...
}
</code>```

Whatever you choose (I suggest you to go for the first approach), in any part of your code in which you have to check the IsCPU property/member for each instance of the Player class, you can just do as follows:

```<code>foreach (Player player in players)
{
    if (player.IsCPU)
        // Do Something...
    else
        // Do Something Else...
}
</code>```

Some interesting links:

Access Modifiers

C# Properties

Why prefer Properties to public variables?

Body:
I'm making a simple dart game in the console for an assignment where I am to practice using private lists and variables everywhere. The basic flow of the program for some context is as follows:

User lands in a menu

User chooses from 1-4. (1 = Add player, 2 = Add CPU, 3 = Start game, 4 = Quit)

Game starts. Players manually add their 3 throws per turn, and CPU gets theirs randomly.

When a player or CPU reaches 301 score, the loop ends and you now see every throw made by the winner.

UML diagram for class structure context: https://i.imgur.com/bL5pZV5.png

Everything is pretty much complete. I've made the program to such an extent that both players and CPUs are getting random values (are treated as CPU players), it prints out everything correctly and follows the flow to the end.

My issue now is that I want to be able to reach the is_CPU variable which is private in the Player class from the Game class and use it in an IF check, directing whether or not the values are manually added or randomly generated.

Pseudo-code:

FOREACH (var player in player_list)
  IF (is_CPU == TRUE)
    THEN Assign random values
  ELSE
    THEN Manually enter values

I tried messing around with the get-set stuff, but I don't fully understand how to use them and how they work. I have looked around on here and still don't see how I should be using them in this case, if at all.

I can think of one way to work around this and that is by making a method just for this where it checks that value and returns true/false, but that seems like a 'lazy' or improper way to do this, and comes with several downsides. I feel like there should be a better way to do this, one that won't come back to bite me in the ass later. Hopefully there is, and I can learn it by asking here.

EDIT: The variables and lists HAVE to be private. It is part of the exercise where we learn how to handle these.

Body:
In order to access private members of a class instance, you either have to define properties on that class with a public getter, as follows:

public class Player
{
    private Boolean m_IsCPU;

    public Boolean IsCPU
    {
        get { return m_IsCPU; }
    }

    // ...
}

or to change these members in order to make them public, as follows:

public class Player
{
    public Boolean IsCPU;

    // ...
}

Whatever you choose (I suggest you to go for the first approach), in any part of your code in which you have to check the IsCPU property/member for each instance of the Player class, you can just do as follows:

foreach (Player player in players)
{
    if (player.IsCPU)
        // Do Something...
    else
        // Do Something Else...
}

Some interesting links:

Access Modifiers

C# Properties

Why prefer Properties to public variables?


问:
Dynamically assign button callback - Python
So I recently started on Python, I love it. I wanted to create a calculator os my first project, I decided to add the buttons with a loop. But the callback of the button is always the last state of the variable that I would like to pass as the argument for the callback function. Here's my code.

```<code>def addButtons():
buttons = []

label = ""
num = 0

posX = 4
posY = 1

for i in range(12):

    if (i % 4 < 3):
        num += 1
        label = str(num)
    else:
        label = "Blank"

    if (i % 4 == 0):
        posY += 1

    if (posX < 3):
        posX += 1
    else:
        posX = 0

    buttons.append(
        Button(buttonPanel, text=label, command=lambda: function(i), relief="flat", borderwidth=0, sticky=w, background="#fff", activebackground="#eee"))
    buttons[i].grid(column=posX, row=posY, sticky=N + S + E + W)

    buttonPanel.grid_columnconfigure(posX, weight=1)
    buttonPanel.grid_rowconfigure(posY, weight=1)

    functions.append(label)

def function(obj):  # the button's functions are identified by this function and executed respectively
    print obj
</code>```

So, When I click a button I always get 11 from the console, no matter what button. Is there a way that I can dynamically set the callback parameter?

Thanks for any help
 - Jacob

答:
The problem you have is that when you write lambda: function(i), the lambda function doesn't save the current value of i. Rather, it only looks it up in the outer namespace when it gets called. That's why you see the last value of i in all of your callbacks, since that's the value it had when it was last modified.

You can avoid this problem by binding the name i to a specific value in the lambda:

```<code>lambda i=i: function(i)
</code>```

This is sort of an abuse of default arguments, but it does exactly what you want. The current value of i in the outer namespace gets bound as the default value for a different i variable in the lambda function's namespace. This happens when the lambda is defined, so it doesn't matter that the outer namespace's i changes values later on.

Another way of doing essentially the same thing is to use the partial type defined in the functools module of the standard library.  It lets you bind some arguments to a function that can be called later. This is most useful when you expect some additional arguments later, but it can be helpful in this situation too. Instead of the lambda, you'd pass partial(function, i) as the callback.

Body:
So I recently started on Python, I love it. I wanted to create a calculator os my first project, I decided to add the buttons with a loop. But the callback of the button is always the last state of the variable that I would like to pass as the argument for the callback function. Here's my code.

def addButtons():
buttons = []

label = ""
num = 0

posX = 4
posY = 1

for i in range(12):

    if (i % 4 < 3):
        num += 1
        label = str(num)
    else:
        label = "Blank"

    if (i % 4 == 0):
        posY += 1

    if (posX < 3):
        posX += 1
    else:
        posX = 0

    buttons.append(
        Button(buttonPanel, text=label, command=lambda: function(i), relief="flat", borderwidth=0, sticky=w, background="#fff", activebackground="#eee"))
    buttons[i].grid(column=posX, row=posY, sticky=N + S + E + W)

    buttonPanel.grid_columnconfigure(posX, weight=1)
    buttonPanel.grid_rowconfigure(posY, weight=1)

    functions.append(label)

def function(obj):  # the button's functions are identified by this function and executed respectively
    print obj

So, When I click a button I always get 11 from the console, no matter what button. Is there a way that I can dynamically set the callback parameter?

Thanks for any help
 - Jacob

Body:
The problem you have is that when you write lambda: function(i), the lambda function doesn't save the current value of i. Rather, it only looks it up in the outer namespace when it gets called. That's why you see the last value of i in all of your callbacks, since that's the value it had when it was last modified.

You can avoid this problem by binding the name i to a specific value in the lambda:

lambda i=i: function(i)

This is sort of an abuse of default arguments, but it does exactly what you want. The current value of i in the outer namespace gets bound as the default value for a different i variable in the lambda function's namespace. This happens when the lambda is defined, so it doesn't matter that the outer namespace's i changes values later on.

Another way of doing essentially the same thing is to use the partial type defined in the functools module of the standard library.  It lets you bind some arguments to a function that can be called later. This is most useful when you expect some additional arguments later, but it can be helpful in this situation too. Instead of the lambda, you'd pass partial(function, i) as the callback.


问:
map to a custom route triggers also loading of static files through that route
I want that my index.cshtml is only returned when the following route is active:

http://www.example.com/2/345044

The below code works, but when the code for returning the razor file via:

return View(Index); then the Index action is hit again multiple times

with values from the script/image/stylesheet tags like:

tag has value 'css' and metaversion has value 'site.css'

thats the url in the Layout.cshtml:

```<code><link rel="stylesheet" href="~/css/site.css" />
</code>```

How can I prevent that the Index action is triggered  with those file requests?

Startup.cs

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc(routes =>
    {
        routes.MapRoute("history", "{tag}/{metaversion}", new { controller = "Home", action = "Index" });
     });
}
</code>```

答:
Static files are not enabled by default.  You must turn on the features you wish to use:</p>

```<code>app.UseStaticFiles();
</code>```

Body:
I want that my index.cshtml is only returned when the following route is active:

http://www.example.com/2/345044

The below code works, but when the code for returning the razor file via:

return View(Index); then the Index action is hit again multiple times

with values from the script/image/stylesheet tags like:

tag has value 'css' and metaversion has value 'site.css'

thats the url in the Layout.cshtml:

<link rel="stylesheet" href="~/css/site.css" />

How can I prevent that the Index action is triggered  with those file requests?

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc(routes =>
    {
        routes.MapRoute("history", "{tag}/{metaversion}", new { controller = "Home", action = "Index" });
     });
}

Body:
Static files are not enabled by default.  You must turn on the features you wish to use:

app.UseStaticFiles();


问:
Restoring auto-renewable subscriptions after
We are using auto-renewable subscriptions, and it works ok except for the one edge case.

If user reset their iPhone to the factory settings, it's not possible for them to restore auto-renewable subscription in our app (or so it seems, we have just two such cases now).

We are using SwiftyStoreKit, but I believe that there is a logic error on our side.

Right now we are restoring purchases this way:

```<code>func checkOldSubscriptions()->Bool {

     //validator
     let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: ss)

      for i in 0..<products.count {

           //checking every available product in receipt
           SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: { (result) in
               switch result {
                   case .success(let receipt):

                let purchaseResult = SwiftyStoreKit.verifySubscription(
                    type: .autoRenewable,
                    productId: products[i].name,
                    inReceipt: receipt)

                    switch purchaseResult {
                        case .purchased(let expiresDate):
                        print("Product is valid until \(expiresDate)")

       ...
       }
       }
</code>```

My hypothesis is that after the reset we just don't have any receipt to verify, and I have to retrieve it directly. It's kind of hard to check on device because, honestly, I don't have a real test device that would be easy to kill for me.

So I want to add something like that (manually refreshing the receipt before trying to verifying it):

```<code>SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: true) { result in
    switch result {
    case .success(let receipt):
</code>```

Does it make any sense? Will it help?

答:
You are correct. A receipt is not likely to be available after a reset.
You need to call restoreCompletedTransactions() on SKPaymentQueue to retrieve any transactions that were previously marked completed.

Since you are using SwiftyStoreKit you can use SwiftyStoreKit.restorePurchases. Check the documentation for details.

Body:
We are using auto-renewable subscriptions, and it works ok except for the one edge case.

If user reset their iPhone to the factory settings, it's not possible for them to restore auto-renewable subscription in our app (or so it seems, we have just two such cases now).

We are using SwiftyStoreKit, but I believe that there is a logic error on our side.

Right now we are restoring purchases this way:

func checkOldSubscriptions()->Bool {

     //validator
     let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: ss)

      for i in 0..<products.count {

           //checking every available product in receipt
           SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: { (result) in
               switch result {
                   case .success(let receipt):

                let purchaseResult = SwiftyStoreKit.verifySubscription(
                    type: .autoRenewable,
                    productId: products[i].name,
                    inReceipt: receipt)

                    switch purchaseResult {
                        case .purchased(let expiresDate):
                        print("Product is valid until \(expiresDate)")

       ...
       }
       }

My hypothesis is that after the reset we just don't have any receipt to verify, and I have to retrieve it directly. It's kind of hard to check on device because, honestly, I don't have a real test device that would be easy to kill for me.

So I want to add something like that (manually refreshing the receipt before trying to verifying it):

SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: true) { result in
    switch result {
    case .success(let receipt):

Does it make any sense? Will it help?


问:
Display/hide div depending on device width
Is it possible to hide a div with (or without) Bootstrap 4 if the screen width is over/under a specific value? Does it need javascript for that?
More specifically, I'm looking for hiding a specific text (that I find useless on a mobile screen). I tried classes like "hidden-sm-up" but I couldn't make it work. Sorry if it's a basic question...</p>

答:
media queries in CSS are what you are looking for.

```<code>.mydiv{display:block; /*default behavior*/}
@media only screen and (max-width: 400px) {
.mydiv{display:none; /*hide div on all screens with 700 and lower width*/}
 }
</code>```

(try dragging the divider between js and outpuut block)
https://jsfiddle.net/qaabhmou/

more you can find here:
https://www.w3schools.com/css/css3_mediaqueries.asp
https://www.w3schools.com/css/css3_mediaqueries_ex.asp

Body:
media queries in CSS are what you are looking for.

.mydiv{display:block; /*default behavior*/}
@media only screen and (max-width: 400px) {
.mydiv{display:none; /*hide div on all screens with 700 and lower width*/}
 }

(try dragging the divider between js and outpuut block)
https://jsfiddle.net/qaabhmou/

more you can find here:
https://www.w3schools.com/css/css3_mediaqueries.asp
https://www.w3schools.com/css/css3_mediaqueries_ex.asp


问:
Age select select box without array?
Is there a way of creating an age select list like this:

```<code><?php
$Array = array('99','98','97','96');
?>
<select name="age">
<option value="" selected>Choose</option>
<?php foreach($Array as $value){ echo('<option value="' . $value . '">' . $value . '</option>');}?>
</select>
</code>```

but without a really long array as I want age range to be from say 18 upto 100 and that would take forever to writeout?

答:
PHP has a range function that you can use in order to generate an array made up of a range of numbers.</p>

```<code>foreach (range(0, 12) as $value ) {
   echo('<option value="' . $value . '">' . $value . '</option>');
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Age select select box without array?

Body:
Is there a way of creating an age select list like this:

<?php
$Array = array('99','98','97','96');
?>
<select name="age">
<option value="" selected>Choose</option>
<?php foreach($Array as $value){ echo('<option value="' . $value . '">' . $value . '</option>');}?>
</select>

but without a really long array as I want age range to be from say 18 upto 100 and that would take forever to writeout?

Body:
PHP has a range function that you can use in order to generate an array made up of a range of numbers.

foreach (range(0, 12) as $value ) {
   echo('<option value="' . $value . '">' . $value . '</option>');
}


问:
Sharing Razor views across projects
I want to share the layout (Header, Navigation and Footer Razor views) across multiple ASP.NET MVC projects. How can I do that?

Can I create a custom NuGet package to wrap the common Razor files, images and CSS?

答:
There are new options (IMHO) better available.
I would take advantage of organizing it as Feature splices in ASP MVC Core, this would save a lot of time down the road, I would recommend it in 2 steps.

First, organize/put it an area called Features splices MSDN ref. wire it up as in the article and well explained.

```<code>// you're telling ASP that you've other Feature areas that it should look
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
    IEnumerable<string> viewLocations)
{
    // Error checking removed for brevity
    var controllerActionDescriptor = context.ActionContext.ActionDescriptor as ControllerActionDescriptor;
    string featureName = controllerActionDescriptor.Properties["feature"] as string;
    foreach (var location in viewLocations)
    {
        yield return location.Replace("{3}", featureName);
    }
}
</code>```

Second, embed Features in a
Shared project or Portable Libraries. I have attached links on
how to do this from R. Williams and MSDN.

In summary, since you already have it in a common area consider it to be a feature and embed it inside a portable lib or a Shared Project. A nice article by R. Williams.

Title: Sharing Razor views across projects

Body:
There are new options (IMHO) better available.
I would take advantage of organizing it as Feature splices in ASP MVC Core, this would save a lot of time down the road, I would recommend it in 2 steps.

First, organize/put it an area called Features splices MSDN ref. wire it up as in the article and well explained.

// you're telling ASP that you've other Feature areas that it should look
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
    IEnumerable<string> viewLocations)
{
    // Error checking removed for brevity
    var controllerActionDescriptor = context.ActionContext.ActionDescriptor as ControllerActionDescriptor;
    string featureName = controllerActionDescriptor.Properties["feature"] as string;
    foreach (var location in viewLocations)
    {
        yield return location.Replace("{3}", featureName);
    }
}

Second, embed Features in a
Shared project or Portable Libraries. I have attached links on
how to do this from R. Williams and MSDN.

In summary, since you already have it in a common area consider it to be a feature and embed it inside a portable lib or a Shared Project. A nice article by R. Williams.


问:
min method in java keeps returning 0 after entering four values
The code I'm posting is actually a class of the tester code.  This is where I think the error is occurring, even though the output is not producing an error message.  The Math.min method is showing zero after four values are inputted.  It should show the smallest value of the four values.  What should I do?  Do I need to add lines or move lines?

```<code>public class DataSetMaxMin
{
   private int value;
   private int count;
   private int maxValue;
   private int minValue;

   public DataSetMaxMin()
   {
      value = 0;
      count = 0;
      maxValue = 0;
      minValue = 0;
   }

   public void addValue (int theValue)
   {
      count++;
      this.maxValue = Math.max(this.maxValue, theValue);
      this.minValue = Math.min(this.minValue, theValue);
   }

   public int getLargest()
   {
      return this.maxValue;
   }

   public int getSmallest()
   {
      return this.minValue;
   }
}
</code>```

The tester program adds four values using addValue(). So if I enter 25, 15, 35, and 65, I'd expect the code to return the largest value 65 and the smallest value 15.

The actual result I get is 65 for the largest value and 0 for the smallest value.

答:
due to the fact that minValue is set to the value 0, it means if you perform Math.min(this.minValue, theValue); the return value of this function call will always be 0 apart from when theValue is less than zero. to overcome the problem, change the minValue field from:

```<code>private int minValue;
</code>```

to:

```<code>private int minValue = Integer.MAX_VALUE;
</code>```

or better set both fields to:

```<code>private int maxValue = Integer.MIN_VALUE;
private int minValue = Integer.MAX_VALUE;
</code>```

Also, the initialisations within the constructor were redundant, and are now wrong. You can remove the constructor entirely.

Body:
The code I'm posting is actually a class of the tester code.  This is where I think the error is occurring, even though the output is not producing an error message.  The Math.min method is showing zero after four values are inputted.  It should show the smallest value of the four values.  What should I do?  Do I need to add lines or move lines?

public class DataSetMaxMin
{
   private int value;
   private int count;
   private int maxValue;
   private int minValue;

   public DataSetMaxMin()
   {
      value = 0;
      count = 0;
      maxValue = 0;
      minValue = 0;
   }

   public void addValue (int theValue)
   {
      count++;
      this.maxValue = Math.max(this.maxValue, theValue);
      this.minValue = Math.min(this.minValue, theValue);
   }

   public int getLargest()
   {
      return this.maxValue;
   }

   public int getSmallest()
   {
      return this.minValue;
   }
}

The tester program adds four values using addValue(). So if I enter 25, 15, 35, and 65, I'd expect the code to return the largest value 65 and the smallest value 15.

The actual result I get is 65 for the largest value and 0 for the smallest value.

Body:
due to the fact that minValue is set to the value 0, it means if you perform Math.min(this.minValue, theValue); the return value of this function call will always be 0 apart from when theValue is less than zero. to overcome the problem, change the minValue field from:

private int minValue;

to:

private int minValue = Integer.MAX_VALUE;

or better set both fields to:

private int maxValue = Integer.MIN_VALUE;
private int minValue = Integer.MAX_VALUE;

Also, the initialisations within the constructor were redundant, and are now wrong. You can remove the constructor entirely.


问:
Python Cryptography Generate Random Keys
I am using the python Cryptography module and I have generated private and public keys using examples from the documentation. The problem I am having is that I want to be able to generate different key pairs. Like I generate one but it is always the same one being generated every time I run it. I've tried reading through the documentation as much as I cam but cannot find any kind of solution to this problem. Thanks.</p>

答:
I actually did that a while ago, so i'll just copy/paste my solution :)

```<code>import os
from Cryptodome.PublicKey import RSA
from Cryptodome import Random

def generate_keypair(bits=2048):
    random_generator = Random.new().read
    rsa_key = RSA.generate(bits, random_generator)
    return rsa_key.exportKey(), rsa_key.publickey().exportKey()
</code>```

To genarate a random key, you have to include a random generator in RSA.generate.

A little more human readable:

```<code>from Cryptodome.PublicKey import RSA
from Cryptodome import Random

def generate_keypair(bits=2048):
    random_generator = Random.new().read
    rsa_key = RSA.generate(bits, random_generator)
    print(repr(rsa_key))
    print(repr(rsa_key.publickey()))

generate_keypair()
</code>```

Body:
I actually did that a while ago, so i'll just copy/paste my solution :)

import os
from Cryptodome.PublicKey import RSA
from Cryptodome import Random

def generate_keypair(bits=2048):
    random_generator = Random.new().read
    rsa_key = RSA.generate(bits, random_generator)
    return rsa_key.exportKey(), rsa_key.publickey().exportKey()

To genarate a random key, you have to include a random generator in RSA.generate.

A little more human readable:

from Cryptodome.PublicKey import RSA
from Cryptodome import Random

def generate_keypair(bits=2048):
    random_generator = Random.new().read
    rsa_key = RSA.generate(bits, random_generator)
    print(repr(rsa_key))
    print(repr(rsa_key.publickey()))

generate_keypair()


问:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

```<code>     s = [1,2,3,4,5,3,9,8]  => s[2] appears first
</code>```

答:
The function below returns the index of the first appearance of a duplicate</p>

```<code>def find_first_duplicate(num_list):
        track_list =[]
        index = 0
        for e in num_list:
            if(e not in track_list):
                track_list += [e]
            else: ## found!
                return index
            index += 1
</code>```

Body:
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

     s = [1,2,3,4,5,3,9,8]  => s[2] appears first

Body:
The function below returns the index of the first appearance of a duplicate

def find_first_duplicate(num_list):
        track_list =[]
        index = 0
        for e in num_list:
            if(e not in track_list):
                track_list += [e]
            else: ## found!
                return index
            index += 1


问:
Extract all model statistics from rms fits?
The rms package contains a wealth of useful statistical functions. However, I cannot find a proper way to extract certain fit statistics from the fitted object. Consider an example:

```<code>library(pacman)
p_load(rms, stringr, readr)

#fit
> (fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris))
Linear Regression Model

 rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length +
     Petal.Width + Species, data = iris)

                Model Likelihood     Discrimination
                   Ratio Test           Indexes
 Obs     150    LR chi2    302.96    R2       0.867
 sigma0.3068    d.f.            5    R2 adj   0.863
 d.f.    144    Pr(> chi2) 0.0000    g        0.882

 Residuals

       Min        1Q    Median        3Q       Max
 -0.794236 -0.218743  0.008987  0.202546  0.731034

                    Coef    S.E.   t     Pr(>|t|)
 Intercept           2.1713 0.2798  7.76 <0.0001
 Sepal.Width         0.4959 0.0861  5.76 <0.0001
 Petal.Length        0.8292 0.0685 12.10 <0.0001
 Petal.Width        -0.3152 0.1512 -2.08 0.0389
 Species=versicolor -0.7236 0.2402 -3.01 0.0031
 Species=virginica  -1.0235 0.3337 -3.07 0.0026
</code>```

So, the print function for the fit prints a lot of useful stuff including standard errors and adjusted R2. Unfortunately, if we inspect the model fit object, the values don't seem to be present anywhere.

```<code>> str(fit)
List of 19
 $ coefficients     : Named num [1:6] 2.171 0.496 0.829 -0.315 -0.724 ...
  ..- attr(*, "names")= chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ residuals        : Named num [1:150] 0.0952 0.1432 -0.0731 -0.2894 -0.0544 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ effects          : Named num [1:150] -71.5659 -1.1884 9.1884 -1.3724 -0.0587 ...
  ..- attr(*, "names")= chr [1:150] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ rank             : int 6
 $ fitted.values    : Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ assign           :List of 4
  ..$ Sepal.Width : int 2
  ..$ Petal.Length: int 3
  ..$ Petal.Width : int 4
  ..$ Species     : int [1:2] 5 6
 $ qr               :List of 5
  ..$ qr   : num [1:150, 1:6] -12.2474 0.0816 0.0816 0.0816 0.0816 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:150] "1" "2" "3" "4" ...
  .. .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  ..$ qraux: num [1:6] 1.08 1.02 1.11 1.02 1.02 ...
  ..$ pivot: int [1:6] 1 2 3 4 5 6
  ..$ tol  : num 1e-07
  ..$ rank : int 6
  ..- attr(*, "class")= chr "qr"
 $ df.residual      : int 144
 $ var              : num [1:6, 1:6] 0.07828 -0.02258 -0.00198 0.01589 -0.02837 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ stats            : Named num [1:6] 150 302.964 5 0.867 0.882 ...
  ..- attr(*, "names")= chr [1:6] "n" "Model L.R." "d.f." "R2" ...
 $ linear.predictors: Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ call             : language rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)
 $ terms            :Classes 'terms', 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, "variables")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "factors")= int [1:5, 1:4] 0 1 0 0 0 0 0 1 0 0 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. .. .. ..$ : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "term.labels")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "order")= int [1:4] 1 1 1 1
  .. ..- attr(*, "intercept")= num 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
  .. ..- attr(*, "predvars")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "dataClasses")= Named chr [1:5] "numeric" "numeric" "numeric" "numeric" ...
  .. .. ..- attr(*, "names")= chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..- attr(*, "formula")=Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. .. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 $ Design           :List of 12
  ..$ name        : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ label       : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ units       : Named chr [1:4] "" "" "" ""
  .. ..- attr(*, "names")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ colnames    : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Species=versicolor" ...
  ..$ mmcolnames  : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Speciesversicolor" ...
  ..$ assume      : chr [1:4] "asis" "asis" "asis" "category"
  ..$ assume.code : int [1:4] 1 1 1 5
  ..$ parms       :List of 1
  .. ..$ Species: chr [1:3] "setosa" "versicolor" "virginica"
  ..$ limits      : list()
  ..$ values      : list()
  ..$ nonlinear   :List of 4
  .. ..$ Sepal.Width : logi FALSE
  .. ..$ Petal.Length: logi FALSE
  .. ..$ Petal.Width : logi FALSE
  .. ..$ Species     : logi [1:2] FALSE FALSE
  ..$ interactions: NULL
 $ non.slopes       : num 1
 $ na.action        : NULL
 $ scale.pred       : chr "Sepal.Length"
 $ fail             : logi FALSE
 $ sformula         :Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 - attr(*, "class")= chr [1:3] "ols" "rms" "lm"
</code>```

There is a 7 year old question on R help where the package creator explains a solution to getting these:

On Wed, 11 Aug 2010, david dav wrote:

Hi,
    I would like to extract the coefficients of a logistic regression
    (estimates and standard error as well) in lrm as in glm with

summary(fit.glm)$coef

Thanks
    David

coef(fit) sqrt(diag(vcov(fit)))

But these will not be very helpful except in the trivial case where
  everything is linear, nothing interacts, and factors have two levels.

Frank

And the solution is according to the author not optimal. This leaves one wondering how the displayed values are calculated. Tracing down the code results in a hunt through the undocumented package code (the package code is on Github). I.e. we begin with print.ols():

```<code>> rms:::print.ols
function (x, digits = 4, long = FALSE, coefs = TRUE, title = "Linear Regression Model",
    ...)
{
    latex <- prType() == "latex"
    k <- 0
    z <- list()
    if (length(zz <- x$na.action)) {
        k <- k + 1
        z[[k]] <- list(type = paste("naprint", class(zz)[1],
            sep = "."), list(zz))
    }
    stats <- x$stats
...
</code>```

Reading further we do find that e.g. R2 adj. is calculated in the print function:

```<code>rsqa <- 1 - (1 - r2) * (n - 1) / rdf
</code>```

We also find some standard error calculations, though no p values.

```<code>  se <- sqrt(diag(x$var))
  z[[k]] <- list(type='coefmatrix',
                 list(coef    = x$coefficients,
                      se      = se,
                      errordf = rdf))
</code>```

All the results are passed down further to prModFit(). We can look it up and find the p value calculation etc. Unfortunately, the print command returns NULL so these values are not available anywhere for programmatic reuse:

```<code>> x = print((fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)))
#printed output...
> x
NULL
</code>```

How does one get all the statistics?

答:
Here is a hack solution where we capture the output of the print command:

```<code>#parser
get_model_stats = function(x, precision=60) {

  # remember old number formatting function
  # (which would round and transforms p-values to formats like "<0.01")
  old_format_np = rms::formatNP
  # substitute it with a function which will print out as many digits as we want
  assignInNamespace("formatNP", function(x, ...) formatC(x, format="f", digits=precision), "rms")

  # remember old width setting
  old_width = options('width')$width
  # substitute it with a setting making sure the table will not wrap
  options(width=old_width + 4 * precision)

  # actually print the data and capture it
  cap = capture.output(print(x))

  # restore original settings
  options(width=old_width)
  assignInNamespace("formatNP", old_format_np, "rms")

  #model stats
  stats = c()
  stats$R2.adj = str_match(cap, "R2 adj\\s+ (\\d\\.\\d+)") %>% na.omit() %>% .[, 2] %>% as.numeric()

  #coef stats lines
  coef_lines = cap[which(str_detect(cap, "Coef\\s+S\\.E\\.")):(length(cap) - 1)]

  #parse
  coef_lines_table = suppressWarnings(readr::read_table(coef_lines %>% stringr::str_c(collapse = "\n")))
  colnames(coef_lines_table)[1] = "Predictor"

  list(
    stats = stats,
    coefs = coef_lines_table
  )
}
</code>```

Example:

```<code>> get_model_stats(fit)
$stats
$stats$R2.adj
[1] 0.86

$coefs
# A tibble: 6 x 5
           Predictor  Coef  S.E.     t `Pr(>|t|)`
               <chr> <dbl> <dbl> <dbl>      <chr>
1          Intercept  2.17 0.280   7.8    <0.0001
2        Sepal.Width  0.50 0.086   5.8    <0.0001
3       Petal.Length  0.83 0.069  12.1    <0.0001
4        Petal.Width -0.32 0.151  -2.1     0.0389
5 Species=versicolor -0.72 0.240  -3.0     0.0031
6  Species=virginica -1.02 0.334  -3.1     0.0026
</code>```

<s>This still has issues, e.g. p values are not returned as numerics and only has 4 digits, which can cause issues in some situations.</s> The updated code should extract digits up to arbitrary precision.

Be extra careful when using this with long variable names as those could wrap the table into multiple rows and introduce missing values (NA) in output even though the stats are in there!

Body:
The rms package contains a wealth of useful statistical functions. However, I cannot find a proper way to extract certain fit statistics from the fitted object. Consider an example:

library(pacman)
p_load(rms, stringr, readr)

#fit
> (fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris))
Linear Regression Model

 rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length +
     Petal.Width + Species, data = iris)

                Model Likelihood     Discrimination
                   Ratio Test           Indexes
 Obs     150    LR chi2    302.96    R2       0.867
 sigma0.3068    d.f.            5    R2 adj   0.863
 d.f.    144    Pr(> chi2) 0.0000    g        0.882

 Residuals

       Min        1Q    Median        3Q       Max
 -0.794236 -0.218743  0.008987  0.202546  0.731034

                    Coef    S.E.   t     Pr(>|t|)
 Intercept           2.1713 0.2798  7.76 <0.0001
 Sepal.Width         0.4959 0.0861  5.76 <0.0001
 Petal.Length        0.8292 0.0685 12.10 <0.0001
 Petal.Width        -0.3152 0.1512 -2.08 0.0389
 Species=versicolor -0.7236 0.2402 -3.01 0.0031
 Species=virginica  -1.0235 0.3337 -3.07 0.0026

So, the print function for the fit prints a lot of useful stuff including standard errors and adjusted R2. Unfortunately, if we inspect the model fit object, the values don't seem to be present anywhere.

> str(fit)
List of 19
 $ coefficients     : Named num [1:6] 2.171 0.496 0.829 -0.315 -0.724 ...
  ..- attr(*, "names")= chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ residuals        : Named num [1:150] 0.0952 0.1432 -0.0731 -0.2894 -0.0544 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ effects          : Named num [1:150] -71.5659 -1.1884 9.1884 -1.3724 -0.0587 ...
  ..- attr(*, "names")= chr [1:150] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ rank             : int 6
 $ fitted.values    : Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ assign           :List of 4
  ..$ Sepal.Width : int 2
  ..$ Petal.Length: int 3
  ..$ Petal.Width : int 4
  ..$ Species     : int [1:2] 5 6
 $ qr               :List of 5
  ..$ qr   : num [1:150, 1:6] -12.2474 0.0816 0.0816 0.0816 0.0816 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:150] "1" "2" "3" "4" ...
  .. .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  ..$ qraux: num [1:6] 1.08 1.02 1.11 1.02 1.02 ...
  ..$ pivot: int [1:6] 1 2 3 4 5 6
  ..$ tol  : num 1e-07
  ..$ rank : int 6
  ..- attr(*, "class")= chr "qr"
 $ df.residual      : int 144
 $ var              : num [1:6, 1:6] 0.07828 -0.02258 -0.00198 0.01589 -0.02837 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ stats            : Named num [1:6] 150 302.964 5 0.867 0.882 ...
  ..- attr(*, "names")= chr [1:6] "n" "Model L.R." "d.f." "R2" ...
 $ linear.predictors: Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ call             : language rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)
 $ terms            :Classes 'terms', 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, "variables")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "factors")= int [1:5, 1:4] 0 1 0 0 0 0 0 1 0 0 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. .. .. ..$ : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "term.labels")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "order")= int [1:4] 1 1 1 1
  .. ..- attr(*, "intercept")= num 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
  .. ..- attr(*, "predvars")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "dataClasses")= Named chr [1:5] "numeric" "numeric" "numeric" "numeric" ...
  .. .. ..- attr(*, "names")= chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..- attr(*, "formula")=Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. .. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 $ Design           :List of 12
  ..$ name        : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ label       : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ units       : Named chr [1:4] "" "" "" ""
  .. ..- attr(*, "names")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ colnames    : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Species=versicolor" ...
  ..$ mmcolnames  : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Speciesversicolor" ...
  ..$ assume      : chr [1:4] "asis" "asis" "asis" "category"
  ..$ assume.code : int [1:4] 1 1 1 5
  ..$ parms       :List of 1
  .. ..$ Species: chr [1:3] "setosa" "versicolor" "virginica"
  ..$ limits      : list()
  ..$ values      : list()
  ..$ nonlinear   :List of 4
  .. ..$ Sepal.Width : logi FALSE
  .. ..$ Petal.Length: logi FALSE
  .. ..$ Petal.Width : logi FALSE
  .. ..$ Species     : logi [1:2] FALSE FALSE
  ..$ interactions: NULL
 $ non.slopes       : num 1
 $ na.action        : NULL
 $ scale.pred       : chr "Sepal.Length"
 $ fail             : logi FALSE
 $ sformula         :Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 - attr(*, "class")= chr [1:3] "ols" "rms" "lm"

There is a 7 year old question on R help where the package creator explains a solution to getting these:

On Wed, 11 Aug 2010, david dav wrote:

Hi,
    I would like to extract the coefficients of a logistic regression
    (estimates and standard error as well) in lrm as in glm with

summary(fit.glm)$coef

Thanks
    David

coef(fit) sqrt(diag(vcov(fit)))

But these will not be very helpful except in the trivial case where
  everything is linear, nothing interacts, and factors have two levels.

Frank

And the solution is according to the author not optimal. This leaves one wondering how the displayed values are calculated. Tracing down the code results in a hunt through the undocumented package code (the package code is on Github). I.e. we begin with print.ols():

> rms:::print.ols
function (x, digits = 4, long = FALSE, coefs = TRUE, title = "Linear Regression Model",
    ...)
{
    latex <- prType() == "latex"
    k <- 0
    z <- list()
    if (length(zz <- x$na.action)) {
        k <- k + 1
        z[[k]] <- list(type = paste("naprint", class(zz)[1],
            sep = "."), list(zz))
    }
    stats <- x$stats
...

Reading further we do find that e.g. R2 adj. is calculated in the print function:

rsqa <- 1 - (1 - r2) * (n - 1) / rdf

We also find some standard error calculations, though no p values.

  se <- sqrt(diag(x$var))
  z[[k]] <- list(type='coefmatrix',
                 list(coef    = x$coefficients,
                      se      = se,
                      errordf = rdf))

All the results are passed down further to prModFit(). We can look it up and find the p value calculation etc. Unfortunately, the print command returns NULL so these values are not available anywhere for programmatic reuse:

> x = print((fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)))
#printed output...
> x
NULL

How does one get all the statistics?

Body:
Here is a hack solution where we capture the output of the print command:

#parser
get_model_stats = function(x, precision=60) {

  # remember old number formatting function
  # (which would round and transforms p-values to formats like "<0.01")
  old_format_np = rms::formatNP
  # substitute it with a function which will print out as many digits as we want
  assignInNamespace("formatNP", function(x, ...) formatC(x, format="f", digits=precision), "rms")

  # remember old width setting
  old_width = options('width')$width
  # substitute it with a setting making sure the table will not wrap
  options(width=old_width + 4 * precision)

  # actually print the data and capture it
  cap = capture.output(print(x))

  # restore original settings
  options(width=old_width)
  assignInNamespace("formatNP", old_format_np, "rms")

  #model stats
  stats = c()
  stats$R2.adj = str_match(cap, "R2 adj\\s+ (\\d\\.\\d+)") %>% na.omit() %>% .[, 2] %>% as.numeric()

  #coef stats lines
  coef_lines = cap[which(str_detect(cap, "Coef\\s+S\\.E\\.")):(length(cap) - 1)]

  #parse
  coef_lines_table = suppressWarnings(readr::read_table(coef_lines %>% stringr::str_c(collapse = "\n")))
  colnames(coef_lines_table)[1] = "Predictor"

  list(
    stats = stats,
    coefs = coef_lines_table
  )
}

Example:

> get_model_stats(fit)
$stats
$stats$R2.adj
[1] 0.86

$coefs
# A tibble: 6 x 5
           Predictor  Coef  S.E.     t `Pr(>|t|)`
               <chr> <dbl> <dbl> <dbl>      <chr>
1          Intercept  2.17 0.280   7.8    <0.0001
2        Sepal.Width  0.50 0.086   5.8    <0.0001
3       Petal.Length  0.83 0.069  12.1    <0.0001
4        Petal.Width -0.32 0.151  -2.1     0.0389
5 Species=versicolor -0.72 0.240  -3.0     0.0031
6  Species=virginica -1.02 0.334  -3.1     0.0026

<s>This still has issues, e.g. p values are not returned as numerics and only has 4 digits, which can cause issues in some situations.</s> The updated code should extract digits up to arbitrary precision.

Be extra careful when using this with long variable names as those could wrap the table into multiple rows and introduce missing values (NA) in output even though the stats are in there!


问:
Adding values to HashMap without casting
I have an interface called InterA which has a method call operate() that has its return value as Result.

```<code> public interface InterA<T>
 {
    Result operate(T source);
 }
</code>```

Assume Class MachineOperator and Class CarOperator are implementations of the above with two T object types.

```<code> public class MachineOperator implements InterA<Machine>
 {
    Result operate(Machine source)
    {
      //Do some operation here and return result.
    }
}

public class CarOperator implements InterA<Car>
{
    Result operate(Car source)
    {
       //Do some operation here and return result.
    }
}
</code>```

And I want to keep these implementations in a map so that when I give the class I can have the implementation. So my map would be like this.

```<code>Map<Class<?>, InterA<T>> map = new HashMap<>();
</code>```

And when I go to fill the map I have to do following,

```<code>map.put(Machine.class, (InterA<T>) new MachineOperator());
map.put(Car.class, (InterA<T>) new CarOperator());
</code>```

Is there any way of defining the map so there is no longer a need to cast when adding?

=============================================================

I have tried the following also which can avoid casting when adding to map.

```<code>public interface InterA
{
    Result <T> operate(T source);
}
</code>```

Then in each implementation I have to have additional casting for each T.

```<code>public class MachineOperator implements InterA
{
    < Machine> Result operate(Machine source)
 {
    (Machine) source; //Need to cast for Machine In-order to read attributes.
    //Do some operation here and return result.
 }
}
</code>```

Out of these what would be the correct approach? Is there any different solution?

答:
You should replace T in Map declaration with some common ancestor for Car and Machine.

If there is no common class, just use Object or ?.

That will eliminate compilation errors, but will increase chances of runtime errors. You will have be sure that the instance of the parameter is what is expected.

Body:
I have an interface called InterA which has a method call operate() that has its return value as Result.

 public interface InterA<T>
 {
    Result operate(T source);
 }

Assume Class MachineOperator and Class CarOperator are implementations of the above with two T object types.

 public class MachineOperator implements InterA<Machine>
 {
    Result operate(Machine source)
    {
      //Do some operation here and return result.
    }
}

public class CarOperator implements InterA<Car>
{
    Result operate(Car source)
    {
       //Do some operation here and return result.
    }
}

And I want to keep these implementations in a map so that when I give the class I can have the implementation. So my map would be like this.

Map<Class<?>, InterA<T>> map = new HashMap<>();

And when I go to fill the map I have to do following,

map.put(Machine.class, (InterA<T>) new MachineOperator());
map.put(Car.class, (InterA<T>) new CarOperator());

Is there any way of defining the map so there is no longer a need to cast when adding?

=============================================================

I have tried the following also which can avoid casting when adding to map.

public interface InterA
{
    Result <T> operate(T source);
}

Then in each implementation I have to have additional casting for each T.

public class MachineOperator implements InterA
{
    < Machine> Result operate(Machine source)
 {
    (Machine) source; //Need to cast for Machine In-order to read attributes.
    //Do some operation here and return result.
 }
}

Out of these what would be the correct approach? Is there any different solution?


答:
I think you just want a get property on your player class.

```<code>public bool IsCpu { get { return is_CPU; }}
</code>```

See also c# properties

Title: Checking a private value in another class [C#]

Body:
I'm making a simple dart game in the console for an assignment where I am to practice using private lists and variables everywhere. The basic flow of the program for some context is as follows:

User lands in a menu

User chooses from 1-4. (1 = Add player, 2 = Add CPU, 3 = Start game, 4 = Quit)

Game starts. Players manually add their 3 throws per turn, and CPU gets theirs randomly.

When a player or CPU reaches 301 score, the loop ends and you now see every throw made by the winner.

UML diagram for class structure context: https://i.imgur.com/bL5pZV5.png

Everything is pretty much complete. I've made the program to such an extent that both players and CPUs are getting random values (are treated as CPU players), it prints out everything correctly and follows the flow to the end.

My issue now is that I want to be able to reach the is_CPU variable which is private in the Player class from the Game class and use it in an IF check, directing whether or not the values are manually added or randomly generated.

Pseudo-code:

FOREACH (var player in player_list)
  IF (is_CPU == TRUE)
    THEN Assign random values
  ELSE
    THEN Manually enter values

I tried messing around with the get-set stuff, but I don't fully understand how to use them and how they work. I have looked around on here and still don't see how I should be using them in this case, if at all.

I can think of one way to work around this and that is by making a method just for this where it checks that value and returns true/false, but that seems like a 'lazy' or improper way to do this, and comes with several downsides. I feel like there should be a better way to do this, one that won't come back to bite me in the ass later. Hopefully there is, and I can learn it by asking here.

EDIT: The variables and lists HAVE to be private. It is part of the exercise where we learn how to handle these.

Body:
I think you just want a get property on your player class.

public bool IsCpu { get { return is_CPU; }}

See also c# properties


问:
Spring Boot Web Application: throwing java.lang.IllegalStateException: getOutputStream() has already been called for this response
In Spring Boot Web Application throwing java.lang.IllegalStateException: getOutputStream() has already been called for this response.

I have in memory database h2 with ORM Relation of @ManyToOne, @ManyToMany,
my class look like

```<code>@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String isbn;
    private String title;
    private String description;
    @ManyToOne
    private Author author;
    @ManyToOne
    private Publisher publisher;
    @ManyToMany
    private List<Reviewer> reviewers;

    protected Book() {
    }

    public Book(String isbn, String title, Author author, Publisher publisher) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.publisher = publisher;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }
}
</code>```

and testing class

```<code>public class StartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private AuthorRepository authorRepository;

    @Autowired
    private PublisherRepository publisherRepository;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Number of books: " + bookRepository.count());
        Author author = new Author("Alex", "Antonov");
        author = authorRepository.save(author);
        Publisher publisher = new Publisher("Packt");
        publisher = publisherRepository.save(publisher);
        Book book = new Book("978-1-78528-415-1", "Spring Boot Recipes", author, publisher);
        bookRepository.save(book);
    }

    @Scheduled(initialDelay = 1000, fixedRate = 10000)
    public void run() {

        logger.info("Number of books: " + bookRepository.count());
    }

}
</code>```

main class

```<code>public class StartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private AuthorRepository authorRepository;

    @Autowired
    private PublisherRepository publisherRepository;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Number of books: " + bookRepository.count());
        Author author = new Author("Alex", "Antonov");
        author = authorRepository.save(author);
        Publisher publisher = new Publisher("Packt");
        publisher = publisherRepository.save(publisher);
        Book book = new Book("978-1-78528-415-1", "Spring Boot Recipes", author, publisher);
        bookRepository.save(book);
    }

    @Scheduled(initialDelay = 1000, fixedRate = 10000)
    public void run() {

        logger.info("Number of books: " + bookRepository.count());
    }

}
</code>```

Trying to access the data http://localhost:8080/books/978-1-78528-415-1
throwing above exception

答:
Not an ideal solution but I was able to get mine working after adding an eager fetch type to the mapped children (i.e. fetch=FetchType.EAGER)

```<code>@ManyToMany (fetch=FetchType.EAGER)
private List<Reviewer> reviewers;
</code>```

Body:
In Spring Boot Web Application throwing java.lang.IllegalStateException: getOutputStream() has already been called for this response.

I have in memory database h2 with ORM Relation of @ManyToOne, @ManyToMany,
my class look like

@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String isbn;
    private String title;
    private String description;
    @ManyToOne
    private Author author;
    @ManyToOne
    private Publisher publisher;
    @ManyToMany
    private List<Reviewer> reviewers;

    protected Book() {
    }

    public Book(String isbn, String title, Author author, Publisher publisher) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.publisher = publisher;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }
}

and testing class

public class StartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private AuthorRepository authorRepository;

    @Autowired
    private PublisherRepository publisherRepository;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Number of books: " + bookRepository.count());
        Author author = new Author("Alex", "Antonov");
        author = authorRepository.save(author);
        Publisher publisher = new Publisher("Packt");
        publisher = publisherRepository.save(publisher);
        Book book = new Book("978-1-78528-415-1", "Spring Boot Recipes", author, publisher);
        bookRepository.save(book);
    }

    @Scheduled(initialDelay = 1000, fixedRate = 10000)
    public void run() {

        logger.info("Number of books: " + bookRepository.count());
    }

}

main class

public class StartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private AuthorRepository authorRepository;

    @Autowired
    private PublisherRepository publisherRepository;

    @Override
    public void run(String... args) throws Exception {
        logger.info("Number of books: " + bookRepository.count());
        Author author = new Author("Alex", "Antonov");
        author = authorRepository.save(author);
        Publisher publisher = new Publisher("Packt");
        publisher = publisherRepository.save(publisher);
        Book book = new Book("978-1-78528-415-1", "Spring Boot Recipes", author, publisher);
        bookRepository.save(book);
    }

    @Scheduled(initialDelay = 1000, fixedRate = 10000)
    public void run() {

        logger.info("Number of books: " + bookRepository.count());
    }

}

Trying to access the data http://localhost:8080/books/978-1-78528-415-1
throwing above exception

Body:
Not an ideal solution but I was able to get mine working after adding an eager fetch type to the mapped children (i.e. fetch=FetchType.EAGER)

@ManyToMany (fetch=FetchType.EAGER)
private List<Reviewer> reviewers;


答: It’s because you already call minValue=0 at the beginning. Simply say: minValue=Integer.MaxValue; and maxValue=Integer.MinValue;

Title: min method in java keeps returning 0 after entering four values


问:
Best way to compare std::strings
What is the best way to compare std::strings? The obvious way would be with if/else:

```<code>std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.
</code>```

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

答:
If you mean "most efficient" by "the best", read ahead.

I'm suggesting using the following method if there really is a lot.

String in Switch is actually something will be in Java 7. (As part of Project Coin)

And according to the proposal, this is the way Java language will implement it.

First, hash value of each of the strings is calculated. This problem is then a "switch int" problem, which is available in most currently language, and is efficient. In each of the case statement, you then check if this is really the string (in very rare cases different strings could hash to the same int).

I personally don't do the last step in practice sometimes as it's necessity depends on the situation you specific program is in, i.e. whether the strings possible are under the programmer's control and how robust the program need to be.

A sample pseudocode the corresponds

```<code>String s = ...
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}
</code>```

from the fore-mentioned proposal to help you understand.

```<code>// Advanced example
{  // new scope for synthetic variables
  boolean $take_default = false;
  boolean $fallthrough = false;
  $default_label: {
      switch(s.hashCode()) { // cause NPE if s is null
      case 3482567: // "quux".hashCode()
          if (!s.equals("quux")) {
              $take_default = true;
              break $default_label;
          }
          processQuux(s);
          $fallthrough = true;
                case 101574: // "foo".hashCode()
          if (!$fallthrough && !s.equals("foo")) {
              $take_default = true;
              break $default_label;
          }
          $fallthrough = true;
      case 97299:  // "bar".hashCode()
          if (!$fallthrough && !s.equals("bar")) {
              $take_default = true;
              break $default_label;
          }
          processFooOrBar(s);
          break;

      case 97307: // "baz".hashCode()
          if (!s.equals("baz")) {
              $take_default = true;
              break $default_label;
          }
          processBaz(s);
          $fallthrough = true;

      default:
          $take_default = true;
          break $default_label;
      }
  }
  if($take_default)
      processDefault(s);
}
</code>```

Title: Best way to compare std::strings

Body:
What is the best way to compare std::strings? The obvious way would be with if/else:

std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

Body:
If you mean "most efficient" by "the best", read ahead.

I'm suggesting using the following method if there really is a lot.

String in Switch is actually something will be in Java 7. (As part of Project Coin)

And according to the proposal, this is the way Java language will implement it.

First, hash value of each of the strings is calculated. This problem is then a "switch int" problem, which is available in most currently language, and is efficient. In each of the case statement, you then check if this is really the string (in very rare cases different strings could hash to the same int).

I personally don't do the last step in practice sometimes as it's necessity depends on the situation you specific program is in, i.e. whether the strings possible are under the programmer's control and how robust the program need to be.

A sample pseudocode the corresponds

String s = ...
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}

from the fore-mentioned proposal to help you understand.

// Advanced example
{  // new scope for synthetic variables
  boolean $take_default = false;
  boolean $fallthrough = false;
  $default_label: {
      switch(s.hashCode()) { // cause NPE if s is null
      case 3482567: // "quux".hashCode()
          if (!s.equals("quux")) {
              $take_default = true;
              break $default_label;
          }
          processQuux(s);
          $fallthrough = true;
                case 101574: // "foo".hashCode()
          if (!$fallthrough && !s.equals("foo")) {
              $take_default = true;
              break $default_label;
          }
          $fallthrough = true;
      case 97299:  // "bar".hashCode()
          if (!$fallthrough && !s.equals("bar")) {
              $take_default = true;
              break $default_label;
          }
          processFooOrBar(s);
          break;

      case 97307: // "baz".hashCode()
          if (!s.equals("baz")) {
              $take_default = true;
              break $default_label;
          }
          processBaz(s);
          $fallthrough = true;

      default:
          $take_default = true;
          break $default_label;
      }
  }
  if($take_default)
      processDefault(s);
}


问:
Clicking, pressing-down, and releasing a button
I have a button in my android studio project and I want the button to perform three different action. First, when it is clicked. Secondly, when it is hold down and lastly, when it is released. I tried using onTouch listener:

```<code>    button.setOnTouchListener (new View.OnTouchListener){
        @Override
        public void onTouch (MotionEvent motionEvent)
            switch (motionEvent.getAction ()){
                case MotionEvent.ACTION_DOWN:
                    //record video
                return true;
                    case MotionEvent.ACTION_UP:
                    //stop record
                    return true;

            }
                return true;
        }
    }

    button.setOnClickListener(new View.OnClickListener){
            @Override
            public void onClick (View view){
                //capture image
            }
        }
</code>```

The problem Is, when the button is tapped once it produces an execption and causes my app to crash

答:
onTouchListener should be to help out, and the code below should be able to:

```<code>view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // PRESSED
            return true; // if you want to handle the touch event
        case MotionEvent.ACTION_UP:
            // RELEASED
            return true; // if you want to handle the touch event
    }
    return false;
}
</code>```

});

Body:
I have a button in my android studio project and I want the button to perform three different action. First, when it is clicked. Secondly, when it is hold down and lastly, when it is released. I tried using onTouch listener:

    button.setOnTouchListener (new View.OnTouchListener){
        @Override
        public void onTouch (MotionEvent motionEvent)
            switch (motionEvent.getAction ()){
                case MotionEvent.ACTION_DOWN:
                    //record video
                return true;
                    case MotionEvent.ACTION_UP:
                    //stop record
                    return true;

            }
                return true;
        }
    }

    button.setOnClickListener(new View.OnClickListener){
            @Override
            public void onClick (View view){
                //capture image
            }
        }

The problem Is, when the button is tapped once it produces an execption and causes my app to crash

Body:
onTouchListener should be to help out, and the code below should be able to:

view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // PRESSED
            return true; // if you want to handle the touch event
        case MotionEvent.ACTION_UP:
            // RELEASED
            return true; // if you want to handle the touch event
    }
    return false;
}

});