问:
gstreamer error when streaming side-by-side 720p
gstreamer raises an error when trying to stream side-by-side video from a stereoscopic UVC camera.

I have a stereoscopic camera attached via USB to an ARM board, but on the highest resolution setting that the camera allows gstreamer is raising an Invalid Dimension 0x0 error.

```<code>v4l2-ctl --list-formats-ext -d /dev/video2
ioctl: VIDIOC_ENUM_FMT
        Index       : 0
        Type        : Video Capture
        Pixel Format: 'MJPG' (compressed)
        Name        : Motion-JPEG
                Size: Discrete 2560x960
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 2560x720
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1280x480
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 640x240
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
$ gst-launch-1.0 -v v4l2src device=/dev/video2 ! "image/jpeg, width=2560, height=960, framerate=60/1" ! progressreport ! rtpjpegpay ! udpsink host=127.0.0.1 port=5000
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstV4l2Src:v4l2src0.GstPad:src: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:src: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstProgressReport:progressreport0.GstPad:src: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0.GstPad:src: caps = application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)JPEG, a-framerate=(string)60.000000, x-dimensions=(string)"2560\,960", payload=(int)26, ssrc=(uint)1656850644, timestamp-offset=(uint)2590317031, seqnum-offset=(uint)18356
/GstPipeline:pipeline0/GstUDPSink:udpsink0.GstPad:sink: caps = application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)JPEG, a-framerate=(string)60.000000, x-dimensions=(string)"2560\,960", payload=(int)26, ssrc=(uint)1656850644, timestamp-offset=(uint)2590317031, seqnum-offset=(uint)18356
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0.GstPad:sink: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstProgressReport:progressreport0.GstPad:sink: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:sink: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
0:00:00.163107430  7652 0x55d47a920a30 WARN          v4l2bufferpool gstv4l2bufferpool.c:790:gst_v4l2_buffer_pool_start:<v4l2src0:pool:src> Uncertain or not enough buffers, enabling copy threshold
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0: timestamp = 2590320450
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0: seqnum = 18356
progressreport0 (00:00:05): 4 seconds
progressreport0 (00:00:10): 9 seconds
progressreport0 (00:00:15): 14 seconds
0:00:15.770955137  7652 0x55d47a920a30 WARN                 v4l2src gstv4l2src.c:968:gst_v4l2src_create:<v4l2src0> lost frames detected: count = 2 - ts: 0:00:15.622372937
progressreport0 (00:00:20): 19 seconds
progressreport0 (00:00:25): 24 seconds
progressreport0 (00:00:30): 29 seconds
progressreport0 (00:00:35): 34 seconds
</code>```

Then on the viewing machine (currently just using localhost on the same laptop):

```<code>$ gst-launch-1.0 -e -v udpsrc port=5000 ! application/x-rtp, encoding-name=JPEG, payload=26 ! rtpjpegdepay ! jpegdec ! autovideosink
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:src: caps = application/x-rtp, encoding-name=(string)JPEG, payload=(int)26, media=(string)video, clock-rate=(int)90000
/GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0.GstPad:sink: caps = application/x-rtp, encoding-name=(string)JPEG, payload=(int)26, media=(string)video, clock-rate=(int)90000
WARNING: from element /GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0: Invalid Dimension 0x0.
Additional debug info:
gstrtpjpegdepay.c(741): gst_rtp_jpeg_depay_process (): /GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0
WARNING: from element /GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0: Invalid Dimension 0x0.
</code>```

The two lowest resolution modes work with this configuration, but the 720p side-by-side mode throws the foregoing errors.

What am I doing wrong here? And does this have anything to do with gst-launch-1.0 not supporting full screen mode perhaps?

Thanks in advance

答:
See RFC 2435 https://www.rfc-editor.org/rfc/rfc2435 on width and height:

```<code>3.1.5.  Width: 8 bits

   This field encodes the width of the image in 8-pixel multiples (e.g.,
   a width of 40 denotes an image 320 pixels wide).  The maximum width
   is 2040 pixels.

3.1.6.  Height: 8 bits

   This field encodes the height of the image in 8-pixel multiples
   (e.g., a height of 30 denotes an image 240 pixels tall). When
   encoding interlaced video, this is the height of a video field, since
   fields are individually JPEG encoded. The maximum height is 2040
   pixels.
</code>```

Here you can see that the limit is 2040 pixels in both dimensions. This is a protocol limitation.

Check the GStreamer source code https://gitlab.freedesktop.org/gstreamer/gst-plugins-good/blob/master/gst/rtp/gstrtpjpegdepay.c:

```<code>  /* allow frame dimensions > 2040, passed in SDP session or media attributes
   * from gstrtspsrc.c (gst_rtspsrc_sdp_attributes_to_caps), or in caps */
  if (!width)
    width = rtpjpegdepay->media_width;

  if (!height)
    height = rtpjpegdepay->media_height;
</code>```

Here you can see the GStreamer devs offer you a solution for this protocol limitation. When receiving images over 2040 pixels in either dimension you probably will have to add width and height information to the caps.

Body:
gstreamer raises an error when trying to stream side-by-side video from a stereoscopic UVC camera.

I have a stereoscopic camera attached via USB to an ARM board, but on the highest resolution setting that the camera allows gstreamer is raising an Invalid Dimension 0x0 error.

v4l2-ctl --list-formats-ext -d /dev/video2
ioctl: VIDIOC_ENUM_FMT
        Index       : 0
        Type        : Video Capture
        Pixel Format: 'MJPG' (compressed)
        Name        : Motion-JPEG
                Size: Discrete 2560x960
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 2560x720
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 1280x480
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
                Size: Discrete 640x240
                        Interval: Discrete 0.017s (60.000 fps)
                        Interval: Discrete 0.033s (30.000 fps)
$ gst-launch-1.0 -v v4l2src device=/dev/video2 ! "image/jpeg, width=2560, height=960, framerate=60/1" ! progressreport ! rtpjpegpay ! udpsink host=127.0.0.1 port=5000
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstV4l2Src:v4l2src0.GstPad:src: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:src: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstProgressReport:progressreport0.GstPad:src: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0.GstPad:src: caps = application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)JPEG, a-framerate=(string)60.000000, x-dimensions=(string)"2560\,960", payload=(int)26, ssrc=(uint)1656850644, timestamp-offset=(uint)2590317031, seqnum-offset=(uint)18356
/GstPipeline:pipeline0/GstUDPSink:udpsink0.GstPad:sink: caps = application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)JPEG, a-framerate=(string)60.000000, x-dimensions=(string)"2560\,960", payload=(int)26, ssrc=(uint)1656850644, timestamp-offset=(uint)2590317031, seqnum-offset=(uint)18356
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0.GstPad:sink: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstProgressReport:progressreport0.GstPad:sink: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:sink: caps = image/jpeg, width=(int)2560, height=(int)960, framerate=(fraction)60/1, pixel-aspect-ratio=(fraction)1/1, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
0:00:00.163107430  7652 0x55d47a920a30 WARN          v4l2bufferpool gstv4l2bufferpool.c:790:gst_v4l2_buffer_pool_start:<v4l2src0:pool:src> Uncertain or not enough buffers, enabling copy threshold
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0: timestamp = 2590320450
/GstPipeline:pipeline0/GstRtpJPEGPay:rtpjpegpay0: seqnum = 18356
progressreport0 (00:00:05): 4 seconds
progressreport0 (00:00:10): 9 seconds
progressreport0 (00:00:15): 14 seconds
0:00:15.770955137  7652 0x55d47a920a30 WARN                 v4l2src gstv4l2src.c:968:gst_v4l2src_create:<v4l2src0> lost frames detected: count = 2 - ts: 0:00:15.622372937
progressreport0 (00:00:20): 19 seconds
progressreport0 (00:00:25): 24 seconds
progressreport0 (00:00:30): 29 seconds
progressreport0 (00:00:35): 34 seconds

Then on the viewing machine (currently just using localhost on the same laptop):

$ gst-launch-1.0 -e -v udpsrc port=5000 ! application/x-rtp, encoding-name=JPEG, payload=26 ! rtpjpegdepay ! jpegdec ! autovideosink
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:src: caps = application/x-rtp, encoding-name=(string)JPEG, payload=(int)26, media=(string)video, clock-rate=(int)90000
/GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0.GstPad:sink: caps = application/x-rtp, encoding-name=(string)JPEG, payload=(int)26, media=(string)video, clock-rate=(int)90000
WARNING: from element /GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0: Invalid Dimension 0x0.
Additional debug info:
gstrtpjpegdepay.c(741): gst_rtp_jpeg_depay_process (): /GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0
WARNING: from element /GstPipeline:pipeline0/GstRtpJPEGDepay:rtpjpegdepay0: Invalid Dimension 0x0.

The two lowest resolution modes work with this configuration, but the 720p side-by-side mode throws the foregoing errors.

What am I doing wrong here? And does this have anything to do with gst-launch-1.0 not supporting full screen mode perhaps?

Thanks in advance

Body:
See RFC 2435 https://www.rfc-editor.org/rfc/rfc2435 on width and height:

3.1.5.  Width: 8 bits

   This field encodes the width of the image in 8-pixel multiples (e.g.,
   a width of 40 denotes an image 320 pixels wide).  The maximum width
   is 2040 pixels.

3.1.6.  Height: 8 bits

   This field encodes the height of the image in 8-pixel multiples
   (e.g., a height of 30 denotes an image 240 pixels tall). When
   encoding interlaced video, this is the height of a video field, since
   fields are individually JPEG encoded. The maximum height is 2040
   pixels.

Here you can see that the limit is 2040 pixels in both dimensions. This is a protocol limitation.

Check the GStreamer source code https://gitlab.freedesktop.org/gstreamer/gst-plugins-good/blob/master/gst/rtp/gstrtpjpegdepay.c:

  /* allow frame dimensions > 2040, passed in SDP session or media attributes
   * from gstrtspsrc.c (gst_rtspsrc_sdp_attributes_to_caps), or in caps */
  if (!width)
    width = rtpjpegdepay->media_width;

  if (!height)
    height = rtpjpegdepay->media_height;

Here you can see the GStreamer devs offer you a solution for this protocol limitation. When receiving images over 2040 pixels in either dimension you probably will have to add width and height information to the caps.


来源: stackexchange

问:
Allow user to delete textfield text but restrict maximum text length
I have UITextField and i want allow user to type only up to 4 symbols. But i also want to allow them to erase symbols with keyboard (i mean, delete last and move caret for left. Symbol look like rectangle left arrow with cross on iOS keyboard).

For now i ended up with:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text, text.count < 4 else { return false }
    return true
  }
</code>```

But i have no idea, how to let users to delete symbols. When text count become 4, i am not allowed to type or do any actions.

答:
use this</p>

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return textField.text!.count + string.count < 5
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have UITextField and i want allow user to type only up to 4 symbols. But i also want to allow them to erase symbols with keyboard (i mean, delete last and move caret for left. Symbol look like rectangle left arrow with cross on iOS keyboard).

For now i ended up with:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text, text.count < 4 else { return false }
    return true
  }

But i have no idea, how to let users to delete symbols. When text count become 4, i am not allowed to type or do any actions.

Body:
use this

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return textField.text!.count + string.count < 5
}


问:
TestNG parallel tests failing
First let me put out the structure of my tests:

There is BaseTest(Singleton) containing a setUp() method which runs @BeforeSuite. This setUp() method initializes  MyObject which is declared as:

protected static ThreadLocal<MyObject> myObject= new ThreadLocal<MyObject>();

All other tests extend this BaseTest.
e.g. Say CustomerTest

This CustomerTest have -

A test with @BeforeClass tag - it gets the stored instance of MyObject.

Other tests will use MyObject, perform some operation and do the tests

A test with @AfterClass tag - does destroy the instance of MyObject

So ideally, this setUp() method should run before any other test. And it runs only once.

I am trying to run test cases parallely in TestNG framework. To achieve that, I have set the parallel attribute on the suite tag of testng.xml as

<suite name="Suite" parallel="classes" thread-count="5">

Now, within the seconds after I fire the build, the build gets failed with all basic tests failed and others as skipped.

Failed test are due to java.lang.NullPointerException

My understanding is, while setUp() method is being run on a thread, some other tests on different threads are trying to access the MyObject which isn't initialized yet. So is the failure. Is my understanding correct?

If yes, what could be the possible solution to this?

Can I do something like - let the thread run first in which setUp() is being run and till then don't let other threads invoke. And once the call to setUp() finishes/ returns, then allow other threads to invoke.

(Note: My project uses Maven)

答:
Two things:

NullPointerExceptions are pretty easy
to track down, what does that one
tell you? You should include the
stack trace and the code.

@BeforeSuite will only be run once,
but based on what you're saying, you
expect it to run before each test
method, which means you should use
@BeforeMethod.

ContentLicense: CC BY-SA 3.0

Title: TestNG parallel tests failing


答:
From the docs of textField(_:shouldChangeCharactersIn:replacementString:)

When the user deletes one or more characters, the replacement string is empty.

Thus, all you're missing is to check if the replacement string is empty:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.isEmpty || (textField.text?.count ?? 0) < 4
}
```

Title: Allow user to delete textfield text but restrict maximum text length


问:
What is the meaning of this output in the console when I run model.fit_generator in Keras?
I am new working with Keras. The code works correctly, but I would like to know the meaning of the values shown in the epochs. I am using the following code.

Where it says 46/46 and 226/277, what is the meaning of these numbers? Why 2 appear when normally only appears for example 100/100?

```<code>import sys
import os
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras import optimizers
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dropout, Flatten, Dense, Activation
from tensorflow.python.keras.layers import  Convolution2D, MaxPooling2D
from tensorflow.python.keras import backend as K

K.clear_session()

data_entrenamiento = '/content/DatosEntrenamiento' #images

"""
Parameters
"""
epocas=20
longitud, altura = 28, 28
batch_size = 32
pasos = 1000
validation_steps = 300
filtrosConv1 = 32
filtrosConv2 = 64
tamano_filtro1 = (3, 3)
tamano_filtro2 = (2, 2)
tamano_pool = (2, 2)
clases = 3
lr = 0.0004

##Preparamos nuestras imagenes

generator = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    )

test_datagen = ImageDataGenerator(rescale=1. / 255,validation_split=0.2)

entrenamiento_generador = generator.flow_from_directory(
    data_entrenamiento,
    target_size=(altura, longitud),
    batch_size=batch_size,
    class_mode='categorical',
    subset='training')

validacion_generador = test_datagen.flow_from_directory(
    data_entrenamiento,
    target_size=(altura, longitud),
    batch_size=batch_size,
    class_mode='categorical',
    subset='validation')

cnn = Sequential()
cnn.add(Convolution2D(filtrosConv1, tamano_filtro1, padding ="same", input_shape=(longitud, altura, 3), activation='relu'))
cnn.add(MaxPooling2D(pool_size=tamano_pool))

cnn.add(Convolution2D(filtrosConv2, tamano_filtro2, padding ="same"))
cnn.add(MaxPooling2D(pool_size=tamano_pool))

cnn.add(Flatten())
cnn.add(Dense(256, activation='relu'))
cnn.add(Dropout(0.5))
cnn.add(Dense(clases, activation='softmax'))

cnn.compile(loss='categorical_crossentropy',
            optimizer=optimizers.Adam(lr=lr),
            metrics=['accuracy'])

his = cnn.fit_generator(
    entrenamiento_generador,
    steps_per_epoch=pasos,
    epochs=epocas,
    validation_data=validacion_generador,
    validation_steps=validation_steps)

</code>```

The output is :

```<code>Found 7230 images belonging to 3 classes.
Found 1446 images belonging to 3 classes.

Epoch 1/20

46/46 [=========] - 1s 21ms/step...

226/226 [======] - 8s 36ms/step...

Epoch 2/20

46/46 [=========] - 1s 21ms/step ...

226/226 [=======] - 8s 35ms/step ...
</code>```

答:
steps_per_epoch: Total number of steps (batches of samples) to yield from generator before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of unique samples of your dataset divided by the batch size.

For training you have 7230 images, it means 226 batches of 32 images. It is also the steps_per_epoch which is normally calculated by steps_per_epoch = train_generator.n/batch_size. But here you declare steps_per_epoch=pasos (=1000) which is larger than available training batches so it will take 226.

validation_steps: Total number of steps (batches of samples) to yield from validation_data generator before stopping at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. Optional for Sequence: if unspecified, will use the len(validation_data) as a number of steps.

Here again, you declare a validation_steps=300 which is higher than available validation batches (1446/32=46 batches). If you dont use validation_steps, you'll only see the training 226/226 [======] - 8s 36ms/step... every epoch.

Body:
I am new working with Keras. The code works correctly, but I would like to know the meaning of the values shown in the epochs. I am using the following code.

Where it says 46/46 and 226/277, what is the meaning of these numbers? Why 2 appear when normally only appears for example 100/100?

import sys
import os
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras import optimizers
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dropout, Flatten, Dense, Activation
from tensorflow.python.keras.layers import  Convolution2D, MaxPooling2D
from tensorflow.python.keras import backend as K

K.clear_session()

data_entrenamiento = '/content/DatosEntrenamiento' #images

"""
Parameters
"""
epocas=20
longitud, altura = 28, 28
batch_size = 32
pasos = 1000
validation_steps = 300
filtrosConv1 = 32
filtrosConv2 = 64
tamano_filtro1 = (3, 3)
tamano_filtro2 = (2, 2)
tamano_pool = (2, 2)
clases = 3
lr = 0.0004

##Preparamos nuestras imagenes

generator = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    )

test_datagen = ImageDataGenerator(rescale=1. / 255,validation_split=0.2)

entrenamiento_generador = generator.flow_from_directory(
    data_entrenamiento,
    target_size=(altura, longitud),
    batch_size=batch_size,
    class_mode='categorical',
    subset='training')

validacion_generador = test_datagen.flow_from_directory(
    data_entrenamiento,
    target_size=(altura, longitud),
    batch_size=batch_size,
    class_mode='categorical',
    subset='validation')

cnn = Sequential()
cnn.add(Convolution2D(filtrosConv1, tamano_filtro1, padding ="same", input_shape=(longitud, altura, 3), activation='relu'))
cnn.add(MaxPooling2D(pool_size=tamano_pool))

cnn.add(Convolution2D(filtrosConv2, tamano_filtro2, padding ="same"))
cnn.add(MaxPooling2D(pool_size=tamano_pool))

cnn.add(Flatten())
cnn.add(Dense(256, activation='relu'))
cnn.add(Dropout(0.5))
cnn.add(Dense(clases, activation='softmax'))

cnn.compile(loss='categorical_crossentropy',
            optimizer=optimizers.Adam(lr=lr),
            metrics=['accuracy'])

his = cnn.fit_generator(
    entrenamiento_generador,
    steps_per_epoch=pasos,
    epochs=epocas,
    validation_data=validacion_generador,
    validation_steps=validation_steps)

The output is :

Found 7230 images belonging to 3 classes.
Found 1446 images belonging to 3 classes.

Epoch 1/20

46/46 [=========] - 1s 21ms/step...

226/226 [======] - 8s 36ms/step...

Epoch 2/20

46/46 [=========] - 1s 21ms/step ...

226/226 [=======] - 8s 35ms/step ...


问:
Trying to calculate user whos spent the most and the least - Excel
I have a spreadsheet of user transactions and naturally some users will have one or more transactions. My objective is to add up the total(spent) of each user ( not necessary display it  )and display the user whos spent the most and spent the least.

I cannot use a pivot table and if you can show me the formula with the simple table below that would be very helpful.

I have tried the max and averageIF functions, but I can't get the code to work. This is just a sample table but concept will apply.

UserID      |  Amount

```<code>1     |      122
2     |      400
3     |      122
1     |      300
4     |      400
5     |      100
2     |      50
1     |      600
3     |      400
2     |      320
</code>```

So the end result will be User with Max spend  = 1 and Min spend = 5

答:
I tried it out and I have a solution, but as I can't just paste the excel sheet it's a bit hard to explain. I try anyway...

Assuming your data starts at A2 and B2 with UserID and Amount, then we have the following captions in row 1: UserID, Amount, Cumulation, Usertotals (over columns D1 and E1), Min, Max, Min spender, Max spender.

sort the data according to UserID ascending

in C2 put the formula =IF(A2=A1;B2+C1;B2) and copy it down for each data row. This cumulates the amounts together.

in D2 put the formula =IF(A2=A3;"";A2) and copy it down for each data row. This leaves only the user id for the total amount there and eliminates the other noise.

in E2 put the formula =IF(A2=A3;"";C2) and copy it down for each data row. This leaves only the total amount of each user there and eliminates the other noise.

in B13 (after the last data row in column B) put the formula =MIN(E2:E11) to determine the minimum amount.

in B14 (after the B13 minimum value) put the formula =MAX(E2:E11) to determine the maximum amount.

in F2 put the formula =B13 and in F3 =F2 and copy it down for each data row. This is just to simplify access to the minimum value.

in G2 put the formula =B14 and in G3 =G2 and copy it down for each data row. This is just to simplify access to the maximum value.

in H2 put the formula =IF(F2=E2;D2;"") and copy it down for each data row. This determines the user that spent the least money.

in I2 put the formula =IF(G2=E2;D2;"") and copy it down for each data row. This determines the user that spent the most money.

in A13 (after the last data row in column A) put the formula =MAX(H2:H11) to transfer the user that spent the least amount.

in A14 (after the minimum amount user) put the formula =MAX(I2:I11) to transfer the user that spent the most amount of money.

hide column C to I.

I hope I didn't make any mistakes translating the formulas from my German excel (it's not a great idea to also translate keywords, Microsoft!).

Body:
I have a spreadsheet of user transactions and naturally some users will have one or more transactions. My objective is to add up the total(spent) of each user ( not necessary display it  )and display the user whos spent the most and spent the least.

I cannot use a pivot table and if you can show me the formula with the simple table below that would be very helpful.

I have tried the max and averageIF functions, but I can't get the code to work. This is just a sample table but concept will apply.

UserID      |  Amount

1     |      122
2     |      400
3     |      122
1     |      300
4     |      400
5     |      100
2     |      50
1     |      600
3     |      400
2     |      320

So the end result will be User with Max spend  = 1 and Min spend = 5


问:
Junit testing a void response method
I have a void method namely invokeEllaAsync that I would like to test in the Spring eco-system and provided below. The method also calls another void method from inside as a nested call.

The mocking information is provided below,

```<code>   @InjectMocks
    private EllaService ellaService;

    private IrisBo validIrisBo;

    @Mock
    private EllaRequestDto ellaRequestDtoMock;

    @Mock
    private EntityServiceConnectable<EllaResponseDto> connectorMock;

    @Mock
    private EllaResponseDto ellaResponseMock;

    @Async
    public void invokeEllaAsync( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        try {
            callEllaService( irisBo );
        }

        /**
         * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
         *
         * @param irisEo
         * @return List<ResultBo>
         * @throws EllaGatewayUnsuccessfulResponseException
         */

        catch( EllaGatewayUnsuccessfulResponseException ex ) {
            throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
        }
    }

    private void callEllaService( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        HttpHeaders elladHeaders = createRequestHeaders( irisBo );

        ServiceResponse<EllaResponseDto> response = connector.call( EllaDtoConverter.convertToRequest( irisBo ), elladHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }

    }
</code>```

I try to test the invokeEllaAsync method as follows,

```<code>    @Test
    public void testInvokeEllaShowsSuccess() {

        ServiceResponse<EllaResponseDto> validServiceResponseMock = mock( ServiceResponse.class );

        when( connectorMock.call( any(), (HttpHeaders) any() ) ).thenReturn( validServiceResponseMock );
        when( validServiceResponseMock.isSuccess() ).thenReturn( true );

        ellaService.invokeEllaAsync( validIrisBo );
        verify( ellaService, times( 1 ) ).invokeEllaAsync( validIrisBo );
    }
</code>```

I get the error provided below,

```<code>org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type EllaService and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();
</code>```

If I understand it correctly, the ellaService is the type of @InjectMocks and not the @Mock. Hence, the test is not executed.

How do I write the test correctly?

答:
After I read the answer, I added this test in the codebase. </p>

```<code>@Test
public void testInvokeEllaAsyncSuccessfullyCallsCallEllaService() {

    ellaService.invokeEllaAsync( validIrisBo );

    PowerMockito.verifyStatic( EllaDtoConverter.class, VerificationModeFactory.times( 1 ) );
    EllaDtoConverter.convertToRequest( validIrisBo );

    verify( connectorMock, times( 1 ) ).call( any(), (HttpHeaders) any() );
}
</code>```

Title: Junit testing a void response method

Body:
I have a void method namely invokeEllaAsync that I would like to test in the Spring eco-system and provided below. The method also calls another void method from inside as a nested call.

The mocking information is provided below,

   @InjectMocks
    private EllaService ellaService;

    private IrisBo validIrisBo;

    @Mock
    private EllaRequestDto ellaRequestDtoMock;

    @Mock
    private EntityServiceConnectable<EllaResponseDto> connectorMock;

    @Mock
    private EllaResponseDto ellaResponseMock;

    @Async
    public void invokeEllaAsync( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        try {
            callEllaService( irisBo );
        }

        /**
         * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
         *
         * @param irisEo
         * @return List<ResultBo>
         * @throws EllaGatewayUnsuccessfulResponseException
         */

        catch( EllaGatewayUnsuccessfulResponseException ex ) {
            throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
        }
    }

    private void callEllaService( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        HttpHeaders elladHeaders = createRequestHeaders( irisBo );

        ServiceResponse<EllaResponseDto> response = connector.call( EllaDtoConverter.convertToRequest( irisBo ), elladHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }

    }

I try to test the invokeEllaAsync method as follows,

    @Test
    public void testInvokeEllaShowsSuccess() {

        ServiceResponse<EllaResponseDto> validServiceResponseMock = mock( ServiceResponse.class );

        when( connectorMock.call( any(), (HttpHeaders) any() ) ).thenReturn( validServiceResponseMock );
        when( validServiceResponseMock.isSuccess() ).thenReturn( true );

        ellaService.invokeEllaAsync( validIrisBo );
        verify( ellaService, times( 1 ) ).invokeEllaAsync( validIrisBo );
    }

I get the error provided below,

org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type EllaService and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();

If I understand it correctly, the ellaService is the type of @InjectMocks and not the @Mock. Hence, the test is not executed.

How do I write the test correctly?

Body:
After I read the answer, I added this test in the codebase.

@Test
public void testInvokeEllaAsyncSuccessfullyCallsCallEllaService() {

    ellaService.invokeEllaAsync( validIrisBo );

    PowerMockito.verifyStatic( EllaDtoConverter.class, VerificationModeFactory.times( 1 ) );
    EllaDtoConverter.convertToRequest( validIrisBo );

    verify( connectorMock, times( 1 ) ).call( any(), (HttpHeaders) any() );
}


答:
You have to check the length in the should change character in range method. Like following

```<code> func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newLength = textField.text.length + (string.length - range.length)

    if newLength <= maxLength {
       return true
    } else {
       return false
    }
}
</code>```

Here maxLength is the maximum length of chracters which you want to allow

Body:
You have to check the length in the should change character in range method. Like following

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newLength = textField.text.length + (string.length - range.length)

    if newLength <= maxLength {
       return true
    } else {
       return false
    }
}

Here maxLength is the maximum length of chracters which you want to allow


问:
Joystick controls mixed with rotation
I have a problem with the Fixed joystick when I apply rotation to the main camera. The controls are mixed. How can I resolve this problem? Do I need to use other type of joystick? Where I should put "-"  ?  in front of which number

using System.Collections.Generic;
using UnityEngine;

[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour
{

    public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    public RotationAxes axes = RotationAxes.MouseXAndY;
    public float sensitivityX = 15F;
    public float sensitivityY = 15F;

    public float minimumX = -360F;
    public float maximumX = 360F;

    public float minimumY = -60F;
    public float maximumY = 60F;

    float rotationY = 0F;

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            float turnAngleChange = (touch.deltaPosition.x / Screen.width) * sensitivityX;
            float pitchAngleChange = (touch.deltaPosition.y / Screen.height) * sensitivityY;

            // Handle any pitch rotation
            if (axes == RotationAxes.MouseXAndY || axes == RotationAxes.MouseY)
            {
                rotationY = Mathf.Clamp(rotationY + pitchAngleChange, minimumY, maximumY);
                transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0f);
            }

            // Handle any turn rotation
            if (axes == RotationAxes.MouseXAndY || axes == RotationAxes.MouseX)
            {
                transform.Rotate(0f, turnAngleChange, 0f);
            }
        }

        void Start()
        {
            //if(!networkView.isMine)
            //enabled = false;

            // Make the rigid body not change rotation
            //if (rigidbody)
            //rigidbody.freezeRotation = true;
        }
    }
}```

答:
I don't really get your question so I'm gonna answer both of my interpretations.

If the rotation of the camera is inverted (if you put your stick to the left the camera rotates to the right) you just need to add a minus in front of the speed you're rotating the camera with.

If the rotation of the camera happens when you use the left stick and you want to use the right stick. Then you should define in your input a field called something like camera-rotation-x and use the axis shown on the following pictures in the article here: https://gamedev.stackexchange.com/questions/150323/unity3d-how-to-use-controller-joystick-to-look-around If you follow that article, your camera rotation should work.

Title: Joystick controls mixed with rotation


问:
Merge Rows of Dataframe based on condition
I have a csv file with only one column "notes". I want to merge rows of data-frame based on some condition.

Input_data={'notes':
            ['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']}

df_in = pd.DataFrame(Input_data)
```

<p>Input looks like this </p>

<p><img src="https://i.stack.imgur.com/CWOAt.png" alt="Sample input"></p>

<p>Output</p>

<pre class="lang-py prettyprint-override"><code>output_Data={'notes':
             ['aaa','bbb','*hello','**my name is xyz',
              '(1) this is temp name',
              '(2) BTW how to solve this',
              '(3) with python','I don’t want this to be added ',
              'I don’t want this to be added ']}
df_out=pd.DataFrame(output_Data)
</code>```

I want to merge the rows with the above row which have either "*" or "(number)" in it. So the output will look like

Other rows which can not be merged should be left.
Also, in case of last row as there is no proper way to know up-to what range we can merge lets say just add only one next row
I solved this but its very long. Any simpler way

```<code>df=pd.DataFrame(Input_data)
notes=[];temp=[];flag='';value='';c=0;chk_star='yes'
for i,row in df.iterrows():
    row[0]=str(row[0])
    if '*' in row[0].strip()[:5] and chk_star=='yes':
        value=row[0].strip()
        temp=temp+[value]
        value=''
        continue

    if '(' in row[0].strip()[:5]:
        chk_star='no'
        temp=temp+[value]
        value='';c=0
        flag='continue'
        value=row[0].strip()
    if flag=='continue' and '(' not in row[0][:5] :
        value=value+row[0]
        c=c+1
    if c>4:
        temp=temp+[value]
        print "111",value,temp
        break
if '' in temp:
    temp.remove('')
df=pd.DataFrame({'notes':temp})
</code>```

答:
Below solution recognises special characters like *,** and (number) at the start of the of the sentence and starts merging later rows except last row.

```<code>import pandas as pd
import re
df = pd.DataFrame({'row':['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']})

pattern = "^\(\d+\)|^\*+" #Pattern to identify string starting with (number),*,**.

#print(df)
#Selecting index based on the above pattern
selected_index = df[df["row"].str.contains(re.compile(pattern))].index.values
delete_index = []
for index in selected_index:
    i=1
    #Merging row until next selected index found and add merged rows to delete_index list
    while(index+i not in selected_index and index+i < len(df)-1):
        df.at[index, 'row'] += ' ' + df.at[index+i, 'row']
        delete_index.append(index+i)
        i+=1

df.drop(delete_index,inplace=True)
#print(df)
</code>```

Output:

```<code>    row
0   aaa
1   bbb
2   *hello
4   **my nameis xyz
7   (1)this istempname
11  (2)BTWhow tosolve this
15  (3)with pythonI don’t want this to be added
18  I don’t want this to be added
</code>```

You can reset index if you want. using df.reset_index()

Body:
I have a csv file with only one column "notes". I want to merge rows of data-frame based on some condition.

Input_data={'notes':
            ['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']}

df_in = pd.DataFrame(Input_data)

Input looks like this

Output

output_Data={'notes':
             ['aaa','bbb','*hello','**my name is xyz',
              '(1) this is temp name',
              '(2) BTW how to solve this',
              '(3) with python','I don’t want this to be added ',
              'I don’t want this to be added ']}
df_out=pd.DataFrame(output_Data)

I want to merge the rows with the above row which have either "*" or "(number)" in it. So the output will look like

Other rows which can not be merged should be left.
Also, in case of last row as there is no proper way to know up-to what range we can merge lets say just add only one next row
I solved this but its very long. Any simpler way

df=pd.DataFrame(Input_data)
notes=[];temp=[];flag='';value='';c=0;chk_star='yes'
for i,row in df.iterrows():
    row[0]=str(row[0])
    if '*' in row[0].strip()[:5] and chk_star=='yes':
        value=row[0].strip()
        temp=temp+[value]
        value=''
        continue

    if '(' in row[0].strip()[:5]:
        chk_star='no'
        temp=temp+[value]
        value='';c=0
        flag='continue'
        value=row[0].strip()
    if flag=='continue' and '(' not in row[0][:5] :
        value=value+row[0]
        c=c+1
    if c>4:
        temp=temp+[value]
        print "111",value,temp
        break
if '' in temp:
    temp.remove('')
df=pd.DataFrame({'notes':temp})

Body:
Below solution recognises special characters like *,** and (number) at the start of the of the sentence and starts merging later rows except last row.

import pandas as pd
import re
df = pd.DataFrame({'row':['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']})

pattern = "^\(\d+\)|^\*+" #Pattern to identify string starting with (number),*,**.

#print(df)
#Selecting index based on the above pattern
selected_index = df[df["row"].str.contains(re.compile(pattern))].index.values
delete_index = []
for index in selected_index:
    i=1
    #Merging row until next selected index found and add merged rows to delete_index list
    while(index+i not in selected_index and index+i < len(df)-1):
        df.at[index, 'row'] += ' ' + df.at[index+i, 'row']
        delete_index.append(index+i)
        i+=1

df.drop(delete_index,inplace=True)
#print(df)

Output:

    row
0   aaa
1   bbb
2   *hello
4   **my nameis xyz
7   (1)this istempname
11  (2)BTWhow tosolve this
15  (3)with pythonI don’t want this to be added
18  I don’t want this to be added

You can reset index if you want. using df.reset_index()


问:
Spring DTO validation using ConstraintValidator
The DTO that I use is annotated with javax.validation annotations

For example

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentDTO {

@NotEmpty
private String name;

@Positive
private Long studentId;

}
</code>```

What if I have to validate using ConstraintValidator for StudentDTO

答:
Spring MVC has the ability to automatically validate @Controller
  inputs. In previous versions it was up to the developer to manually
  invoke validation logic.

But in your case , you are trying to validate a DTO object in which case , springboot might not be automatically binding your validator to your model and call the validator.So, in that case, you will need to manually bind the object to the validator.

or you can manually invoke the validator on a bean like :

```<code>@AutoWired
Validator validator;
...

validator.validate(book);
</code>```

You can define a custom validator in springboot for model classes if you want and use annotations :

```<code>@Documented
@Constraint(validatedBy = CustomDataValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDataConstraint {
    String message() default "Invalid data";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
</code>```

and then define a validator class like :

```<code>public class CustomDataValidator implements
  ConstraintValidator<CustomDataConstraint, String> {

    @Override
    public void initialize(CustomDataConstraint data) {
    }

    @Override
    public boolean isValid(String field,
      ConstraintValidatorContext cxt) {
        return field!= null;
    }

}
</code>```

Your validator class must implement the ConstraintValidator interface and must implement the isValid method to define the validation rules, define the validation rules can be anything as you wish.Then, you can simply add the annotation to your field like :

```<code>@CustomDataConstraint
private String name;
</code>```

Body:
The DTO that I use is annotated with javax.validation annotations

For example

@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentDTO {

@NotEmpty
private String name;

@Positive
private Long studentId;

}

What if I have to validate using ConstraintValidator for StudentDTO

Body:
Spring MVC has the ability to automatically validate @Controller
  inputs. In previous versions it was up to the developer to manually
  invoke validation logic.

But in your case , you are trying to validate a DTO object in which case , springboot might not be automatically binding your validator to your model and call the validator.So, in that case, you will need to manually bind the object to the validator.

or you can manually invoke the validator on a bean like :

@AutoWired
Validator validator;
...

validator.validate(book);

You can define a custom validator in springboot for model classes if you want and use annotations :

@Documented
@Constraint(validatedBy = CustomDataValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDataConstraint {
    String message() default "Invalid data";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

and then define a validator class like :

public class CustomDataValidator implements
  ConstraintValidator<CustomDataConstraint, String> {

    @Override
    public void initialize(CustomDataConstraint data) {
    }

    @Override
    public boolean isValid(String field,
      ConstraintValidatorContext cxt) {
        return field!= null;
    }

}

Your validator class must implement the ConstraintValidator interface and must implement the isValid method to define the validation rules, define the validation rules can be anything as you wish.Then, you can simply add the annotation to your field like :

@CustomDataConstraint
private String name;


问:
How to pass an intent back to MainActivity
My app has a RecyclerView in the MainActivity with an onClickListener which sends an intent to a DetailActivity. The DetailActivity has a button to go back without doing anything and a button to send an intent to the `Activity.
I already checked other posts in here like How to pass intent with extras to an already running activity  and others, but no one results.

Here is a version that I tried:

MainActivity:

```<code>@Override
protected void onNewIntent(Intent intent) {
    int codPedido = getIntent().getIntExtra("CodPedido",1);

    //Toast to test if it's working
    Toast.makeText(getApplicationContext(), String.valueOf(codPedido), Toast.LENGTH_SHORT).show();
}
</code>```

OnClick of RecyclerViewAdapter:

```<code>Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
</code>```

DetailActivity:

```<code>public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_confirm) {
            Intent intent = new Intent(DetailActivity.this, MainActivity.class);
            intent.putExtra("CodPedido", codPedido);
            startActivityForResult(intent, 1);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
</code>```

Edit:

This is what I tried now:

```<code>    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity mActivity = new MainActivity();
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            mActivity.startActivityForResult(intent, 1);
        }
    });
</code>```

and it gives method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

What I was doing before was using the context which is here in the constructor

```<code>public RvPedidosAdapter(List<Pedido> pedidos, Context context) {
    this.pedidos = pedidos;
    this.context = context;
}
</code>```

like this:

```<code>    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            context.startActivity(intent);
        }
    });
</code>```

答:
```<code>    On Your code please pass startActivityForResult() with intent param with result code and get the result on MainActivity in onActivityResult();

    Intent intent = new Intent(context, DetailActivity.class);
    intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
    intent.putExtra("Local", pedidos.get(i).getLocal());
    intent.putExtra("Dia",pedidos.get(i).getDia());
    intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
    intent.putExtra("urgente", pedidos.get(i).isUrgente());
    intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
    intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
    startActivityForResult(intent, 1);

    On your second activity please use this code.
    Intent intent = new Intent(DetailActivity.this, MainActivity.class);
            intent.putExtra("CodPedido", codPedido);
            setResult(RESULT_OK, intent);
            finish();
</code>```

and move to your MainActivity.class to get the result data in onActivityResult() method like this.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

         if(resultCode == RESULT_OK){
             (data.getIntExtra("CodPedido");
         }

}
</code>```

Body:
My app has a RecyclerView in the MainActivity with an onClickListener which sends an intent to a DetailActivity. The DetailActivity has a button to go back without doing anything and a button to send an intent to the `Activity.
I already checked other posts in here like How to pass intent with extras to an already running activity  and others, but no one results.

Here is a version that I tried:

MainActivity:

@Override
protected void onNewIntent(Intent intent) {
    int codPedido = getIntent().getIntExtra("CodPedido",1);

    //Toast to test if it's working
    Toast.makeText(getApplicationContext(), String.valueOf(codPedido), Toast.LENGTH_SHORT).show();
}

OnClick of RecyclerViewAdapter:

Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());

DetailActivity:

public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_confirm) {
            Intent intent = new Intent(DetailActivity.this, MainActivity.class);
            intent.putExtra("CodPedido", codPedido);
            startActivityForResult(intent, 1);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

Edit:

This is what I tried now:

    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity mActivity = new MainActivity();
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            mActivity.startActivityForResult(intent, 1);
        }
    });

and it gives method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

What I was doing before was using the context which is here in the constructor

public RvPedidosAdapter(List<Pedido> pedidos, Context context) {
    this.pedidos = pedidos;
    this.context = context;
}

like this:

    viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
            intent.putExtra("Local", pedidos.get(i).getLocal());
            intent.putExtra("Dia",pedidos.get(i).getDia());
            intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
            intent.putExtra("urgente", pedidos.get(i).isUrgente());
            intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
            intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
            context.startActivity(intent);
        }
    });

Body:
    On Your code please pass startActivityForResult() with intent param with result code and get the result on MainActivity in onActivityResult();

    Intent intent = new Intent(context, DetailActivity.class);
    intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
    intent.putExtra("Local", pedidos.get(i).getLocal());
    intent.putExtra("Dia",pedidos.get(i).getDia());
    intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
    intent.putExtra("urgente", pedidos.get(i).isUrgente());
    intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
    intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
    startActivityForResult(intent, 1);

    On your second activity please use this code.
    Intent intent = new Intent(DetailActivity.this, MainActivity.class);
            intent.putExtra("CodPedido", codPedido);
            setResult(RESULT_OK, intent);
            finish();

and move to your MainActivity.class to get the result data in onActivityResult() method like this.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

         if(resultCode == RESULT_OK){
             (data.getIntExtra("CodPedido");
         }

}


问:
Pandas read_csv from FileStorage in Flask
I'm trying to create pandas dataframe from uploaded csv file without saving file. When I do df = pd.read_csv(request.file['file']) pandas read this as a file but EmptyDataError: No columns to parse from file is shown. But this file is loaded properly to dataframe from console. request.file['file'].stream doesn't work also.

答:
If you are receiving your csv as a string try it using StringIO:

```<code>from io import StringIO
pd.read_csv(StringIO(request.file['file']))
</code>```

Body:
If you are receiving your csv as a string try it using StringIO:

from io import StringIO
pd.read_csv(StringIO(request.file['file']))


问:
Invoke-Sqlcmd : A parameter cannot be found that matches parameter name 'OutputAs'
I have a powershell script that will run a sql command and output the results as a dataset.

PowerShell:

```<code>(Invoke-Sqlcmd -ServerInstance $Server -Database 'STARS' -Username $Username -Password $Password -query $sqlCommand -OutputAs DataSet)
</code>```

I am getting the following error when I try to run the script.

```<code>Invoke-Sqlcmd : A parameter cannot be found that matches parameter name 'OutputAs'.
At D:\PipelinePowerShellScripts\UnitTests\Generate.Auth.Tokens.ps1:163 char:132
+ ... me $Username -Password $Password -query $sqlCommand -OutputAs DataSet ...
+                                                         ~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Sqlcmd], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
</code>```

PowerShell Version:

Major.Minor.Build.Revision

5.1.14409.1005

When I run this script on my local if runs without issues. However trying to run this on a Windows Server 2012 R2 returns the error above.

答:
I had the same problem because the module has been completely re-written for powershell v5.
You need to run the get-help invoke-sqlcmd -full on that server to see the available methods in that version.

HERE - you have it better explained ("two products" section)

I think that the easiest way would be to upgrade the powershell on the servers to 5+ and to use the new SQL Module.

Body:
I have a powershell script that will run a sql command and output the results as a dataset.

PowerShell:

(Invoke-Sqlcmd -ServerInstance $Server -Database 'STARS' -Username $Username -Password $Password -query $sqlCommand -OutputAs DataSet)

I am getting the following error when I try to run the script.

Invoke-Sqlcmd : A parameter cannot be found that matches parameter name 'OutputAs'.
At D:\PipelinePowerShellScripts\UnitTests\Generate.Auth.Tokens.ps1:163 char:132
+ ... me $Username -Password $Password -query $sqlCommand -OutputAs DataSet ...
+                                                         ~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Sqlcmd], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

PowerShell Version:

Major.Minor.Build.Revision

5.1.14409.1005

When I run this script on my local if runs without issues. However trying to run this on a Windows Server 2012 R2 returns the error above.


问:
Files that are not changed are triggering nodemon restarts
I use handlebars and nodemon on Windows. I've noticed (when using the debug argument for nodemon), hbs files - even when they aren't being edited - trigger a nodemon change.

Are the files actually changing? Why are they changing if I'm not editing them?

```<code>[11:22:46] [nodemon] files triggering change check: ..\forgot-sent.hbs
[11:22:46] [nodemon] matched rule: C:\Users\me\Documents\myapp\views/**/*
[11:22:46] [nodemon] changes after filters (before/after): 1/1
[11:22:46] [nodemon] restarting due to changes...
[11:22:46] [nodemon] views\forgot-sent.hbs
</code>```

How can I make nodemon refresh when files are changed, and not refresh when files are not changed?

Edit: looks like a bug on nodemon/Windows, see https://github.com/remy/nodemon/issues/1208

答:
This was a bug in nodemon (or more specifically, chokidar, a dependency of nodemon)

It was fixed on Feb 8 2019

Upgrade to the latest nodemon to get the fix.

Body:
I use handlebars and nodemon on Windows. I've noticed (when using the debug argument for nodemon), hbs files - even when they aren't being edited - trigger a nodemon change.

Are the files actually changing? Why are they changing if I'm not editing them?

[11:22:46] [nodemon] files triggering change check: ..\forgot-sent.hbs
[11:22:46] [nodemon] matched rule: C:\Users\me\Documents\myapp\views/**/*
[11:22:46] [nodemon] changes after filters (before/after): 1/1
[11:22:46] [nodemon] restarting due to changes...
[11:22:46] [nodemon] views\forgot-sent.hbs

How can I make nodemon refresh when files are changed, and not refresh when files are not changed?

Edit: looks like a bug on nodemon/Windows, see https://github.com/remy/nodemon/issues/1208


问:
How to quckly search repeated values in pandas?
I have a column from data frame: 900k rows. Structure of pandas Series:

base['SampleID'] =

```<code>231233
124123
213h213
jkiu12341
213i12i24u
</code>```

I have also a listOfNames contains 84k strings
ex. listOFNames =[jkiu12341,das2123,233213,321n3ju213]

What I need to do?

I need to compare each value from the list to data series (base['SampleID]') rows and check if it contains repetition.

If the script found the same value in Series, should save it (append) to another DataFrame, if not it should just pass.

Problems:

I need to use regex, coz sometimes in the list I would have for example ff5434when in Series: '00ff5434' - and it's should be read as repetition.

I wrote a function in python but it's horribly slow. Compared 900k rows take 35-40 min.

My code:

```<code>found = 0
notfound = 0

for i in range(len(listOfNames)):
    if len(base[base['SampleId'].str.contains(listOfNames[i], regex=False)]) > 0 :
        found += 1
    else:
        notfound+= 1
</code>```

So it's very simple for loop scanning the whole Series. And it's not append founded rows to a data frame yet, just counts how many repeated I have.

Expecting result:

Dataframe with repetition. In the above example it will be: just dataframe or list contains jkiu12341.

Maybe someone knows native pandas function, or any other library helps do it faster and replace my for function?

答:
How about where from pandas? info here. Or, also, where from numpy? info here

Without a  minimal, complete and verifiable example (mcve) as @anky_91 pointed out is difficult to do more.

Body:
I have a column from data frame: 900k rows. Structure of pandas Series:

base['SampleID'] =

231233
124123
213h213
jkiu12341
213i12i24u

I have also a listOfNames contains 84k strings
ex. listOFNames =[jkiu12341,das2123,233213,321n3ju213]

What I need to do?

I need to compare each value from the list to data series (base['SampleID]') rows and check if it contains repetition.

If the script found the same value in Series, should save it (append) to another DataFrame, if not it should just pass.

Problems:

I need to use regex, coz sometimes in the list I would have for example ff5434when in Series: '00ff5434' - and it's should be read as repetition.

I wrote a function in python but it's horribly slow. Compared 900k rows take 35-40 min.

My code:

found = 0
notfound = 0

for i in range(len(listOfNames)):
    if len(base[base['SampleId'].str.contains(listOfNames[i], regex=False)]) > 0 :
        found += 1
    else:
        notfound+= 1

So it's very simple for loop scanning the whole Series. And it's not append founded rows to a data frame yet, just counts how many repeated I have.

Expecting result:

Dataframe with repetition. In the above example it will be: just dataframe or list contains jkiu12341.

Maybe someone knows native pandas function, or any other library helps do it faster and replace my for function?


问:
Heroku Error - Error: Failed to lookup view "index" in views directory
I keep getting this error when deploing to Heroku. Build process was succesfull but then I get this error. Can't figure out what is the problem and shouldn't path be src/server/views? Everything is working locally.

```<code>Error: Failed to lookup view "index" in views directory "src\server/views"
[web.1]:at /app/node_modules/express/lib/router/index.js:281:22
app[web.1]:at param (/app/node_modules/express/lib/router/index.js:354:14)
app[web.1]:at Function.render(/app/node_modules/express/lib/application.js:580:17)
app[web.1]:at param (/app/node_modules/express/lib/router/index.js:365:14)
app[web.1]:at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
app[web.1]:at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
</code>```

I use webpack tu bundle my server side code and I use html-webpack-plugin to inject my index.ejs template from views folder to webpack bundle.

webpack.config.server.js

```<code>module.exports = {
  devtool: 'source-map',
  performance: {
    hints: false
  },
  target: 'node',
  node: {
    __dirname: true,
    __filename: true
  },
  entry: {
    bundle: './src/server/prodServer.js'
  },
  output: {
    path: path.join(buildPath, 'build'),
    filename: '[name].js'
  }
...
  plugins: [
      new HtmlWebpackPlugin({
        template: 'ejs-loader!./src/server/views/index.ejs'
      })
    ]
</code>```

prodServer.js

```<code>app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))
</code>```

folder structure

as you can see I have index.ejs inside views folder. prodServer is my server file and after webpack build I get bundle file and index.html.

In Heroku start script I run node ./src/build/bundle.js

答:
It is because of how your __dirname is defined in Heroku.  If you run heroku run bash and then run pwd you will see that your current working directory is /app, hence why /app is added in front of all your paths.

Try to play around with the command ls in your bash to see if your server folder is listed, and then with a cd server command see if the views file is there as well.  Note that it is case sensitive, so most likely you had it defined in uppercase.

Also, note that it adds a src\ (with a backward slash instead of forward slash) to your src\server/views path, which could be from a wrong configuration in your webpack.config.server.js file.

Body:
I keep getting this error when deploing to Heroku. Build process was succesfull but then I get this error. Can't figure out what is the problem and shouldn't path be src/server/views? Everything is working locally.

Error: Failed to lookup view "index" in views directory "src\server/views"
[web.1]:at /app/node_modules/express/lib/router/index.js:281:22
app[web.1]:at param (/app/node_modules/express/lib/router/index.js:354:14)
app[web.1]:at Function.render(/app/node_modules/express/lib/application.js:580:17)
app[web.1]:at param (/app/node_modules/express/lib/router/index.js:365:14)
app[web.1]:at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
app[web.1]:at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)

I use webpack tu bundle my server side code and I use html-webpack-plugin to inject my index.ejs template from views folder to webpack bundle.

webpack.config.server.js

module.exports = {
  devtool: 'source-map',
  performance: {
    hints: false
  },
  target: 'node',
  node: {
    __dirname: true,
    __filename: true
  },
  entry: {
    bundle: './src/server/prodServer.js'
  },
  output: {
    path: path.join(buildPath, 'build'),
    filename: '[name].js'
  }
...
  plugins: [
      new HtmlWebpackPlugin({
        template: 'ejs-loader!./src/server/views/index.ejs'
      })
    ]

prodServer.js

app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))

folder structure

as you can see I have index.ejs inside views folder. prodServer is my server file and after webpack build I get bundle file and index.html.

In Heroku start script I run node ./src/build/bundle.js


问:
Add a column with a default value to an existing table in SQL Server
How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?</p>

答:
When adding a nullable column, WITH VALUES will ensure that the specific DEFAULT value is applied to existing rows:

```<code>ALTER TABLE table
ADD column BIT     -- Demonstration with NULL-able column added
CONSTRAINT Constraint_name DEFAULT 0 WITH VALUES
</code>```

OwnerDisplayName: Mathias

LastEditorDisplayName: Nigel Campbell

Body:
When adding a nullable column, WITH VALUES will ensure that the specific DEFAULT value is applied to existing rows:

ALTER TABLE table
ADD column BIT     -- Demonstration with NULL-able column added
CONSTRAINT Constraint_name DEFAULT 0 WITH VALUES


问:
Shortcode exclude category
How can I exclude only one category from my homepage?

This is one shortcode that I'm using to show the newest posts

```<code>[vc_row][vc_column][td_block_big_grid category_id="22" sort="newest_posts"][/vc_column][/vc_row]
</code>```

But it shows even the posts I don't want them to be there.

答:
FOUND solution:

What I did was to add on category_id the negative number of the category.
For example, I had category_id="22" and then, added another category category_id="22, 23" and both categories showed up.

After, I changed it to category_id="-22, 23" which made the posts from category 22 to not show up.

Title: Shortcode exclude category

Body:
How can I exclude only one category from my homepage?

This is one shortcode that I'm using to show the newest posts

[vc_row][vc_column][td_block_big_grid category_id="22" sort="newest_posts"][/vc_column][/vc_row]

But it shows even the posts I don't want them to be there.


问:
Get issue "Route [register] not defined."
I recently set up a local Laravel environment via Composer and call the project via VirtualHost, following my opinion:

000-default.conf

```<code><VirtualHost *: 80>
         ServerName inb.local
         ServerAdmin mail@private.com
         DocumentRoot "/var/www/html/laravel_test/public/"
         DirectoryIndex index.php
         <Directory "/var/www/html/laravel_test/public/">
             AllowOverride All
             Allow from All
         </ Directory>
         ErrorLog $ {APACHE_LOG_DIR} /error.log
         CustomLog $ {APACHE_LOG_DIR} /access.log combined
</ VirtualHost>
</code>```

/etc/hosts

```<code>127.0.0.1 inb.local
</code>```

I can also call this page via inb.local and see the homepage with the Laravel headline and the URLs to the pages. For fun, I wanted to install a routing, but unfortunately does not work. My code looks like this:

welcome.blade.php

```<code><!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="{{ route('register') }}">Register</a>
                    <a href="https://laravel.com/docs">Docs</a>
                    <a href="https://laracasts.com">Laracasts</a>
                    <a href="https://laravel-news.com">News</a>
                    <a href="https://blog.laravel.com">Blog</a>
                    <a href="https://nova.laravel.com">Nova</a>
                    <a href="https://forge.laravel.com">Forge</a>
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

routes/web.php

```<code><?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/register', ['name' => 'User']);
</code>```

register.blade.php

```<code><!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Hallo {{ $name }}!
                </div>
            </div>
        </div>
    </body>
</html>
</code>```

I update the start page now, I get the error

```<code> ErrorException (E_ERROR)
Route [register] not defined. (View: /var/www/html/laravel_test/resources/views/welcome.blade.php)
Previous exceptions

    Route [register] not defined. (0)
</code>```

Am I missing a shot or what did I miss?

答:
Route() helper only works with named routes. For example a named route is like

```<code>Route::get('/hello, 'HelloController@hello)->name('hey');
</code>```

then you can use it like route('hey')

So, in your case

```<code>Route::get('/register', 'SomeController@method')->name('register');
</code>```

For more info: https://laravel.com/docs/5.8/routing#named-routes

Body:
I recently set up a local Laravel environment via Composer and call the project via VirtualHost, following my opinion:

000-default.conf

<VirtualHost *: 80>
         ServerName inb.local
         ServerAdmin mail@private.com
         DocumentRoot "/var/www/html/laravel_test/public/"
         DirectoryIndex index.php
         <Directory "/var/www/html/laravel_test/public/">
             AllowOverride All
             Allow from All
         </ Directory>
         ErrorLog $ {APACHE_LOG_DIR} /error.log
         CustomLog $ {APACHE_LOG_DIR} /access.log combined
</ VirtualHost>

/etc/hosts

127.0.0.1 inb.local

I can also call this page via inb.local and see the homepage with the Laravel headline and the URLs to the pages. For fun, I wanted to install a routing, but unfortunately does not work. My code looks like this:

welcome.blade.php

<!doctype html>
getLocale()) }}">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

            @if (Route::has('login'))

                    @auth
                        Home
                    @else
                        Login

                        @if (Route::has('register'))
                            Register
                        @endif
                    @endauth

            @endif

                    Laravel

                    Register
                    Docs
                    Laracasts
                    News
                    Blog
                    Nova
                    Forge
                    GitHub

routes/web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/register', ['name' => 'User']);

register.blade.php

<!doctype html>
getLocale()) }}">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

            @if (Route::has('login'))

                    @auth
                        Home
                    @else
                        Login

                        @if (Route::has('register'))
                            Register
                        @endif
                    @endauth

            @endif

                    Hallo {{ $name }}!

I update the start page now, I get the error

 ErrorException (E_ERROR)
Route [register] not defined. (View: /var/www/html/laravel_test/resources/views/welcome.blade.php)
Previous exceptions

    Route [register] not defined. (0)

Am I missing a shot or what did I miss?

Body:
Route() helper only works with named routes. For example a named route is like

Route::get('/hello, 'HelloController@hello)->name('hey');

then you can use it like route('hey')

So, in your case

Route::get('/register', 'SomeController@method')->name('register');

For more info: https://laravel.com/docs/5.8/routing#named-routes


问:
How to click item in a listview using a custom Adapter
I want to use a switch case statement on the clicked item in a custom listview but I'm unable to store that data value I click on and I can't store the item position to use it for my case statement.</p>

答:
You need to add OnItemClickListener callback:

```<code>list.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
       String value = list.getSelectedItem();
   }
}
</code>```

Body:
You need to add OnItemClickListener callback:

list.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
       String value = list.getSelectedItem();
   }
}


问:
How to fix 'must be an aggregate expression or appear in GROUP BY clause' with 'as' clause
I am trying to get the number of request by hour of my CloudFront distribution using athena query.

I created cloudfront_logs table guided by this Link in my sample_db

Below is the query I made to get the number of request by hour

```<code>SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY TIME
ORDER BY TIME ASC;
</code>```

However it returns error like this

```<code>SYNTAX_ERROR: line 2:8: '"date_trunc"('hour', "from_iso8601_timestamp"("concat"("concat"("date_format"("date", '%Y-%m-%d'), 'T'), "time")))' must be an aggregate expression or appear in GROUP BY clause
</code>```

Therefore, I replaced the TIME after GROUP BY to date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))), and tried again.

```<code>SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)))
ORDER BY TIME ASC;
</code>```

Finally, I got result.

I think, it should work with the first query also. Can I get any advice on the first query? Because It looks more simple.

答:
Athena is based on Presto. In Presto, you cannot use SELECT clause column aliases in the GROUP BY clause.
However, you can use identical expression, e.g.:

```<code>SELECT some_expression(a) FROM ... GROUP BY some_expression(a)
</code>```

Also, you can refer to SELECT clause columns using their position in the SELECT list:

```<code>SELECT some_expression(a) FROM ... GROUP BY 1
</code>```

This is ANSI SQL standard syntax. See Presto GROUP BY documentation for mode details.

This can be used in ORDER BY as well, so your query would be something like

```<code>SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE ...
GROUP BY 1
ORDER BY 1 ASC;
</code>```

Body:
I am trying to get the number of request by hour of my CloudFront distribution using athena query.

I created cloudfront_logs table guided by this Link in my sample_db

Below is the query I made to get the number of request by hour

SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY TIME
ORDER BY TIME ASC;

However it returns error like this

SYNTAX_ERROR: line 2:8: '"date_trunc"('hour', "from_iso8601_timestamp"("concat"("concat"("date_format"("date", '%Y-%m-%d'), 'T'), "time")))' must be an aggregate expression or appear in GROUP BY clause

Therefore, I replaced the TIME after GROUP BY to date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))), and tried again.

SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
    from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)))
ORDER BY TIME ASC;

Finally, I got result.

I think, it should work with the first query also. Can I get any advice on the first query? Because It looks more simple.

Body:
Athena is based on Presto. In Presto, you cannot use SELECT clause column aliases in the GROUP BY clause.
However, you can use identical expression, e.g.:

SELECT some_expression(a) FROM ... GROUP BY some_expression(a)

Also, you can refer to SELECT clause columns using their position in the SELECT list:

SELECT some_expression(a) FROM ... GROUP BY 1

This is ANSI SQL standard syntax. See Presto GROUP BY documentation for mode details.

This can be used in ORDER BY as well, so your query would be something like

SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE ...
GROUP BY 1
ORDER BY 1 ASC;


问:
DI not resolving base Interface from sub-Interface
I have a rather simple setup for a repository design. Using DI to resolve repositories in controller constructors.

However DI is behaving rather strangely. It appears to be unable to resolve a dependency which is resolved as the base of a registered interface. I believe it should be able to do this as any type that satisfies the sub-interface must also satisfy the base.

Interested to know if anyone knows why this may be happening?

Example:

Base Interface

```<code>public interface IReadOnlyRepository<T>
{
    void DoSomething();
}
</code>```

Sub Interface

```<code>public interface IReadWriteRepository<T> : IReadOnlyRepository<T>
{
    void DoSomethingElse();
}
</code>```

Implementation

```<code>public class AccountRepository: IReadWriteRepository<Account>
{
    public void DoSomething() { /* BLAH */ }
    public void DoSomethingElse() { /* BLAH */ }
}
</code>```

Registration

```<code>services.AddTransient<IReadWriteRepository<Account>, AccountRepository>();
</code>```

Resolution

```<code>provider.Resolve<IReadWriteRepository<Account>>(); // SUCCEEDS :)
provider.Resolve<IReadOnlyRepository<Account>>(); // FAILS! :(
</code>```

答:
That is not how dependency injection works. If you want IReadOnlyRepository<Account> to resolve to AccountRepository you will have to register that, too.

```<code>services.AddTransient<IReadOnlyRepository<Account>, AccountRepository>();
</code>```

Otherwise, how would the DI container know what to generate. Imagine what you have in mind would actually work, what would happen if you would ask it to resolve IDisposable or IEnumerable? It cannot magically know what you need, you have to be explicit.

Body:
I have a rather simple setup for a repository design. Using DI to resolve repositories in controller constructors.

However DI is behaving rather strangely. It appears to be unable to resolve a dependency which is resolved as the base of a registered interface. I believe it should be able to do this as any type that satisfies the sub-interface must also satisfy the base.

Interested to know if anyone knows why this may be happening?

Example:

Base Interface

public interface IReadOnlyRepository<T>
{
    void DoSomething();
}

Sub Interface

public interface IReadWriteRepository<T> : IReadOnlyRepository<T>
{
    void DoSomethingElse();
}

Implementation

public class AccountRepository: IReadWriteRepository<Account>
{
    public void DoSomething() { /* BLAH */ }
    public void DoSomethingElse() { /* BLAH */ }
}

Registration

services.AddTransient<IReadWriteRepository<Account>, AccountRepository>();

Resolution

provider.Resolve<IReadWriteRepository<Account>>(); // SUCCEEDS :)
provider.Resolve<IReadOnlyRepository<Account>>(); // FAILS! :(

Body:
That is not how dependency injection works. If you want IReadOnlyRepository<Account> to resolve to AccountRepository you will have to register that, too.

services.AddTransient<IReadOnlyRepository<Account>, AccountRepository>();

Otherwise, how would the DI container know what to generate. Imagine what you have in mind would actually work, what would happen if you would ask it to resolve IDisposable or IEnumerable? It cannot magically know what you need, you have to be explicit.


问:
Testing NSWidowController using OCMock
I've been trying to come up with a a way to unit test my applicationDidFinishLaunching delegate using OCMock. My NSWindowController is instantiated here and I'd like to test it.  Here's my test code:

```<code>id mockWindowController = [OCMockObject niceMockForClass:[URLTimerWindowController class]];
[[mockWindowController expect] showWindow:self];
NSUInteger preRetainCount = [mockWindowController retainCount];

[appDelegate applicationDidFinishLaunching:nil];

[mockWindowController verify];
</code>```

When I run the test, I get the error:

"OCMockObject[URLTimerWindowController]: expected method was not invoked: showWindow:-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]"

The log gives more detail:

```<code>"Test Case '-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]' started.
2011-04-11 08:36:57.558 otest-x86_64[3868:903] -[URLTimerWindowController loadWindow]: failed to load window nib file 'TimerWindow'.
Unknown.m:0: error: -[URLTimerAppDelegateTests testApplicationDidFinishLaunching] : OCMockObject[URLTimerWindowController]: expected method was not invoked: showWindow:-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]
Test Case '-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]' failed (0.005 seconds).
"
</code>```

So I see that the NIB fails to load. Ok, so how do I make it load while unit testing or somehow mock its load? I've already looked at the OCMock docs, Chris Hanson's tips on unit testing and a few other resources, including the WhereIsMyMac source code which behave in a similar fashion. My application for instantiating the window controller is this:

```<code>self.urlTimerWindowController = [[URLTimerWindowController alloc] init];
[self.urlTimerWindowController showWindow:self];
</code>```

Any tips greatly appreciated.

答:
The problem with your test is that mockWindowController and urlTimerWindowController are not the same object. And self in your test is not the same as self in the class under test. It doesn't really matter that the nib doesn't load in this case.

You generally can't mock an object when it's instantiated inside the method you want to test. One alternative is to instantiate the object in one method, then pass it to another method that finishes the setup. Then you can test the setup method. For example:

```<code>-(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.urlTimerWindowController = [[URLTimerWindowController alloc] init];
    [self setUpTimerWindow:urlTimerWindowController];
}

-(void)setUpTimerWindow:(URLTimerWindowController *)controller {
    [controller showWindow:self];
}
</code>```

Then, you would test setUpTimerWindow::

```<code>-(void)testSetUpTimerWindowShouldShowWindow {
    URLTimerAppDelegate *appDelegate = [[URLTimerAppDelegate alloc] init];

    id mockWindowController = [OCMockObject niceMockForClass:[URLTimerWindowController class]];
    [[mockWindowController expect] showWindow:appDelegate]; // this seems weird. does showWindow really take the app delegate as a parameter?

    [appDelegate setUpTimerWindow:mockWindowController];

    [mockWindowController verify];
    [appDelegate release];
}
</code>```

Title: Testing NSWidowController using OCMock

Body:
I've been trying to come up with a a way to unit test my applicationDidFinishLaunching delegate using OCMock. My NSWindowController is instantiated here and I'd like to test it.  Here's my test code:

id mockWindowController = [OCMockObject niceMockForClass:[URLTimerWindowController class]];
[[mockWindowController expect] showWindow:self];
NSUInteger preRetainCount = [mockWindowController retainCount];

[appDelegate applicationDidFinishLaunching:nil];

[mockWindowController verify];

When I run the test, I get the error:

"OCMockObject[URLTimerWindowController]: expected method was not invoked: showWindow:-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]"

The log gives more detail:

"Test Case '-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]' started.
2011-04-11 08:36:57.558 otest-x86_64[3868:903] -[URLTimerWindowController loadWindow]: failed to load window nib file 'TimerWindow'.
Unknown.m:0: error: -[URLTimerAppDelegateTests testApplicationDidFinishLaunching] : OCMockObject[URLTimerWindowController]: expected method was not invoked: showWindow:-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]
Test Case '-[URLTimerAppDelegateTests testApplicationDidFinishLaunching]' failed (0.005 seconds).
"

So I see that the NIB fails to load. Ok, so how do I make it load while unit testing or somehow mock its load? I've already looked at the OCMock docs, Chris Hanson's tips on unit testing and a few other resources, including the WhereIsMyMac source code which behave in a similar fashion. My application for instantiating the window controller is this:

self.urlTimerWindowController = [[URLTimerWindowController alloc] init];
[self.urlTimerWindowController showWindow:self];

Any tips greatly appreciated.

Body:
The problem with your test is that mockWindowController and urlTimerWindowController are not the same object. And self in your test is not the same as self in the class under test. It doesn't really matter that the nib doesn't load in this case.

You generally can't mock an object when it's instantiated inside the method you want to test. One alternative is to instantiate the object in one method, then pass it to another method that finishes the setup. Then you can test the setup method. For example:

-(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.urlTimerWindowController = [[URLTimerWindowController alloc] init];
    [self setUpTimerWindow:urlTimerWindowController];
}

-(void)setUpTimerWindow:(URLTimerWindowController *)controller {
    [controller showWindow:self];
}

Then, you would test setUpTimerWindow::

-(void)testSetUpTimerWindowShouldShowWindow {
    URLTimerAppDelegate *appDelegate = [[URLTimerAppDelegate alloc] init];

    id mockWindowController = [OCMockObject niceMockForClass:[URLTimerWindowController class]];
    [[mockWindowController expect] showWindow:appDelegate]; // this seems weird. does showWindow really take the app delegate as a parameter?

    [appDelegate setUpTimerWindow:mockWindowController];

    [mockWindowController verify];
    [appDelegate release];
}