问:
Slick: How to filter by isBefore Timestamp database attribute?
I naively did the following on Slick 4.0.1. I have an expiry database field and I need to find all the rows where the expiry is before a given timestamp.

This is what the Slick mapping looks like:

```<code>/** Table description of table auth_token. Objects of this class serve as prototypes for rows in queries. */
class AuthToken(_tableTag: Tag) extends profile.api.Table[AuthTokenRow](_tableTag, Some("myappdb"), "auth_token") with IdentifyableTable[Long] {
  override def id = userId

  def * = (userId, tokenId, expiry) <> (AuthTokenRow.tupled, AuthTokenRow.unapply)
  /** Maps whole row to an option. Useful for outer joins. */
  def ? = ((Rep.Some(userId), Rep.Some(tokenId), Rep.Some(expiry))).shaped.<>({ r => import r._; _1.map(_ => AuthTokenRow.tupled((_1.get, _2.get, _3.get))) }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))

  /** Database column user_id SqlType(BIGINT UNSIGNED) */
  val userId: Rep[Long] = column[Long]("user_id")
  /** Database column token_id SqlType(CHAR), Length(36,false) */
  val tokenId: Rep[String] = column[String]("token_id", O.Length(36, varying = false))
  /** Database column expiry SqlType(TIMESTAMP) */
  val expiry: Rep[java.sql.Timestamp] = column[java.sql.Timestamp]("expiry")

  /** Foreign key referencing User (database name auth_token_ibfk_1) */
  lazy val userFk = foreignKey("auth_token_ibfk_1", userId, User)(r => r.id, onUpdate = ForeignKeyAction.NoAction, onDelete = ForeignKeyAction.Cascade)

  /** Index over (tokenId) (database name idx_token_id) */
  val index1 = index("idx_token_id", tokenId)
}
/** Collection-like TableQuery object for table AuthToken */
lazy val AuthToken = new TableQuery(tag => new AuthToken(tag))
</code>```

and then I need to do:

```<code>/**
 * Finds expired tokens.
 *
 * @param dateTime The current date time.
 */
def findExpired(dateTime: org.joda.time.DateTime): Future[Seq[AuthTokenRow]] = {
  val action = AuthToken.filter(authToken => authToken.expiry.isBefore(dateTime)).result
  db.run(action)
}
</code>```

How to cover this use-case correctly/officially in Slick?

答:
I solved this by reusing the project slick-joda-mapper. This solution is a bit involved because of working with the Slick generator etc but it is VERY clean, I love it. Basically it enables mapping database date time types to the Joda types like org.joda.time.DateTime. Therefore my solution becomes as simple as using comparison operators supported by Joda DateTime:

```<code>/**
 * Finds expired tokens.
 *
 * @param dateTime The current date time.
 */
override def findExpired(dateTime: org.joda.time.DateTime): Future[Seq[AuthTokenRow]] = {
  val action = AuthToken.filter(authToken => authToken.expiry < dateTime).result
  db.run(action)
}
</code>```

Body:
I naively did the following on Slick 4.0.1. I have an expiry database field and I need to find all the rows where the expiry is before a given timestamp.

This is what the Slick mapping looks like:

/** Table description of table auth_token. Objects of this class serve as prototypes for rows in queries. */
class AuthToken(_tableTag: Tag) extends profile.api.Table[AuthTokenRow](_tableTag, Some("myappdb"), "auth_token") with IdentifyableTable[Long] {
  override def id = userId

  def * = (userId, tokenId, expiry) <> (AuthTokenRow.tupled, AuthTokenRow.unapply)
  /** Maps whole row to an option. Useful for outer joins. */
  def ? = ((Rep.Some(userId), Rep.Some(tokenId), Rep.Some(expiry))).shaped.<>({ r => import r._; _1.map(_ => AuthTokenRow.tupled((_1.get, _2.get, _3.get))) }, (_: Any) => throw new Exception("Inserting into ? projection not supported."))

  /** Database column user_id SqlType(BIGINT UNSIGNED) */
  val userId: Rep[Long] = column[Long]("user_id")
  /** Database column token_id SqlType(CHAR), Length(36,false) */
  val tokenId: Rep[String] = column[String]("token_id", O.Length(36, varying = false))
  /** Database column expiry SqlType(TIMESTAMP) */
  val expiry: Rep[java.sql.Timestamp] = column[java.sql.Timestamp]("expiry")

  /** Foreign key referencing User (database name auth_token_ibfk_1) */
  lazy val userFk = foreignKey("auth_token_ibfk_1", userId, User)(r => r.id, onUpdate = ForeignKeyAction.NoAction, onDelete = ForeignKeyAction.Cascade)

  /** Index over (tokenId) (database name idx_token_id) */
  val index1 = index("idx_token_id", tokenId)
}
/** Collection-like TableQuery object for table AuthToken */
lazy val AuthToken = new TableQuery(tag => new AuthToken(tag))

and then I need to do:

/**
 * Finds expired tokens.
 *
 * @param dateTime The current date time.
 */
def findExpired(dateTime: org.joda.time.DateTime): Future[Seq[AuthTokenRow]] = {
  val action = AuthToken.filter(authToken => authToken.expiry.isBefore(dateTime)).result
  db.run(action)
}

How to cover this use-case correctly/officially in Slick?

Body:
I solved this by reusing the project slick-joda-mapper. This solution is a bit involved because of working with the Slick generator etc but it is VERY clean, I love it. Basically it enables mapping database date time types to the Joda types like org.joda.time.DateTime. Therefore my solution becomes as simple as using comparison operators supported by Joda DateTime:

/**
 * Finds expired tokens.
 *
 * @param dateTime The current date time.
 */
override def findExpired(dateTime: org.joda.time.DateTime): Future[Seq[AuthTokenRow]] = {
  val action = AuthToken.filter(authToken => authToken.expiry < dateTime).result
  db.run(action)
}


来源: stackexchange

问:
There's problem with PDFKit appeared after update to Xcode 10.2. Is there any way to solve?
The app crashes when I try to use pdfkit to display pdf-file. Here's the simple example:

```<code>import UIKit
import PDFKit

class ViewController: UIViewController {

    @IBOutlet weak var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let path = Bundle.main.path(forResource: "file", ofType: "pdf") {
            let url = URL(fileURLWithPath: path)
            if let pdfDocument = PDFDocument(url: url) {
                pdfView.displayMode = .singlePageContinuous
                pdfView.autoScales = true
                // pdfView.displayDirection = .horizontal
                pdfView.document = pdfDocument
            }
        }
    }
}
</code>```

This crashes with "uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'":

```<code>2019-03-26 21:09:47.837837+0400 pdfKitTest[3163:93151] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
2019-03-26 21:09:47.927078+0400 pdfKitTest[3163:93151] *** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010e2326fb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x000000010c8daac5 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010e232555 +[NSException raise:format:] + 197
    3   QuartzCore                          0x00000001112d52ae _ZN2CA5Layer12set_positionERKNS_4Vec2IdEEb + 140
    4   QuartzCore                          0x00000001112c468b -[CALayer setPosition:] + 57
    5   QuartzCore                          0x00000001112c4de3 -[CALayer setFrame:] + 560
    6   PDFKit                              0x000000010c059097 -[PDFPageLayerTile initWithFrame:forPageLayer:withRenderingTransform:tileContentsScale:generationID:] + 168
    7   PDFKit                              0x000000010c05e805 -[PDFPageLayer _updateTiles] + 3439
    8   PDFKit                              0x000000010c059d8e -[PDFPageLayer setNeedsTilesUpdate] + 87
    9   PDFKit                              0x000000010c06e97d -[PDFPageView setNeedsTilesUpdate] + 48
    10  PDFKit                              0x000000010c070816 -[PDFPageView setFrame:] + 334
    11  PDFKit                              0x000000010c06711c -[PDFDocumentView createPageViewForPageAtIndex:] + 764
    12  PDFKit                              0x000000010c068326 -[PDFDocumentView updateVisibility] + 1726
    13  PDFKit                              0x000000010c0d776f -[PDFView resizeDisplayView:] + 517
    14  PDFKit                              0x000000010c0d0cdf -[PDFView layoutDocumentView] + 464
    15  PDFKit                              0x000000010c0cc36a -[PDFView setDocument:waitDuration:] + 1246
    16  pdfKitTest                          0x000000010bd277e2 $s10pdfKitTest14ViewControllerC11viewDidLoadyyF + 1506
    17  pdfKitTest                          0x000000010bd27924 $s10pdfKitTest14ViewControllerC11viewDidLoadyyFTo + 36
    18  UIKitCore                           0x0000000112fda43b -[UIViewController loadViewIfRequired] + 1183
    19  UIKitCore                           0x0000000112fda868 -[UIViewController view] + 27
    20  UIKitCore                           0x0000000113612c33 -[UIWindow addRootViewControllerViewIfPossible] + 122
    21  UIKitCore                           0x0000000113613327 -[UIWindow _setHidden:forced:] + 289
    22  UIKitCore                           0x0000000113625f86 -[UIWindow makeKeyAndVisible] + 42
    23  UIKitCore                           0x00000001135d5f1c -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4555
    24  UIKitCore                           0x00000001135db0c6 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1617
    25  UIKitCore                           0x0000000112e206d6 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 904
    26  UIKitCore                           0x0000000112e28fce +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
    27  UIKitCore                           0x0000000112e202ec -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 236
    28  UIKitCore                           0x0000000112e20c48 -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 1091
    29  UIKitCore                           0x0000000112e1efba __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 782
    30  UIKitCore                           0x0000000112e1ec71 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 433
    31  UIKitCore                           0x0000000112e239b6 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 576
    32  UIKitCore                           0x0000000112e24610 _performActionsWithDelayForTransitionContext + 100
    33  UIKitCore                           0x0000000112e2371d -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 223
    34  UIKitCore                           0x0000000112e286d0 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
    35  UIKitCore                           0x00000001135d99a8 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 514
    36  UIKitCore                           0x0000000113190dfa -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 361
    37  FrontBoardServices                  0x00000001194cd125 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 448
    38  FrontBoardServices                  0x00000001194d6ed6 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 283
    39  FrontBoardServices                  0x00000001194d6700 __40-[FBSWorkspace _performDelegateCallOut:]_block_invoke + 53
    40  libdispatch.dylib                   0x000000010f5c5db5 _dispatch_client_callout + 8
    41  libdispatch.dylib                   0x000000010f5c92ba _dispatch_block_invoke_direct + 300
    42  FrontBoardServices                  0x0000000119508146 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
    43  FrontBoardServices                  0x0000000119507dfe -[FBSSerialQueue _performNext] + 451
    44  FrontBoardServices                  0x0000000119508393 -[FBSSerialQueue _performNextFromRunLoopSource] + 42
    45  CoreFoundation                      0x000000010e199be1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    46  CoreFoundation                      0x000000010e199463 __CFRunLoopDoSources0 + 243
    47  CoreFoundation                      0x000000010e193b1f __CFRunLoopRun + 1231
    48  CoreFoundation                      0x000000010e193302 CFRunLoopRunSpecific + 626
    49  GraphicsServices                    0x00000001166b42fe GSEventRunModal + 65
    50  UIKitCore                           0x00000001135dcba2 UIApplicationMain + 140
    51  pdfKitTest                          0x000000010bd28a7b main + 75
    52  libdyld.dylib                       0x000000010f63a541 start + 1
    53  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

If I comment this line:

```<code> pdfView.document = pdfDocument
</code>```

the app doesn't crash, but pdf-file also doesn't show, of course. How to fix this problem?

答:
As an alternative I would like to point out that you can also resolve (/hack) this issue by refraining from setting the frame for PDFView before viewDidLayoutSubviews (via: Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'). I'm guessing this delays calls that otherwise lead to the crash.

This is useful when moving the pdfView.document = pdfDocument is cumbersome because for instance the PDFView preparation happens outside of the Viewcontroller. (Personally I would have had to change the entire structure of my program to perform the document setting in viewDidLayoutSubviews).

In short, after changing this:

```<code>self.pdfView = PDFView(frame: containerFrame)
</code>```

to this:

```<code>self.pdfView = PDFView()
</code>```

I could set pdfView.document without crashing the app.

ContentLicense: CC BY-SA 4.0

Body:
The app crashes when I try to use pdfkit to display pdf-file. Here's the simple example:

import UIKit
import PDFKit

class ViewController: UIViewController {

    @IBOutlet weak var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let path = Bundle.main.path(forResource: "file", ofType: "pdf") {
            let url = URL(fileURLWithPath: path)
            if let pdfDocument = PDFDocument(url: url) {
                pdfView.displayMode = .singlePageContinuous
                pdfView.autoScales = true
                // pdfView.displayDirection = .horizontal
                pdfView.document = pdfDocument
            }
        }
    }
}

This crashes with "uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'":

2019-03-26 21:09:47.837837+0400 pdfKitTest[3163:93151] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
2019-03-26 21:09:47.927078+0400 pdfKitTest[3163:93151] *** Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010e2326fb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x000000010c8daac5 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010e232555 +[NSException raise:format:] + 197
    3   QuartzCore                          0x00000001112d52ae _ZN2CA5Layer12set_positionERKNS_4Vec2IdEEb + 140
    4   QuartzCore                          0x00000001112c468b -[CALayer setPosition:] + 57
    5   QuartzCore                          0x00000001112c4de3 -[CALayer setFrame:] + 560
    6   PDFKit                              0x000000010c059097 -[PDFPageLayerTile initWithFrame:forPageLayer:withRenderingTransform:tileContentsScale:generationID:] + 168
    7   PDFKit                              0x000000010c05e805 -[PDFPageLayer _updateTiles] + 3439
    8   PDFKit                              0x000000010c059d8e -[PDFPageLayer setNeedsTilesUpdate] + 87
    9   PDFKit                              0x000000010c06e97d -[PDFPageView setNeedsTilesUpdate] + 48
    10  PDFKit                              0x000000010c070816 -[PDFPageView setFrame:] + 334
    11  PDFKit                              0x000000010c06711c -[PDFDocumentView createPageViewForPageAtIndex:] + 764
    12  PDFKit                              0x000000010c068326 -[PDFDocumentView updateVisibility] + 1726
    13  PDFKit                              0x000000010c0d776f -[PDFView resizeDisplayView:] + 517
    14  PDFKit                              0x000000010c0d0cdf -[PDFView layoutDocumentView] + 464
    15  PDFKit                              0x000000010c0cc36a -[PDFView setDocument:waitDuration:] + 1246
    16  pdfKitTest                          0x000000010bd277e2 $s10pdfKitTest14ViewControllerC11viewDidLoadyyF + 1506
    17  pdfKitTest                          0x000000010bd27924 $s10pdfKitTest14ViewControllerC11viewDidLoadyyFTo + 36
    18  UIKitCore                           0x0000000112fda43b -[UIViewController loadViewIfRequired] + 1183
    19  UIKitCore                           0x0000000112fda868 -[UIViewController view] + 27
    20  UIKitCore                           0x0000000113612c33 -[UIWindow addRootViewControllerViewIfPossible] + 122
    21  UIKitCore                           0x0000000113613327 -[UIWindow _setHidden:forced:] + 289
    22  UIKitCore                           0x0000000113625f86 -[UIWindow makeKeyAndVisible] + 42
    23  UIKitCore                           0x00000001135d5f1c -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4555
    24  UIKitCore                           0x00000001135db0c6 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1617
    25  UIKitCore                           0x0000000112e206d6 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 904
    26  UIKitCore                           0x0000000112e28fce +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
    27  UIKitCore                           0x0000000112e202ec -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 236
    28  UIKitCore                           0x0000000112e20c48 -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 1091
    29  UIKitCore                           0x0000000112e1efba __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 782
    30  UIKitCore                           0x0000000112e1ec71 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 433
    31  UIKitCore                           0x0000000112e239b6 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 576
    32  UIKitCore                           0x0000000112e24610 _performActionsWithDelayForTransitionContext + 100
    33  UIKitCore                           0x0000000112e2371d -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 223
    34  UIKitCore                           0x0000000112e286d0 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
    35  UIKitCore                           0x00000001135d99a8 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 514
    36  UIKitCore                           0x0000000113190dfa -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 361
    37  FrontBoardServices                  0x00000001194cd125 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 448
    38  FrontBoardServices                  0x00000001194d6ed6 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 283
    39  FrontBoardServices                  0x00000001194d6700 __40-[FBSWorkspace _performDelegateCallOut:]_block_invoke + 53
    40  libdispatch.dylib                   0x000000010f5c5db5 _dispatch_client_callout + 8
    41  libdispatch.dylib                   0x000000010f5c92ba _dispatch_block_invoke_direct + 300
    42  FrontBoardServices                  0x0000000119508146 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
    43  FrontBoardServices                  0x0000000119507dfe -[FBSSerialQueue _performNext] + 451
    44  FrontBoardServices                  0x0000000119508393 -[FBSSerialQueue _performNextFromRunLoopSource] + 42
    45  CoreFoundation                      0x000000010e199be1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    46  CoreFoundation                      0x000000010e199463 __CFRunLoopDoSources0 + 243
    47  CoreFoundation                      0x000000010e193b1f __CFRunLoopRun + 1231
    48  CoreFoundation                      0x000000010e193302 CFRunLoopRunSpecific + 626
    49  GraphicsServices                    0x00000001166b42fe GSEventRunModal + 65
    50  UIKitCore                           0x00000001135dcba2 UIApplicationMain + 140
    51  pdfKitTest                          0x000000010bd28a7b main + 75
    52  libdyld.dylib                       0x000000010f63a541 start + 1
    53  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

If I comment this line:

 pdfView.document = pdfDocument

the app doesn't crash, but pdf-file also doesn't show, of course. How to fix this problem?

Body:
As an alternative I would like to point out that you can also resolve (/hack) this issue by refraining from setting the frame for PDFView before viewDidLayoutSubviews (via: Terminating app due to uncaught exception 'CALayerInvalidGeometry', reason: 'CALayer position contains NaN: [nan nan]'). I'm guessing this delays calls that otherwise lead to the crash.

This is useful when moving the pdfView.document = pdfDocument is cumbersome because for instance the PDFView preparation happens outside of the Viewcontroller. (Personally I would have had to change the entire structure of my program to perform the document setting in viewDidLayoutSubviews).

In short, after changing this:

self.pdfView = PDFView(frame: containerFrame)

to this:

self.pdfView = PDFView()

I could set pdfView.document without crashing the app.


问:
How do you create a light inside the player?
Im trying to create a light when the player spawns in but im running into multiple problems

I've tried many formats and functions always keep getting either

"Attempt to index nil value"

"[head(and other things)] is not a member of [humanoid(and other things)]"

```<code>game.Players.PlayerAdded:Connect(function(playersdude)
    playersdude.CharacterAdded:Connect(function(char)
        local humanoid = char:WaitForChild("Humanoid")
        local light = Instance.new("PointLight")
        light.Parent = game.Players.LocalPlayer.HumanoidRootPart
    end)
end)

</code>```

答:
You're running into the same problem as this guy : (attempt to index field 'LocalPlayer' (a nil value))

I'm assuming that you've written this in a Script somewhere. LocalPlayercan only be accessed in a LocalScript. Trying to access it from a server Script will result in LocalPlayer being nil. Luckily, you don't need to use LocalPlayer at all!

You can use the char provided in the CharacterAdded connection to find the player's head.

```<code>game.Players.PlayerAdded:Connect(function(playersdude)
    playersdude.CharacterAdded:Connect(function(char)
        -- search through the character model to find the head
        local head = char:FindFirstChild("Head", true)

        -- add a light bright enough to make them glow like the mid-morning sun
        local light = Instance.new("PointLight", head)
        light.Brightness = 100
    end)
end)
</code>```

Body:
Im trying to create a light when the player spawns in but im running into multiple problems

I've tried many formats and functions always keep getting either

"Attempt to index nil value"

"[head(and other things)] is not a member of [humanoid(and other things)]"

game.Players.PlayerAdded:Connect(function(playersdude)
    playersdude.CharacterAdded:Connect(function(char)
        local humanoid = char:WaitForChild("Humanoid")
        local light = Instance.new("PointLight")
        light.Parent = game.Players.LocalPlayer.HumanoidRootPart
    end)
end)

Body:
You're running into the same problem as this guy : (attempt to index field 'LocalPlayer' (a nil value))

I'm assuming that you've written this in a Script somewhere. LocalPlayercan only be accessed in a LocalScript. Trying to access it from a server Script will result in LocalPlayer being nil. Luckily, you don't need to use LocalPlayer at all!

You can use the char provided in the CharacterAdded connection to find the player's head.

game.Players.PlayerAdded:Connect(function(playersdude)
    playersdude.CharacterAdded:Connect(function(char)
        -- search through the character model to find the head
        local head = char:FindFirstChild("Head", true)

        -- add a light bright enough to make them glow like the mid-morning sun
        local light = Instance.new("PointLight", head)
        light.Brightness = 100
    end)
end)


问:
How to Install Driver with a cat file?
I have kernel driver. When installing on 32 bit systems and Windows XP and below, I had no problem and used SetupCopyOEMInf, but 64 bit drivers are required to be signed. I have signed it and I need to have a cat file with the driver copied somewhere on the computer, and this method of install doesn't work. How should I install it?

EDIT: Clarified the question.

答:
In Windows Vista and Windows 7 there a new utility for handling drivers setup call PnPUtil. It handles exactly this kind of work. Just copy all your driver relevant files(*.inf, *.cat, *.sys) to a directory on the target computer and use PnPUtil -i -a <InfName>.inf

Note: You will need to be in an administrator context to successfully use this tool.

ContentLicense: CC BY-SA 3.0

Title: How to Install Driver with a cat file?


问:
How to fix undefined result in $scope select options array?
I'm using AngularJS and trying to set up a select dropbox field with options that are contained in an array, and added via an input box by the end user. I have the $scope successfully adding to the array, but the dropdown select box just shows "undefined" for all options.

I have looked for similar answers but none of them specifically address what my error is, or are using Angular 2+ which doesn't help.

<select class="form-control" id="maidOfHonor" ng-model="name"
        ng-options="names.value as names.value for name in names">
</select>
```

<pre class="lang-js prettyprint-override"><code>$scope.names = [
    {
        name: "Position Not Filled",
        value: "Position Not Filled"
    }
];
$scope.addName = function() {
    $scope.names.push({ name: this.party.addName, value: this.party.addName });
    console.log($scope.names);
}
</code>```

Ideally, I would like whatever "name" that is added via the $scope.addName() function to be added to the dropdown select box as the value or the name, instead of undefined of course.

答:
you can try ng-repeat which is comparatively easier than ng-options

here is a working fiddle

Body:
I'm using AngularJS and trying to set up a select dropbox field with options that are contained in an array, and added via an input box by the end user. I have the $scope successfully adding to the array, but the dropdown select box just shows "undefined" for all options.

I have looked for similar answers but none of them specifically address what my error is, or are using Angular 2+ which doesn't help.

<select class="form-control" id="maidOfHonor" ng-model="name"
        ng-options="names.value as names.value for name in names">
</select>

$scope.names = [
    {
        name: "Position Not Filled",
        value: "Position Not Filled"
    }
];
$scope.addName = function() {
    $scope.names.push({ name: this.party.addName, value: this.party.addName });
    console.log($scope.names);
}

Ideally, I would like whatever "name" that is added via the $scope.addName() function to be added to the dropdown select box as the value or the name, instead of undefined of course.


答:
You need to get an Authenticode signature, create a catalog file, and sign it with that. Microsoft decided that, for 64-bit systems, it will require the driver to come untampered from the vendor, by checking it signature.

(Note: This is not the same as WHQL, which tests the quality of the driver. Authenticode merely indicates that the driver hasn't been tampered with by some malicious user or virus; it doesn't say anything about what the driver does, so it's a relatively easy -- although pricey -- signature to obtain.)

Another solution is test-signing, if you don't plan on redistributing your program.
https://technet.microsoft.com/library/dd919230.aspx

Title: How to Install Driver with a cat file?

Body:
I have kernel driver. When installing on 32 bit systems and Windows XP and below, I had no problem and used SetupCopyOEMInf, but 64 bit drivers are required to be signed. I have signed it and I need to have a cat file with the driver copied somewhere on the computer, and this method of install doesn't work. How should I install it?

EDIT: Clarified the question.


问:
ROKU: How can I add MarkupGrid and Rowlist in same scene?
I'm building my first Roku app and while I'm able to separately render the MarkupGrid and Rowlist, when I try to implement the Rowlist on the same scene as the MarkupGrid, my screen turns black.

I decided to place the RowList in a separate Group Node but I'm not sure how to make the RowList visible within the HomeScene again.

HomeScene.XML

```<code><component name="HomeScene" extends="Scene"  initialFocus = "headerMarkupGrid">

    <script type="text/brightscript" uri="pkg:/components/HomeScene.brs" />

        <children>

        <Poster
                    id="logo"
                    uri="pkg:/images/logo.png"
                    width="350"
                    height="150" />
   <MarkupGrid
            id="headerMarkupGrid"
            translation = "[ 275, 10 ]"
            itemComponentName="TopNavGroup"
            itemSize="[550,150]"
            itemSpacing = "[ 0, 10 ]"
            drawFocusFeedback = "false"
            numRows="1"
            numColumns = "4"
            />

        </children>
</component>
</code>```

HomeScene.brs

```<code> sub init()
    home = m.top.findNode("HomeScene")
        ' grab content from my ContentNode
    MarkupGrid = m.top.findNode("headerMarkupGrid")
    MarkupGrid.content = CreateObject("roSGNode","MarkupGridContent")

    rowList = m.top.findNode("rowList")
    m.top.setFocus(true)
end sub
</code>```

headerRowList.XML

```<code><?xml version="1.0" encoding="utf-8" ?>

<component name="headerRowList" extends="Group"  initialFocus="RowList">

    <children>

       <RowList
            id="RowList"
            itemSpacing = "[ 0, 10 ]"
            itemComponentName="PosterItem"
            itemSize="[1920,300]"
            numRows="3"
            rowItemSize="[[800,400],[400,300]]"
            rowHeights="[500,300]"
            rowItemSpacing="[[30,0],[120,0]]"
            focusXOffset="[300,30]"
            />
    </children>

</component>
</code>```

headerRowList.brs

```<code>Function init()
    m.top.setFocus(true)

    m.RowList = m.top.findNode("RowList")

    content = CreateObject("roSGNode", "ContentNode")
    For i = 1 To 3
        rowContent = content.CreateChild("ContentNode")
        rowContent.TITLE = "Row " + i.ToStr()
        content.AppendChild(rowContent)
    Next
    m.RowList.observeField("content", "rowListContentChanged")
    m.RowList.content = content

    m.LoadTask = CreateObject("roSGNode", "RowListContentTaskVarWidth")
    m.LoadTask.content = content
    m.LoadTask.control = "RUN"

End Function
</code>```

I want the Scene to look something like this:

```<code>[Nav option 1] [Nav option 2] [Nav option 3]
  ----------

{Rowlist that associates with "Nav Option 1" would go here.}
</code>```

答:
Since you've create a separate component for your RowList (named headerRowList), you'll need to reference it in you HomeScene.xml:

```<code><component name="HomeScene" extends="Scene"  initialFocus = "headerMarkupGrid">

    <script type="text/brightscript" uri="pkg:/components/HomeScene.brs" />

    <children>
        <Poster
            id="logo"
            uri="pkg:/images/logo.png"
            width="350"
            height="150" />
        <MarkupGrid
            id="headerMarkupGrid"
            translation="[275,10]"
            itemComponentName="TopNavGroup"
            itemSize="[550,150]"
            itemSpacing="[0,10]"
            drawFocusFeedback="false"
            numRows="1"
            numColumns="4" />
        <HeaderRowList id="rowList" />
    </children>
</component>
</code>```

This will make it visible and accessible in your main scene.

Body:
I'm building my first Roku app and while I'm able to separately render the MarkupGrid and Rowlist, when I try to implement the Rowlist on the same scene as the MarkupGrid, my screen turns black.

I decided to place the RowList in a separate Group Node but I'm not sure how to make the RowList visible within the HomeScene again.

HomeScene.XML

<component name="HomeScene" extends="Scene"  initialFocus = "headerMarkupGrid">

Body:
Since you've create a separate component for your RowList (named headerRowList), you'll need to reference it in you HomeScene.xml:

<component name="HomeScene" extends="Scene"  initialFocus = "headerMarkupGrid">

    <script type="text/brightscript" uri="pkg:/components/HomeScene.brs" />

    <children>
        <Poster
            id="logo"
            uri="pkg:/images/logo.png"
            width="350"
            height="150" />
        <MarkupGrid
            id="headerMarkupGrid"
            translation="[275,10]"
            itemComponentName="TopNavGroup"
            itemSize="[550,150]"
            itemSpacing="[0,10]"
            drawFocusFeedback="false"
            numRows="1"
            numColumns="4" />
        <HeaderRowList id="rowList" />
    </children>
</component>

This will make it visible and accessible in your main scene.


问:
How do I manage / delete my Azure logic app connections
We are building a logic app in Azure.

It consists of an Office 365 new mail item and a service bus queue item.

What we cant work out is how to manage / delete the connections:

Any advice would be greatly appreciated

答: For sake of completeness, you can access the API connections associated to your Logic App from the options menu:


问:
Django sending users to the wrong template location?
I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error.

I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html

but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory.

learning_log\users\urls.py

from django.contrib.auth import views as auth_views

from . import views

app_name = 'users'
urlpatterns = [
    # Login page.
    path('login/',
        auth_views.LoginView.as_view(template_name='users/login.html'),
        name='login'),
]
```

<p>learning_logs\urls.py</p>

<pre class="lang-py prettyprint-override"><code>"""learning_logs URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

"""Defines URL patterns for learning_logs."""

from django.urls import path

from . import views

app_name = 'learning_logs'
urlpatterns = [
    # Home page.
    path('', views.index, name='index'),

    #Show all topics.
    path('topics/', views.topics, name='topics'),

    #Detail page for a single topic.
    path('topics/<int:topic_id>/', views.topic, name='topic'),

    #Page for adding a new topic.
    path('new_topic/', views.new_topic, name='new_topic'),

    #Page for adding a new entry.
    path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),

    #Page for editing an entry.
    path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'),
]
</code>```

learning_log\urls.py

"""learning_log URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('', include('learning_logs.urls')),
]
```

<p>Here is the browser error:</p>

<pre class="lang-py prettyprint-override"><code>TemplateDoesNotExist at /users/login/
users/login.html
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.1
Exception Type:
TemplateDoesNotExist
Exception Value:
users/login.html
Exception Location:
C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py in select_template, line 47
Python Executable:
C:\Users\kevin\Documents\webapps\11_env\Scripts\python.exe
Python Version:
3.7.3
Python Path:
['C:\\Users\\kevin\\Documents\\webapps',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env\\lib\\site-packages']
Server time:
Sun, 26 May 2019 22:14:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\admin\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\auth\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\learning_logs\templates\users\login.html (Source does not exist)
</code>```

Here is the server error:

    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:27] "GET /users/login/ HTTP/1.1" 500 79384
    Not Found: /users/
    [26/May/2019 15:12:39] "GET /users/ HTTP/1.1" 404 3224
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:43] "GET /users/login/ HTTP/1.1" 500 79384
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html

```

答:
double check your templates directory in settings and make sure slashes are forward slashes / not \</p>

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [''],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
</code>```

Body:
I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error.

I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html

but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory.

learning_log\users\urls.py

from django.contrib.auth import views as auth_views

from . import views

app_name = 'users'
urlpatterns = [
    # Login page.
    path('login/',
        auth_views.LoginView.as_view(template_name='users/login.html'),
        name='login'),
]

learning_logs\urls.py

"""learning_logs URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

"""Defines URL patterns for learning_logs."""

from django.urls import path

from . import views

app_name = 'learning_logs'
urlpatterns = [
    # Home page.
    path('', views.index, name='index'),

    #Show all topics.
    path('topics/', views.topics, name='topics'),

    #Detail page for a single topic.
    path('topics/<int:topic_id>/', views.topic, name='topic'),

    #Page for adding a new topic.
    path('new_topic/', views.new_topic, name='new_topic'),

    #Page for adding a new entry.
    path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),

    #Page for editing an entry.
    path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'),
]

learning_log\urls.py

"""learning_log URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('', include('learning_logs.urls')),
]

Here is the browser error:

TemplateDoesNotExist at /users/login/
users/login.html
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.1
Exception Type:
TemplateDoesNotExist
Exception Value:
users/login.html
Exception Location:
C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py in select_template, line 47
Python Executable:
C:\Users\kevin\Documents\webapps\11_env\Scripts\python.exe
Python Version:
3.7.3
Python Path:
['C:\\Users\\kevin\\Documents\\webapps',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env\\lib\\site-packages']
Server time:
Sun, 26 May 2019 22:14:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\admin\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\auth\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\learning_logs\templates\users\login.html (Source does not exist)

Here is the server error:

    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:27] "GET /users/login/ HTTP/1.1" 500 79384
    Not Found: /users/
    [26/May/2019 15:12:39] "GET /users/ HTTP/1.1" 404 3224
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:43] "GET /users/login/ HTTP/1.1" 500 79384
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html

Body:
double check your templates directory in settings and make sure slashes are forward slashes / not \

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [''],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },


问:
Asp .Net Core 2.2 Razor Pages Ajax Call Post not working
I've done so many ajax in razor pages but i can't figure out why this does not work. It keeps giving me error 400 on dev tools. It does not reach the page handler no matter what.

```<code><script>
     $.ajax({
                    url: "/Account/Users/Index?handler=Delete",
                    type: "POST",
                    data: {
                        id: id
                    },
                    success: function () {
                        swal("Utilizador Desactivado!", {
                            icon: "success",
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        swal("Falha na ligação ao servidor. Tente novamente mais tarde.");
                    }
                });
</script>
</code>```

page handler

```<code>  public async Task<IActionResult> OnPostDeleteAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await _context.Users.FindAsync(id);

        if (user != null)
        {
            user.IsActivo = false;
            _context.Users.Attach(user).Property( u => u.IsActivo).IsModified = true;
            await _context.SaveChangesAsync();
        }

        return RedirectToPage("./Index");
    }
</code>```

I tried many url combinations and none work. I don't see what is wrong in here....

EDIT

It seems like the problem is the anti forgery token not being validated on razor page.

I wrote Ignore Anti forgery Token on the page model and everything works correctly

答:
I don't know what you mapping of URL use, but as usual it consists of controllerName/actionName/. In your case try to use:

url: "/Account/OnPostDeleteAsync"

or

url: "/Users/OnPostDeleteAsync"
but if your URL is correct, then try to use [FromForm] attribute

public async Task<IActionResult> OnPostDeleteAsync([FromForm]int? id)

I hope this will help

Body:
I've done so many ajax in razor pages but i can't figure out why this does not work. It keeps giving me error 400 on dev tools. It does not reach the page handler no matter what.

page handler

  public async Task<IActionResult> OnPostDeleteAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await _context.Users.FindAsync(id);

        if (user != null)
        {
            user.IsActivo = false;
            _context.Users.Attach(user).Property( u => u.IsActivo).IsModified = true;
            await _context.SaveChangesAsync();
        }

        return RedirectToPage("./Index");
    }

I tried many url combinations and none work. I don't see what is wrong in here....

EDIT

It seems like the problem is the anti forgery token not being validated on razor page.

I wrote Ignore Anti forgery Token on the page model and everything works correctly


问:
Issue with running optaplanner code via mvn integration-test goal
I have an application that uses Optaplanner to generate a plan. When I write an Integration test and invoke the test from the terminal's command line using mvn integration-test, optaplanner throws an exception. The exception is "java.lang.IllegalStateException: zip file closed" caused by "at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:84)".

The production code works and my hunch is that it is not able to find the solver config resource using this path :

```<code>solverFactoryBase = SolverFactory
                .createFromXmlResource("solver/solverConfig-minDistanceTimeToProcess.xml");
</code>```

This is the exception stack trace:

```<code>java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.ensureOpen(ZipFile.java:686)
    at java.util.zip.ZipFile.access$200(ZipFile.java:60)
    at java.util.zip.ZipFile$ZipEntryIterator.hasNext(ZipFile.java:508)
    at java.util.zip.ZipFile$ZipEntryIterator.hasMoreElements(ZipFile.java:503)
    at java.util.jar.JarFile$JarEntryIterator.hasNext(JarFile.java:253)
    at java.util.jar.JarFile$JarEntryIterator.hasMoreElements(JarFile.java:262)
    at org.reflections.vfs.ZipDir$1$1.computeNext(ZipDir.java:30)
    at org.reflections.vfs.ZipDir$1$1.computeNext(ZipDir.java:26)
    at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:145)
    at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:140)
    at org.reflections.Reflections.scan(Reflections.java:243)
    at org.reflections.Reflections.scan(Reflections.java:202)
    at org.reflections.Reflections.<init>(Reflections.java:123)
    at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:84)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolutionDescriptor(SolverConfig.java:341)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolver(SolverConfig.java:251)
    at org.optaplanner.core.impl.solver.AbstractSolverFactory.buildSolver(AbstractSolverFactory.java:61)
    at com.brc.planner.app.UavRoutePlanner.callSolver(UavRoutePlanner.java:190)
    at com.brc.planner.app.UavRoutePlanner.lambda$createReceive$0(UavRoutePlanner.java:138)
    at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:26)
    at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:21)
    at scala.PartialFunction.applyOrElse(PartialFunction.scala:123)
    at scala.PartialFunction.applyOrElse$(PartialFunction.scala:122)
    at akka.japi.pf.UnitCaseStatement.applyOrElse(CaseStatements.scala:21)
    at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:171)
    at akka.actor.Actor.aroundReceive(Actor.scala:517)
    at akka.actor.Actor.aroundReceive$(Actor.scala:515)
    at akka.actor.AbstractActor.aroundReceive(AbstractActor.scala:180)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:588)
    at akka.actor.ActorCell.invoke(ActorCell.scala:557)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:258)
    at akka.dispatch.Mailbox.run(Mailbox.scala:225)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:235)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
</code>```

答:
Don't confuse createFromXmlResource() with createFromXmlFile().

createFromXmlResource() expects a classpath resource, which is normally in a namespace (= java package), such as "/org/foo/barSolverConfig.xml" to avoid trouble when it gets uber-jarred or zipped.

Body:
I have an application that uses Optaplanner to generate a plan. When I write an Integration test and invoke the test from the terminal's command line using mvn integration-test, optaplanner throws an exception. The exception is "java.lang.IllegalStateException: zip file closed" caused by "at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:84)".

The production code works and my hunch is that it is not able to find the solver config resource using this path :

solverFactoryBase = SolverFactory
                .createFromXmlResource("solver/solverConfig-minDistanceTimeToProcess.xml");

This is the exception stack trace:

java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.ensureOpen(ZipFile.java:686)
    at java.util.zip.ZipFile.access$200(ZipFile.java:60)
    at java.util.zip.ZipFile$ZipEntryIterator.hasNext(ZipFile.java:508)
    at java.util.zip.ZipFile$ZipEntryIterator.hasMoreElements(ZipFile.java:503)
    at java.util.jar.JarFile$JarEntryIterator.hasNext(JarFile.java:253)
    at java.util.jar.JarFile$JarEntryIterator.hasMoreElements(JarFile.java:262)
    at org.reflections.vfs.ZipDir$1$1.computeNext(ZipDir.java:30)
    at org.reflections.vfs.ZipDir$1$1.computeNext(ZipDir.java:26)
    at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:145)
    at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:140)
    at org.reflections.Reflections.scan(Reflections.java:243)
    at org.reflections.Reflections.scan(Reflections.java:202)
    at org.reflections.Reflections.<init>(Reflections.java:123)
    at org.optaplanner.core.config.domain.ScanAnnotatedClassesConfig.buildSolutionDescriptor(ScanAnnotatedClassesConfig.java:84)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolutionDescriptor(SolverConfig.java:341)
    at org.optaplanner.core.config.solver.SolverConfig.buildSolver(SolverConfig.java:251)
    at org.optaplanner.core.impl.solver.AbstractSolverFactory.buildSolver(AbstractSolverFactory.java:61)
    at com.brc.planner.app.UavRoutePlanner.callSolver(UavRoutePlanner.java:190)
    at com.brc.planner.app.UavRoutePlanner.lambda$createReceive$0(UavRoutePlanner.java:138)
    at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:26)
    at akka.japi.pf.UnitCaseStatement.apply(CaseStatements.scala:21)
    at scala.PartialFunction.applyOrElse(PartialFunction.scala:123)
    at scala.PartialFunction.applyOrElse$(PartialFunction.scala:122)
    at akka.japi.pf.UnitCaseStatement.applyOrElse(CaseStatements.scala:21)
    at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:171)
    at akka.actor.Actor.aroundReceive(Actor.scala:517)
    at akka.actor.Actor.aroundReceive$(Actor.scala:515)
    at akka.actor.AbstractActor.aroundReceive(AbstractActor.scala:180)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:588)
    at akka.actor.ActorCell.invoke(ActorCell.scala:557)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:258)
    at akka.dispatch.Mailbox.run(Mailbox.scala:225)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:235)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)


问:
How can I import CSV into table if the CSV does not have all the tables fields?
I am trying to import a CSV file that contains a bunch of data.  The data does not have a Primary Key or a unique identifier, so I created a table with an "id" field that is the primary key and auto increments.

Lets say the table has three fields id, LastName, and FirstName.  My CSV file just has LastName,FirstName.   I am getting a bunch of errors that say Row X does not contain data for all columns.

I have tried to explicitly name the fields I want to add thinking the auto increment would assign a value, it does not work when I do this:

```<code>LOAD DATA LOCAL INFILE '/path/insert.csv' INTO TABLE data (LastName, FirstName);
</code>```

I get the same error, Row X does not contain data for all columns...

I tried to then explicitly set id to be Null by:

```<code>LOAD DATA LOCAL INFILE '/path/insert.csv' INTO TABLE data (id, LastName, FirstName)
SET id=null;
</code>```

Same error Row X does not contain data for all columns.  I have tried:

```<code>LOAD DATA LOCAL INFILE '/path/insert.csv' INTO TABLE data
FIELDS TERMINATED BY ',' LINES TERMINATED BY '/n' SET id=null;
</code>```

When I do that it tries to take the first value in my CSV and assign it to the id field and then gives me an Incorrect Integer Value for column 'id' at row 1.

How can I add data to a table if the CSV file I am using does not contain every single field in the table?  Thank you!

EDIT:

Here are the table fields:

```<code>id        | int(11)  | NO   | PRI | NULL    | auto_increment

LastName  | tinytext | YES  |     | NULL    |

FirstName | tinytext | YES  |     | NULL    |
</code>```

Here is the CSV File:

```<code>Smith,John
Coconut,Joe
Ann,Pattye
</code>```

Those are on diff lines I cannot get the stackoverflow formatting to cooperate.

答:
```<code>LOAD DATA LOCAL
    INFILE '/path/insert.csv'
    INTO TABLE data (@x, LastName, FirstName);
</code>```

That is, put things you don't need or want into @variables.

That technique also provides a way to programmatically modify the text before actually storing.  (See the manual.)

Another approach is to build a table that has a set of columns that matches the input file; LOAD into it; then use INSERT ... SELECT ... to copy stuff over into the 'real' table.  This gives you even more power to adjust your data before storing it into the real place.

Body:
I am trying to import a CSV file that contains a bunch of data.  The data does not have a Primary Key or a unique identifier, so I created a table with an "id" field that is the primary key and auto increments.

Lets say the table has three fields id, LastName, and FirstName.  My CSV file just has LastName,FirstName.   I am getting a bunch of errors that say Row X does not contain data for all columns.

I have tried to explicitly name the fields I want to add thinking the auto increment would assign a value, it does not work when I do this:

LOAD DATA LOCAL INFILE '/path/insert.csv' INTO TABLE data (LastName, FirstName);

I get the same error, Row X does not contain data for all columns...

I tried to then explicitly set id to be Null by:

LOAD DATA LOCAL INFILE '/path/insert.csv' INTO TABLE data (id, LastName, FirstName)
SET id=null;

Same error Row X does not contain data for all columns.  I have tried:

LOAD DATA LOCAL INFILE '/path/insert.csv' INTO TABLE data
FIELDS TERMINATED BY ',' LINES TERMINATED BY '/n' SET id=null;

When I do that it tries to take the first value in my CSV and assign it to the id field and then gives me an Incorrect Integer Value for column 'id' at row 1.

How can I add data to a table if the CSV file I am using does not contain every single field in the table?  Thank you!

EDIT:

Here are the table fields:

id        | int(11)  | NO   | PRI | NULL    | auto_increment

LastName  | tinytext | YES  |     | NULL    |

FirstName | tinytext | YES  |     | NULL    |

Here is the CSV File:

Smith,John
Coconut,Joe
Ann,Pattye

Those are on diff lines I cannot get the stackoverflow formatting to cooperate.

Body:
LOAD DATA LOCAL
    INFILE '/path/insert.csv'
    INTO TABLE data (@x, LastName, FirstName);

That is, put things you don't need or want into @variables.

That technique also provides a way to programmatically modify the text before actually storing.  (See the manual.)

Another approach is to build a table that has a set of columns that matches the input file; LOAD into it; then use INSERT ... SELECT ... to copy stuff over into the 'real' table.  This gives you even more power to adjust your data before storing it into the real place.


问:
form_tag remote true not processing as json request rails 5
I have a form in my application as this

```<code><%= form_tag(studios_path, method: :get, id: "studios_filter", remote: true) do %>

<% end %>
</code>```

in my application.js, i have this

```<code>//= require jquery
//= require jquery_ujs
//= require rails-ujs
//= require jquery3
//= require turbolinks
//= require cocoon
//= require bootstrap
//= require_tree .
</code>```

Both somehow whenever this form is submitted, i get it as this

```<code>Started GET "/studios?utf8=%E2%9C%93&workout_category_id_list=&neighbourhood_list=Kuala+Lumpur&studio_id_list=" for 127.0.0.1 at 2018-12-28 12:42:12 +0800
Processing by StudiosController#index as HTML
</code>```

It is processing as HTML instead of processing as JSON since remote: true is already added.

Any ideas as to why this happening. Running out of options

答:
I struggled with the same issue: Rails 5 was processing my remote: true form submits as HTML no matter what I did. The solution for me was to add

```<code>//= require jquery_ujs
</code>```

to application.js. OP already has this in their file above, which is what made me give it a try. Not sure why OP is still having issues, but this solved it for me ... so maybe this'll solve it for others!

Body:
I have a form in my application as this

<%= form_tag(studios_path, method: :get, id: "studios_filter", remote: true) do %>

<% end %>

in my application.js, i have this

//= require jquery
//= require jquery_ujs
//= require rails-ujs
//= require jquery3
//= require turbolinks
//= require cocoon
//= require bootstrap
//= require_tree .

Both somehow whenever this form is submitted, i get it as this

Started GET "/studios?utf8=%E2%9C%93&workout_category_id_list=&neighbourhood_list=Kuala+Lumpur&studio_id_list=" for 127.0.0.1 at 2018-12-28 12:42:12 +0800
Processing by StudiosController#index as HTML

It is processing as HTML instead of processing as JSON since remote: true is already added.

Any ideas as to why this happening. Running out of options

Body:
I struggled with the same issue: Rails 5 was processing my remote: true form submits as HTML no matter what I did. The solution for me was to add

//= require jquery_ujs

to application.js. OP already has this in their file above, which is what made me give it a try. Not sure why OP is still having issues, but this solved it for me ... so maybe this'll solve it for others!


问:
Create space at the beginning of a UITextField
I want to leave a bit of space at the beginning of a UITextField, just like here:
Add lefthand margin to UITextField

But I don't know how to do that with Swift.

答:
* Extending UITextField in Swift 5 *

```<code>import UIKit

@IBDesignable
extension UITextField {

    @IBInspectable var paddingLeftCustom: CGFloat {
        get {
            return leftView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            leftView = paddingView
            leftViewMode = .always
        }
    }

    @IBInspectable var paddingRightCustom: CGFloat {
        get {
            return rightView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            rightView = paddingView
            rightViewMode = .always
        }
    }

}
</code>```

Body:
* Extending UITextField in Swift 5 *

import UIKit

@IBDesignable
extension UITextField {

    @IBInspectable var paddingLeftCustom: CGFloat {
        get {
            return leftView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            leftView = paddingView
            leftViewMode = .always
        }
    }

    @IBInspectable var paddingRightCustom: CGFloat {
        get {
            return rightView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            rightView = paddingView
            rightViewMode = .always
        }
    }

}


问:
CakePHP 3.x - File Upload Results in Token Mismatch
I have a form that is type => file, with an file upload control.

When I submit this form without a file, it submits as expected.

However, When I submit the form with a file attached, I get a CSRF Token Mismatch.

Any ideas why this might be happening?

EDIT: I noticed that the csrf token is the same when i refresh the page, maybe this is part of the problem?

EDIT-2: When I disable the CSRF protection, the $this->request->getData() array is empty

EDIT-3: I have hooked XDebug up and these are the results...

Apparently $post and $header are null/empty on line 194, resulting in token mismatch

Here is my Form

```<code>    <div class="col-lg-offset-1 col-lg-10">
        <?php if(isset($ledger->id)) { ?>
        <?= $this->Form->create($ledger, ['url' => '/shortcut/ledger_save/' . $ledger->id, 'type' => 'file', 'class' => 'form-horizontal']); ?>
        <?php } else { ?>
        <?= $this->Form->create($ledger, ['url' => '/shortcut/ledger_new', 'type' => 'file', 'class' => 'form-horizontal']); ?>
        <?php } ?>
        <?php $this->Form->setTemplates(['inputContainer' => '{{content}}', 'submitContainer' => '{{content}}']); ?>
        <!-- Default box -->
            <div class="box">
                <div class="box-header with-border">
                    <?php if(isset($ledger->id)) { ?>
                    <h3 class="box-title">Edit <?= $ledger->ledger_title ?> Form</h3>
                    <?php } else { ?>
                    <h3 class="box-title">Create Ledger Form</h3>
                    <?php } ?>
                </div>
                <div class="box-body">
                    <div class="form-group">
                        <center>
                            <?php if($ledger->disabled == 'n') { ?>
                                <?= $this->Form->control('disabled', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal']) ?>  Check to disable (hide) ledger.
                            <?php } else { ?>
                                <?= $this->Form->control('disabled', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'checked']) ?>  Uncheck to enable (show) ledger.
                            <?php } ?>
                        </center>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-2 control-label">Ledger Title</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('ledger_title', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Ledger Title', 'autofocus']) ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Total Plates</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('total_plates', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Total Plates (Total Images)']) ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Total Pages</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('total_pages', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Total Pages (Total Physical Pages)']) ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Check Tribes</label>
                    </div>
                    <div class="form-group">
                        <?php $x = 0; ?>
                        <?php foreach($tribes as $tribe) { ?>
                            <?php if($x == 0) { echo '<div class="form-group"><div class="col-sm-3"> </div>'; } ?>
                                <div class="col-sm-4">
                                    <?php if(in_array($tribe->id, $ledger_tribes)) { ?>
                                    <?= $this->Form->control('tribe_id[]', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => $tribe->id, 'checked']) ?>  <?= $tribe->name ?>
                                    <?php } else { ?>
                                    <?= $this->Form->control('tribe_id[]', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => $tribe->id]) ?>  <?= $tribe->name ?>
                                    <?php } ?>
                                </div>
                            <?php $x = $x + 1; ?>
                            <?php if($x == 2) { echo '</div>'; $x = 0; } ?>
                        <?php } ?>
                        <?php if($x == 1) { echo '</div>'; $x = 0; } ?>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Custodian</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('custodian', ['type' => 'textarea', 'label' => false, 'class' => 'form-control', 'style' => 'width: 100%', 'placeholder' => 'Custodian']) ?>
                            <?php if(!isset($ledger->overwrite_custodian) || $ledger->overwrite_custodian == 'n') { ?>
                                <?= $this->Form->control('overwrite_custodian_checkbox', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => 'y']); ?> Overwrite Plate Custodian
                            <?php } else { ?>
                                <?= $this->Form->control('overwrite_custodian_checkbox', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => 'y', 'checked']); ?> Overwrite Plate Custodian
                            <?php } ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Image Source</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('image_source', ['label' => false, 'type' => 'text', 'class' => 'form-control', 'placeholder' => 'Image Source']) ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Provenance</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('provenance', ['type' => 'textarea', 'label' => false, 'class' => 'form-control', 'style' => 'width: 100%', 'placeholder' => 'Provenance']) ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Global Keywords</label>
                        <div class="col-sm-10">
                            <?php $keywordOptions = []; ?>
                            <?php $keywordValues = []; ?>
                            <?php $foundKeywords = []; ?>
                            <?php foreach($keywords as $keyword) { ?>
                            <?php       if(trim($keyword->keyword) == '') { continue; } ?>
                            <?php       $keywordOptions[$keyword->keyword] = $keyword->keyword; ?>
                            <?php       if(in_array($keyword->keyword, $ledger_keywords)) { $keywordValues[$keyword->id] = $keyword->keyword; $foundKeywords[] = $keyword->keyword; } ?>
                            <?php } ?>
                            <?= $this->Form->select('keyword', $keywordOptions, ['class' => 'form-control select2', 'value' => $keywordValues, 'multiple' => true]); ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Additional Keywords</label>

                        <div class="col-sm-10">
                            <?php $additionalKeywords = ''; ?>
                            <?php foreach($ledger_keywords as $keyword) { ?>
                            <?php       if(in_array($keyword, $foundKeywords) == false) { ?>
                            <?php           $additionalKeywords = $additionalKeywords . $keyword . ', '; ?>
                            <?php       } ?>
                            <?php } ?>
                            <?php $additionalKeywords = substr($additionalKeywords, 0, strlen($additionalKeywords) - 2); ?>

                            <?= $this->Form->control('additional_keywords', ['type' => 'textarea', 'value' => $additionalKeywords, 'label' => false, 'class' => 'form-control', 'style' => 'width: 100%', 'placeholder' => 'Additional Keywords']) ?>

                            <p class="help-block">Seperated by commas.</p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Arist</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('artist', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Artist']) ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Media</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('media', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Media']) ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputPassword3" class="col-sm-2 control-label">Dimensions</label>

                        <div class="col-sm-10">
                            <?= $this->Form->control('dimensions', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Dimensions']) ?>
                        </div>
                    </div>
                    <?php if(!isset($ledger->id)) { ?>
                        <div class="form-group">
                            <label for="exampleInputFile" class="col-sm-2 control-label">Batch Upload</label>

                            <div class="col-sm-10">
                                <?= $this->Form->file('uploadfile', array('label' => false, 'type' => 'file')) ?>

                                <p class="help-block">Select the ledger images archive here.</p>
                            </div>
                        </div>
                    <?php } ?>
                </div>
                <!-- /.box-body -->
                <div class="box-footer">
                    <?= $this->Form->button('Submit', ['type' => 'submit', 'class' => 'btn btn-success btn-pill pull-right']) ?>
                </div>
            <!-- /.box-footer-->
            </div>
        <?= $this->Form->end() ?>
    <!-- /.box -->
    </div>
</code>```

Here is the Form html output

```<code><!-- Main content -->
<section class="content">

    <div class="col-lg-offset-1 col-lg-10">
                    <form enctype="multipart/form-data" method="post" accept-charset="utf-8" class="form-horizontal" action="/shortcut/ledger_new"><div style="display:none;"><input type="hidden" name="_method" value="POST"/><input type="hidden" name="_csrfToken" autocomplete="off" value="06d11527d1e431fd1d1b73a6b96e9af1eec6a1fd6c2ede60cfdb06afdcff5b3c02216614f61ba68bf1bf0beeba8b5f7500319ec94ec278141ee4f480b4a4505f"/></div>

                ..... SNIPPED TO MAKE MAX CHARS ALLOWED ....

                <div class="box-footer">
                    <button type="submit" class="btn btn-success btn-pill pull-right">Submit</button>                    </div>
            <!-- /.box-footer-->
            </div>
                    </form>        <!-- /.box -->
    </div>
</section>
</code>```

Here is the inspection headers

Here is the inspection headers without the file upload populated, as you can see, in the above picture there is no Form Data, and in the below picture there is.

答:
The post_max_size inside the /etc/php.ini file was set to 8M, it has to be set larger than the uploaded file size.

So, what I did was, I set

```<code> post_max_size = 80M
</code>```

and I set

```<code> upload_max_filesize = 60M
</code>```

and the form submitted as expected after that

Body:
I have a form that is type => file, with an file upload control.

When I submit this form without a file, it submits as expected.

However, When I submit the form with a file attached, I get a CSRF Token Mismatch.

Any ideas why this might be happening?

EDIT: I noticed that the csrf token is the same when i refresh the page, maybe this is part of the problem?

EDIT-2: When I disable the CSRF protection, the $this->request->getData() array is empty

EDIT-3: I have hooked XDebug up and these are the results...

Apparently $post and $header are null/empty on line 194, resulting in token mismatch

Here is my Form

        <?php if(isset($ledger->id)) { ?>
        <?= $this->Form->create($ledger, ['url' => '/shortcut/ledger_save/' . $ledger->id, 'type' => 'file', 'class' => 'form-horizontal']); ?>
        <?php } else { ?>
        <?= $this->Form->create($ledger, ['url' => '/shortcut/ledger_new', 'type' => 'file', 'class' => 'form-horizontal']); ?>
        <?php } ?>
        <?php $this->Form->setTemplates(['inputContainer' => '{{content}}', 'submitContainer' => '{{content}}']); ?>

                    <?php if(isset($ledger->id)) { ?>

Edit <?= $ledger->ledger_title ?> Form

                    <?php } else { ?>

Create Ledger Form

                    <?php } ?>

                            <?php if($ledger->disabled == 'n') { ?>
                                <?= $this->Form->control('disabled', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal']) ?>  Check to disable (hide) ledger.
                            <?php } else { ?>
                                <?= $this->Form->control('disabled', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'checked']) ?>  Uncheck to enable (show) ledger.
                            <?php } ?>

                        Ledger Title

                            <?= $this->Form->control('ledger_title', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Ledger Title', 'autofocus']) ?>

                        Total Plates

                            <?= $this->Form->control('total_plates', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Total Plates (Total Images)']) ?>

                        Total Pages

                            <?= $this->Form->control('total_pages', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Total Pages (Total Physical Pages)']) ?>

                        Check Tribes

                        <?php $x = 0; ?>
                        <?php foreach($tribes as $tribe) { ?>
                            <?php if($x == 0) { echo '

'; } ?>

                                    <?php if(in_array($tribe->id, $ledger_tribes)) { ?>
                                    <?= $this->Form->control('tribe_id[]', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => $tribe->id, 'checked']) ?>  <?= $tribe->name ?>
                                    <?php } else { ?>
                                    <?= $this->Form->control('tribe_id[]', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => $tribe->id]) ?>  <?= $tribe->name ?>
                                    <?php } ?>

                            <?php $x = $x + 1; ?>
                            <?php if($x == 2) { echo '
'; $x = 0; } ?>
                        <?php } ?>
                        <?php if($x == 1) { echo '
'; $x = 0; } ?>

                        Custodian

                            <?= $this->Form->control('custodian', ['type' => 'textarea', 'label' => false, 'class' => 'form-control', 'style' => 'width: 100%', 'placeholder' => 'Custodian']) ?>
                            <?php if(!isset($ledger->overwrite_custodian) || $ledger->overwrite_custodian == 'n') { ?>
                                <?= $this->Form->control('overwrite_custodian_checkbox', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => 'y']); ?> Overwrite Plate Custodian
                            <?php } else { ?>
                                <?= $this->Form->control('overwrite_custodian_checkbox', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => 'y', 'checked']); ?> Overwrite Plate Custodian
                            <?php } ?>

                        Image Source

                            <?= $this->Form->control('image_source', ['label' => false, 'type' => 'text', 'class' => 'form-control', 'placeholder' => 'Image Source']) ?>

                        Provenance

                            <?= $this->Form->control('provenance', ['type' => 'textarea', 'label' => false, 'class' => 'form-control', 'style' => 'width: 100%', 'placeholder' => 'Provenance']) ?>

                        Global Keywords

                            <?php $keywordOptions = []; ?>
                            <?php $keywordValues = []; ?>
                            <?php $foundKeywords = []; ?>
                            <?php foreach($keywords as $keyword) { ?>
                            <?php       if(trim($keyword->keyword) == '') { continue; } ?>
                            <?php       $keywordOptions[$keyword->keyword] = $keyword->keyword; ?>
                            <?php       if(in_array($keyword->keyword, $ledger_keywords)) { $keywordValues[$keyword->id] = $keyword->keyword; $foundKeywords[] = $keyword->keyword; } ?>
                            <?php } ?>
                            <?= $this->Form->select('keyword', $keywordOptions, ['class' => 'form-control select2', 'value' => $keywordValues, 'multiple' => true]); ?>

                        Additional Keywords

                            <?php $additionalKeywords = ''; ?>
                            <?php foreach($ledger_keywords as $keyword) { ?>
                            <?php       if(in_array($keyword, $foundKeywords) == false) { ?>
                            <?php           $additionalKeywords = $additionalKeywords . $keyword . ', '; ?>
                            <?php       } ?>
                            <?php } ?>
                            <?php $additionalKeywords = substr($additionalKeywords, 0, strlen($additionalKeywords) - 2); ?>

                            <?= $this->Form->control('additional_keywords', ['type' => 'textarea', 'value' => $additionalKeywords, 'label' => false, 'class' => 'form-control', 'style' => 'width: 100%', 'placeholder' => 'Additional Keywords']) ?>

Seperated by commas.

                        Arist

                            <?= $this->Form->control('artist', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Artist']) ?>

                        Media

                            <?= $this->Form->control('media', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Media']) ?>

                        Dimensions

                            <?= $this->Form->control('dimensions', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Dimensions']) ?>

                    <?php if(!isset($ledger->id)) { ?>

                            Batch Upload

                                <?= $this->Form->file('uploadfile', array('label' => false, 'type' => 'file')) ?>

Select the ledger images archive here.

                    <?php } ?>

                    <?= $this->Form->button('Submit', ['type' => 'submit', 'class' => 'btn btn-success btn-pill pull-right']) ?>

        <?= $this->Form->end() ?>

Here is the Form html output

                    <form enctype="multipart/form-data" method="post" accept-charset="utf-8" class="form-horizontal" action="/shortcut/ledger_new">
<input type="hidden" name="_method" value="POST"/><input type="hidden" name="_csrfToken" autocomplete="off" value="06d11527d1e431fd1d1b73a6b96e9af1eec6a1fd6c2ede60cfdb06afdcff5b3c02216614f61ba68bf1bf0beeba8b5f7500319ec94ec278141ee4f480b4a4505f"/>

                ..... SNIPPED TO MAKE MAX CHARS ALLOWED ....

                    <button type="submit" class="btn btn-success btn-pill pull-right">Submit</button>

                    </form>

Here is the inspection headers

Here is the inspection headers without the file upload populated, as you can see, in the above picture there is no Form Data, and in the below picture there is.

Body:
The post_max_size inside the /etc/php.ini file was set to 8M, it has to be set larger than the uploaded file size.

So, what I did was, I set

 post_max_size = 80M

and I set

 upload_max_filesize = 60M

and the form submitted as expected after that


问:
No module named import_export although it is installed
I'm trying to use django-import-export in my django site. I installed it in my virtual environment using "pip install django-import-export" and I know it's there because I ran pip freeze but it still gives an error when I do "eb create django-env": "ModuleNotFoundError: No module named 'import_export'".

It is included in INSTALLED_APPS in settings.py and I ran "python manage.py collectstatic" before I got the error.

```<code>2019-05-26 06:21:41    ERROR   [Instance: i-08f7c48c9afd84a8f] Command failed on instance. Return code: 1 Output: (TRUNCATED)...ile "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'import_export'.
container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.
2019-05-26 06:21:41    INFO    Command execution completed on all instances. Summary: [Successful: 0, Failed: 1].
2019-05-26 06:22:44    ERROR   Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.

ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.
</code>```

I am a beginner and this is my first question on StackOverflow. I appreciate any help.

答:
I think I understand what I did wrong before. I checked the requirements.txt file in my environment and it didn't mention django-import-export.

"Elastic Beanstalk uses requirements.txt to determine which package to install on the EC2 instances that run your application."

So I did pip freeze > requirements.txt, then checked to make sure that the requirements.txt file was updated. After that the deployment worked and I can now see the import button in the admin!

Body:
I'm trying to use django-import-export in my django site. I installed it in my virtual environment using "pip install django-import-export" and I know it's there because I ran pip freeze but it still gives an error when I do "eb create django-env": "ModuleNotFoundError: No module named 'import_export'".

It is included in INSTALLED_APPS in settings.py and I ran "python manage.py collectstatic" before I got the error.

2019-05-26 06:21:41    ERROR   [Instance: i-08f7c48c9afd84a8f] Command failed on instance. Return code: 1 Output: (TRUNCATED)...ile "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'import_export'.
container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.
2019-05-26 06:21:41    INFO    Command execution completed on all instances. Summary: [Successful: 0, Failed: 1].
2019-05-26 06:22:44    ERROR   Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.

ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation.

I am a beginner and this is my first question on StackOverflow. I appreciate any help.