问:
AVAudioPlayerNode scheduled buffers and audio route change in iOS11
I am seeing different behaviour between iOS 9/10 and iOS 11 for buffers that are future scheduled on an AVAudioPlayerNode when an audio route change occurs (e.g. you plug in headphones).  Has anyone experienced anything similar and how did you resolve it? Note that I reported this issue up on Apple's AVFoundation support forum almost two weeks ago and have received exactly zero response.

The code that exhibits this problem is shown below - a brief explanation first: the code is a simple loop that repeatedly schedules a buffer to play at a time in the future. The process is kicked off by invoking the 'runSequence' method which schedules an audio buffer to play at a time in the future and sets the completion callback to the nested method 'audioCompleteHandler.' The completion callback again calls the 'runSequence' method which schedules another buffer and keeps the process going forever. It is that case that there is always a buffer scheduled except when the completion handler is executing. The 'trace' method in various places is an internal method for printing only when debugging so can be ignored.

In the audio route change notification handler (handleAudioRouteChange), when a new device becomes available (case .newDeviceAvailable), the code restarts the engine and player, reactivates the audio session and calls 'runSequence' to kick the loop back into life.

This all works fine on iOS 9.3.5 (iPhone 5C) and iOS 10.3.3 (iPhone 6) but fails on iOS 11.1.1 (iPad Air). The nature of the failure is that the AVAudioPlayerNode does not play the audio but immediately calls the completion handler instead. This causes a runaway situation.  If I remove the line that kicks off the loop again (as indicated in the code), it works fine on iOS 11.1.1 but fails on iOS 9.3.5 and iOS 10.3.3. This failure is different: the audio just stops and, in the debugger, I can see that the loop is not looping.

So, a possible explanation is that, under iOS 9.x and iOS 10.x, future scheduled buffers are unscheduled when an audio route change occurs while under iOS 11.x future scheduled buffers are not unscheduled.

This leads to two questions:
 1. Has anyone seen any similar behaviour to this and what was the resolution?
 2. Can anyone point me to documentation that describes the exact state of the engine, player(s) and session when an audio route change (or an audio interruption) occurs?

```<code>private func runSequence() {

    // For test ony
    var timeBaseInfo = mach_timebase_info_data_t()
    mach_timebase_info(&timeBaseInfo)
    // End for test only

    let audioCompleteHandler = { [unowned self] in
        DispatchQueue.main.async {
            trace(level: .skim, items: "Player: \(self.player1.isPlaying), Engine: \(self.engine.isRunning)")
            self.player1.stop()
            switch self.runStatus {
            case .Run:
                self.runSequence()
            case .Restart:
                self.runStatus = .Run
                self.tickSeq.resetSequence()
                //self.updateRenderHostTime()
                self.runSequence()
            case .Halt:
                self.stopEngine()
                self.player1.stop()
                self.activateAudioSession(activate: false)
            }
        }
    }

    // Schedule buffer...
    if self.engine.isRunning {
        if let thisElem: (buffer: AVAudioPCMBuffer, duration: Int) = tickSeq.next() {
            self.player1.scheduleBuffer(thisElem.buffer, at: nil, options: [], completionHandler: audioCompleteHandler)
            self.player1.prepare(withFrameCount: thisElem.buffer.frameLength)
            self.player1.play(at: AVAudioTime(hostTime: self.startHostTime))
            self.startHostTime += AVAudioTime.hostTime(forSeconds: TimeInterval(Double(60.0 / Double(self.model.bpm.value)) * Double(thisElem.duration)))
            trace(level: .skim, items:
                "Samples: \(thisElem.buffer.frameLength)",
                "Time: \(mach_absolute_time() * (UInt64(timeBaseInfo.numer) / UInt64(timeBaseInfo.denom))) ",
                "Sample Time: \(player1.lastRenderTime!.hostTime)",
                "Play At: \(self.startHostTime) ",
                "Player: \(self.player1.isPlaying)",
                "Engine: \(self.engine.isRunning)")
        }
        else {
        }
    }
}

@objc func handleAudioRouteChange(_ notification: Notification) {

    trace(level: .skim, items: "Route change: Player: \(self.player1.isPlaying) Engine: \(self.engine.isRunning)")
    guard let userInfo = notification.userInfo,
        let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
        let reason = AVAudioSessionRouteChangeReason(rawValue:reasonValue) else { return }

    trace(level: .skim, items: audioSession.currentRoute, audioSession.mode)
    trace(level: .none, items: "Reason Value: \(String(describing: userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt)); Reason: \(String(describing: AVAudioSessionRouteChangeReason(rawValue:reasonValue)))")

    switch reason {
    case .newDeviceAvailable:
        trace(level: .skim, items: "In handleAudioRouteChange.newDeviceAvailable")
        for output in audioSession.currentRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
            startEngine()
            player1.play()
            activateAudioSession(activate: true)
            //updateRenderHostTime()
            runSequence() // <<--- Problem: works for iOS9,10; fails on iOS11. Remove it and iOS9,10 fail, works on iOS11
        }
    case .oldDeviceUnavailable:
        trace(level: .skim, items: "In handleAudioRouteChange.oldDeviceUnavailable")
        if let previousRoute =
            userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
            for output in previousRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
                player1.stop()
                stopEngine()
                tickSeq.resetSequence()
                DispatchQueue.main.async {
                    if let pp = self.playPause as UIButton? { pp.isSelected = false }
                }
           }
        }
</code>```

答:
So, problem solved with some further digging/testing:

There is a difference in behaviour between iOS 9/10 and iOS 11 when AVAudioSession issues a route change notification. In the notification handler, the engine state is not running (engine.isRunning == false) about 90% of the time for iOS 9/10 whereas for iOS 11 the engine state is always running (engine.isRunning == true)

For the 10% of the time that iOS 9/10 indicates that the engine is running (engine.isRunning == true), this is in fact not the case. The engine is NOT running regardless of what engine.isRunning says

Because the engine has been stopped in iOS 9/10, previously prepared audio has been released and audio will not start just by restarting the engine; you have to reschedule the file or buffer at the sample point where the engine was stopped. Sadly, you can't find the current sample time when the engine is stopped (the player returns nil) so you have to:

Start the engine

Grab the sample time and accumulate it (+=) in a persistent property

Stop the player

Reschedule the audio (and prepare it) starting at the sample time just grabbed

Start the player

The engine state is the same in iOS 9/10 for both the headphone plugged in case (.newDeviceAvailable) and the headphone removed case (.oldDeviceUnavailable) so you need to do similar to the above for the removed case as well (accumulating the sample time is needed so that you can restart the audio from the point where it was stopped since player.stop() will reset sample time to 0)

None of this is needed for iOS 11 but the code below works for iOS 9/10 and 11 so it's probably best to do it the same way for all versions

The code below works on my test devices for iOS 9.3.5 (iPhone 5C), iOS 10.3.3 (iPhone 6) and iOS 11.1.1 (iPad Air) (but I am still bothered by the fact that I can find no prior commentary on how to correctly handle a route change and there must be hundreds of folks out there who have come across this issue..?? Normally, when I cannot find any prior commentary on a topic I assume that I am doing something wrong or just don't get it... Oh well...):

```<code>@objc func handleAudioRouteChange(_ notification: Notification) {

    guard let userInfo = notification.userInfo,
        let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
        let reason = AVAudioSessionRouteChangeReason(rawValue:reasonValue) else { return }

    switch reason {
    case .newDeviceAvailable:

        for output in audioSession.currentRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
            headphonesConnected = true
        }

        startEngine()   // Do this regardless of whether engine.isRunning == true

        if let lrt = player.lastRenderTime, let st = player.playerTime(forNodeTime: lrt)?.sampleTime {
            playSampleOffset += st  // Accumulate so that multiple inserts/removals move the play point forward
            stopPlayer()
            scheduleSegment(file: playFile, at: nil, player: player, start: playSampleOffset, length: AVAudioFrameCount(playFile.length - playSampleOffset))
            startPlayer()
        }
        else {
            // Unknown problem with getting sampleTime; reset engine, player(s), restart as appropriate
        }

    case .oldDeviceUnavailable:
        if let previousRoute =
            userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
            for output in previousRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
                headphonesConnected = false
            }
        }

        startEngine()   // Do this regardless of whether engine.isRunning == true

        if let lrt = player.lastRenderTime, let st = player.playerTime(forNodeTime: lrt)?.sampleTime  {
            playSampleOffset += st  // Accumulate...
            stopPlayer()
            scheduleSegment(file: playFile, at: nil, player: player, start: playSampleOffset, length: AVAudioFrameCount(playFile.length - playSampleOffset))
            startPlayer()   // Test only, in reality don't restart here; set play control to allow user to start audio
        }
        else {
            // Unknown problem with getting sampleTime; reset engine, player(s), restart as appropriate
        }
</code>```

...

Body:
I am seeing different behaviour between iOS 9/10 and iOS 11 for buffers that are future scheduled on an AVAudioPlayerNode when an audio route change occurs (e.g. you plug in headphones).  Has anyone experienced anything similar and how did you resolve it? Note that I reported this issue up on Apple's AVFoundation support forum almost two weeks ago and have received exactly zero response.

The code that exhibits this problem is shown below - a brief explanation first: the code is a simple loop that repeatedly schedules a buffer to play at a time in the future. The process is kicked off by invoking the 'runSequence' method which schedules an audio buffer to play at a time in the future and sets the completion callback to the nested method 'audioCompleteHandler.' The completion callback again calls the 'runSequence' method which schedules another buffer and keeps the process going forever. It is that case that there is always a buffer scheduled except when the completion handler is executing. The 'trace' method in various places is an internal method for printing only when debugging so can be ignored.

In the audio route change notification handler (handleAudioRouteChange), when a new device becomes available (case .newDeviceAvailable), the code restarts the engine and player, reactivates the audio session and calls 'runSequence' to kick the loop back into life.

This all works fine on iOS 9.3.5 (iPhone 5C) and iOS 10.3.3 (iPhone 6) but fails on iOS 11.1.1 (iPad Air). The nature of the failure is that the AVAudioPlayerNode does not play the audio but immediately calls the completion handler instead. This causes a runaway situation.  If I remove the line that kicks off the loop again (as indicated in the code), it works fine on iOS 11.1.1 but fails on iOS 9.3.5 and iOS 10.3.3. This failure is different: the audio just stops and, in the debugger, I can see that the loop is not looping.

So, a possible explanation is that, under iOS 9.x and iOS 10.x, future scheduled buffers are unscheduled when an audio route change occurs while under iOS 11.x future scheduled buffers are not unscheduled.

This leads to two questions:
 1. Has anyone seen any similar behaviour to this and what was the resolution?
 2. Can anyone point me to documentation that describes the exact state of the engine, player(s) and session when an audio route change (or an audio interruption) occurs?

private func runSequence() {

    // For test ony
    var timeBaseInfo = mach_timebase_info_data_t()
    mach_timebase_info(&timeBaseInfo)
    // End for test only

    let audioCompleteHandler = { [unowned self] in
        DispatchQueue.main.async {
            trace(level: .skim, items: "Player: \(self.player1.isPlaying), Engine: \(self.engine.isRunning)")
            self.player1.stop()
            switch self.runStatus {
            case .Run:
                self.runSequence()
            case .Restart:
                self.runStatus = .Run
                self.tickSeq.resetSequence()
                //self.updateRenderHostTime()
                self.runSequence()
            case .Halt:
                self.stopEngine()
                self.player1.stop()
                self.activateAudioSession(activate: false)
            }
        }
    }

    // Schedule buffer...
    if self.engine.isRunning {
        if let thisElem: (buffer: AVAudioPCMBuffer, duration: Int) = tickSeq.next() {
            self.player1.scheduleBuffer(thisElem.buffer, at: nil, options: [], completionHandler: audioCompleteHandler)
            self.player1.prepare(withFrameCount: thisElem.buffer.frameLength)
            self.player1.play(at: AVAudioTime(hostTime: self.startHostTime))
            self.startHostTime += AVAudioTime.hostTime(forSeconds: TimeInterval(Double(60.0 / Double(self.model.bpm.value)) * Double(thisElem.duration)))
            trace(level: .skim, items:
                "Samples: \(thisElem.buffer.frameLength)",
                "Time: \(mach_absolute_time() * (UInt64(timeBaseInfo.numer) / UInt64(timeBaseInfo.denom))) ",
                "Sample Time: \(player1.lastRenderTime!.hostTime)",
                "Play At: \(self.startHostTime) ",
                "Player: \(self.player1.isPlaying)",
                "Engine: \(self.engine.isRunning)")
        }
        else {
        }
    }
}

@objc func handleAudioRouteChange(_ notification: Notification) {

    trace(level: .skim, items: "Route change: Player: \(self.player1.isPlaying) Engine: \(self.engine.isRunning)")
    guard let userInfo = notification.userInfo,
        let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
        let reason = AVAudioSessionRouteChangeReason(rawValue:reasonValue) else { return }

    trace(level: .skim, items: audioSession.currentRoute, audioSession.mode)
    trace(level: .none, items: "Reason Value: \(String(describing: userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt)); Reason: \(String(describing: AVAudioSessionRouteChangeReason(rawValue:reasonValue)))")

    switch reason {
    case .newDeviceAvailable:
        trace(level: .skim, items: "In handleAudioRouteChange.newDeviceAvailable")
        for output in audioSession.currentRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
            startEngine()
            player1.play()
            activateAudioSession(activate: true)
            //updateRenderHostTime()
            runSequence() // <<--- Problem: works for iOS9,10; fails on iOS11. Remove it and iOS9,10 fail, works on iOS11
        }
    case .oldDeviceUnavailable:
        trace(level: .skim, items: "In handleAudioRouteChange.oldDeviceUnavailable")
        if let previousRoute =
            userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
            for output in previousRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
                player1.stop()
                stopEngine()
                tickSeq.resetSequence()
                DispatchQueue.main.async {
                    if let pp = self.playPause as UIButton? { pp.isSelected = false }
                }
           }
        }

Body:
So, problem solved with some further digging/testing:

There is a difference in behaviour between iOS 9/10 and iOS 11 when AVAudioSession issues a route change notification. In the notification handler, the engine state is not running (engine.isRunning == false) about 90% of the time for iOS 9/10 whereas for iOS 11 the engine state is always running (engine.isRunning == true)

For the 10% of the time that iOS 9/10 indicates that the engine is running (engine.isRunning == true), this is in fact not the case. The engine is NOT running regardless of what engine.isRunning says

Because the engine has been stopped in iOS 9/10, previously prepared audio has been released and audio will not start just by restarting the engine; you have to reschedule the file or buffer at the sample point where the engine was stopped. Sadly, you can't find the current sample time when the engine is stopped (the player returns nil) so you have to:

Start the engine

Grab the sample time and accumulate it (+=) in a persistent property

Stop the player

Reschedule the audio (and prepare it) starting at the sample time just grabbed

Start the player

The engine state is the same in iOS 9/10 for both the headphone plugged in case (.newDeviceAvailable) and the headphone removed case (.oldDeviceUnavailable) so you need to do similar to the above for the removed case as well (accumulating the sample time is needed so that you can restart the audio from the point where it was stopped since player.stop() will reset sample time to 0)

None of this is needed for iOS 11 but the code below works for iOS 9/10 and 11 so it's probably best to do it the same way for all versions

The code below works on my test devices for iOS 9.3.5 (iPhone 5C), iOS 10.3.3 (iPhone 6) and iOS 11.1.1 (iPad Air) (but I am still bothered by the fact that I can find no prior commentary on how to correctly handle a route change and there must be hundreds of folks out there who have come across this issue..?? Normally, when I cannot find any prior commentary on a topic I assume that I am doing something wrong or just don't get it... Oh well...):

@objc func handleAudioRouteChange(_ notification: Notification) {

    guard let userInfo = notification.userInfo,
        let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
        let reason = AVAudioSessionRouteChangeReason(rawValue:reasonValue) else { return }

    switch reason {
    case .newDeviceAvailable:

        for output in audioSession.currentRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
            headphonesConnected = true
        }

        startEngine()   // Do this regardless of whether engine.isRunning == true

        if let lrt = player.lastRenderTime, let st = player.playerTime(forNodeTime: lrt)?.sampleTime {
            playSampleOffset += st  // Accumulate so that multiple inserts/removals move the play point forward
            stopPlayer()
            scheduleSegment(file: playFile, at: nil, player: player, start: playSampleOffset, length: AVAudioFrameCount(playFile.length - playSampleOffset))
            startPlayer()
        }
        else {
            // Unknown problem with getting sampleTime; reset engine, player(s), restart as appropriate
        }

    case .oldDeviceUnavailable:
        if let previousRoute =
            userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
            for output in previousRoute.outputs where output.portType == AVAudioSessionPortHeadphones {
                headphonesConnected = false
            }
        }

        startEngine()   // Do this regardless of whether engine.isRunning == true

        if let lrt = player.lastRenderTime, let st = player.playerTime(forNodeTime: lrt)?.sampleTime  {
            playSampleOffset += st  // Accumulate...
            stopPlayer()
            scheduleSegment(file: playFile, at: nil, player: player, start: playSampleOffset, length: AVAudioFrameCount(playFile.length - playSampleOffset))
            startPlayer()   // Test only, in reality don't restart here; set play control to allow user to start audio
        }
        else {
            // Unknown problem with getting sampleTime; reset engine, player(s), restart as appropriate
        }

...


来源: stackexchange

问:
Decode android's hardware encoded H264 camera feed using ffmpeg in real time
I'm trying to use the hardware H264 encoder on Android to create video from the camera, and use FFmpeg to mux in audio (all on the Android phone itself)

What I've accomplished so far is packetizing the H264 video into rtsp packets, and decoding it using VLC (over UDP), so I know the video is at least correctly formatted. However, I'm having trouble getting the video data to ffmpeg in a format it can understand.

I've tried sending the same rtsp packets to a port 5006 on localhost (over UDP), then providing ffmpeg with the sdp file that tells it which local port the video stream is coming in on and how to decode the video, if I understand rtsp streaming correctly. However this doesn't work and I'm having trouble diagnosing why, as ffmpeg just sits there waiting for input.

For reasons of latency and scalability I can't just send the video and audio to the server and mux it there, it has to be done on the phone, in as lightweight a manner as possible.

What I guess I'm looking for are suggestions as to how this can be accomplished. The optimal solution would be sending the packetized H264 video to ffmpeg over a pipe, but then I can't send ffmpeg the sdp file parameters it needs to decode the video.

I can provide more information on request, like how ffmpeg is compiled for Android but I doubt that's necessary.

Oh, and the way I start ffmpeg is through command line, I would really rather avoid mucking about with jni if that's at all possible.

And help would be much appreciated, thanks.

答:
A little bit late but I think this is a good question and it doesn't have a good answer yet.

If you want to stream the camera and mic from an android device you have two main alternatives: Java or NDK implementations.

Java implementation.

I'm only going to mention the idea but basically it is implement an RTSP Server and RTP Protocol in java based on these standards Real-Time Streaming Protocol Version 2.0 and RTP Payload Format for H.264 Video. This task will be very long and hard. But if you are doing your PhP it could be nice to have a nice RTSP Java lib for Android.

NDK implementation.

This is alternative include various solutions. The main idea is to use a power C or C++ library in our Android application. For this instance, FFmpeg. This library can be compiled for Android and may support various architectures.
The problem of this approach is that you may need to learn about the Android NDK, C and C++ to accomplish this.

But there is an alternative. You can wrap the c library and use the FFmpeg. But how?

For example, using FFmpeg Android, which has been compiled with x264, libass, fontconfig, freetype and fribidi and supports various architectures. But it still hard to program the if you want to stream in real-time you need to deal with file descriptors and in/out streams.

The best alternative, from a Java programming point of view, is to use JavaCV. JavaCV uses wrappers from  commonly used libraries of computer vision that includes: (OpenCV, FFmpeg, etc, and provides utility classes to make their functionality easier to use on the Java platform, including (of course) Android.

JavaCV also comes with hardware accelerated full-screen image display (CanvasFrame and GLCanvasFrame), easy-to-use methods to execute code in parallel on multiple cores (Parallel), user-friendly geometric and color calibration of cameras and projectors (GeometricCalibrator, ProCamGeometricCalibrator, ProCamColorCalibrator), detection and matching of feature points (ObjectFinder), a set of classes that implement direct image alignment of projector-camera systems (mainly GNImageAligner, ProjectiveTransformer, ProjectiveColorTransformer, ProCamTransformer, and ReflectanceInitializer), a blob analysis package (Blobs), as well as miscellaneous functionality in the JavaCV class. Some of these classes also have an OpenCL and OpenGL counterpart, their names ending with CL or starting with GL, i.e.: JavaCVCL, GLCanvasFrame, etc.

But how can we use this solution?

Here we have a basic implementation to stream using UDP.

```<code>String streamURL = "udp://ip_destination:port";
recorder = new FFmpegFrameRecorder(streamURL, frameWidth, frameHeight, 1);
recorder.setInterleaved(false);
// video options //
recorder.setFormat("mpegts");
recorder.setVideoOption("tune", "zerolatency");
recorder.setVideoOption("preset", "ultrafast");
recorder.setVideoBitrate(5 * 1024 * 1024);
recorder.setFrameRate(30);
recorder.setSampleRate(AUDIO_SAMPLE_RATE);
recorder.setVideoCodec(AV_CODEC_ID_H264);
recorder.setAudioCodec(AV_CODEC_ID_AAC);
</code>```

This part of the code shows how to initialize the FFmpegFrameRecorder object called recorder. This object will capture and encode the frames obtained from the camera and the samples obtained from the microphone.

If you want to capture a preview in the same Android app then we need to implement a CameraPreview Class this class will convert the raw data served from the Camera and it will create the Preview and the Frame for the FFmpegFrameRecorder.

Remember to replace the ip_destination with the ip of the pc or device where you want to send the stream. The port can be 8080 as example.

```<code>@Override
public Mat onCameraFrame(Mat mat)
{
    if (audioRecordRunnable == null) {
        startTime = System.currentTimeMillis();
        return mat;
    }
    if (recording && mat != null) {
        synchronized (semaphore) {
            try {
                Frame frame = converterToMat.convert(mat);
                long t = 1000 * (System.currentTimeMillis() - startTime);
                if (t > recorder.getTimestamp()) {
                    recorder.setTimestamp(t);
                }
                recorder.record(frame);
            } catch (FFmpegFrameRecorder.Exception e) {
                LogHelper.i(TAG, e.getMessage());
                e.printStackTrace();
            }
        }
    }
    return mat;
}
</code>```

This method shows the implementation of the onCameraFrame method that get the Mat (picture) from the camera and it is converted as a Frame and recorded by the FFmpegFrameRecorder object.

```<code>@Override
public void onSampleReady(ShortBuffer audioData)
{
    if (recorder == null) return;
    if (recording && audioData == null) return;

    try {
        long t = 1000 * (System.currentTimeMillis() - startTime);
        if (t > recorder.getTimestamp()) {
            recorder.setTimestamp(t);
        }
        LogHelper.e(TAG, "audioData: " + audioData);
        recorder.recordSamples(audioData);
    } catch (FFmpegFrameRecorder.Exception e) {
        LogHelper.v(TAG, e.getMessage());
        e.printStackTrace();
    }
}
</code>```

Same with the audio the audioData is a ShortBuffer object that will be recorder by the FFmpegFrameRecorder.

In the PC or device destination you can run the following command to get the stream.

```<code>ffplay udp://ip_source:port
</code>```

The ip_source is the ip of the smartphone that is streaming the camera and mic stream. The port must be the same 8080.

I created a solution in my github repository here: UDPAVStreamer.

Good luck

ContentLicense: CC BY-SA 3.0

Body:
A little bit late but I think this is a good question and it doesn't have a good answer yet.

If you want to stream the camera and mic from an android device you have two main alternatives: Java or NDK implementations.

Java implementation.

I'm only going to mention the idea but basically it is implement an RTSP Server and RTP Protocol in java based on these standards Real-Time Streaming Protocol Version 2.0 and RTP Payload Format for H.264 Video. This task will be very long and hard. But if you are doing your PhP it could be nice to have a nice RTSP Java lib for Android.

NDK implementation.

This is alternative include various solutions. The main idea is to use a power C or C++ library in our Android application. For this instance, FFmpeg. This library can be compiled for Android and may support various architectures.
The problem of this approach is that you may need to learn about the Android NDK, C and C++ to accomplish this.

But there is an alternative. You can wrap the c library and use the FFmpeg. But how?

For example, using FFmpeg Android, which has been compiled with x264, libass, fontconfig, freetype and fribidi and supports various architectures. But it still hard to program the if you want to stream in real-time you need to deal with file descriptors and in/out streams.

The best alternative, from a Java programming point of view, is to use JavaCV. JavaCV uses wrappers from  commonly used libraries of computer vision that includes: (OpenCV, FFmpeg, etc, and provides utility classes to make their functionality easier to use on the Java platform, including (of course) Android.

JavaCV also comes with hardware accelerated full-screen image display (CanvasFrame and GLCanvasFrame), easy-to-use methods to execute code in parallel on multiple cores (Parallel), user-friendly geometric and color calibration of cameras and projectors (GeometricCalibrator, ProCamGeometricCalibrator, ProCamColorCalibrator), detection and matching of feature points (ObjectFinder), a set of classes that implement direct image alignment of projector-camera systems (mainly GNImageAligner, ProjectiveTransformer, ProjectiveColorTransformer, ProCamTransformer, and ReflectanceInitializer), a blob analysis package (Blobs), as well as miscellaneous functionality in the JavaCV class. Some of these classes also have an OpenCL and OpenGL counterpart, their names ending with CL or starting with GL, i.e.: JavaCVCL, GLCanvasFrame, etc.

But how can we use this solution?

Here we have a basic implementation to stream using UDP.

String streamURL = "udp://ip_destination:port";
recorder = new FFmpegFrameRecorder(streamURL, frameWidth, frameHeight, 1);
recorder.setInterleaved(false);
// video options //
recorder.setFormat("mpegts");
recorder.setVideoOption("tune", "zerolatency");
recorder.setVideoOption("preset", "ultrafast");
recorder.setVideoBitrate(5 * 1024 * 1024);
recorder.setFrameRate(30);
recorder.setSampleRate(AUDIO_SAMPLE_RATE);
recorder.setVideoCodec(AV_CODEC_ID_H264);
recorder.setAudioCodec(AV_CODEC_ID_AAC);

This part of the code shows how to initialize the FFmpegFrameRecorder object called recorder. This object will capture and encode the frames obtained from the camera and the samples obtained from the microphone.

If you want to capture a preview in the same Android app then we need to implement a CameraPreview Class this class will convert the raw data served from the Camera and it will create the Preview and the Frame for the FFmpegFrameRecorder.

Remember to replace the ip_destination with the ip of the pc or device where you want to send the stream. The port can be 8080 as example.

@Override
public Mat onCameraFrame(Mat mat)
{
    if (audioRecordRunnable == null) {
        startTime = System.currentTimeMillis();
        return mat;
    }
    if (recording && mat != null) {
        synchronized (semaphore) {
            try {
                Frame frame = converterToMat.convert(mat);
                long t = 1000 * (System.currentTimeMillis() - startTime);
                if (t > recorder.getTimestamp()) {
                    recorder.setTimestamp(t);
                }
                recorder.record(frame);
            } catch (FFmpegFrameRecorder.Exception e) {
                LogHelper.i(TAG, e.getMessage());
                e.printStackTrace();
            }
        }
    }
    return mat;
}

This method shows the implementation of the onCameraFrame method that get the Mat (picture) from the camera and it is converted as a Frame and recorded by the FFmpegFrameRecorder object.

@Override
public void onSampleReady(ShortBuffer audioData)
{
    if (recorder == null) return;
    if (recording && audioData == null) return;

    try {
        long t = 1000 * (System.currentTimeMillis() - startTime);
        if (t > recorder.getTimestamp()) {
            recorder.setTimestamp(t);
        }
        LogHelper.e(TAG, "audioData: " + audioData);
        recorder.recordSamples(audioData);
    } catch (FFmpegFrameRecorder.Exception e) {
        LogHelper.v(TAG, e.getMessage());
        e.printStackTrace();
    }
}

Same with the audio the audioData is a ShortBuffer object that will be recorder by the FFmpegFrameRecorder.

In the PC or device destination you can run the following command to get the stream.

ffplay udp://ip_source:port

The ip_source is the ip of the smartphone that is streaming the camera and mic stream. The port must be the same 8080.

I created a solution in my github repository here: UDPAVStreamer.

Good luck


问:
Only permit one instance of a row with a particular column value in a multidimensional array
In my input array, I have multiple rows with a userTag of All, but I only want a maximum of one.  Other rows my have duplicated userTag values (such as Seeker), but extra All rows must be removed.

```<code>$input = [
    0 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 70],
    1 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 14],
    2 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => null],
    3 => ['userTag' => 'Seeker', 'fbId' => 10207897577195936, 'price' => 65],
    6 => ['userTag' => 'Seeker', 'fbId' => 709288842611719, 'price' => 75],
    17 => ['userTag' => 'Trader', 'fbId' => 2145752308783752, 'price' => null]
];
</code>```

My current code:

```<code>$dat = array();
$dat2 = array();
foreach ($input as $key => $value)
{
    $i = 0;
    $j = 0;
    if (count($dat) == 0) {
        $dat = $input[$key];
        $i++;
    } else {
        if ($input[$key]['userTag'] == "All") {
            if ($this->check($input[$key]['fbId'], $dat) == false) {
                $dat[$i] = $input[$key];
                $i++;
            }
        } else {
            $dat2[$j] = $input[$key];
            $j++;
        }
    }
}
$data =  array_merge($dat, $dat2);
return $data;
</code>```

The check() function:

```<code>public function check($val, $array) {
    foreach ($array as $vl) {
        if ($val == $array[$vl]['fbId']) {
             return true;
             break;
        }
    }
    return false;
}
</code>```

答:
You can try something simple like this:</p>

```<code>$data = [];
foreach($input as $key => $value)
{
  $counter = 0;
  if($value['userTag'] =="All"){
       if($counter == 0 ) {//test if is the first userTag == All
          $counter = 1;//increment the counter so the if doesn't trigger and the value isn't appended
          $data[] = $value;//add it to the array
       }
   } else {
   $data[] = $value;//keep the rest of the values
   }
}
      return $data;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my input array, I have multiple rows with a userTag of All, but I only want a maximum of one.  Other rows my have duplicated userTag values (such as Seeker), but extra All rows must be removed.

$input = [
    0 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 70],
    1 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 14],
    2 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => null],
    3 => ['userTag' => 'Seeker', 'fbId' => 10207897577195936, 'price' => 65],
    6 => ['userTag' => 'Seeker', 'fbId' => 709288842611719, 'price' => 75],
    17 => ['userTag' => 'Trader', 'fbId' => 2145752308783752, 'price' => null]
];

My current code:

$dat = array();
$dat2 = array();
foreach ($input as $key => $value)
{
    $i = 0;
    $j = 0;
    if (count($dat) == 0) {
        $dat = $input[$key];
        $i++;
    } else {
        if ($input[$key]['userTag'] == "All") {
            if ($this->check($input[$key]['fbId'], $dat) == false) {
                $dat[$i] = $input[$key];
                $i++;
            }
        } else {
            $dat2[$j] = $input[$key];
            $j++;
        }
    }
}
$data =  array_merge($dat, $dat2);
return $data;

The check() function:

public function check($val, $array) {
    foreach ($array as $vl) {
        if ($val == $array[$vl]['fbId']) {
             return true;
             break;
        }
    }
    return false;
}

Body:
You can try something simple like this:

$data = [];
foreach($input as $key => $value)
{
  $counter = 0;
  if($value['userTag'] =="All"){
       if($counter == 0 ) {//test if is the first userTag == All
          $counter = 1;//increment the counter so the if doesn't trigger and the value isn't appended
          $data[] = $value;//add it to the array
       }
   } else {
   $data[] = $value;//keep the rest of the values
   }
}
      return $data;


问:
Not getting keycode in keyup function
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

```<code>$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");
</code>```

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

```<code>function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}
</code>```

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

答:
Here is What You need.

You named the function as testKeyUp() and the real name of the function is shippingPackageKeyValueKeyUp(e). Also you wont get this but event

JS

```<code>$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(event)'>");

function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}
</code>```

Title: Not getting keycode in keyup function

Body:
I'm trying to add a keyup function to an input field which is added to DOM using jquery.

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(this)'>");

I want to do some operations once user enters value in testTextbox and enter key is pressed.

The keyup function is like:

function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}

The e.keyCode and e.which is returning undefined.

How can I get the keycode in keyup function? Can anyone help me to fix this? Thanks in advance.

Body:
Here is What You need.

You named the function as testKeyUp() and the real name of the function is shippingPackageKeyValueKeyUp(e). Also you wont get this but event

JS

$("#testDiv").html("<input id='testTextbox' name='testTextbox' type='text' onkeyup='testKeyUp(event)'>");

function testKeyUp(e) {
alert(e.keyCode+" : "+e.which);
}


问:
Simple MatLab Issue Regarding fplot and function files
The explicit problem is as follows: Write a function and use the fplot command to plot f(x)=x^3-x+8 versus x, for values of x from 0 to 100.

The easy way, throw the following code into matlab and call it a day:

```<code>Testing = @(x) x^3 - x + 8
fplot(Testing, [0 100])
</code>```

and done!

but I want to take a slightly more 'difficult' approach. Basically I made a seperate .m file that has the following:

```<code>function [y] = blah(x)
y = (x^3) - x + 8;
end
</code>```

and a script with the following

```<code>fplot('blah', [0 100])
</code>```

but it doesn't work. whyyyy ( i keep getting a positive-sloped line)

Thanks!

答:
In my version of Matlab (2016b), it works when blah is not a string:

```<code>blah = @(x) (x.^3) - x + 8;

plot(0:100, blah(0:100),'r.-')
hold all
fplot(blah,[0 100],'kx-')
</code>```

Body:
The explicit problem is as follows: Write a function and use the fplot command to plot f(x)=x^3-x+8 versus x, for values of x from 0 to 100.

The easy way, throw the following code into matlab and call it a day:

Testing = @(x) x^3 - x + 8
fplot(Testing, [0 100])

and done!

but I want to take a slightly more 'difficult' approach. Basically I made a seperate .m file that has the following:

function [y] = blah(x)
y = (x^3) - x + 8;
end

and a script with the following

fplot('blah', [0 100])

but it doesn't work. whyyyy ( i keep getting a positive-sloped line)

Thanks!

Body:
In my version of Matlab (2016b), it works when blah is not a string:

blah = @(x) (x.^3) - x + 8;

plot(0:100, blah(0:100),'r.-')
hold all
fplot(blah,[0 100],'kx-')


问:
Laravel Model Using Or in where Condition?
I want to get the template from user_webhook table in my database.In WHERE condition i am checking user_id,app_id and if either notify_admin or notify_customer value is 1 in user_webhook table.I am using query..

```<code>$templates= $this->where('notify_admin',1)
                 ->orwhere('notify_customer',1)
                 ->where('user_webhooks.user_id',$user_id)
                 ->where('user_webhooks.app_id',$app_id)
                 ->select(  'webhooks.id as webhook_id','webhooks.app_id','webhooks.topic','webhooks.type','webhooks.action',
                            'webhooks.sms_template','user_webhooks.id','user_webhooks.notify_admin',
                            'user_webhooks.notify_customer','user_webhooks.user_id','user_webhooks.sms_template_status',
                            'user_webhooks.sms_template as sms'
                         )
                 ->join ('webhooks',function($join){
                      $join>on('webhooks.id','=','user_webhooks.webhook_id');
                        })
                 ->get()
                 ->toArray();
</code>```

when i get query using DB::getQueryLog(), I found the query seems Like

```<code>select `telhok_webhooks`.`id` as `webhook_id`, `telhok_webhooks`.`app_id`,
 `telhok_webhooks`.`topic`, `telhok_webhooks`.`type`, `telhok_webhooks`.`action`,
 `telhok_webhooks`.`sms_template`, `telhok_user_webhooks`.`id`,
 `telhok_user_webhooks`.`notify_admin`, `telhok_user_webhooks`.`notify_customer`,
 `telhok_user_webhooks`.`user_id`, `telhok_user_webhooks`.`sms_template_status`,
 `telhok_user_webhooks`.`sms_template` as `sms` from `telhok_user_webhooks`

 inner join
 `telhok_webhooks` on `telhok_webhooks`.`id` = `telhok_user_webhooks`.`webhook_id`

  where `notify_admin` = ? or `notify_customer` = ? and `telhok_user_webhooks`.`user_id`
  = ? and  `telhok_user_webhooks`.`app_id` = ?
</code>```

The result of query giving result of all app_id and user_id.
So Please tell me use of OR in where condition.
Thanks in advance.

答:
You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:

```<code>$users = DB::table('users')
                ->where('votes', '>', 100)
                ->orWhere('name', 'John')
                ->get();
</code>```

Advanced usage:

```<code>Usere::where('id', 46)
      ->where('id', 2)
      ->where(function($q) {
          $q->where('Cab', 2)
            ->orWhere('Cab', 4);
      })
      ->get();
</code>```

The whereIn method verifies that a given column's value is contained within the given array:

```<code>$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();
</code>```

More: https://laravel.com/docs/5.5/queries

Body:
I want to get the template from user_webhook table in my database.In WHERE condition i am checking user_id,app_id and if either notify_admin or notify_customer value is 1 in user_webhook table.I am using query..

$templates= $this->where('notify_admin',1)
                 ->orwhere('notify_customer',1)
                 ->where('user_webhooks.user_id',$user_id)
                 ->where('user_webhooks.app_id',$app_id)
                 ->select(  'webhooks.id as webhook_id','webhooks.app_id','webhooks.topic','webhooks.type','webhooks.action',
                            'webhooks.sms_template','user_webhooks.id','user_webhooks.notify_admin',
                            'user_webhooks.notify_customer','user_webhooks.user_id','user_webhooks.sms_template_status',
                            'user_webhooks.sms_template as sms'
                         )
                 ->join ('webhooks',function($join){
                      $join>on('webhooks.id','=','user_webhooks.webhook_id');
                        })
                 ->get()
                 ->toArray();

when i get query using DB::getQueryLog(), I found the query seems Like

select `telhok_webhooks`.`id` as `webhook_id`, `telhok_webhooks`.`app_id`,
 `telhok_webhooks`.`topic`, `telhok_webhooks`.`type`, `telhok_webhooks`.`action`,
 `telhok_webhooks`.`sms_template`, `telhok_user_webhooks`.`id`,
 `telhok_user_webhooks`.`notify_admin`, `telhok_user_webhooks`.`notify_customer`,
 `telhok_user_webhooks`.`user_id`, `telhok_user_webhooks`.`sms_template_status`,
 `telhok_user_webhooks`.`sms_template` as `sms` from `telhok_user_webhooks`

 inner join
 `telhok_webhooks` on `telhok_webhooks`.`id` = `telhok_user_webhooks`.`webhook_id`

  where `notify_admin` = ? or `notify_customer` = ? and `telhok_user_webhooks`.`user_id`
  = ? and  `telhok_user_webhooks`.`app_id` = ?

The result of query giving result of all app_id and user_id.
So Please tell me use of OR in where condition.
Thanks in advance.

Body:
You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:

$users = DB::table('users')
                ->where('votes', '>', 100)
                ->orWhere('name', 'John')
                ->get();

Advanced usage:

Usere::where('id', 46)
      ->where('id', 2)
      ->where(function($q) {
          $q->where('Cab', 2)
            ->orWhere('Cab', 4);
      })
      ->get();

The whereIn method verifies that a given column's value is contained within the given array:

$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();

More: https://laravel.com/docs/5.5/queries


问:
how to crop image in to pieces using - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
i need to crop single image into 9 pieces.

for that most of them suggest the fallowing method.

```<code> - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
</code>```

But i did n't fine any where how do it using this.

can any one please help me.

how can i crop image using this method.

Thank u in advance.

答:
The method stretchableImageWithLeftCapWidth:topCapHeight is not cropping the image. It allows you to stretch an image with vertical and horyzontal margin.

In the doc you will read :

stretchableImageWithLeftCapWidth:topCapHeight:
  Creates and returns a new image object
  with the specified cap values.

To crop an image you should use CGImageCreateWithImageInRect :

CGImageCreateWithImageInRect
  Creates a bitmap image using the data contained within a subregion of an existing bitmap image.

You can achieve what you want with a method such as this one :

```<code>- (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {

    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:1.0 orientation:image.imageOrientation];
    CGImageRelease(newImageRef);
    return newImage;
}
</code>```

Hope this helps,
Vincent

ContentLicense: CC BY-SA 2.5

Body:
i need to crop single image into 9 pieces.

for that most of them suggest the fallowing method.

 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

But i did n't fine any where how do it using this.

can any one please help me.

how can i crop image using this method.

Thank u in advance.

Body:
The method stretchableImageWithLeftCapWidth:topCapHeight is not cropping the image. It allows you to stretch an image with vertical and horyzontal margin.

In the doc you will read :

stretchableImageWithLeftCapWidth:topCapHeight:
  Creates and returns a new image object
  with the specified cap values.

To crop an image you should use CGImageCreateWithImageInRect :

CGImageCreateWithImageInRect
  Creates a bitmap image using the data contained within a subregion of an existing bitmap image.

You can achieve what you want with a method such as this one :

- (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {

    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:1.0 orientation:image.imageOrientation];
    CGImageRelease(newImageRef);
    return newImage;
}

Hope this helps,
Vincent


问:
Hourglass Array Submission error
I am trying to solve the hourglass problem on hackerrank.you can find the details of problem here (https://www.hackerrank.com/challenges/2d-array).

On my machine code works fine and give correct results even for the testcase that gives error on hackerrank.

Here is the code:

```<code>maxSum = -70
#hourglass = []
arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
for row in range(0,6):
    for col in range(0,6):
        if (row + 2) < 6 and (col + 2) < 6 :
            sum = arr[row][col] + arr[row][col+1] + arr[row][col+2] + arr[row+1][col+1] + arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2]
            if sum > maxSum:
                #hourglass.append(arr[row][col])
                #hourglass.append(arr[row][col+1])
                #hourglass.append(arr[row][col+2])
                #hourglass.append(arr[row+1][col+1])
                #hourglass.append(arr[row+2][col])
                #hourglass.append(arr[row+2][col+1])
                #hourglass.append(arr[row+2][col+2])
                maxSum = sum
print(maxSum)
#print(hourglass)
</code>```

Following error rased while running code:

```<code>Traceback (most recent call last):
  File "solution.py", line 4, in <module>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
ValueError: invalid literal for int() with base 10: '1 1 1 0 0 0'
</code>```

The testcase for which error is raised is:

```<code>1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
</code>```

答:
Solution in Python:
    #!/bin/python3</p>

```<code>import sys
arr   = []
matt  = []
v_sum = 0
for arr_i in range(6):
   arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
   arr.append(arr_t)
for i in range(len(arr)-2):
    for j in range(len(arr)-2):
        v_sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1] + arr[i+2][j+2]
        matt.append(v_sum)

total = max(matt)
print (total)
</code>```

Title: Hourglass Array Submission error

Body:
I am trying to solve the hourglass problem on hackerrank.you can find the details of problem here (https://www.hackerrank.com/challenges/2d-array).

On my machine code works fine and give correct results even for the testcase that gives error on hackerrank.

Here is the code:

maxSum = -70
#hourglass = []
arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
for row in range(0,6):
    for col in range(0,6):
        if (row + 2) < 6 and (col + 2) < 6 :
            sum = arr[row][col] + arr[row][col+1] + arr[row][col+2] + arr[row+1][col+1] + arr[row+2][col] + arr[row+2][col+1] + arr[row+2][col+2]
            if sum > maxSum:
                #hourglass.append(arr[row][col])
                #hourglass.append(arr[row][col+1])
                #hourglass.append(arr[row][col+2])
                #hourglass.append(arr[row+1][col+1])
                #hourglass.append(arr[row+2][col])
                #hourglass.append(arr[row+2][col+1])
                #hourglass.append(arr[row+2][col+2])
                maxSum = sum
print(maxSum)
#print(hourglass)

Following error rased while running code:

Traceback (most recent call last):
  File "solution.py", line 4, in <module>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
  File "solution.py", line 4, in <listcomp>
    arr = [[int(input()) for x in range(0,6)] for y in range(0,6)]
ValueError: invalid literal for int() with base 10: '1 1 1 0 0 0'

The testcase for which error is raised is:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0

Body:
Solution in Python:
    #!/bin/python3

import sys
arr   = []
matt  = []
v_sum = 0
for arr_i in range(6):
   arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
   arr.append(arr_t)
for i in range(len(arr)-2):
    for j in range(len(arr)-2):
        v_sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1] + arr[i+2][j+2]
        matt.append(v_sum)

total = max(matt)
print (total)


答:
You can use the below code, This will remove all duplicate values from your array.

```<code>$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
</code>```

UPDATED ANSWER

The updated answer below is the accurate solution asked in the question which helps with All rows data too.

```<code>$temp = array();
foreach($arr as $key => $val) {
    if ($val['userTag'] == "All" && empty($temp)) {
        $temp[$key] = $arr[$key];
        unset($arr[$key]);
    }
    else if ($val['userTag'] == "All") {
        unset($arr[$key]);
    }
}
$arr = array_merge($arr, $temp);
</code>```

Title: Only permit one instance of a row with a particular column value in a multidimensional array

Body:
You can use the below code, This will remove all duplicate values from your array.

$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));

UPDATED ANSWER

The updated answer below is the accurate solution asked in the question which helps with All rows data too.

$temp = array();
foreach($arr as $key => $val) {
    if ($val['userTag'] == "All" && empty($temp)) {
        $temp[$key] = $arr[$key];
        unset($arr[$key]);
    }
    else if ($val['userTag'] == "All") {
        unset($arr[$key]);
    }
}
$arr = array_merge($arr, $temp);


问:
Modifying specific array elements in Python 3.1
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

```<code> for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))
</code>```

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

答:
If I understand correctly your problem, here is a possible solution:

```<code>for e in array:
    for lc in least_common:
        if e is lc[0]:
            new_array.append(e + e * (md[1] / 100))
            break
    else:
        new_array.append(e)
</code>```

The else clause in the for loop is executed when the loop terminates through exhaustion of the list, but not when the loop is terminated by a break statement.

Note that there is no need to use range or len, in Python you can just iterate on the elements of a sequence without involving indexes - you may use enumerate for that, but in this case you don't need to. Also, please don't use built-in names such as mod for your variables: here, I have renamed your dictionary md.

Body:
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

 for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

Body:
If I understand correctly your problem, here is a possible solution:

for e in array:
    for lc in least_common:
        if e is lc[0]:
            new_array.append(e + e * (md[1] / 100))
            break
    else:
        new_array.append(e)

The else clause in the for loop is executed when the loop terminates through exhaustion of the list, but not when the loop is terminated by a break statement.

Note that there is no need to use range or len, in Python you can just iterate on the elements of a sequence without involving indexes - you may use enumerate for that, but in this case you don't need to. Also, please don't use built-in names such as mod for your variables: here, I have renamed your dictionary md.


答:
Firstly i notice that your function name for the event handler does not match the onkeyup callback name.

Make sure the two match. And secondly

```<code>onkeyup='testKeyUp(e)'
</code>```

Title: Not getting keycode in keyup function

Body:
Firstly i notice that your function name for the event handler does not match the onkeyup callback name.

Make sure the two match. And secondly

onkeyup='testKeyUp(e)'


问:
Android Studio: Failed to update SDK or SDK Tools
Android Studio (v2.2 Preview 3) suddenly failed to update the tools. It keeps giving the error pasted below:

To install:
- LLDB 2.2 (lldb;2.2)
Preparing "Install LLDB 2.2".
Failed to read or create install properties file.
Failed packages:
- LLDB 2.2 (lldb;2.2)

I gave the folder full permissions. Ran android studio on administrator mode. End-tasked adb from task manager. Disabled antivirus. Deleted the folder and then ran the update again. But nothing works.

I also tried to create a new sdk location on my drive. But then that failed to, it gave the same error as above. -> Failed to read or create install properties file.

Any ideas?

答:
You cannot edit local.properties it is a generated file, right click your project and select 'Open Module Settings' under SDK Location put your location for your SDK.

paste in  /Users/gururaj/Library/Android/sdk

Clean and rebuild your project

Update

Try to delete your local.properties file and create a new one, but do not check it into version control.

Right click top level of project and Create new file 'local.properties' then add: sdk.dir=/Users/gururaj/Library/Android/sdk

Clean and build


问:
How can I set the default Java platform in NetBeans 8.2?
I want to set the default Java Platform which is used to build my projects in NetBeans 8.2 (netbeans_jdkhome).

Prior versions allowed me to do that. See this answer.

The only problem is that I want to set this platform to be 1.7 (instead of current 1.8), but NetBeans 8.2 requires to run on 1.8, so I cannot have 1.7 as the default Java Platform.

Is there a way to override it?

答:
There is no Eclipse-like default option.

You can set the Java platform for every imported project.
See Change JRE in a NetBeans project


问:
How to include file from another directory
In the root (www) I have two folders.

In the first folder, "folder1", I put a file called register.php.

In the next folder, "folder2", I put files called header.php and footer.php.

I need to include the header and footer files from folder2 in the register.php file.

How can i do this? I tried to use this include ../folder2/header.php

..but it does not work

答:
Try This it is work in my case

<?php require_once __DIR__."/../filename.php";?>```


问:
powershell command doesn't run successfully via ruby interpreter
I was trying to run some commands inside  a powershell script. The scrpt execution doesn't show any error. Script content is like:

```<code>Export-PfxCertificate –Cert $selectedcert_CA –FilePath "C:\\Windows\\System32\\CA_cert.pfx" -Password $SecurePassword -Verbose -force
</code>```

But when I  execute the powershell script from ruby as:
powershell.exe -file  file.ps1 arg1 arg2

It displays file is created on path but I don't see any file created. If I run the same command separately (not in script just as a powershell command), it creates the file perfectly.

Is there any rights issue or I need to run the script with some permissions.

答:
This snippet will run the powershell console with administrative rights</p>

```<code>PS> Start-Process powershell -Verb runAs
</code>```

Body:
I was trying to run some commands inside  a powershell script. The scrpt execution doesn't show any error. Script content is like:

Export-PfxCertificate –Cert $selectedcert_CA –FilePath "C:\\Windows\\System32\\CA_cert.pfx" -Password $SecurePassword -Verbose -force

But when I  execute the powershell script from ruby as:
powershell.exe -file  file.ps1 arg1 arg2

It displays file is created on path but I don't see any file created. If I run the same command separately (not in script just as a powershell command), it creates the file perfectly.

Is there any rights issue or I need to run the script with some permissions.

Body:
This snippet will run the powershell console with administrative rights

PS> Start-Process powershell -Verb runAs


答:
Change

```<code>->where('notify_admin',1)
->orwhere('notify_customer',1)
</code>```

to

```<code>->where(function($q){
  $q->where('notify_admin',1)
  ->orWhere('notify_customer',1);
})
</code>```

Without this, the orWhere will compare to all other wheres in your query instead of just comparing those two columns

Title: Laravel Model Using Or in where Condition?

Body:
Change

->where('notify_admin',1)
->orwhere('notify_customer',1)

to

->where(function($q){
  $q->where('notify_admin',1)
  ->orWhere('notify_customer',1);
})

Without this, the orWhere will compare to all other wheres in your query instead of just comparing those two columns


问:
Cant access uploaded files (flv&images) in drupal
I have a custom upload field with a content type which allows to upload flv files. And I have jw player in my theme which plays it for me. Everything works fine in my localhost.
But after uploading it show Access Denied or File not found Error.

I checked the permission of files folder, it seems to be ok. Directly typing the link to the file also returns page not found.

What is the problem? What can be done?
I tried with absolute url using print $base_url and also tried with print $base_path both of which work really well in localhost.

Update: even the thumbnail of image_cache or any uploaded images are not accessible. This is kind of weird. I cant figure this out.

.htacess is same in localhost and server. But why only in server I cant access? I checked
the log and its show pagenotfound error for all attempts.

My .htaccess file :

```<code>> #
> # Apache/PHP/Drupal settings:
> #
> # Protect files and directories from prying eyes. <FilesMatch
> "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl|svn-base)$|^(code-style\.pl|Entries.*|Repository|Root|Tag|Template|all-wcprops|entries|format)$">
> Order allow,deny </FilesMatch>
> # Don't show directory listings for URLs which map to a directory. Options
> -Indexes
>
>
>
> # Make Drupal handle any 404 errors. ErrorDocument 404 /index.php
>
> # Force simple error message for requests for non-existent favicon.ico.
> <Files favicon.ico>   # There is no
> end quote below, for compatibility
> with Apache 1.3.   ErrorDocument 404
> "The requested file favicon.ico was
> not found. </Files>
>
> # Set the default handler. DirectoryIndex index.php
>
> # Override PHP settings. More in sites/default/settings.php
> # but the following cannot be changed at runtime.
>
> # PHP 4, Apache 1. <IfModule mod_php4.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 4, Apache 2. <IfModule sapi_apache2.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 5, Apache 1 and 2. <IfModule mod_php5.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # Requires mod_expires to be enabled. <IfModule mod_expires.c>   # Enable
> expirations.   ExpiresActive On
>
>   # Cache all files for 2 weeks after
> access (A).   ExpiresDefault A1209600
>
>   <FilesMatch \.php$>
>     # Do not allow PHP scripts to be cached unless they explicitly send
> cache
>     # headers themselves. Otherwise all scripts would have to overwrite
> the
>     # headers set by mod_expires if they want another caching behavior.
> This may
>     # fail if an error occurs early in the bootstrap process, and it may
> cause
>     # problems if a non-Drupal PHP file is installed in a subdirectory.
>     ExpiresActive Off   </FilesMatch> </IfModule>
>
> # Various rewrite rules. <IfModule mod_rewrite.c>   RewriteEngine on
>
>   # If your site can be accessed both
> with and without the 'www.' prefix,
> you   # can use one of the following
> settings to redirect users to your
> preferred   # URL, either WITH or
> WITHOUT the 'www.' prefix. Choose ONLY
> one option:   #   # To redirect all
> users to access the site WITH the
> 'www.' prefix,   #
> (http://example.com/... will be
> redirected to
> http://www.example.com/...)   # adapt
> and uncomment the following:   #
> RewriteCond %{HTTP_HOST}
> ^example\.com$ [NC]   # RewriteRule
> ^(.*)$ http://www.example.com/$1
> [L,R=301]   #   # To redirect all
> users to access the site WITHOUT the
> 'www.' prefix,   #
> (http://www.example.com/... will be
> redirected to http://example.com/...)
> # uncomment and adapt the following:   # RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]   #
> RewriteRule ^(.*)$
> http://example.com/$1 [L,R=301]
>
>   # Modify the RewriteBase if you are
> using Drupal in a subdirectory or in a
> # VirtualDocumentRoot and the rewrite rules are not working properly.   #
> For example if your site is at
> http://example.com/drupal uncomment
> and   # modify the following line:   #
> RewriteBase /drupal   #   # If your
> site is running in a
> VirtualDocumentRoot at
> http://example.com/,   # uncomment the
> following line:   # RewriteBase /
>
>   # Rewrite URLs of the form 'x' to
> the form 'index.php?q=x'.
> RewriteCond %{REQUEST_FILENAME} !-f
> RewriteCond %{REQUEST_FILENAME} !-d
> RewriteCond %{REQUEST_URI}
> !=/favicon.ico   RewriteRule ^(.*)$
> index.php?q=$1 [L,QSA] </IfModule>
>
> # $Id: .htaccess,v 1.90.2.5 2010/02/02 07:25:22 dries Exp $
</code>```

.htacess in the file directory:

```<code>> SetHandler
> Drupal_Security_Do_Not_Remove_See_SA_2006_006
> Options None Options -FollowSymLinks
</code>```

答: There should be another htaccess in your files directory. Any permissions set in this file will override those set at the root level. As an alternative you could set Drupal to handle your files (the private filesystem option). Be aware that setting files to private will have a performance impact.</p>

Body:
I have a custom upload field with a content type which allows to upload flv files. And I have jw player in my theme which plays it for me. Everything works fine in my localhost.
But after uploading it show Access Denied or File not found Error.

I checked the permission of files folder, it seems to be ok. Directly typing the link to the file also returns page not found.

What is the problem? What can be done?
I tried with absolute url using print $base_url and also tried with print $base_path both of which work really well in localhost.

Update: even the thumbnail of image_cache or any uploaded images are not accessible. This is kind of weird. I cant figure this out.

.htacess is same in localhost and server. But why only in server I cant access? I checked
the log and its show pagenotfound error for all attempts.

My .htaccess file :

> #
> # Apache/PHP/Drupal settings:
> #
> # Protect files and directories from prying eyes. <FilesMatch
> "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl|svn-base)$|^(code-style\.pl|Entries.*|Repository|Root|Tag|Template|all-wcprops|entries|format)$">
> Order allow,deny </FilesMatch>
> # Don't show directory listings for URLs which map to a directory. Options
> -Indexes
>
>
>
> # Make Drupal handle any 404 errors. ErrorDocument 404 /index.php
>
> # Force simple error message for requests for non-existent favicon.ico.
> <Files favicon.ico>   # There is no
> end quote below, for compatibility
> with Apache 1.3.   ErrorDocument 404
> "The requested file favicon.ico was
> not found. </Files>
>
> # Set the default handler. DirectoryIndex index.php
>
> # Override PHP settings. More in sites/default/settings.php
> # but the following cannot be changed at runtime.
>
> # PHP 4, Apache 1. <IfModule mod_php4.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 4, Apache 2. <IfModule sapi_apache2.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # PHP 5, Apache 1 and 2. <IfModule mod_php5.c>   php_value
> magic_quotes_gpc                0
> php_value register_globals
> 0   php_value session.auto_start
> 0   php_value mbstring.http_input
> pass   php_value mbstring.http_output
> pass   php_value
> mbstring.encoding_translation   0
> </IfModule>
>
> # Requires mod_expires to be enabled. <IfModule mod_expires.c>   # Enable
> expirations.   ExpiresActive On
>
>   # Cache all files for 2 weeks after
> access (A).   ExpiresDefault A1209600
>
>   <FilesMatch \.php$>
>     # Do not allow PHP scripts to be cached unless they explicitly send
> cache
>     # headers themselves. Otherwise all scripts would have to overwrite
> the
>     # headers set by mod_expires if they want another caching behavior.
> This may
>     # fail if an error occurs early in the bootstrap process, and it may
> cause
>     # problems if a non-Drupal PHP file is installed in a subdirectory.
>     ExpiresActive Off   </FilesMatch> </IfModule>
>
> # Various rewrite rules. <IfModule mod_rewrite.c>   RewriteEngine on
>
>   # If your site can be accessed both
> with and without the 'www.' prefix,
> you   # can use one of the following
> settings to redirect users to your
> preferred   # URL, either WITH or
> WITHOUT the 'www.' prefix. Choose ONLY
> one option:   #   # To redirect all
> users to access the site WITH the
> 'www.' prefix,   #
> (http://example.com/... will be
> redirected to
> http://www.example.com/...)   # adapt
> and uncomment the following:   #
> RewriteCond %{HTTP_HOST}
> ^example\.com$ [NC]   # RewriteRule
> ^(.*)$ http://www.example.com/$1
> [L,R=301]   #   # To redirect all
> users to access the site WITHOUT the
> 'www.' prefix,   #
> (http://www.example.com/... will be
> redirected to http://example.com/...)
> # uncomment and adapt the following:   # RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]   #
> RewriteRule ^(.*)$
> http://example.com/$1 [L,R=301]
>
>   # Modify the RewriteBase if you are
> using Drupal in a subdirectory or in a
> # VirtualDocumentRoot and the rewrite rules are not working properly.   #
> For example if your site is at
> http://example.com/drupal uncomment
> and   # modify the following line:   #
> RewriteBase /drupal   #   # If your
> site is running in a
> VirtualDocumentRoot at
> http://example.com/,   # uncomment the
> following line:   # RewriteBase /
>
>   # Rewrite URLs of the form 'x' to
> the form 'index.php?q=x'.
> RewriteCond %{REQUEST_FILENAME} !-f
> RewriteCond %{REQUEST_FILENAME} !-d
> RewriteCond %{REQUEST_URI}
> !=/favicon.ico   RewriteRule ^(.*)$
> index.php?q=$1 [L,QSA] </IfModule>
>
> # $Id: .htaccess,v 1.90.2.5 2010/02/02 07:25:22 dries Exp $

.htacess in the file directory:

> SetHandler
> Drupal_Security_Do_Not_Remove_See_SA_2006_006
> Options None Options -FollowSymLinks


问:
store woocommerce checkout form data to custom table using api
I want to send the values of the checkout form to my API in woo commerce when customer clicks on the place order button, so that i can store this data using API. But i don't know how to use hooks to achieve this. Please can anybody suggest me a way to do this.</p>

答:
Put one of below hook in your function.php file and check proces after place and order or at the time of checkout process.Make you function  as per hook.

add_action( 'woocommerce_checkout_order_processed', 'my_status_pending',  1, 1  );

add_action( 'woocommerce_new_order', 'my_status_pending',  1, 1  );

Or if you want to add after payment try below code:

```<code>add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
    $order = new WC_Order( $order_id );
    $myuser_id = (int)$order->user_id;
    $user_info = get_userdata($myuser_id);
    $items = $order->get_items();
    foreach ($items as $item) {
        if ($item['product_id']==24) {
          // Do something clever
        }
    }
    return $order_id;
}
</code>```

Body:
Put one of below hook in your function.php file and check proces after place and order or at the time of checkout process.Make you function  as per hook.

add_action( 'woocommerce_checkout_order_processed', 'my_status_pending',  1, 1  );

add_action( 'woocommerce_new_order', 'my_status_pending',  1, 1  );

Or if you want to add after payment try below code:

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
    $order = new WC_Order( $order_id );
    $myuser_id = (int)$order->user_id;
    $user_info = get_userdata($myuser_id);
    $items = $order->get_items();
    foreach ($items as $item) {
        if ($item['product_id']==24) {
          // Do something clever
        }
    }
    return $order_id;
}


问:
Laravel: How to use composer to inject data across all views?
I want to offload some HTML sections of my site into partials (includes) files rather than repeating the information in each view or layout. However, I also need them to contain specific data. An obvious example is the head section; I would like to put this into a partial, however I also want to be able to set the document title and META fields for each page.

I think the best way is to use Laravel's view-composer

As per the docs, I can use an array to define the composer for multiple views at once:

```<code>View::composer(array('view1','view2', 'view3'), function($view)
{
    $view->with('count', User::count());
});
</code>```

However, what if I want to use this composer for every view, as I do in this case?

There's a few answers kicking around SO (such as this one) which suggests I use a wildcard. So here's my code:

```<code>View::composer('*', function($view)
{
    $view->with('header', View::make('partials.head', $view->getData()));
    $view->with('footer', View::make('partials.footer', $view->getData()));
});
</code>```

Here's the problem: Using this is currently giving me an out of memory error, which suggests that it is very inefficient (and therefore that I really shouldn't be doing this).

So do I really need to pass an array listing every page on my website?

Isn't there a way to use composer for every page rendered, like I can with View::share(); ?

答:
This is now possible in Laravel 5.5

Put this is your AppServiceProvider boot method:

```<code>View::share('data', [1, 2, 3]);
</code>```

Body:
I want to offload some HTML sections of my site into partials (includes) files rather than repeating the information in each view or layout. However, I also need them to contain specific data. An obvious example is the head section; I would like to put this into a partial, however I also want to be able to set the document title and META fields for each page.

I think the best way is to use Laravel's view-composer

As per the docs, I can use an array to define the composer for multiple views at once:

View::composer(array('view1','view2', 'view3'), function($view)
{
    $view->with('count', User::count());
});

However, what if I want to use this composer for every view, as I do in this case?

There's a few answers kicking around SO (such as this one) which suggests I use a wildcard. So here's my code:

View::composer('*', function($view)
{
    $view->with('header', View::make('partials.head', $view->getData()));
    $view->with('footer', View::make('partials.footer', $view->getData()));
});

Here's the problem: Using this is currently giving me an out of memory error, which suggests that it is very inefficient (and therefore that I really shouldn't be doing this).

So do I really need to pass an array listing every page on my website?

Isn't there a way to use composer for every page rendered, like I can with View::share(); ?

Body:
This is now possible in Laravel 5.5

Put this is your AppServiceProvider boot method:

View::share('data', [1, 2, 3]);


问:
Execution failed with app:processDebugGoogleServices'

I have been trying to add retrieve some of my images from Firebase firestore. After I added the dependencies I have the following error

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin (information about the latest version is
  available at
  https://bintray.com/android/android-tools/com.google.gms.google-services/)
  or updating the version of com.google.android.gms to 10.0.1."

This is my module app gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "com.example.rimapps.charpapers"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.+'
    compile 'com.android.support:recyclerview-v7:27.+'
    compile 'com.android.support:cardview-v7:27.+'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.firebase:firebase-firestore:11.4.2'
    compile 'com.google.firebase:firebase-appindexing:10.0.1'

}
apply plugin: 'com.google.gms.google-services'```
</div>
</div>

This is my project gradle </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}</code>```

Please help to solve this problem I have tried all I could.

答:
Read Error Log

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin

You should use SAME version (Version conflict) . Use 11.4.2

```<code> compile 'com.google.firebase:firebase-messaging:11.4.2'
 compile 'com.google.firebase:firebase-firestore:11.4.2'
 compile 'com.google.firebase:firebase-appindexing:11.4.2'
</code>```

After that, Clean-Rebuild-Run.

FYI

SDK Version 11.6.2 has been launched. You can use 11.6.2 version.

Body:
I have been trying to add retrieve some of my images from Firebase firestore. After I added the dependencies I have the following error

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin (information about the latest version is
  available at
  https://bintray.com/android/android-tools/com.google.gms.google-services/)
  or updating the version of com.google.android.gms to 10.0.1."

This is my module app gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "com.example.rimapps.charpapers"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.+'
    compile 'com.android.support:recyclerview-v7:27.+'
    compile 'com.android.support:cardview-v7:27.+'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.firebase:firebase-firestore:11.4.2'
    compile 'com.google.firebase:firebase-appindexing:10.0.1'

}
apply plugin: 'com.google.gms.google-services'

This is my project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Please help to solve this problem I have tried all I could.

Body:
Read Error Log

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin

You should use SAME version (Version conflict) . Use 11.4.2

 compile 'com.google.firebase:firebase-messaging:11.4.2'
 compile 'com.google.firebase:firebase-firestore:11.4.2'
 compile 'com.google.firebase:firebase-appindexing:11.4.2'

After that, Clean-Rebuild-Run.

FYI

SDK Version 11.6.2 has been launched. You can use 11.6.2 version.


问:
I'm getting the time picker value in 24 hr format. How can I convert it to 12 hr format?
Code

```<code>    public static class TimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR);
            int minute = c.get(Calendar.MINUTE);
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }
        @Override
        public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
//            displayCurrentTime.setText(String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
            displayCurrentTime.setText(String.format("%02d:%02d %s", hourOfDay == 0 ? 12 : hourOfDay,
                    minute, hourOfDay < 12 ? "am" : "pm"));
        }
    }
</code>```

This is the code that I'm using to display the time from the time picker. But the time is being displayed in 24hr format because of is24HourFormat.
 How do I convert the same into 12hr format?

答:
Use SimpleDateFormate.</p>

```<code>  @Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
    Calendar calendar=Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
    calendar.set(Calendar.MINUTE,minute);
    String dateIn12Hour=new SimpleDateFormat("hh:mm a").format(calendar.getTimeInMillis());
    displayCurrentTime.setText(dateIn12Hour);
}
</code>```

Body:
Code

    public static class TimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR);
            int minute = c.get(Calendar.MINUTE);
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }
        @Override
        public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
//            displayCurrentTime.setText(String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
            displayCurrentTime.setText(String.format("%02d:%02d %s", hourOfDay == 0 ? 12 : hourOfDay,
                    minute, hourOfDay < 12 ? "am" : "pm"));
        }
    }

This is the code that I'm using to display the time from the time picker. But the time is being displayed in 24hr format because of is24HourFormat.
 How do I convert the same into 12hr format?

Body:
Use SimpleDateFormate.

  @Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
    Calendar calendar=Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
    calendar.set(Calendar.MINUTE,minute);
    String dateIn12Hour=new SimpleDateFormat("hh:mm a").format(calendar.getTimeInMillis());
    displayCurrentTime.setText(dateIn12Hour);
}


问:
NSTextField Clear Button
On the iPhone a UITextField can have a clearButtonMode set to show a small clear button (X) at the end of a text input. Similarly, on the Mac the NSSearchField has a nice clear button on it at the end. My question is - is there a way to enable this on a normal NSTextField?

答:
There's nothing built-in; just use a search field and turn off the magnifying glass:</p>

```<code>[[button cell] setSearchButtonCell:nil];
</code>```

Title: NSTextField Clear Button

Body:
There's nothing built-in; just use a search field and turn off the magnifying glass:

[[button cell] setSearchButtonCell:nil];


答:
Use setIs24HourView method of TimePicker and set it to false.

https://developer.android.com/reference/android/widget/TimePicker.html#setIs24HourView(java.lang.Boolean)

Title: I'm getting the time picker value in 24 hr format. How can I convert it to 12 hr format?


问:
Why load incorrect manifest.mf when I execute jar
```<code>InputStream manifestStream = ServiceController.class.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF")

Manifest manifest= new Manifest(manifestStream);
</code>```

As above code in jar file, when I execute jar in command line on Mac, it reads other manifest file.

As far as I can test, this case just appear MAC and AWS service instance, it is not appear windows and linux server. that means this jar can reads expected manifest file in windows and linux server.

Can someone please take a look?

Executed command: java -jar xxx.jar

Jar file structure:

答:
Open file.jar by 7z or zip and look folder META-INF -> check  MANIFEST.MF file -> Check your Main-Class in this manifest file.
And you must remove *.RSA, *.MF in folder META-INF (only keep MANIFEST.MF file)</p>

Body:
InputStream manifestStream = ServiceController.class.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF")

Manifest manifest= new Manifest(manifestStream);

As above code in jar file, when I execute jar in command line on Mac, it reads other manifest file.

As far as I can test, this case just appear MAC and AWS service instance, it is not appear windows and linux server. that means this jar can reads expected manifest file in windows and linux server.

Can someone please take a look?

Executed command: java -jar xxx.jar

Jar file structure:


问:
get_the_category_list to display only two categories
I am using get_the_category_list()  function for getting categories but for a particular post if there is too many categories it looks bad.

I want to display just 2 or 3 categories not all.

How can I achieve this using get_the_category_list()  function

答:
There are so many methods. if you want 2, then you can simply use index.

first category $categories_list[0];
second category $categories_list[1];

you can also add (isset($categories_list[1]))  to avoid undefined index errors.


问:
Fetching data with respect to array with in array Json
I need to fetch two arrays from a json response
Here is my response.

```<code>{
"data": [
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            }
        ],
        "id": "14",
        "cat_id": "x",
        "category": "Casual shirts"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            }
        ],
        "id": "15",
        "cat_id": "x",
        "category": "Jackets"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            },
            {
                "id": "833",
                "cat_id": "154",
                "sub_category": "Pepe jeans"
            },
            {
                "id": "834",
                "cat_id": "154",
                "sub_category": "John players"
            }
        ],
        "id": "154",
        "cat_id": "x",
        "category": "Jeans"
    }
],
"status": 100
}
</code>```

While trying to fetch data, and put it in to a list adapter in which i want to display categories in one text box and subcategories in other with comma separation.
Like this:

```<code>Category : Jeans

Sub Category :John players,Pepe jeans,Pan America,Roadster,wildcraft
</code>```

I tried implementing this by creating model class for both category and sub category. Getting category correctly, but getting all subcategories.

答:
```<code>JsonObject root = new JsonObject(your json);
JsonArray data =  root.getJsonArray("data");
for loop data.size
inside loop
JsonObject jObj = data.getJsonObject(i);
JsonArray sub_cat = jObj.getJsonArray("sub_cat");
 for loop int j=0 to sub_cat.length
inside loop
JsonObject obj= sub_cat .getJsonObject(i);
String sub_category = obj.getString("sub_category");// here you will get all sub_category data
</code>```

Body:
I need to fetch two arrays from a json response
Here is my response.

{
"data": [
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            }
        ],
        "id": "14",
        "cat_id": "x",
        "category": "Casual shirts"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            }
        ],
        "id": "15",
        "cat_id": "x",
        "category": "Jackets"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            },
            {
                "id": "833",
                "cat_id": "154",
                "sub_category": "Pepe jeans"
            },
            {
                "id": "834",
                "cat_id": "154",
                "sub_category": "John players"
            }
        ],
        "id": "154",
        "cat_id": "x",
        "category": "Jeans"
    }
],
"status": 100
}

While trying to fetch data, and put it in to a list adapter in which i want to display categories in one text box and subcategories in other with comma separation.
Like this:

Category : Jeans

Sub Category :John players,Pepe jeans,Pan America,Roadster,wildcraft

I tried implementing this by creating model class for both category and sub category. Getting category correctly, but getting all subcategories.


问:
Run DJango server from outside of virtual environment by using script
I have created DJango Project inside virtual environment.
Let's say virtual environment  DJangoProject project name is Mysite
I am tired of running ./manage.py runserver everytime so that I wanted to automate running server when I was logged into ubuntu.I tried many ways but was always failing to access the path of virtual environment. So help me to  run manage.py runserver from outside of virtual environment using bash or shell scripting.
 any help can be appreciate!

答:
What are looking for is something like Gunicorn, because runserver is only for development purposes. This is detailed tutorial for you to use

Link


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答:
I prefer to keep the .h file as clean as possible. Therefore, small functions that are as simple as get/set I often use to put in a separate file as inline-defined functions, and then include that file (where I use the extension .inl) into the .h header file:

```<code>// foo.h

class foo
{
public:
   int bar() const;

private:
   int m_bar;
};

#include "foo.inl"

// foo.inl

inline
int foo::bar() const
{
   return m_bar;
}
</code>```

I think that this gives the best of two worlds, at the same time hiding most of the implementation from the header, and still keep the advantage of inlining simple code (as a rule of thumb I keep it within at most 3 statements).

LastEditorDisplayName: Eddie Parker

Body:
I prefer to keep the .h file as clean as possible. Therefore, small functions that are as simple as get/set I often use to put in a separate file as inline-defined functions, and then include that file (where I use the extension .inl) into the .h header file:

// foo.h

class foo
{
public:
   int bar() const;

private:
   int m_bar;
};

#include "foo.inl"

// foo.inl

inline
int foo::bar() const
{
   return m_bar;
}

I think that this gives the best of two worlds, at the same time hiding most of the implementation from the header, and still keep the advantage of inlining simple code (as a rule of thumb I keep it within at most 3 statements).

OwnerDisplayName: Stefan Rådström