问:
Response Data via URLSessionUploadTask
I am writing simple handler for communication with REST API on server (currently local). Everything goes well so far with downloading and uploading data from/to server.

What I am trying to achieve now is to be able to handle JSON response returned by server after uploading data. This message is something like this:

```<code>{"message":"Record successfully added.","recordID":30}
</code>```

Important is for me the recordID, because I need to assign it to relevant NSManagedObject. I use delegation attitude instead of completionHandler so I would be able to manage progress of the upload. Appropriate delegate class implements these protocols with all methods:

```<code>class ConstructoHTTPHelper:NSObject, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate, URLSessionStreamDelegate { ... }
</code>```

Here comes the issue because as far as I create upload task with something like this:

```<code>let config = URLSessionConfiguration.default
self.session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) //URLSession(configuration: config)
var request:URLRequest = URLRequest(url:address)
request.httpMethod = "POST"
let data = // creation of data ...
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("uploadData")
do {
   try data.write(to: fileURL)
}   catch {
   // handling error
}
self.sessionUploadTask = self.session?.uploadTask(with: request, fromFile: fileURL)
self.sessionUploadTask!.resume()
</code>```

The delegate func for handling data:

```<code>func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}
</code>```

returned by server is never called.
What is strange to me is that when I use completion Handler like the one below, It prints the JSON well:

```<code>self.sessionUploadTask = self.session?.uploadTask(with: request, from: data, completionHandler: { (data, response, error) in
   print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
})
</code>```

So it looks to me that uploadTask is limited in this way. Any suggestions?

Thanks

答:
try this!, get a NSMutableData as buffer like this globally

```<code>fileprivate var buffer:NSMutableData = NSMutableData()
</code>```

and in your URLSession delegate method add,

```<code>func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  if let _ = error {
        print(error!.localizedDescription)
    }else {
      // do your parsing with buffer here.
    }
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    buffer.append(data)
}
</code>```

Title: Response Data via URLSessionUploadTask

Body:
I am writing simple handler for communication with REST API on server (currently local). Everything goes well so far with downloading and uploading data from/to server.

What I am trying to achieve now is to be able to handle JSON response returned by server after uploading data. This message is something like this:

{"message":"Record successfully added.","recordID":30}

Important is for me the recordID, because I need to assign it to relevant NSManagedObject. I use delegation attitude instead of completionHandler so I would be able to manage progress of the upload. Appropriate delegate class implements these protocols with all methods:

class ConstructoHTTPHelper:NSObject, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate, URLSessionStreamDelegate { ... }

Here comes the issue because as far as I create upload task with something like this:

let config = URLSessionConfiguration.default
self.session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) //URLSession(configuration: config)
var request:URLRequest = URLRequest(url:address)
request.httpMethod = "POST"
let data = // creation of data ...
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("uploadData")
do {
   try data.write(to: fileURL)
}   catch {
   // handling error
}
self.sessionUploadTask = self.session?.uploadTask(with: request, fromFile: fileURL)
self.sessionUploadTask!.resume()

The delegate func for handling data:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}

returned by server is never called.
What is strange to me is that when I use completion Handler like the one below, It prints the JSON well:

self.sessionUploadTask = self.session?.uploadTask(with: request, from: data, completionHandler: { (data, response, error) in
   print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)
})

So it looks to me that uploadTask is limited in this way. Any suggestions?

Thanks

Body:
try this!, get a NSMutableData as buffer like this globally

fileprivate var buffer:NSMutableData = NSMutableData()

and in your URLSession delegate method add,

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  if let _ = error {
        print(error!.localizedDescription)
    }else {
      // do your parsing with buffer here.
    }
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    buffer.append(data)
}


来源: stackexchange

问:
Transferring text range from 1 power point to another to change template
I am very new with Powerpoint VBA and would like to know if there is a short way to transfer one text range from PowerPoint A to another text range located in Powerpoint B in a specific sequence.

Page a1 = b1

Page a2 = b2

Page a3 = b3

The template is changing and I need to adapt 5 powerpoints of 100 slides so I tought it would be easier with this solution.

Thank you in advance for your help.

PRECISION : I don't want to copy and paste the text range but to copy the text inside the range to put it inside the new range. Please find below the code I already have but It doesnt' Paste it inside my new range.

```<code>Sub copier_texte()  'je veux copier le contenu de la forme, et non pas la forme en entier

Dim nb_slide As Integer
nb_slide = ActivePresentation.Slides.Count

With ActivePresentation
.Slides(1).Shapes(2).TextFrame.TextRange.Copy 'je sélectionne uniquement le contenu de la forme
For i = 2 To .Slides.Count
        .Slides(i).Select
        ActiveWindow.View.Paste
Next i
End With

End Sub
</code>```

答:
Your question has a number of different interpretations, below is my attempt to answer what I believe the question is. There are a number of stage to this solution.

1. Ensure we save the VBA we write

Firstly, we have to assume a master presentation, that is one that will hold the values to be copied into all others. This will need to be saved as a macro enabled presentation (pptm) to allow us to save our VBA. This is done via File > Save-As and while selecting the save location choose PowerPoint Macro-Enabled Presentation in the Save as type box.

2. Enable Windows scripting runtime

Within the pptm 'master' presentation that we now have, open the VBA IDE (Alt+F11). In the menu bar select Tools > References... and tick Microsoft Scripting Runtime from the list that is presented. Click OK to close the references dialog box with your tick remembered. This is needed for some error handling in the code, it checks to see if the presentation exists before trying to open it.

3. Insert the provided code

Right-click on VBAProject in the upper right area (the Project explorer) and select Insert > Module.

In the main editing area paste the below (I have added commenting to describe what is happening): -

```<code>Option Explicit

Public Sub Update()
Dim AryPresentations(4) As String
Dim LngPID              As Long
Dim FSO                 As New FileSystemObject
Dim PP_Src              As Presentation
Dim PP_Dest             As Presentation
Dim Sld_Src             As Slide
Dim Sld_Dest            As Slide
Dim Shp_Src             As Shape
Dim Shp_Dest            As Shape
Dim LngFilesMissing     As Long
Dim BlnWasOpen          As Boolean

'If there is an error, this will handle it and stop the process
On Error GoTo ErrorHandle

'Increase the size of AryPresentations and and the paths as shown in the example below
AryPresentations(0) = "C:\Users\garye\Desktop\PP2.pptx"
AryPresentations(1) = "C:\Users\garye\Desktop\PP3.pptx"
AryPresentations(2) = "C:\Users\garye\Desktop\PP4.pptx"
AryPresentations(3) = "C:\Users\garye\Desktop\PP5.pptx"
AryPresentations(4) = "C:\Users\garye\Desktop\PP6.pptx"

'PP_Src is this, our 'master' presentation
Set PP_Src = ActivePresentation

'This loops through each item in AryPresentations
For LngPID = 0 To UBound(AryPresentations, 1)

    'We rememeber if you had it open already as if you did, then we won't close it when we are done
    BlnWasOpen = False

    'Check all currently open presentations to see if one if the presentation we are due to update
    For Each PP_Dest In PowerPoint.Presentations
        If Trim(UCase(PP_Dest.FullName)) = Trim(UCase(AryPresentations(LngPID))) Then Exit For
    Next

    'If it was not already open, check it exists and if it does, then open in
    If PP_Dest Is Nothing Then
        If FSO.FileExists(AryPresentations(LngPID)) Then
            Set PP_Dest = PowerPoint.Presentations.Open(AryPresentations(LngPID))
        End If
    Else
        BlnWasOpen = True
    End If

    If PP_Dest Is Nothing Then
        Debug.Print "File note found"
        LngFilesMissing = LngFilesMissing + 1
    Else
        'The below connects to the slide (Sld_Src) you want to pick up from, the shape (Shp_Src) you want to pick up from and then
        'places it in the slide (Sld_Dest) you want it to go to into the shape (Shp_Dest) you want it to go in to
        Set Sld_Src = PP_Src.Slides(1)
            Set Sld_Dest = PP_Dest.Slides(1)
                Set Shp_Src = Sld_Src.Shapes(1)
                    Set Shp_Dest = Sld_Dest.Shapes(1)
                        Shp_Dest.TextFrame.TextRange.Text = Shp_Src.TextFrame.TextRange.Text
                    Set Shp_Dest = Nothing
                Set Shp_Src = Nothing
            Set Sld_Dest = Nothing
        Set Sld_Src = Nothing
        'Repeat the above for each piece of text to copy

        'Finally save the changes
        PP_Dest.Save

        'Close the presentation if it was not already open
        If Not BlnWasOpen Then PP_Dest.Close

    End If
Next

MsgBox "Process complete. Number of missing files: " & LngFilesMissing, vbOKOnly + vbInformation, "Complete"

Exit Sub
</code>```

ErrorHandle:
    MsgBox "There was an error: - " & vbNewLine & vbNewLine & Err.Number & ": " & Err.Description, vbOKOnly + vbExclamation, "Error"
    Err.Clear
    End Sub

4. Customise code

You'll want to add the paths and location of the changes in and then it should run.

ContentLicense: CC BY-SA 4.0

Body:
I am very new with Powerpoint VBA and would like to know if there is a short way to transfer one text range from PowerPoint A to another text range located in Powerpoint B in a specific sequence.

Page a1 = b1

Page a2 = b2

Page a3 = b3

The template is changing and I need to adapt 5 powerpoints of 100 slides so I tought it would be easier with this solution.

Thank you in advance for your help.

PRECISION : I don't want to copy and paste the text range but to copy the text inside the range to put it inside the new range. Please find below the code I already have but It doesnt' Paste it inside my new range.

Sub copier_texte()  'je veux copier le contenu de la forme, et non pas la forme en entier

Dim nb_slide As Integer
nb_slide = ActivePresentation.Slides.Count

With ActivePresentation
.Slides(1).Shapes(2).TextFrame.TextRange.Copy 'je sélectionne uniquement le contenu de la forme
For i = 2 To .Slides.Count
        .Slides(i).Select
        ActiveWindow.View.Paste
Next i
End With

End Sub

Body:
Your question has a number of different interpretations, below is my attempt to answer what I believe the question is. There are a number of stage to this solution.

1. Ensure we save the VBA we write

Firstly, we have to assume a master presentation, that is one that will hold the values to be copied into all others. This will need to be saved as a macro enabled presentation (pptm) to allow us to save our VBA. This is done via File > Save-As and while selecting the save location choose PowerPoint Macro-Enabled Presentation in the Save as type box.

2. Enable Windows scripting runtime

Within the pptm 'master' presentation that we now have, open the VBA IDE (Alt+F11). In the menu bar select Tools > References... and tick Microsoft Scripting Runtime from the list that is presented. Click OK to close the references dialog box with your tick remembered. This is needed for some error handling in the code, it checks to see if the presentation exists before trying to open it.

3. Insert the provided code

Right-click on VBAProject in the upper right area (the Project explorer) and select Insert > Module.

In the main editing area paste the below (I have added commenting to describe what is happening): -

Option Explicit

Public Sub Update()
Dim AryPresentations(4) As String
Dim LngPID              As Long
Dim FSO                 As New FileSystemObject
Dim PP_Src              As Presentation
Dim PP_Dest             As Presentation
Dim Sld_Src             As Slide
Dim Sld_Dest            As Slide
Dim Shp_Src             As Shape
Dim Shp_Dest            As Shape
Dim LngFilesMissing     As Long
Dim BlnWasOpen          As Boolean

'If there is an error, this will handle it and stop the process
On Error GoTo ErrorHandle

'Increase the size of AryPresentations and and the paths as shown in the example below
AryPresentations(0) = "C:\Users\garye\Desktop\PP2.pptx"
AryPresentations(1) = "C:\Users\garye\Desktop\PP3.pptx"
AryPresentations(2) = "C:\Users\garye\Desktop\PP4.pptx"
AryPresentations(3) = "C:\Users\garye\Desktop\PP5.pptx"
AryPresentations(4) = "C:\Users\garye\Desktop\PP6.pptx"

'PP_Src is this, our 'master' presentation
Set PP_Src = ActivePresentation

'This loops through each item in AryPresentations
For LngPID = 0 To UBound(AryPresentations, 1)

    'We rememeber if you had it open already as if you did, then we won't close it when we are done
    BlnWasOpen = False

    'Check all currently open presentations to see if one if the presentation we are due to update
    For Each PP_Dest In PowerPoint.Presentations
        If Trim(UCase(PP_Dest.FullName)) = Trim(UCase(AryPresentations(LngPID))) Then Exit For
    Next

    'If it was not already open, check it exists and if it does, then open in
    If PP_Dest Is Nothing Then
        If FSO.FileExists(AryPresentations(LngPID)) Then
            Set PP_Dest = PowerPoint.Presentations.Open(AryPresentations(LngPID))
        End If
    Else
        BlnWasOpen = True
    End If

    If PP_Dest Is Nothing Then
        Debug.Print "File note found"
        LngFilesMissing = LngFilesMissing + 1
    Else
        'The below connects to the slide (Sld_Src) you want to pick up from, the shape (Shp_Src) you want to pick up from and then
        'places it in the slide (Sld_Dest) you want it to go to into the shape (Shp_Dest) you want it to go in to
        Set Sld_Src = PP_Src.Slides(1)
            Set Sld_Dest = PP_Dest.Slides(1)
                Set Shp_Src = Sld_Src.Shapes(1)
                    Set Shp_Dest = Sld_Dest.Shapes(1)
                        Shp_Dest.TextFrame.TextRange.Text = Shp_Src.TextFrame.TextRange.Text
                    Set Shp_Dest = Nothing
                Set Shp_Src = Nothing
            Set Sld_Dest = Nothing
        Set Sld_Src = Nothing
        'Repeat the above for each piece of text to copy

        'Finally save the changes
        PP_Dest.Save

        'Close the presentation if it was not already open
        If Not BlnWasOpen Then PP_Dest.Close

    End If
Next

MsgBox "Process complete. Number of missing files: " & LngFilesMissing, vbOKOnly + vbInformation, "Complete"

Exit Sub

ErrorHandle:
    MsgBox "There was an error: - " & vbNewLine & vbNewLine & Err.Number & ": " & Err.Description, vbOKOnly + vbExclamation, "Error"
    Err.Clear
    End Sub

4. Customise code

You'll want to add the paths and location of the changes in and then it should run.

ContentLicense: CC BY-SA 3.0


问:
Log4jConfigListener not working if log4j jar is in webApp's lib
I come across log4j initialization error, while deploying multiple war files in tomcat.
I have all of the dependencies in Tomcat/lib, except log4j.jar, which is in webApp's web-inf , lib folder. and log4j.properties in web-inf/classes folder.

Since App1.war and App2.war have their own log4j, i have kept the log4j.jar in respective web Apps lib folder.

Then I get below error,

```<code>29-May-2017 13:15:01.871 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing log4j from [file:D:\Users\vissurve\Softwares\apache-tomcat-9.0.0.M17-windows-x64\apache-tomcat-9.0.0.M17\webapps\sho-sp-item\WEB-INF\classes\log4j.properties]
29-May-2017 13:15:01.875 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.springframework.web.util.Log4jConfigListener
 java.lang.NoClassDefFoundError: org/apache/log4j/PropertyConfigurator
    at org.springframework.util.Log4jConfigurer.initLogging(Log4jConfigurer.java:78)
    at org.springframework.web.util.Log4jWebConfigurer.initLogging(Log4jWebConfigurer.java:154)
    at org.springframework.web.util.Log4jConfigListener.contextInitialized(Log4jConfigListener.java:49)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.PropertyConfigurator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more

29-May-2017 13:15:01.887 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Shutting down log4j
29-May-2017 13:15:01.888 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStop Exception sending context destroyed event to listener instance of class org.springframework.web.util.Log4jConfigListener
 java.lang.NoClassDefFoundError: org/apache/log4j/LogManager
    at org.springframework.util.Log4jConfigurer.shutdownLogging(Log4jConfigurer.java:123)
    at org.springframework.web.util.Log4jWebConfigurer.shutdownLogging(Log4jWebConfigurer.java:172)
    at org.springframework.web.util.Log4jConfigListener.contextDestroyed(Log4jConfigListener.java:54)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4764)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5401)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:187)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.LogManager
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 17 more
</code>```

Please suggest. I have googled a lot, there are similar post but some how my issue does not get solved with those solutions.

Each war's web.xml is like below,

```<code><context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>SomeUniqueValue</param-value>
</context-param>

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>file:${catalina.base}\webapps\MyAppName\WEB-INF\classes\log4j.properties</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
</code>```

It works fine if I move log4j.jar in tomcat/lib folder instead but then it starts logging all logs in one log file.

Please suggest, why can't it find the dependencies if they are in tomcat/lib.

答:
This is how I fixed the above problem.

Tomcat : PreResources tag not loading jars

Also, my log4j and apachecommons and all other jars are now externalized and does not make my war file huge and bulky. A common tomcat's context.xml loadeds all jars.

Body:
I come across log4j initialization error, while deploying multiple war files in tomcat.
I have all of the dependencies in Tomcat/lib, except log4j.jar, which is in webApp's web-inf , lib folder. and log4j.properties in web-inf/classes folder.

Since App1.war and App2.war have their own log4j, i have kept the log4j.jar in respective web Apps lib folder.

Then I get below error,

29-May-2017 13:15:01.871 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing log4j from [file:D:\Users\vissurve\Softwares\apache-tomcat-9.0.0.M17-windows-x64\apache-tomcat-9.0.0.M17\webapps\sho-sp-item\WEB-INF\classes\log4j.properties]
29-May-2017 13:15:01.875 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.springframework.web.util.Log4jConfigListener
 java.lang.NoClassDefFoundError: org/apache/log4j/PropertyConfigurator
    at org.springframework.util.Log4jConfigurer.initLogging(Log4jConfigurer.java:78)
    at org.springframework.web.util.Log4jWebConfigurer.initLogging(Log4jWebConfigurer.java:154)
    at org.springframework.web.util.Log4jConfigListener.contextInitialized(Log4jConfigListener.java:49)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4717)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.PropertyConfigurator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more

29-May-2017 13:15:01.887 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Shutting down log4j
29-May-2017 13:15:01.888 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStop Exception sending context destroyed event to listener instance of class org.springframework.web.util.Log4jConfigListener
 java.lang.NoClassDefFoundError: org/apache/log4j/LogManager
    at org.springframework.util.Log4jConfigurer.shutdownLogging(Log4jConfigurer.java:123)
    at org.springframework.web.util.Log4jWebConfigurer.shutdownLogging(Log4jWebConfigurer.java:172)
    at org.springframework.web.util.Log4jConfigListener.contextDestroyed(Log4jConfigListener.java:54)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4764)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5401)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:257)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:187)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.LogManager
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 17 more

Please suggest. I have googled a lot, there are similar post but some how my issue does not get solved with those solutions.

Each war's web.xml is like below,

<context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>SomeUniqueValue</param-value>
</context-param>

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>file:${catalina.base}\webapps\MyAppName\WEB-INF\classes\log4j.properties</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

It works fine if I move log4j.jar in tomcat/lib folder instead but then it starts logging all logs in one log file.

Please suggest, why can't it find the dependencies if they are in tomcat/lib.


问:
how to check key existence for dictionary within a dictionary in C#
In below code, how can I check key existence for dictionary within a dictionary?

Current execution throws key existence error.

Output,
For Key "a", another key "X" with both values 1 and 2

Do we have any better collection for this?

```<code> var data = new Dictionary<string, Dictionary<string, object>>();

        foreach (var j in GetTopData())
        {
            foreach (var p in BottomData())
            {
                if (data.Keys.Contains(j.ToString()))
                {
                    data[j].Add(p.Name, p.Value);
                }
                else
                {
                    data.Add(j, new Dictionary<string, object> { { p.Name, p.Value } });
                }
            }
        }
</code>```

Here are the data classes,

```<code>private static List<TempData> BottomData()
    {
        return new List<TempData>
        {
            new TempData{ Name="X", Value=1},
            new TempData{ Name="X", Value=2}
        };
    }

    private static List<string> GetTopData()
    {
        return new List<string> { "a"};
    }

public class TempData
{
    public string Name { get; set; }
    public object Value { get; set; }
}
</code>```

答:
Because you need one key to contain multiple values, Dictionary<string, Dictionary<string, object>> will not work for you (it allows only 1 value for particular key). You can use Dictionary<string, Dictionary<string, List<object>>>, but it is hard to read and difficult to work with. So I thing it is better to use Dictionary, where both keys are combined into one as shown bellow in CombinedKey class (in C# 7.0, ValueTuple<string, string> will work too):

```<code>public class CombinedKey
{
    public string Key1;
    public string Key2;

    // It is necessary to override Equals and GetHashCode to make
    // it work properly as a dictionary key.
    public override bool Equals(object obj)
    {
        var otherCombinedKey = obj as CombinedKey;

        return otherCombinedKey != null
            && otherCombinedKey.Key1 == this.Key1
            && otherCombinedKey.Key2 == this.Key2;
    }

    public override int GetHashCode()
    {
        return Key1.GetHashCode() ^ Key2.GetHashCode();
    }
}
</code>```

Then use it this way:

```<code>Dictionary<CombinedKey, List<object>> data = new Dictionary<CombinedKey, List<object>>();

foreach (var j in GetTopData())
{
    foreach (var p in BottomData())
    {
        var key = new CombinedKey() { Key1 = j, Key2 = p.Name };
        List<object> list;
        if(!data.TryGetValue(key, out list))
        {
            data[key] = list = new List<object>();
        }
        list.Add(p.Value);
    }
}
</code>```

If your data are immutable, you could also use Lookup<CombinedKey, object> class instead.

Body:
In below code, how can I check key existence for dictionary within a dictionary?

Current execution throws key existence error.

Output,
For Key "a", another key "X" with both values 1 and 2

Do we have any better collection for this?

 var data = new Dictionary<string, Dictionary<string, object>>();

        foreach (var j in GetTopData())
        {
            foreach (var p in BottomData())
            {
                if (data.Keys.Contains(j.ToString()))
                {
                    data[j].Add(p.Name, p.Value);
                }
                else
                {
                    data.Add(j, new Dictionary<string, object> { { p.Name, p.Value } });
                }
            }
        }

Here are the data classes,

private static List<TempData> BottomData()
    {
        return new List<TempData>
        {
            new TempData{ Name="X", Value=1},
            new TempData{ Name="X", Value=2}
        };
    }

    private static List<string> GetTopData()
    {
        return new List<string> { "a"};
    }

public class TempData
{
    public string Name { get; set; }
    public object Value { get; set; }
}

Body:
Because you need one key to contain multiple values, Dictionary<string, Dictionary<string, object>> will not work for you (it allows only 1 value for particular key). You can use Dictionary<string, Dictionary<string, List<object>>>, but it is hard to read and difficult to work with. So I thing it is better to use Dictionary, where both keys are combined into one as shown bellow in CombinedKey class (in C# 7.0, ValueTuple<string, string> will work too):

public class CombinedKey
{
    public string Key1;
    public string Key2;

    // It is necessary to override Equals and GetHashCode to make
    // it work properly as a dictionary key.
    public override bool Equals(object obj)
    {
        var otherCombinedKey = obj as CombinedKey;

        return otherCombinedKey != null
            && otherCombinedKey.Key1 == this.Key1
            && otherCombinedKey.Key2 == this.Key2;
    }

    public override int GetHashCode()
    {
        return Key1.GetHashCode() ^ Key2.GetHashCode();
    }
}

Then use it this way:

Dictionary<CombinedKey, List<object>> data = new Dictionary<CombinedKey, List<object>>();

foreach (var j in GetTopData())
{
    foreach (var p in BottomData())
    {
        var key = new CombinedKey() { Key1 = j, Key2 = p.Name };
        List<object> list;
        if(!data.TryGetValue(key, out list))
        {
            data[key] = list = new List<object>();
        }
        list.Add(p.Value);
    }
}

If your data are immutable, you could also use Lookup<CombinedKey, object> class instead.


问:
Spinner#setDropDownVerticalOffset for API lower 16
I'm using Spinner and I have an issue that setDropDownVerticalOffset() solves perfectly, but my min api level is 14 and method's min required is 16.

How to use that method for APIs lower 16?

答: Use android.support.v7.widget.AppCompatSpinner instead of android.widget.Spinner.


问:
how do you write the output of this script to a file
gives you the no.of days in a particular month</p>

```<code>enter code here
month_name = input("Input the name of Month: ")
if month_name == "February":
   print("No. of days: 28/29 ")
elif month_name in ("April", "June", "September", "November"):
   print("No. of days: 30 ")
elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
   print("No. of days: 31 ")
else:
   print("Wrong month name/write the name of the month with an uppercase at the begining")
</code>```

答:
You have tagged this question Python-2.7 but it looks to me as if you are actually writing Python 3.

Which means there is an issue with your code: when you use input() in Python 2 it expects the input to be a valid Python expression. But you are not telling your user to enclose their input in quotes. If they respond to your prompt like this (as any reasonable user would):

```<code>Input the name of Month: January
</code>```

your program will fail with the error NameError: name 'January' is not defined. In Python 2.7 use raw_input() instead.

Also in Python 2.7, you need to have from __future__ import print_function at the top of your program to get the same behaviour as Python 3. I'm not going to offer you the Python 2 print statement syntax because there is no point in your learning it.

To write to a file, first open it and then name it as the file parameter of your print() call, like this:

```<code>from __future__ import print_function
with open("myfile.txt","w") as output:
    month_name = raw_input("Input the name of Month: ") # change to input() in Python 3
    if month_name == "February":
       print("No. of days: 28/29 ",file=output)
    elif month_name in ("April", "June", "September", "November"):
       print("No. of days: 30 ",file=output)
    elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
       print("No. of days: 31 ",file=output)
    else:
       print("Wrong month name/write the name of the month with an uppercase at the beginning")
</code>```

Apart from raw_input() this code will work in Python 2.7 and in Python 3.6.

Body:
gives you the no.of days in a particular month

enter code here
month_name = input("Input the name of Month: ")
if month_name == "February":
   print("No. of days: 28/29 ")
elif month_name in ("April", "June", "September", "November"):
   print("No. of days: 30 ")
elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
   print("No. of days: 31 ")
else:
   print("Wrong month name/write the name of the month with an uppercase at the begining")

Body:
You have tagged this question Python-2.7 but it looks to me as if you are actually writing Python 3.

Which means there is an issue with your code: when you use input() in Python 2 it expects the input to be a valid Python expression. But you are not telling your user to enclose their input in quotes. If they respond to your prompt like this (as any reasonable user would):

Input the name of Month: January

your program will fail with the error NameError: name 'January' is not defined. In Python 2.7 use raw_input() instead.

Also in Python 2.7, you need to have from __future__ import print_function at the top of your program to get the same behaviour as Python 3. I'm not going to offer you the Python 2 print statement syntax because there is no point in your learning it.

To write to a file, first open it and then name it as the file parameter of your print() call, like this:

from __future__ import print_function
with open("myfile.txt","w") as output:
    month_name = raw_input("Input the name of Month: ") # change to input() in Python 3
    if month_name == "February":
       print("No. of days: 28/29 ",file=output)
    elif month_name in ("April", "June", "September", "November"):
       print("No. of days: 30 ",file=output)
    elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
       print("No. of days: 31 ",file=output)
    else:
       print("Wrong month name/write the name of the month with an uppercase at the beginning")

Apart from raw_input() this code will work in Python 2.7 and in Python 3.6.


问:
Pandas - Merge Two Dataframes - sum across column
I am trying to merge two dataframes (call them DF1 & DF2) that basically look like the below.  My goal is:

I want open/close/low/high to all come from DF1.

I want numEvents and Volume = DF1 + DF2.

In cases where DF2 has rows that don't exist in DF1, I want open/close/low/high to be NaN (so I can later backfill them), and numEvents and Volume to come from DF2 as is.

Any help is much appreciated!

答:
Use the left_on and right_on attributes of pd.merge(). You choose the fields that you want to merge.

```<code>DF1.merge(DF2, how='outer', right_on=<keys>...)
</code>```

Body:
Use the left_on and right_on attributes of pd.merge(). You choose the fields that you want to merge.

DF1.merge(DF2, how='outer', right_on=<keys>...)


问:
XML Schema for Tagged Union
I have an XML doc that includes a repeating series of addresses whose actual content depends on the value of an included enumeration. I suppose this is a type of "tagged union" [or "discriminated union"?]:

```<code>{
<AddressList>
    <Address>
        <AddressType type="addressEnum" fixed="CanadianAddress"/>
        <AddressValue>
            <Street type="textstring">123 Yonge Street</Street>
            <Province type="provinceEnum" value="Ontario"/>
            <PostalCode type="postalCodeType" value="M1N 2O3"/>
        </AddressValue>
    </Address>
    <Address>
        <AddressType type="addressEnum" fixed="USAddress"/>
        <AddressValue>
            <Street type="textstring">456 Front Street</Street>
            <State type="stateEnum" value="New York"/>
            <ZipCode type="zipCodeType" value="12345"/>
        </AddressValue>
    </Address>
</AddressList>
}
</code>```

I'm unclear how to express an XML schema [i.e. XSD] for the above XML. Do I need an empty 'AddressType' which both 'CanadianAddressType' and 'USAddressType' would extend? If I have 50 AddressTypes, would I require 50 such extensions?

NOTE: In case it's not obvious, the elements of a USAddress cannot appear following a CanadianAddress enumeration. Likewise, the elements of a CanadianAddress cannot appear following a USAddress enumeration.

答:
It is possible by using alternative components of XSD 1.1. Then you will be able to apply type for <AddressValue> node in depends on fixed attribute value of AddressType element, so

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
    vc:minVersion="1.1">
  <xs:element name="AddressList" >
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Address" minOccurs="1" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence minOccurs="1" maxOccurs="1">
              <xs:element name="AddressType" type="AddressTypeTag"/>
              <xs:element name="AddressValue" type="USAddressValue">
                <xs:alternative test="../AddressType/@fixed='CanadianAddress'" type="CanadianAddressValue"/>
                <xs:alternative test="../AddressType/@fixed='USAddress'" type="USAddressValue"/>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="CanadianAddressValue">
    <xs:sequence minOccurs="1" maxOccurs="1">
      <xs:element name="Street" type="StreetValue"/>
      <xs:element name="Province" type="TypeAndValue"/>
      <xs:element name="PostalCode" type="TypeAndValue"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="USAddressValue">
    <xs:sequence minOccurs="1" maxOccurs="1">
      <xs:element name="Street" type="StreetValue"/>
      <xs:element name="State" type="TypeAndValue"/>
      <xs:element name="ZipCode" type="TypeAndValue"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="StreetValue">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="type" type="xs:string"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="TypeAndValue">
    <xs:attribute name="type" type="xs:string"/>
    <xs:attribute name="value" type="xs:string"/>
  </xs:complexType>
  <xs:complexType name="AddressTypeTag">
    <xs:attribute name="type" fixed="addressEnum" type="xs:string" />
    <xs:attribute name="fixed" >
      <xs:simpleType>
        <xs:restriction base="xs:string">
          <xs:enumeration value="CanadianAddress"></xs:enumeration>
          <xs:enumeration value="USAddress"></xs:enumeration>
        </xs:restriction>
      </xs:simpleType>
    </xs:attribute>
  </xs:complexType>
</xs:schema>
</code>```

Title: XML Schema for Tagged Union

Body:
I have an XML doc that includes a repeating series of addresses whose actual content depends on the value of an included enumeration. I suppose this is a type of "tagged union" [or "discriminated union"?]:

{
<AddressList>
    <Address>
        <AddressType type="addressEnum" fixed="CanadianAddress"/>
        <AddressValue>
            <Street type="textstring">123 Yonge Street</Street>
            <Province type="provinceEnum" value="Ontario"/>
            <PostalCode type="postalCodeType" value="M1N 2O3"/>
        </AddressValue>
    </Address>
    <Address>
        <AddressType type="addressEnum" fixed="USAddress"/>
        <AddressValue>
            <Street type="textstring">456 Front Street</Street>
            <State type="stateEnum" value="New York"/>
            <ZipCode type="zipCodeType" value="12345"/>
        </AddressValue>
    </Address>
</AddressList>
}

I'm unclear how to express an XML schema [i.e. XSD] for the above XML. Do I need an empty 'AddressType' which both 'CanadianAddressType' and 'USAddressType' would extend? If I have 50 AddressTypes, would I require 50 such extensions?

NOTE: In case it's not obvious, the elements of a USAddress cannot appear following a CanadianAddress enumeration. Likewise, the elements of a CanadianAddress cannot appear following a USAddress enumeration.

Body:
It is possible by using alternative components of XSD 1.1. Then you will be able to apply type for <AddressValue> node in depends on fixed attribute value of AddressType element, so

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
    vc:minVersion="1.1">
  <xs:element name="AddressList" >
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Address" minOccurs="1" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence minOccurs="1" maxOccurs="1">
              <xs:element name="AddressType" type="AddressTypeTag"/>
              <xs:element name="AddressValue" type="USAddressValue">
                <xs:alternative test="../AddressType/@fixed='CanadianAddress'" type="CanadianAddressValue"/>
                <xs:alternative test="../AddressType/@fixed='USAddress'" type="USAddressValue"/>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="CanadianAddressValue">
    <xs:sequence minOccurs="1" maxOccurs="1">
      <xs:element name="Street" type="StreetValue"/>
      <xs:element name="Province" type="TypeAndValue"/>
      <xs:element name="PostalCode" type="TypeAndValue"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="USAddressValue">
    <xs:sequence minOccurs="1" maxOccurs="1">
      <xs:element name="Street" type="StreetValue"/>
      <xs:element name="State" type="TypeAndValue"/>
      <xs:element name="ZipCode" type="TypeAndValue"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="StreetValue">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="type" type="xs:string"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="TypeAndValue">
    <xs:attribute name="type" type="xs:string"/>
    <xs:attribute name="value" type="xs:string"/>
  </xs:complexType>
  <xs:complexType name="AddressTypeTag">
    <xs:attribute name="type" fixed="addressEnum" type="xs:string" />
    <xs:attribute name="fixed" >
      <xs:simpleType>
        <xs:restriction base="xs:string">
          <xs:enumeration value="CanadianAddress"></xs:enumeration>
          <xs:enumeration value="USAddress"></xs:enumeration>
        </xs:restriction>
      </xs:simpleType>
    </xs:attribute>
  </xs:complexType>
</xs:schema>


问:
Pandas groupby with delimiter join
I tried to use groupby to group rows with multiple values.

```<code>col val
A  Cat
A  Tiger
B  Ball
B  Bat

import pandas as pd
df = pd.read_csv("Inputfile.txt", sep='\t')
group = df.groupby(['col'])['val'].sum()
</code>```

I got

```<code>A CatTiger
B BallBat
</code>```

I want to introduce a delimiter, so that my output looks like

```<code>A Cat-Tiger
B Ball-Bat
</code>```

I tried,

```<code>group = df.groupby(['col'])['val'].sum().apply(lambda x: '-'.join(x))
</code>```

this yielded,

```<code>A C-a-t-T-i-g-e-r
B B-a-l-l-B-a-t
</code>```

What is the issue here ?

Thanks,

AP

答:
Alternatively you can do it this way:

```<code>In [48]: df.groupby('col')['val'].agg('-'.join)
Out[48]:
col
A    Cat-Tiger
B     Ball-Bat
Name: val, dtype: object
</code>```

UPDATE: answering question from the comment:

```<code>In [2]: df
Out[2]:
  col    val
0   A    Cat
1   A  Tiger
2   A  Panda
3   B   Ball
4   B    Bat
5   B  Mouse
6   B    Egg

In [3]: df.groupby('col')['val'].agg('-'.join)
Out[3]:
col
A       Cat-Tiger-Panda
B    Ball-Bat-Mouse-Egg
Name: val, dtype: object
</code>```

Last for convert index or MultiIndex to columns:

```<code>df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')
</code>```

Title: Pandas groupby with delimiter join

Body:
I tried to use groupby to group rows with multiple values.

col val
A  Cat
A  Tiger
B  Ball
B  Bat

import pandas as pd
df = pd.read_csv("Inputfile.txt", sep='\t')
group = df.groupby(['col'])['val'].sum()

I got

A CatTiger
B BallBat

I want to introduce a delimiter, so that my output looks like

A Cat-Tiger
B Ball-Bat

I tried,

group = df.groupby(['col'])['val'].sum().apply(lambda x: '-'.join(x))

this yielded,

A C-a-t-T-i-g-e-r
B B-a-l-l-B-a-t

What is the issue here ?

Thanks,

AP

Body:
Alternatively you can do it this way:

In [48]: df.groupby('col')['val'].agg('-'.join)
Out[48]:
col
A    Cat-Tiger
B     Ball-Bat
Name: val, dtype: object

UPDATE: answering question from the comment:

In [2]: df
Out[2]:
  col    val
0   A    Cat
1   A  Tiger
2   A  Panda
3   B   Ball
4   B    Bat
5   B  Mouse
6   B    Egg

In [3]: df.groupby('col')['val'].agg('-'.join)
Out[3]:
col
A       Cat-Tiger-Panda
B    Ball-Bat-Mouse-Egg
Name: val, dtype: object

Last for convert index or MultiIndex to columns:

df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')


问:
Excel - automatically append data from sql
how can i make to automatically every day run my excel file, reload data from db and append in existing data.

Do I need to use vba script or...???

答:
I have an idea that might work,

Write a script in any backend language of your choice (Java, Python...) that creates an active connection to the database

Run it to periodically query a database table(MySQl,..) and store newly entered data into variables

Continuously append that data into the excel file as you normally would any file.

Most languages have packages to handle excel files, I think it should do it.
Good luck


问:
css class not working properly
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h1>Audio Projects</h1>
    <blockquote>
     <h3>

              Class D Amplifier

      </h3>
      <div class="wrapper">
          <div class="left">
              <img src="Damp/Damp_front.JPG"/>
          </div>
          <div class="right">
              Some text that should be next to image
          </div>
      </div>
  </blockquote>
</article></code>```

答:
well, what i can advice you is to put the text in the same division as the image like  in paragraph tag and then give the image css attribute called "float:left" according to what you want.

thank you
hope this is going to help you

Title: css class not working properly

Body:
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}

Audio Projects

              Class D Amplifier

              Some text that should be next to image


问:
Camel Splitter store CamelSplitSize and processed rows on failure
http://camel.apache.org/splitter.html  [1]

From [1] link i saw CamelSplitSize will be on the completed Exchange.

I am learning camel and i would like to know is there a way possible to split the xml file containing 100 rows (assuming 100 rows)

If the split failed while processing the 50th row and we need to show CamelSplitIndex as 50, CamelSplitSize as 100 and CamelSplitComplete as false

```<code>.bean(Splitter.class,"saveFile("${camelContext.properties[mySplitSize]}, ${camelContext.properties[mySplitIndex]}, ${camelContext.properties[mySplitComplete]})")
</code>```

I could not find a way to accomplish this as the link [1] clearly states CamelSplitSize will be stored only on the completed Exchang. Any way to achieve this ??

答:
If you need this properties you can catch exception that causes stopping splitter and get exchange which caused the exception. There you will find your properties.</p>

```<code> public void show(Exchange exchange) {
    CamelExchangeException camelExceptionCaught = (CamelExchangeException) exchange.getProperty("CamelExceptionCaught");
    System.out.println(camelExceptionCaught.getExchange().getProperty("CamelSplitSize"));
    System.out.println(camelExceptionCaught.getExchange().getProperty("CamelSplitComplete"));
    System.out.println(camelExceptionCaught.getExchange().getProperty("CamelSplitIndex"));
}
</code>```

Body:
http://camel.apache.org/splitter.html  [1]

From [1] link i saw CamelSplitSize will be on the completed Exchange.

I am learning camel and i would like to know is there a way possible to split the xml file containing 100 rows (assuming 100 rows)

If the split failed while processing the 50th row and we need to show CamelSplitIndex as 50, CamelSplitSize as 100 and CamelSplitComplete as false

.bean(Splitter.class,"saveFile("${camelContext.properties[mySplitSize]}, ${camelContext.properties[mySplitIndex]}, ${camelContext.properties[mySplitComplete]})")

I could not find a way to accomplish this as the link [1] clearly states CamelSplitSize will be stored only on the completed Exchang. Any way to achieve this ??

Body:
If you need this properties you can catch exception that causes stopping splitter and get exchange which caused the exception. There you will find your properties.

 public void show(Exchange exchange) {
    CamelExchangeException camelExceptionCaught = (CamelExchangeException) exchange.getProperty("CamelExceptionCaught");
    System.out.println(camelExceptionCaught.getExchange().getProperty("CamelSplitSize"));
    System.out.println(camelExceptionCaught.getExchange().getProperty("CamelSplitComplete"));
    System.out.println(camelExceptionCaught.getExchange().getProperty("CamelSplitIndex"));
}


问:
Codeigniter login system with session to redirect user to page if password correct
I created a login system but every time I setup an if statement it loops back to the login page when I enter correct password. I need the index function in the controller, the list_employee function and View_employee function to redirect user to login page if they access it directly but if they enter correct password allow them to go to it.

user_authentication controller

```<code><?php

session_start(); //we need to start session in order to access it through CI

Class User_Authentication extends CI_Controller {

public function __construct() {
parent::__construct();

// Load form helper library
$this->load->helper('form');

// Load form validation library
$this->load->library('form_validation');

// Load session library
$this->load->library('session');

// Load database
$this->load->model('login_database');

}

// Show login page
public function user_login_show() {
$this->load->view('login_form');
}

// Show registration page
public function user_registration_show() {
$this->load->view('registration_form');
}

// Validate and store registration data in database
public function new_user_registration() {

// Check validation for user input in SignUp form
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('registration_form');
} else {
$data = array(
'name' => $this->input->post('name'),
'user_name' => $this->input->post('username'),
'user_email' => $this->input->post('email_value'),
'user_password' => $this->input->post('password')
);
$result = $this->login_database->registration_insert($data) ;
if ($result == TRUE) {
$data['message_display'] = 'Registration Successfully !';
$this->load->view('login_form', $data);
} else {
$data['message_display'] = 'Username already exist!';
$this->load->view('registration_form', $data);
}
}
}

// Check for user login process
public function user_login_process() {

$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);

// Add user data in session
$this->session->set_userdata('logged_in', $sess_array);
$result = $this->login_database->read_user_information($sess_array);
if($result != false){
$data = array(
'name' =>$result[0]->name,
'username' =>$result[0]->user_name,
'email' =>$result[0]->user_email,
'password' =>$result[0]->user_password
);
redirect('employee');
}
}else{
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
}
}

// Logout from admin page
public function logout() {

// Removing session data
$sess_array = array(
'username' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('login_form', $data);
}
}

?>
</code>```

employee controller

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Employee extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->model('login/employee_model');

        }

    //Shows the dashboard
    public function index()
    {

        $this->load->view('header');
        $this->load->view('employee');
        $this->load->view('login/footer');

    }
    //Insert the employee
    public function  insert_employee()
    {

        $data=array('name'=>$this->input->post('name'),
            'LanId'=>$this->input->post('LanId'),
            'reason'=>$this->input->post('reason'),
            'PepNumber'=>$this->input->post('PepNumber'),
            'Employee_Number'=>$this->input->post('Employee_Number'),
            'department'=>$this->input->post('department'),

            'status'=>1);
        //print_r($data);

        $result=$this->employee_model->insert_employee($data);
        if($result==true)
        {
            $this->session->set_flashdata('msg',"Employee Records Added Successfully");
            redirect('employee');

        }
        else
        {

            $this->session->set_flashdata('msg1',"Employee Records Added Failed");
            redirect('employee');

        }
    }
    //List of Employees
        public function list_employees()
    {

            $data['employee']=$this->employee_model->get_employee();
            $this->load->view('header');
            $this->load->view('list_of_employees',$data);
             $this->load->view('login/footer');

    }
    //List of Employees
        public function viewlist_employees()
    {

            $data['employee']=$this->employee_model->get_employee();
            $this->load->view('header');
            $this->load->view('viewlist_of_employees',$data);
             $this->load->view('login/footer');

    }

    public function delete_employee()
    {
        $id=$this->input->post('id');
        $data=array('status'=>0);
        $result=$this->employee_model->delete_employee($id,$data);
        if($result==true)
        {
            $this->session->set_flashdata('msg1',"Deleted Successfully");
            redirect('employee/list_employees');

        }
        else
        {

            $this->session->set_flashdata('msg1',"Employee Records Deletion Failed");
            redirect('employee/list_employees');

        }

    }
    public function edit_employee()
    {
        $id=$this->uri->segment(3);
        $data['employee']=$this->employee_model->edit_employee($id);
        $this->load->view('header',$data);
        $this->load->view('edit_employee');
    }
    public function  update_employee()
    {
        $id=$this->input->post('id');

        $data=array('name'=>$this->input->post('name'),
            'LanID'=>$this->input->post('LanID'),
            'reason'=>$this->input->post('reason'),
            'PepNumber'=>$this->input->post('PepNumber'),
            'Employee_Number'=>$this->input->post('Employee_Number'),
            'department'=>$this->input->post('department'),

            'status'=>1);

        $result=$this->employee_model->update_employee($data,$id);
        if($result==true)
        {
            $this->session->set_flashdata('msg',"Employee Records Updated Successfully");
            redirect('employee/list_employees');

        }
        else
        {

            $this->session->set_flashdata('msg1',"No changes Made in Employee Records");
            redirect('employee/list_employees');

        }
    }

}
?>
</code>```

login_database model

```<code><?php

Class Login_Database extends CI_Model {

// Insert registration data in database
public function registration_insert($data) {

// Query to check whether username already exist or not
$condition = "user_name =" . "'" . $data['user_name'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {

// Query to insert data in database
$this->db->insert('user_login', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}

// Read data using username and password
public function login($data) {

$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}

// Read data from database to show data in admin page
public function read_user_information($sess_array) {

$condition = "user_name =" . "'" . $sess_array['username'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}

}

?>
</code>```

employee_model

```<code><?php

class Employee_model extends CI_Model
{

    public function insert_employee($data)
    {
        $this->db->insert('employee_list',$data);
        return ($this->db->affected_rows() != 1 ) ? false:true;
    }
    public function get_employee()
    {
        $this->db->select('*');
        $this->db->from('employee_list');
        $this->db->where('status',1);

        $query =$this->db->get();
        return $query->result();
    }
    public function delete_employee($id,$data)
    {
        $this->db->where('id',$id);
        $this->db->update('employee_list',$data);
        return ($this->db->affected_rows() != 1 ) ? false:true;
    }
    public function edit_employee($id)
    {
        $this->db->select('*');
        $this->db->from('employee_list');
        $this->db->where('id',$id);
        $this->db->where('status',1);
        $query =$this->db->get();
        return $query->result();

    }
    public function update_employee($data,$id)
    {
        $this->db->where('id',$id);
        $this->db->update('employee_list',$data);
        return ($this->db->affected_rows() != 1 ) ? false:true;
    }
}
</code>```

答:
Add this line of code to your constructors:

```<code>$this->load->library('session');
</code>```

This will help you.

Body:
I created a login system but every time I setup an if statement it loops back to the login page when I enter correct password. I need the index function in the controller, the list_employee function and View_employee function to redirect user to login page if they access it directly but if they enter correct password allow them to go to it.

user_authentication controller

<?php

session_start(); //we need to start session in order to access it through CI

Class User_Authentication extends CI_Controller {

public function __construct() {
parent::__construct();

// Load form helper library
$this->load->helper('form');

// Load form validation library
$this->load->library('form_validation');

// Load session library
$this->load->library('session');

// Load database
$this->load->model('login_database');

}

// Show login page
public function user_login_show() {
$this->load->view('login_form');
}

// Show registration page
public function user_registration_show() {
$this->load->view('registration_form');
}

// Validate and store registration data in database
public function new_user_registration() {

// Check validation for user input in SignUp form
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('registration_form');
} else {
$data = array(
'name' => $this->input->post('name'),
'user_name' => $this->input->post('username'),
'user_email' => $this->input->post('email_value'),
'user_password' => $this->input->post('password')
);
$result = $this->login_database->registration_insert($data) ;
if ($result == TRUE) {
$data['message_display'] = 'Registration Successfully !';
$this->load->view('login_form', $data);
} else {
$data['message_display'] = 'Username already exist!';
$this->load->view('registration_form', $data);
}
}
}

// Check for user login process
public function user_login_process() {

$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);

// Add user data in session
$this->session->set_userdata('logged_in', $sess_array);
$result = $this->login_database->read_user_information($sess_array);
if($result != false){
$data = array(
'name' =>$result[0]->name,
'username' =>$result[0]->user_name,
'email' =>$result[0]->user_email,
'password' =>$result[0]->user_password
);
redirect('employee');
}
}else{
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
}
}

// Logout from admin page
public function logout() {

// Removing session data
$sess_array = array(
'username' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('login_form', $data);
}
}

?>

employee controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Employee extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->model('login/employee_model');

        }

    //Shows the dashboard
    public function index()
    {

        $this->load->view('header');
        $this->load->view('employee');
        $this->load->view('login/footer');

    }
    //Insert the employee
    public function  insert_employee()
    {

        $data=array('name'=>$this->input->post('name'),
            'LanId'=>$this->input->post('LanId'),
            'reason'=>$this->input->post('reason'),
            'PepNumber'=>$this->input->post('PepNumber'),
            'Employee_Number'=>$this->input->post('Employee_Number'),
            'department'=>$this->input->post('department'),

            'status'=>1);
        //print_r($data);

        $result=$this->employee_model->insert_employee($data);
        if($result==true)
        {
            $this->session->set_flashdata('msg',"Employee Records Added Successfully");
            redirect('employee');

        }
        else
        {

            $this->session->set_flashdata('msg1',"Employee Records Added Failed");
            redirect('employee');

        }
    }
    //List of Employees
        public function list_employees()
    {

            $data['employee']=$this->employee_model->get_employee();
            $this->load->view('header');
            $this->load->view('list_of_employees',$data);
             $this->load->view('login/footer');

    }
    //List of Employees
        public function viewlist_employees()
    {

            $data['employee']=$this->employee_model->get_employee();
            $this->load->view('header');
            $this->load->view('viewlist_of_employees',$data);
             $this->load->view('login/footer');

    }

    public function delete_employee()
    {
        $id=$this->input->post('id');
        $data=array('status'=>0);
        $result=$this->employee_model->delete_employee($id,$data);
        if($result==true)
        {
            $this->session->set_flashdata('msg1',"Deleted Successfully");
            redirect('employee/list_employees');

        }
        else
        {

            $this->session->set_flashdata('msg1',"Employee Records Deletion Failed");
            redirect('employee/list_employees');

        }

    }
    public function edit_employee()
    {
        $id=$this->uri->segment(3);
        $data['employee']=$this->employee_model->edit_employee($id);
        $this->load->view('header',$data);
        $this->load->view('edit_employee');
    }
    public function  update_employee()
    {
        $id=$this->input->post('id');

        $data=array('name'=>$this->input->post('name'),
            'LanID'=>$this->input->post('LanID'),
            'reason'=>$this->input->post('reason'),
            'PepNumber'=>$this->input->post('PepNumber'),
            'Employee_Number'=>$this->input->post('Employee_Number'),
            'department'=>$this->input->post('department'),

            'status'=>1);

        $result=$this->employee_model->update_employee($data,$id);
        if($result==true)
        {
            $this->session->set_flashdata('msg',"Employee Records Updated Successfully");
            redirect('employee/list_employees');

        }
        else
        {

            $this->session->set_flashdata('msg1',"No changes Made in Employee Records");
            redirect('employee/list_employees');

        }
    }

}
?>

login_database model

<?php

Class Login_Database extends CI_Model {

// Insert registration data in database
public function registration_insert($data) {

// Query to check whether username already exist or not
$condition = "user_name =" . "'" . $data['user_name'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {

// Query to insert data in database
$this->db->insert('user_login', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}

// Read data using username and password
public function login($data) {

$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}

// Read data from database to show data in admin page
public function read_user_information($sess_array) {

$condition = "user_name =" . "'" . $sess_array['username'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}

}

?>

employee_model

<?php

class Employee_model extends CI_Model
{

    public function insert_employee($data)
    {
        $this->db->insert('employee_list',$data);
        return ($this->db->affected_rows() != 1 ) ? false:true;
    }
    public function get_employee()
    {
        $this->db->select('*');
        $this->db->from('employee_list');
        $this->db->where('status',1);

        $query =$this->db->get();
        return $query->result();
    }
    public function delete_employee($id,$data)
    {
        $this->db->where('id',$id);
        $this->db->update('employee_list',$data);
        return ($this->db->affected_rows() != 1 ) ? false:true;
    }
    public function edit_employee($id)
    {
        $this->db->select('*');
        $this->db->from('employee_list');
        $this->db->where('id',$id);
        $this->db->where('status',1);
        $query =$this->db->get();
        return $query->result();

    }
    public function update_employee($data,$id)
    {
        $this->db->where('id',$id);
        $this->db->update('employee_list',$data);
        return ($this->db->affected_rows() != 1 ) ? false:true;
    }
}

Body:
Add this line of code to your constructors:

$this->load->library('session');

This will help you.


问:
Downsizing header, removing footer entirely
I am working/designing the front-end (working on the layout html+css, later will use php, mvc pattern) of a website. The website has a header, body, side menu and a footer The layout is ready.

There are a few forms which are unusually long/huge since all fields are necessary and I could not make them any shorter. The form opens in a new page.

Not to scare the user away I am planning to downsize the header on the form template (the design change will only apply to the form templates) and get rid of the footer completely.

I tried looking a few places but did not find how to go it done. In short, I want the site to have all block i.e. header, body, footer but when it comes to the form I would want to downsize the header and remove the footer to make the form look sleeker.

Is there a way to do this?

Note: I post no code because I have no problem with the code but the concept.

答:
```<code>You can also done this thing using angularjs
ng-include
  <!DOCTYPE html>
 <html>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body >
     <div ng-include="'header.html'">
     </div>
      <div ng-include="'footer.html'">
     </div>
</body>
</html>
</code>```


问:
list view problem with respect to my problem
I have a listview in wpf and i am swapping two items index..

the swapping must be visible to the user.

i tried giving thread delay..

it didnt work

How to do that..

答:
I am not sure whether it will work for your problem or not.

I think you need some kind of animation there. If it is web project, you can use jQuery animation to do that.

ContentLicense: CC BY-SA 2.5


问:
Filtering sum of specific value
I have data source with different steps in a flow for different dates, and their counts let's say:

```<code>1 xxx 500
2 yyy 200
3 ddd 100
NA test 50
NA test2 600
NA test3 400
</code>```

I'd like to visualize counts, but if the value is NA to filter based on amount. I already tried this

IF [step_number] == "NA" THEN [step_count] END

But dragging this to filter actually filters everything. My goal is to only filter if the step_number is "NA". Any advice?

To clarify, filtering by 500 with this calculated field would show step_numbers 1,2,3 and NA-test2

答:
if you want to only filter NA just click on keep only on NA

Your filter 'NA' data

Title: Filtering sum of specific value

Body:
I have data source with different steps in a flow for different dates, and their counts let's say:

1 xxx 500
2 yyy 200
3 ddd 100
NA test 50
NA test2 600
NA test3 400

I'd like to visualize counts, but if the value is NA to filter based on amount. I already tried this

IF [step_number] == "NA" THEN [step_count] END

But dragging this to filter actually filters everything. My goal is to only filter if the step_number is "NA". Any advice?

To clarify, filtering by 500 with this calculated field would show step_numbers 1,2,3 and NA-test2


问:
SELECT A, B, C, GMTDATE FROM TABLE_NAME: with constant GMT
```<code> SELECT A, B, C, GMTDATE
   FROM TABLE_NAME
</code>```

Here when Data is large.

```<code>     A  B  C             GMTDATE
    X1 Y1 Z1 2017.06.05.17:17:59
    X2 Y2 Z2 2017.06.05.17:17:59
    X3 Y3 Z3 2017.06.05.17:17:59
    X4 Y4 Z4 2017.06.05.17:18:00
</code>```

Exmplanation:  I want same GMT date for all data.
Then GMT Date will be different at every second in the table: it display's time of at the time of execution. Where I want same GMTDATE for ALL Data. Either it should be GMT DATE of starting of execution the query or Execution end of the query.

答:
```<code>SELECT A, B, C, DT.gmtvalue
   FROM TABLE_NAME, (select GMTDATE gmtvalue) DT
</code>```

Body:
 SELECT A, B, C, GMTDATE
   FROM TABLE_NAME

Here when Data is large.

     A  B  C             GMTDATE
    X1 Y1 Z1 2017.06.05.17:17:59
    X2 Y2 Z2 2017.06.05.17:17:59
    X3 Y3 Z3 2017.06.05.17:17:59
    X4 Y4 Z4 2017.06.05.17:18:00

Exmplanation:  I want same GMT date for all data.
Then GMT Date will be different at every second in the table: it display's time of at the time of execution. Where I want same GMTDATE for ALL Data. Either it should be GMT DATE of starting of execution the query or Execution end of the query.