问:
Top Banner border width sizing?
so I am a bit confused about some of my code and why it isn't working?   The top header border which has navigation buttons which direct the user to different places within the site.  I am trying to make the width fit screen and for some reason, there is a small gap where the black bar doesn't fill on the top left.

Code is below:

#top-menu-conainer2 {
  height: 20px;
  background: #000000;
  width: 4000px;
}

#top-menu-item2 {
  width: 4000px;
  margin: 0 auto;
}

#top-menu-item2 li a {
  font-weight: 700;
  color: #ffffff;
  text-decoration: none;
}

#top-menu-item2 li a:hover {
  text-decoration: underline;
}

#top-menu-item2 li a.bolder_link {
  font-weight: 700;
}

.top-menu-item2 {
  float: left;
  font-size: 12px;
  padding-top: 2px;
  padding-left: 30px;
  letter-spacing: 1px;
  line-height: 15px;
  padding-right: 8px;
}

.top-menu-item2 li a:hover {
  text-decoration: underline;
  color: #F8F9FA;
}

#header-details {
  margin: 0 auto;
  background-color: #000000;
  width: 100%;
  max-width: 5000px;
  height: 20px;
  border-left: 600rem;
  border-right: 600rem;
}

@media screen and (max-width:850px) {
  .top-menu-container2 {
    display: none !important;
  }
}

@media screen and (max-width:850px) {
  .top-menu2 {
    display: none !important;
  }
}

@media screen and (max-width:2000px) and (min-width:850px) {
  .mobile-menu2 {
    display: none !important;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--Start Test Code For NEW banner-->
<div id="top-menu-container2">
  <div class="top-menu-item2">
    <div class="top-menu2" id="top-menu2">
      <div class="top-menu-item2">
        <li>Home</li>
      </div>
      <div class="top-menu-item2">
        <li>About Us</li>
      </div>
      <div class="top-menu-item2">
        <li>Gallery</li>
      </div>
      <div class="top-menu-item2">
        <li>Brochures</li>
      </div>
      <div class="top-menu-item2">
        <li>Testimonial</li>
      </div>
      <div class="top-menu-item2">
        <li>Login/Sign-Up</li>
      </div>

      <div style="background-color: #000000">
        <div id="header-details">

          </ul>
        </div>
      </div>
    </div>
  </div>
</div>
<!--End Test Code for NEW banner--></code>```

答:
```<code>body {
  margin: 0;
}

#top-menu-conainer2{
  background: #000000;
}

.top-menu-item2{
  padding: 0 !important;
}

#top-menu-item2 li a{
  font-weight: 700;
  color: #ffffff;
  text-decoration: none;
}

#top-menu-item2 li a:hover{
  text-decoration: underline;
}

#top-menu-item2 li a.bolder_link{
  font-weight: 700;
}

.top-menu-item2 {
  float: left;
  font-size: 12px;
  padding-top: 2px;
  padding-left: 30px;
  letter-spacing: 1px;
  line-height: 15px;
  padding-right: 8px;
}

.top-menu-item2 li a:hover{
  text-decoration: underline;
  color: #F8F9FA;
}

#header-details{
  margin: 0 auto;
  background-color: #000000;
  width: 100%;
  max-width: 5000px;
  height: 20px;
  border-left: 600rem;
  border-right: 600rem;
}
@media screen and (max-width:850px){
  .top-menu-container2{
     display:none !important;}
   }
@media screen and (max-width:850px){
  .top-menu2{
    display:none !important;
  }
}

@media screen and (max-width:2000px) and (min-width:850px){
  .mobile-menu2 {
     display: none !important;
   }
}
</code>```

Improvements on naming and using classes instead of id's

Title: Top Banner border width sizing?

Body:
so I am a bit confused about some of my code and why it isn't working?   The top header border which has navigation buttons which direct the user to different places within the site.  I am trying to make the width fit screen and for some reason, there is a small gap where the black bar doesn't fill on the top left.

Code is below:

#top-menu-conainer2 {
  height: 20px;
  background: #000000;
  width: 4000px;
}

#top-menu-item2 {
  width: 4000px;
  margin: 0 auto;
}

#top-menu-item2 li a {
  font-weight: 700;
  color: #ffffff;
  text-decoration: none;
}

#top-menu-item2 li a:hover {
  text-decoration: underline;
}

#top-menu-item2 li a.bolder_link {
  font-weight: 700;
}

.top-menu-item2 {
  float: left;
  font-size: 12px;
  padding-top: 2px;
  padding-left: 30px;
  letter-spacing: 1px;
  line-height: 15px;
  padding-right: 8px;
}

.top-menu-item2 li a:hover {
  text-decoration: underline;
  color: #F8F9FA;
}

#header-details {
  margin: 0 auto;
  background-color: #000000;
  width: 100%;
  max-width: 5000px;
  height: 20px;
  border-left: 600rem;
  border-right: 600rem;
}

@media screen and (max-width:850px) {
  .top-menu-container2 {
    display: none !important;
  }
}

@media screen and (max-width:850px) {
  .top-menu2 {
    display: none !important;
  }
}

@media screen and (max-width:2000px) and (min-width:850px) {
  .mobile-menu2 {
    display: none !important;
  }
}

Home

About Us

Gallery

Brochures

Testimonial

Login/Sign-Up

Body:
body {
  margin: 0;
}

#top-menu-conainer2{
  background: #000000;
}

.top-menu-item2{
  padding: 0 !important;
}

#top-menu-item2 li a{
  font-weight: 700;
  color: #ffffff;
  text-decoration: none;
}

#top-menu-item2 li a:hover{
  text-decoration: underline;
}

#top-menu-item2 li a.bolder_link{
  font-weight: 700;
}

.top-menu-item2 {
  float: left;
  font-size: 12px;
  padding-top: 2px;
  padding-left: 30px;
  letter-spacing: 1px;
  line-height: 15px;
  padding-right: 8px;
}

.top-menu-item2 li a:hover{
  text-decoration: underline;
  color: #F8F9FA;
}

#header-details{
  margin: 0 auto;
  background-color: #000000;
  width: 100%;
  max-width: 5000px;
  height: 20px;
  border-left: 600rem;
  border-right: 600rem;
}
@media screen and (max-width:850px){
  .top-menu-container2{
     display:none !important;}
   }
@media screen and (max-width:850px){
  .top-menu2{
    display:none !important;
  }
}

@media screen and (max-width:2000px) and (min-width:850px){
  .mobile-menu2 {
     display: none !important;
   }
}

Improvements on naming and using classes instead of id's


来源: stackexchange

问:
Java 6 Update 25 VM crash: insufficient memory
For an update of this question - see below.

I experience a (reproducible, at least for me) JVM crash (not an OutOfMemoryError)
(The application which crashes is eclipse 3.6.2).
However, looking at the crash log makes me wonder:

```<code>#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (malloc) failed to allocate 65544 bytes for Chunk::new
# Possible reasons:
#   The system is out of physical RAM or swap space
#   In 32-bit mode, the process size limit was hit
# Possible solutions:
#   Reduce memory load on the system
#   Increase physical memory or swap space
#   Check if swap backing store is full
#   Use 64 bit Java on a 64 bit OS
#   Decrease Java heap size (-Xmx/-Xms)
#   Decrease number of Java threads
#   Decrease Java thread stack sizes (-Xss)
#   Set larger code cache with -XX:ReservedCodeCacheSize=
# This output file may be truncated or incomplete.

Current thread (0x531d6000):  JavaThread "C2 CompilerThread1" daemon
[_thread_in_native, id=7812, stack(0x53af0000,0x53bf0000)]

Stack: [0x53af0000,0x53bf0000],  sp=0x53bee860,  free space=1018k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [jvm.dll+0x1484aa]
V  [jvm.dll+0x1434fc]
V  [jvm.dll+0x5e6fc]
V  [jvm.dll+0x5e993]
V  [jvm.dll+0x27a571]
V  [jvm.dll+0x258672]
V  [jvm.dll+0x25ed93]
V  [jvm.dll+0x260072]
V  [jvm.dll+0x24e59a]
V  [jvm.dll+0x47edd]
V  [jvm.dll+0x48a6f]
V  [jvm.dll+0x12dcd4]
V  [jvm.dll+0x155a0c]
C  [MSVCR71.dll+0xb381]
C  [kernel32.dll+0xb729]
</code>```

I am using Windows XP 32-bit SP3. I have 4GB RAM.
Before starting the application I had 2 GB free according to the task manager (+ 1 GB system cache which might be freed as well.). I am definitely having enough free RAM.

From the start till the crash I logged the JVM memory statistics using visualvm and jconsole.
I acquired the memory consumption statistics until the last moments before the crash.

The statistics shows the following allocated memory sizes:

HeapSize: 751 MB (used 248 MB)

Non-HeapSize(PermGen & CodeCache): 150 MB (used 95 MB)

Size of memory management areas (Edenspace, Old-gen etc.): 350 MB

Thread stack sizes: 17 MB  (according to oracle and due the fact that  51 threads are running)

I am running the application (jre 6 update 25, server vm) using the parameters:

```<code>-XX:PermSize=128m
-XX:MaxPermSize=192m
-XX:ReservedCodeCacheSize=96m
-Xms500m
-Xmx1124m
</code>```

Question:

Why does the JVM crash when there's obviously enough memory on the VM and OS?

With the above settings I think that I cannot hit the 2GB 32-bit limit (1124MB+192MB+96MB+thread stacks < 2GB). In any other case (too much heap allocation), I would rather expect an OutOfMemoryError than a JVM crash

Who can help me to figure out what is going wrong here?

(Note: I upgraded recently to Eclipse 3.6.2 from Eclipse 3.4.2 and from Java 5 to Java 6. I suspect that there's a connection between the crashes and these changes because I haven't seen these before)

UPDATE

It seems to be a JVM bug introduced in Java 6 Update 25 and has something to do with the new jit compiler. See also this blog entry.
According to the blog, the fix of this bug should be part of the next java 6 updates.
In the meanwhile, I got a native stack trace during a crash. I've updated the above crash log.

The proposed workaround, using the VM argument -XX:-DoEscapeAnalysis works (at least it notably lowers the probability of a crash)

答:
2GB on 32-bit JVM on Windows is incorrect.  https://blogs.sap.com/2019/10/07/does-32-bit-or-64-bit-jvm-matter-anymore/

Since you are on Windows-XP you are stuck with a 32 bit JVM.

The max heap is 1.5GB on 32 bit VM on Windows.  You are at 1412MB to begin with without threads.  Did you try decreasing the swap stack size -Xss, and have you tried eliminating the PermSize allocated initially: -XX:PermSize=128m?  Sounds like this is an eclipse problem, not a memory-problem per-se.

Can you move to a newer JVM or different (64-bit) JVM on a different machine?  Even if you are targeting windows-XP there is no reason to develop on it, unless you HAVE to.  Eclipse can run, debug and deploy code on remote machines easily.

Eclipse's JVM can be different then the JVM of things you run in or with eclipse.  Eclipse is a memory pig.  You can eliminate unnecessary eclipse plug-ins to use less eclipse memory, it comes with things out of the box you probably don't need or want.

Try to null out references (to eliminate circularly un-collectible GC objects), re-use allocated memory, use singletons, and profile your memory usage to eliminate unnecessary objects, references and allocations.  Additional tips:

Prefer static memory allocation, i.e allocate once per VM as opposed
to dynamically.

Avoid creation of temporary objects within functions - consider a reset() method which can allow the object to reused

Avoid String mutations and mutation of auto boxed types.

ContentLicense: CC BY-SA 4.0

Body:
For an update of this question - see below.

I experience a (reproducible, at least for me) JVM crash (not an OutOfMemoryError)
(The application which crashes is eclipse 3.6.2).
However, looking at the crash log makes me wonder:

#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (malloc) failed to allocate 65544 bytes for Chunk::new
# Possible reasons:
#   The system is out of physical RAM or swap space
#   In 32-bit mode, the process size limit was hit
# Possible solutions:
#   Reduce memory load on the system
#   Increase physical memory or swap space
#   Check if swap backing store is full
#   Use 64 bit Java on a 64 bit OS
#   Decrease Java heap size (-Xmx/-Xms)
#   Decrease number of Java threads
#   Decrease Java thread stack sizes (-Xss)
#   Set larger code cache with -XX:ReservedCodeCacheSize=
# This output file may be truncated or incomplete.

Current thread (0x531d6000):  JavaThread "C2 CompilerThread1" daemon
[_thread_in_native, id=7812, stack(0x53af0000,0x53bf0000)]

Stack: [0x53af0000,0x53bf0000],  sp=0x53bee860,  free space=1018k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [jvm.dll+0x1484aa]
V  [jvm.dll+0x1434fc]
V  [jvm.dll+0x5e6fc]
V  [jvm.dll+0x5e993]
V  [jvm.dll+0x27a571]
V  [jvm.dll+0x258672]
V  [jvm.dll+0x25ed93]
V  [jvm.dll+0x260072]
V  [jvm.dll+0x24e59a]
V  [jvm.dll+0x47edd]
V  [jvm.dll+0x48a6f]
V  [jvm.dll+0x12dcd4]
V  [jvm.dll+0x155a0c]
C  [MSVCR71.dll+0xb381]
C  [kernel32.dll+0xb729]

I am using Windows XP 32-bit SP3. I have 4GB RAM.
Before starting the application I had 2 GB free according to the task manager (+ 1 GB system cache which might be freed as well.). I am definitely having enough free RAM.

From the start till the crash I logged the JVM memory statistics using visualvm and jconsole.
I acquired the memory consumption statistics until the last moments before the crash.

The statistics shows the following allocated memory sizes:

HeapSize: 751 MB (used 248 MB)

Non-HeapSize(PermGen & CodeCache): 150 MB (used 95 MB)

Size of memory management areas (Edenspace, Old-gen etc.): 350 MB

Thread stack sizes: 17 MB  (according to oracle and due the fact that  51 threads are running)

I am running the application (jre 6 update 25, server vm) using the parameters:

-XX:PermSize=128m
-XX:MaxPermSize=192m
-XX:ReservedCodeCacheSize=96m
-Xms500m
-Xmx1124m

Question:

Why does the JVM crash when there's obviously enough memory on the VM and OS?

With the above settings I think that I cannot hit the 2GB 32-bit limit (1124MB+192MB+96MB+thread stacks < 2GB). In any other case (too much heap allocation), I would rather expect an OutOfMemoryError than a JVM crash

Who can help me to figure out what is going wrong here?

(Note: I upgraded recently to Eclipse 3.6.2 from Eclipse 3.4.2 and from Java 5 to Java 6. I suspect that there's a connection between the crashes and these changes because I haven't seen these before)

UPDATE

It seems to be a JVM bug introduced in Java 6 Update 25 and has something to do with the new jit compiler. See also this blog entry.
According to the blog, the fix of this bug should be part of the next java 6 updates.
In the meanwhile, I got a native stack trace during a crash. I've updated the above crash log.

The proposed workaround, using the VM argument -XX:-DoEscapeAnalysis works (at least it notably lowers the probability of a crash)


问:
Converting Mat to one dimensional float array for EM?
I'm trying to convert a Python code to Java. However, I'm unable to find a way to create the sample to train the Expectation Maximization as it should be a one-channel matrix with 2 values (S and V from HSV Color Space) as below:

row 0: S, V

row 1: S, V

row 2: S, V

row 3: S, V

In Python, I was able to do it as follow:

```<code>def convert_to_samples(image, height, width):
    samples = []
    for y in range(0, height):
        for x in range(0, width):
            samples.append(image[y, x])
    samples = np.float32(np.vstack(samples))
    return samples
</code>```

I have tried as following without success as the result is not a Mat and I can't find a way to transform it back.

```<code>public double[][] convert_to_samples(Mat image) {
    double[][] samples = new double[image.height()][];
        for(int i = 0; i < image.height(); i++) {
            for(int j = 0; j < image.width(); j++) {
                samples[i] = image.get(i, j);
            }
        }
    return sortRowWise(samples);
}

private static double[][] sortRowWise(double[][] m) {
    for (double[] values : m) Arrays.sort(values);
    return m;
}
</code>```

Could someone help me transform the Mat?

答:
```<code>public Mat convert_to_samples(Mat image) {
    double[][] samples = new double[image.height()][];
    for(int i = 0; i < image.height(); i++) {
        for(int j = 0; j < image.width(); j++) {
            samples[i] = image.get(i, j);
        }
    }
    sortRowWise(samples);
    Mat matSamples = new Mat(image.height(), 2, CvType.CV_64FC1);
    for (int i = 0; i < image.height(); i++) {
        matSamples.put(i, 0, samples[i]);
    }
    return matSamples;
}

private static void sortRowWise(double[][] m) {
    for (double[] values : m) Arrays.sort(values);
}
</code>```

Body:
I'm trying to convert a Python code to Java. However, I'm unable to find a way to create the sample to train the Expectation Maximization as it should be a one-channel matrix with 2 values (S and V from HSV Color Space) as below:

row 0: S, V

row 1: S, V

row 2: S, V

row 3: S, V

In Python, I was able to do it as follow:

def convert_to_samples(image, height, width):
    samples = []
    for y in range(0, height):
        for x in range(0, width):
            samples.append(image[y, x])
    samples = np.float32(np.vstack(samples))
    return samples

I have tried as following without success as the result is not a Mat and I can't find a way to transform it back.

public double[][] convert_to_samples(Mat image) {
    double[][] samples = new double[image.height()][];
        for(int i = 0; i < image.height(); i++) {
            for(int j = 0; j < image.width(); j++) {
                samples[i] = image.get(i, j);
            }
        }
    return sortRowWise(samples);
}

private static double[][] sortRowWise(double[][] m) {
    for (double[] values : m) Arrays.sort(values);
    return m;
}

Could someone help me transform the Mat?


问:
MVC 3 using a custom httphandler with a different extension
Can you create a custom httphandler with a custom extension in MVC?

I want an image handler that has the following path (if possible),
domain.com/picture/{id of the picture}

Is it possible from inside MVC or do i have to do it in IIS 7?

答:
There's no need to add a httphandler. You should do this in asp.net mvc via a controller
example:

```<code>public class PictureController : Controller
{
    public FileResult GetImage(int pictureID)
    {
        byte[] fileContents = null;
        //Get the file here.
        return File(fileContents, "image/jpeg");
    }
}
</code>```

in global.asax you can define

```<code>routes.MapRoute("Picture-GetImage", "picture/{pictureID}",
new { controller = "Picture", action = "GetImage" }
</code>```

You could also use System.Web.Helpers.WebImage helper, or do it manually, example:

```<code>public static byte[] ProcessCropResizeImage(string imageurl, Size outputSize)
{
    if (File.Exists(imageurl))
    {
        MemoryStream result = new MemoryStream();
        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(m => m.MimeType == "image/jpeg");
        if (codec == null)
            throw new ArgumentException(string.Format("Unsupported mimeType specified for encoding ({0})", "image/jpeg"), "encodingMimeType");
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
        using (FileStream fs = File.OpenRead(imageurl))
        {
            using (Image image = Image.FromStream(fs))
            {
                using (Bitmap b = new Bitmap(outputSize.Width, outputSize.Height))
                {
                    using (Graphics g = Graphics.FromImage((Image)b))
                    {
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(image, 0, 0, outputSize.Width, outputSize.Height);
                        g.DrawImage(image, outputSize.Width, outputSize.Height);
                    }
                    b.Save(result, codec, encoderParams);
                }
            }
        }

        return result.GetBuffer();
    }
    return null;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There's no need to add a httphandler. You should do this in asp.net mvc via a controller
example:

public class PictureController : Controller
{
    public FileResult GetImage(int pictureID)
    {
        byte[] fileContents = null;
        //Get the file here.
        return File(fileContents, "image/jpeg");
    }
}

in global.asax you can define

routes.MapRoute("Picture-GetImage", "picture/{pictureID}",
new { controller = "Picture", action = "GetImage" }

You could also use System.Web.Helpers.WebImage helper, or do it manually, example:

public static byte[] ProcessCropResizeImage(string imageurl, Size outputSize)
{
    if (File.Exists(imageurl))
    {
        MemoryStream result = new MemoryStream();
        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(m => m.MimeType == "image/jpeg");
        if (codec == null)
            throw new ArgumentException(string.Format("Unsupported mimeType specified for encoding ({0})", "image/jpeg"), "encodingMimeType");
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
        using (FileStream fs = File.OpenRead(imageurl))
        {
            using (Image image = Image.FromStream(fs))
            {
                using (Bitmap b = new Bitmap(outputSize.Width, outputSize.Height))
                {
                    using (Graphics g = Graphics.FromImage((Image)b))
                    {
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(image, 0, 0, outputSize.Width, outputSize.Height);
                        g.DrawImage(image, outputSize.Width, outputSize.Height);
                    }
                    b.Save(result, codec, encoderParams);
                }
            }
        }

        return result.GetBuffer();
    }
    return null;
}


问:
Spring boot ExceptionHandler when an exception is thrown within a service
I am using ControllerAdvice to handle exceptions in my spring boot application.

```<code>@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ErrorApiHandler extends ResponseEntityExceptionHandler {

    final
    ResponsesHelper rh;

    public ErrorApiHandler(ResponsesHelper rh) {
        this.rh = rh;
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<Object> handleUsernameNotFoundException(UsernameNotFoundException ex) {
    log.error(ExceptionUtils.getStackTrace(ex));

    var error = buildError(ex);
    return rh.buildResponse(error, HttpStatus.NOT_FOUND);
    }
...
}
</code>```

It works fine for exceptions thrown within my controllers.
However, with exceptions thrown, for example within a service the ControllerAdvice is not executed.

```<code>@Service
public class CustomUserDetailsService implements UserDetailsService {

    final
    UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public User loadUserByUsername(String email)
            throws UsernameNotFoundException {

        log.debug(String.format("Loading user %s", email));

        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> {

                    log.debug(String.format("User %s not found", email));
                    return new UsernameNotFoundException("User not found : " + email); // <- This exception is not handled.
                });

        log.debug(String.format("User %s loaded", user));
        return user;
    }
</code>```

How can I handle all exceptions thrown within my application?

Thanks in advance.

答:
@ControllerAdvice is meant to handle exceptions that propagate through controller methods (that are thrown from within controller method calls - including bubbling exceptions). So whenever you directly throw exceptions in your controller method or something that controller method is calling throws an exception, an attempt to handle it through advice will be made.

If you want your exceptions to be handled (somehow) outside of web context with a similar manner, your will have to write your own aspect that will literally wrap everything try-catch and will let you handle the exception.

Body:
I am using ControllerAdvice to handle exceptions in my spring boot application.

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ErrorApiHandler extends ResponseEntityExceptionHandler {

    final
    ResponsesHelper rh;

    public ErrorApiHandler(ResponsesHelper rh) {
        this.rh = rh;
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<Object> handleUsernameNotFoundException(UsernameNotFoundException ex) {
    log.error(ExceptionUtils.getStackTrace(ex));

    var error = buildError(ex);
    return rh.buildResponse(error, HttpStatus.NOT_FOUND);
    }
...
}

It works fine for exceptions thrown within my controllers.
However, with exceptions thrown, for example within a service the ControllerAdvice is not executed.

@Service
public class CustomUserDetailsService implements UserDetailsService {

    final
    UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public User loadUserByUsername(String email)
            throws UsernameNotFoundException {

        log.debug(String.format("Loading user %s", email));

        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> {

                    log.debug(String.format("User %s not found", email));
                    return new UsernameNotFoundException("User not found : " + email); // <- This exception is not handled.
                });

        log.debug(String.format("User %s loaded", user));
        return user;
    }

How can I handle all exceptions thrown within my application?

Thanks in advance.


问:
ggplot scale_color_manual with breaks does not match expected order
I'm making a scatter plot and I'd like to specify the order of the text in the legend, as well as the colors. Using ggplot, the color order does not match the text order as written.

My Code:

```<code>MyX<-c(1,2,3,4,5)
MyY<-c(3,4,5,2,7)
MyCat<-c("Dark","Medium","DarkLight","LightDark","Light")
MyDF<-data.frame(MyX,MyY,MyCat)

ggplot(MyDF, aes(x=MyX, y=MyY, color=MyCat)) +
  geom_point()+
  xlab("Time") +
  ylab("Num") +
  scale_color_manual(breaks =     c("Dark","DarkLight","Medium","LightDark","Light"),
                     values=c("red", "orange","yellow","cadetblue2","dodgerblue"))
</code>```

I don't want the default order of the text in the legend, so I'd like to change the order to be:

"Dark","DarkLight","Medium","LightDark","Light"

I also want the colors to be in the gradient:

"red", "orange","yellow","cadetblue2","dodgerblue"

So that Dark = Red, DarkLight = orange, Medium = yellow, LightDark = cadetblue2, Light = blue.

Which is what I would assume would happen with above code. But as plotted the text does not match the color and I have:

Dark = Red, DarkLight = orange, Medium = Blue, LightDark = cadetblue2, Light = yellow.

Note- I have the same issue when using a color ramp:

```<code>  gs.pal <- colorRampPalette(c("red","blue"),bias=.1,space="rgb")
+scale_color_manual(breaks = c("Dark","DarkLight","Medium","LightDark","Light"),
                       values=gs.pal(5))
</code>```

答:
This sets legend names, colors, and order at the same time.

```<code>p <- ggplot(dd) +
      geom_line(aes(x=num_round, y = goods, color = "Good"), size=1) +
      geom_line(aes(x=num_round, y = mediums, color = "Medium"), size=1) +
      geom_line(aes(x=num_round, y = bads, color = "Bad"), size=1) +
      scale_color_manual("State", breaks=c("Good", "Medium", "Bad"),
                         values=c("Good"="green","Medium"="orange","Bad"="red"))
print(p)
</code>```

Body:
I'm making a scatter plot and I'd like to specify the order of the text in the legend, as well as the colors. Using ggplot, the color order does not match the text order as written.

My Code:

MyX<-c(1,2,3,4,5)
MyY<-c(3,4,5,2,7)
MyCat<-c("Dark","Medium","DarkLight","LightDark","Light")
MyDF<-data.frame(MyX,MyY,MyCat)

ggplot(MyDF, aes(x=MyX, y=MyY, color=MyCat)) +
  geom_point()+
  xlab("Time") +
  ylab("Num") +
  scale_color_manual(breaks =     c("Dark","DarkLight","Medium","LightDark","Light"),
                     values=c("red", "orange","yellow","cadetblue2","dodgerblue"))

I don't want the default order of the text in the legend, so I'd like to change the order to be:

"Dark","DarkLight","Medium","LightDark","Light"

I also want the colors to be in the gradient:

"red", "orange","yellow","cadetblue2","dodgerblue"

So that Dark = Red, DarkLight = orange, Medium = yellow, LightDark = cadetblue2, Light = blue.

Which is what I would assume would happen with above code. But as plotted the text does not match the color and I have:

Dark = Red, DarkLight = orange, Medium = Blue, LightDark = cadetblue2, Light = yellow.

Note- I have the same issue when using a color ramp:

  gs.pal <- colorRampPalette(c("red","blue"),bias=.1,space="rgb")
+scale_color_manual(breaks = c("Dark","DarkLight","Medium","LightDark","Light"),
                       values=gs.pal(5))

Body:
This sets legend names, colors, and order at the same time.

p <- ggplot(dd) +
      geom_line(aes(x=num_round, y = goods, color = "Good"), size=1) +
      geom_line(aes(x=num_round, y = mediums, color = "Medium"), size=1) +
      geom_line(aes(x=num_round, y = bads, color = "Bad"), size=1) +
      scale_color_manual("State", breaks=c("Good", "Medium", "Bad"),
                         values=c("Good"="green","Medium"="orange","Bad"="red"))
print(p)


答:
You can use a HAVING Clause GROUPED BY ID to list the desired ID values

```<code>SELECT ID
  FROM foo
 GROUP BY ID
HAVING COUNT( distinct day )>=3 AND SUM( NVL(Total,0) ) >= 150
</code>```

Demo

Title: With Oracle SQL how can I find 3 days where total sum >= 150

Body:
I have a report that needs to list activity where total is >= 150 over 3 consecutive days.

Let's say I've created a temp table foo, to summarize daily totals.

| ID | Day        | Total |
| -- | ---------- | ----- |
| 01 | 2020-01-01 |   10  |
| 01 | 2020-01-02 |   50  |
| 01 | 2020-01-03 |   50  |
| 01 | 2020-01-04 |   50  |
| 01 | 2020-01-05 |   20  |
| 02 | 2020-01-01 |   10  |
| 02 | 2020-01-02 |   10  |
| 02 | 2020-01-03 |   10  |
| 02 | 2020-01-04 |   10  |
| 02 | 2020-01-05 |   10  |

How Would I write SQL to return ID 01, but not 02?

Example Result:

| ID |
| -- |
| 01 |

Body:
You can use a HAVING Clause GROUPED BY ID to list the desired ID values

SELECT ID
  FROM foo
 GROUP BY ID
HAVING COUNT( distinct day )>=3 AND SUM( NVL(Total,0) ) >= 150

Demo


问:
Template Meta Programming: How to combine parameter packs to new parameter pack
I'm trying to implement a way of removing some types from a tuple; for instance I want to be able to e.g. only take a tuple of the first 2 template arguments for a tuple depending on a condition:

Is it possible to 'pack' the types of which a tuple consists back into a parameter pack? (tuple -> typename... contained_types)

Is it possible to combine a param. pack with a typename (e.g. use "Pack1..., Pack2..." specifying a single parameter pack for a struct?

#include <cstdint>
#include <tuple>

template <typename... tpl> struct Helper {
  template <std::size_t rem, typename curr, typename... rest> struct take {
    using type = Helper<(tpl..., curr)>::take<rem-1, rest...>::type; // here, I'm trying (2.)
  };

  template <typename curr, typename... rest> struct take<0, curr, rest...> {
    using type = std::tuple<tpl...>;
  };
};

template <std::size_t s, typename... tpl> using take_t = Helper<>::take<s, tpl...>;

int main() {
  take_t<2, int, int, int> k = std::make_tuple(1, 2);
}
```

<p><strong>edit</strong> The line Helper fails with the following message:</p>

```/home/juli/test.cc:6:18: error: need ‘typename’ before ‘Helper<tpl ..., curr>::take’ because ‘Helper<tpl ..., curr>’ is a dependent scope
    6 |     using type = Helper<tpl..., curr>::take<rem-1, rest...>::type;
```

<p>and when I provide typename </p>

```/home/juli/test.cc:6:53: error: expected ‘;’ before ‘<’ token
    6 |     using type = typename Helper<tpl..., curr>::take<rem-1, rest...>::type;
```

edit2
I achieved this via [helper functions](https://gist.github.com/juliusHuelsmann/669f537aeb5e7105386d510d186b24e1
), but those fail with non primitive types when the constructor is not constexpr so I cannot use it in my use case and am curious to know how to achieve this and why my approach failed.

答:
The answer to  Question 2)
Yes it is possible, as @user253751 suggested, my original approach (Helper<tpl..., curr>) is correct, I made a different error though, which caused the aforementioned error in that line by omitting 'template' after the used type.
The code below shows the fix and works fine:

```<code>#include <cstdint>
#include <tuple>

template <typename... tpl> struct Helper {
  template <std::size_t rem, typename curr, typename... rest> struct take {
    using tp = Helper<tpl..., curr>;
    using type = tp::template take<rem-1, rest...>::type;
  };

  template <typename curr, typename... rest> struct take<0, curr, rest...> {
    using type = std::tuple<tpl...>;
  };
};

template <std::size_t s, typename... tpl> using take_t = Helper<>::take<s, tpl...>;

int main() {
  take_t<2, int, int, int>::type k = std::make_tuple(1, 2);
}
</code>```

The answer to Question 1 is given by the trick performed here, see a full example here. It is possible e.g. by the following construct (adapted from the example on-the-fly and untested):

```<code>template <class tuple> struct foo;

template <class ... args> struct foo<std::tuple<args...> {
    // implementation here!
};
</code>```

which is very neat and can be used for integer_sequence aswell (which I tried and did not succeed to do until now).

An entire implementation of what I wanted to achieve that is much clearer than my initial approach above can be found here:

template <size_t s, typename is, typename ...args> struct thlp;

template <size_t s, size_t... i, class... args> struct thlp<s, std::index_sequence, args...> {
  static_assert(s <= sizeof...(args), "Requested new tuple size exceeds old one.");
  using type = std::tuple<std::tuple_element_t<i, std::tuple<args...>>...>;
};

template <size_t s, typename... args>
using conditional_tuple_t = thlp<s, decltype(std::make_index_sequence<s>()), args...>::type;
```

Body:
I'm trying to implement a way of removing some types from a tuple; for instance I want to be able to e.g. only take a tuple of the first 2 template arguments for a tuple depending on a condition:

Is it possible to 'pack' the types of which a tuple consists back into a parameter pack? (tuple -> typename... contained_types)

Is it possible to combine a param. pack with a typename (e.g. use "Pack1..., Pack2..." specifying a single parameter pack for a struct?

#include <cstdint>
#include <tuple>

template <typename... tpl> struct Helper {
  template <std::size_t rem, typename curr, typename... rest> struct take {
    using type = Helper<(tpl..., curr)>::take<rem-1, rest...>::type; // here, I'm trying (2.)
  };

  template <typename curr, typename... rest> struct take<0, curr, rest...> {
    using type = std::tuple<tpl...>;
  };
};

template <std::size_t s, typename... tpl> using take_t = Helper<>::take<s, tpl...>;

int main() {
  take_t<2, int, int, int> k = std::make_tuple(1, 2);
}

edit The line Helper fails with the following message:

/home/juli/test.cc:6:18: error: need ‘typename’ before ‘Helper<tpl ..., curr>::take’ because ‘Helper<tpl ..., curr>’ is a dependent scope
    6 |     using type = Helper<tpl..., curr>::take<rem-1, rest...>::type;

and when I provide typename

/home/juli/test.cc:6:53: error: expected ‘;’ before ‘<’ token
    6 |     using type = typename Helper<tpl..., curr>::take<rem-1, rest...>::type;

edit2
I achieved this via [helper functions](https://gist.github.com/juliusHuelsmann/669f537aeb5e7105386d510d186b24e1
), but those fail with non primitive types when the constructor is not constexpr so I cannot use it in my use case and am curious to know how to achieve this and why my approach failed.

Body:
The answer to  Question 2)
Yes it is possible, as @user253751 suggested, my original approach (Helper<tpl..., curr>) is correct, I made a different error though, which caused the aforementioned error in that line by omitting 'template' after the used type.
The code below shows the fix and works fine:

#include <cstdint>
#include <tuple>

template <typename... tpl> struct Helper {
  template <std::size_t rem, typename curr, typename... rest> struct take {
    using tp = Helper<tpl..., curr>;
    using type = tp::template take<rem-1, rest...>::type;
  };

  template <typename curr, typename... rest> struct take<0, curr, rest...> {
    using type = std::tuple<tpl...>;
  };
};

template <std::size_t s, typename... tpl> using take_t = Helper<>::take<s, tpl...>;

int main() {
  take_t<2, int, int, int>::type k = std::make_tuple(1, 2);
}

The answer to Question 1 is given by the trick performed here, see a full example here. It is possible e.g. by the following construct (adapted from the example on-the-fly and untested):

template <class tuple> struct foo;

template <class ... args> struct foo<std::tuple<args...> {
    // implementation here!
};

which is very neat and can be used for integer_sequence aswell (which I tried and did not succeed to do until now).

An entire implementation of what I wanted to achieve that is much clearer than my initial approach above can be found here:

template <size_t s, typename is, typename ...args> struct thlp;

template <size_t s, size_t... i, class... args> struct thlp<s, std::index_sequence<i...>, args...> {
  static_assert(s <= sizeof...(args), "Requested new tuple size exceeds old one.");
  using type = std::tuple<std::tuple_element_t<i, std::tuple<args...>>...>;
};

template <size_t s, typename... args>
using conditional_tuple_t = thlp<s, decltype(std::make_index_sequence<s>()), args...>::type;


问:
Programming probability of patients being well in R
I'm going to preface this with the fact that I am a complete R novice.

I have the following problem:

Consider a simple model that progresses year-by-year. In year i, let W_i = patient is well, I_i = patient is ill, and D_i = patient is dead. Transitions can be modeled as a set of conditional probabilities.

Let L = number of years that the patient is well.

I have come up with the probability mass function of L to be P(L)=(1-p)(p)^{L-1}.

The given information is that a patient is well in year 1 and given their age and risk factors, P(W_{i+1}|W_{i})=0.2 for all i

The problem is to write a function in R that simulates the trajectory of a single patient and returns the number of years the patient is well.

I thought that this could be programmed in R as a binomial distribution using the rbinom function. For a single patient,

```<code>rbinom(1, 1, 0.2)
</code>```

but I don't think that this would return the number of years that the patient is well. I'm thinking that the rbinom function should be the start, and that it would need to be paired with a way to count the number of years that a patient is well, but I don't know how to do that.

The next problem is to use R to simulate 1000 patient trajectories and find the sample mean of years of wellness. I'm assuming that this would be an extension of the previous part, just replacing the 1 patient with 1000. However I can't quite figure out where to replace the 1 with 1000: n or size

```<code>rbinom(n, size, prob)
</code>```

This is assuming that using rbinom is the correct thing to do in the first place...
If I were to do this in another programming language (say Python) I would use a while loop conditional on patient_status=W and starting with L=0 iterate through the loop and add 1 each successful iteration. I'm not sure if R works in the same way.

答:
Let's start with what rbinom(1, 1, 0.2) does: it returns 1 instance of 1 independent Bernoulli (that is, 0-1) random variables added together that have a probability of 0.2 of being equal to 1. So, that line will only give outputs 0 (which it will do 80% of the time) or 1 (which it will do the other 20% of the time). As you noted, this isn't what you want.

The issue here is the selection of a random variable. A binomial variable is great for something like, "I roll ten dice. How many land on 6?" because it has the following essential components:

outcomes dichotomized into success / failure

a fixed number (ten) of trials

a consistent probability of success (1/6)

independent trials (dice do not affect each other)

The situation you're describing doesn't have those features. So, what to do?

Option 1: Go with your instinct for a while() loop. I'll preface this by saying that while() loops are discouraged in R for various reasons (chiefly inefficiency). But, since you already understand the concept, let's run with it.

```<code>one_patient <- function(){
  status <- 1                       # 1 = healthy, 0 = ill
  years <- (-1)                     # count how many years completed while healthy
  while(status == 1){
    years <- years + 1              # this line will run at least one time
    status <- rbinom(1, 1, 0.2)     # your rbinom(1, 1, 0.2) line makes an appearance!
  }
  return(years)
}
</code>```

Now, executing one_patient() will result in the number of the years the patient successfully transitioned from well to well. This will be at least 0, since years starts at -1 and is incremented at least one time. It could be very high, if the patient is lucky, though it most likely won't. You can experiment with this by changing the 0.2 parameter to something more optimistic like 0.99 to simulate long life spans.

Option 2: Rethink the random variable. I mentioned above that the variable wasn't binomial; in fact, it's geometric. A situation like, "I roll a die until it lands on 6. How many rolls did it take?" is geometric because it has the following essential components:

outcomes dichotomized into success / failure

a consistent probability of success

repeated trials that terminate when the first success is reached

independent trials

Much like how binomial variables have useful functions in R such as rbinom(), pbinom(), qbinom(), dbinom(), there is a corresponding collection for geometric variables: rgeom(), pgeom(), qgeom(), dgeom().

To use rgeom(), we need to be careful about one detail: here, a "success" is characterized as the patient becoming ill, because that's when the experiment ends. (Above, by encoding the patient being well as 1, we're implicitly using the reverse perspective.) This means that the "success" probability is 0.8. rgeom(1, 0.8) will return the number of draws strictly before the first success, which is equivalent to the number of years the patient went from well to well, as above. Note that the 1 parameter refers to the number of times we want to run this experiment and not something else. Hence:

```<code>rgeom(1, 0.8)
</code>```

will accomplish the same task as the one_patient() function we defined above. (That is, the distribution of outputs for each will be the same.)

For multiple patients, you can either wrap the one_patient() function inside replicate(), or you can just directly adjust the first parameter of rgeom(1, 0.8). The second option is much faster, though both are fast if just simulating 1000 patients.

Addendum

Proof that both have the same effect:

```<code>sims1 <- replicate(10000, one_patient())
hist(sims1, breaks = seq(-0.5, max(sims1) + 0.5, by = 1))

sims2 <- rgeom(10000, 0.8)
hist(sims2, breaks = seq(-0.5, max(sims2) + 0.5, by = 1))
</code>```

Proof that rgeom() is faster:

```<code>library(microbenchmark)
microbenchmark(
  replicate(10000, one_patient()),
  rgeom(10000, 0.8)
)
#Unit: milliseconds
#                            expr     min       lq      mean   median       uq     max neval
# replicate(10000, one_patient()) 35.4520 38.77585 44.135562 43.82195 46.05920 73.5090   100
#               rgeom(10000, 0.8)  1.1978  1.22540  1.273766  1.23640  1.27485  1.9734   100
</code>```

Body:
I'm going to preface this with the fact that I am a complete R novice.

I have the following problem:

Consider a simple model that progresses year-by-year. In year i, let W_i = patient is well, I_i = patient is ill, and D_i = patient is dead. Transitions can be modeled as a set of conditional probabilities.

Let L = number of years that the patient is well.

I have come up with the probability mass function of L to be P(L)=(1-p)(p)^{L-1}.

The given information is that a patient is well in year 1 and given their age and risk factors, P(W_{i+1}|W_{i})=0.2 for all i

The problem is to write a function in R that simulates the trajectory of a single patient and returns the number of years the patient is well.

I thought that this could be programmed in R as a binomial distribution using the rbinom function. For a single patient,

rbinom(1, 1, 0.2)

but I don't think that this would return the number of years that the patient is well. I'm thinking that the rbinom function should be the start, and that it would need to be paired with a way to count the number of years that a patient is well, but I don't know how to do that.

The next problem is to use R to simulate 1000 patient trajectories and find the sample mean of years of wellness. I'm assuming that this would be an extension of the previous part, just replacing the 1 patient with 1000. However I can't quite figure out where to replace the 1 with 1000: n or size

rbinom(n, size, prob)

This is assuming that using rbinom is the correct thing to do in the first place...
If I were to do this in another programming language (say Python) I would use a while loop conditional on patient_status=W and starting with L=0 iterate through the loop and add 1 each successful iteration. I'm not sure if R works in the same way.

Body:
Let's start with what rbinom(1, 1, 0.2) does: it returns 1 instance of 1 independent Bernoulli (that is, 0-1) random variables added together that have a probability of 0.2 of being equal to 1. So, that line will only give outputs 0 (which it will do 80% of the time) or 1 (which it will do the other 20% of the time). As you noted, this isn't what you want.

The issue here is the selection of a random variable. A binomial variable is great for something like, "I roll ten dice. How many land on 6?" because it has the following essential components:

outcomes dichotomized into success / failure

a fixed number (ten) of trials

a consistent probability of success (1/6)

independent trials (dice do not affect each other)

The situation you're describing doesn't have those features. So, what to do?

Option 1: Go with your instinct for a while() loop. I'll preface this by saying that while() loops are discouraged in R for various reasons (chiefly inefficiency). But, since you already understand the concept, let's run with it.

one_patient <- function(){
  status <- 1                       # 1 = healthy, 0 = ill
  years <- (-1)                     # count how many years completed while healthy
  while(status == 1){
    years <- years + 1              # this line will run at least one time
    status <- rbinom(1, 1, 0.2)     # your rbinom(1, 1, 0.2) line makes an appearance!
  }
  return(years)
}

Now, executing one_patient() will result in the number of the years the patient successfully transitioned from well to well. This will be at least 0, since years starts at -1 and is incremented at least one time. It could be very high, if the patient is lucky, though it most likely won't. You can experiment with this by changing the 0.2 parameter to something more optimistic like 0.99 to simulate long life spans.

Option 2: Rethink the random variable. I mentioned above that the variable wasn't binomial; in fact, it's geometric. A situation like, "I roll a die until it lands on 6. How many rolls did it take?" is geometric because it has the following essential components:

outcomes dichotomized into success / failure

a consistent probability of success

repeated trials that terminate when the first success is reached

independent trials

Much like how binomial variables have useful functions in R such as rbinom(), pbinom(), qbinom(), dbinom(), there is a corresponding collection for geometric variables: rgeom(), pgeom(), qgeom(), dgeom().

To use rgeom(), we need to be careful about one detail: here, a "success" is characterized as the patient becoming ill, because that's when the experiment ends. (Above, by encoding the patient being well as 1, we're implicitly using the reverse perspective.) This means that the "success" probability is 0.8. rgeom(1, 0.8) will return the number of draws strictly before the first success, which is equivalent to the number of years the patient went from well to well, as above. Note that the 1 parameter refers to the number of times we want to run this experiment and not something else. Hence:

rgeom(1, 0.8)

will accomplish the same task as the one_patient() function we defined above. (That is, the distribution of outputs for each will be the same.)

For multiple patients, you can either wrap the one_patient() function inside replicate(), or you can just directly adjust the first parameter of rgeom(1, 0.8). The second option is much faster, though both are fast if just simulating 1000 patients.

Addendum

Proof that both have the same effect:

sims1 <- replicate(10000, one_patient())
hist(sims1, breaks = seq(-0.5, max(sims1) + 0.5, by = 1))

sims2 <- rgeom(10000, 0.8)
hist(sims2, breaks = seq(-0.5, max(sims2) + 0.5, by = 1))

Proof that rgeom() is faster:

library(microbenchmark)
microbenchmark(
  replicate(10000, one_patient()),
  rgeom(10000, 0.8)
)
#Unit: milliseconds
#                            expr     min       lq      mean   median       uq     max neval
# replicate(10000, one_patient()) 35.4520 38.77585 44.135562 43.82195 46.05920 73.5090   100
#               rgeom(10000, 0.8)  1.1978  1.22540  1.273766  1.23640  1.27485  1.9734   100


问:
Regex for multiline matches
I have a format like this:

```<code>-Note1: Value is 02
-Note 2: Line 1
Line 2
</code>```

When I do String replace with regex, i want it to group like this:

```<code>"Note1" "Value is 02"
"Note 2" "Line 1
Line 2" (the value for Note 2 spans 2 lines, which makes it "Line 1\nLine 2")
</code>```

My current regex have this output:

```<code>"Note1" "Value is 02"
"Note 2" "Line 1" (and leave out Line 2)
</code>```

Current regex:

```<code>/-(.*):(.*|\n*)/g
</code>```

What can I do to achieve what I want?

答:
Since JavaScript does not support the Singleline (/s) flag you need to get creative:

```<code>/^-(.*?):(.*(?:[\r\n]+[^-].*)*)/gm
</code>```

/^- - start with a dash

(.*?): - capture everything which is not a colon into group 1

(.* - start group 2 and capture everything

(?:[\r\n]+[^-].*)* - if a newline is detected and the line does not start with a dash then capture the entire line into group 2; repeat zero or more times as needed

) - close group 2

/gm - global and multiline flags

https://regex101.com/r/3YW3Mg/1

Title: Regex for multiline matches

Body:
I have a format like this:

-Note1: Value is 02
-Note 2: Line 1
Line 2

When I do String replace with regex, i want it to group like this:

"Note1" "Value is 02"
"Note 2" "Line 1
Line 2" (the value for Note 2 spans 2 lines, which makes it "Line 1\nLine 2")

My current regex have this output:

"Note1" "Value is 02"
"Note 2" "Line 1" (and leave out Line 2)

Current regex:

/-(.*):(.*|\n*)/g

What can I do to achieve what I want?

Body:
Since JavaScript does not support the Singleline (/s) flag you need to get creative:

/^-(.*?):(.*(?:[\r\n]+[^-].*)*)/gm

/^- - start with a dash

(.*?): - capture everything which is not a colon into group 1

(.* - start group 2 and capture everything

(?:[\r\n]+[^-].*)* - if a newline is detected and the line does not start with a dash then capture the entire line into group 2; repeat zero or more times as needed

) - close group 2

/gm - global and multiline flags

https://regex101.com/r/3YW3Mg/1


问:
Stop Characters from Encoding in HTML from C# Code Behind
Hello and thank you in advance.  I am generating controls from C# code behind and want to apply an onclick attribute that will sent a modal to block display.  When the code executes, apostrophes in the onclick function string are encoded to ' and I want to stop that from happening and pass the raw text.

I have tried the following to solve the problem with no resolution:

\'

''

<%= myString %>

HtmlString(myString).ToHtmlString();

There are probably other iteration that i tried but I lost track of them all.

This is the code section creating the control:

```<code>HtmlGenericControl viewMoreInfo = new HtmlGenericControl("span");
//HtmlString onclick1 = new HtmlString($"document.getElementById('{i.il_itemcode}Modal').style.display = 'block'");
string onclick1 = $"document.getElementById('{i.il_itemcode}Modal').style.display = 'block'";
viewMoreInfo.Attributes["onclick"] = onclick1;
viewMoreInfo.Attributes["class"] = "w3-bar-item w3-button w3-white w3-xlarge w3-right";
viewMoreInfo.InnerText = "+";
</code>```

Here is an example of what it renders as:

```<code><span onclick="document.getElementById('TEST1Modal').style.display = 'block'" class="w3-bar-item w3-button w3-white w3-xlarge w3-right">+</span>
</code>```

I need the apostrophe to render correctly for the function to work.

Any help would be greatly appropriated.

答:
Your question is misleading because "I need the apostrophe to render correctly for the function to work." is incorrect.  Note the following which is an exact copy of your example, and the click event works just fine as it currently being rendered.

This is hidden until clicked

+```

Body:
Hello and thank you in advance.  I am generating controls from C# code behind and want to apply an onclick attribute that will sent a modal to block display.  When the code executes, apostrophes in the onclick function string are encoded to ' and I want to stop that from happening and pass the raw text.

I have tried the following to solve the problem with no resolution:

\'

''

<%= myString %>

HtmlString(myString).ToHtmlString();

There are probably other iteration that i tried but I lost track of them all.

This is the code section creating the control:

HtmlGenericControl viewMoreInfo = new HtmlGenericControl("span");
//HtmlString onclick1 = new HtmlString($"document.getElementById('{i.il_itemcode}Modal').style.display = 'block'");
string onclick1 = $"document.getElementById('{i.il_itemcode}Modal').style.display = 'block'";
viewMoreInfo.Attributes["onclick"] = onclick1;
viewMoreInfo.Attributes["class"] = "w3-bar-item w3-button w3-white w3-xlarge w3-right";
viewMoreInfo.InnerText = "+";

Here is an example of what it renders as:

+

I need the apostrophe to render correctly for the function to work.

Any help would be greatly appropriated.

Body:
Your question is misleading because "I need the apostrophe to render correctly for the function to work." is incorrect.  Note the following which is an exact copy of your example, and the click event works just fine as it currently being rendered.

<p id="TEST1Modal" style="display:none">This is hidden until clicked</p>
<span onclick="document.getElementById(&#39;TEST1Modal&#39;).style.display = &#39;block&#39;" class="w3-bar-item w3-button w3-white w3-xlarge w3-right">+</span>


问:
Navigation Bar will not become transparent
I need the navigation bar to become transparent. Here is what i have put in my ViewController:

```<code>class ViewController: UIViewController {

  @IBOutlet weak var navbar: UINavigationBar!

  override func viewDidLoad() {
    super.viewDidLoad()
    navbar.isTranslucent=true
    navbar.shadowImage = UIImage()
    navbar.backgroundColor = UIColor.clear
  }
</code>```

According to debug view hierarchy UIVisualEffectBackdropView, UIVisualEffectSubview and UIVisualEffectSubview(yes two of them) are preventing it from becoming transparent.
Ps: I am not using a Navigation Controller.

How can i fix it?

答:
If you build with the lastest beta iOS 13.4 and XCode 11.4, the xmhafiz answer won't work anymore.
I've found another way, maybe it's just a bug in the beta software, but I'm writing it down there, just in case</p>

```<code>import UIKit

class TransparentNavBar :UINavigationBar {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        self.backgroundColor = .clear
        if #available(iOS 13.0, *) {
            self.standardAppearance.backgroundColor = .clear
            self.standardAppearance.backgroundEffect = .none
            self.standardAppearance.shadowColor = .clear
        }
    }
}
</code>```

Body:
I need the navigation bar to become transparent. Here is what i have put in my ViewController:

class ViewController: UIViewController {

  @IBOutlet weak var navbar: UINavigationBar!

  override func viewDidLoad() {
    super.viewDidLoad()
    navbar.isTranslucent=true
    navbar.shadowImage = UIImage()
    navbar.backgroundColor = UIColor.clear
  }

According to debug view hierarchy UIVisualEffectBackdropView, UIVisualEffectSubview and UIVisualEffectSubview(yes two of them) are preventing it from becoming transparent.
Ps: I am not using a Navigation Controller.

How can i fix it?

Body:
If you build with the lastest beta iOS 13.4 and XCode 11.4, the xmhafiz answer won't work anymore.
I've found another way, maybe it's just a bug in the beta software, but I'm writing it down there, just in case

import UIKit

class TransparentNavBar :UINavigationBar {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()
        self.isTranslucent = true
        self.backgroundColor = .clear
        if #available(iOS 13.0, *) {
            self.standardAppearance.backgroundColor = .clear
            self.standardAppearance.backgroundEffect = .none
            self.standardAppearance.shadowColor = .clear
        }
    }
}


问:
Extract data from several netcdf files using ncks in for loop
I am trying to extract certain variables from netcdf files.
The following code works if I apply it to a single file:

```<code>ncks -C -F -d nj_u,151,152,1 ni_u,234,235,1 -v vel_u 20091208000001.nc testU.nc
</code>```

See also question: Hyperslab of a 4D netcdf variable using ncks for explanation.
Now I want to use this code on several .nc files with following names:

```<code>20091208000001.nc
20091208000002.nc
20091208000003.nc
</code>```

I tried the following loop:

```<code># !bin/bash
for ((x=1;x<=3;x+=1))
do
ncks -C -F -d nj_u,151,152,1 ni_u,234,235,1 -v vel_u 2009120800000$x.nc testU.nc
done
</code>```

I get the error

```<code>ncks: ERROR received 4 filenames; need no more than two
</code>```

How do I get the loop to only extract from one file at a time and then append the extracted output from all the files into a single output file?

答:
I edited the code above according to the dimensions I wanted (lat, lon)

```<code>ncrcat -C -F -d nj_u,151,152,1 -d ni_u,234,235,1 -v vel_u 2009120800000?.nc testU.nc
</code>```

and the feedback was this:

HINT: If operation fails, try multislabbing
  (http://nco.sf.net/nco.html#msa) wrapped dimension using ncks first,
  and then apply ncrcat to the resulting file

Body:
I am trying to extract certain variables from netcdf files.
The following code works if I apply it to a single file:

ncks -C -F -d nj_u,151,152,1 ni_u,234,235,1 -v vel_u 20091208000001.nc testU.nc

See also question: Hyperslab of a 4D netcdf variable using ncks for explanation.
Now I want to use this code on several .nc files with following names:

20091208000001.nc
20091208000002.nc
20091208000003.nc

I tried the following loop:

# !bin/bash
for ((x=1;x<=3;x+=1))
do
ncks -C -F -d nj_u,151,152,1 ni_u,234,235,1 -v vel_u 2009120800000$x.nc testU.nc
done

I get the error

ncks: ERROR received 4 filenames; need no more than two

How do I get the loop to only extract from one file at a time and then append the extracted output from all the files into a single output file?

Body:
I edited the code above according to the dimensions I wanted (lat, lon)

ncrcat -C -F -d nj_u,151,152,1 -d ni_u,234,235,1 -v vel_u 2009120800000?.nc testU.nc

and the feedback was this:

HINT: If operation fails, try multislabbing
  (http://nco.sf.net/nco.html#msa) wrapped dimension using ncks first,
  and then apply ncrcat to the resulting file


问:
Issue with routing and link using nextjs
I am facing an issue with routing and links in Nextjs. I have created a blog like page using React+Typescript and I would like to use the same code in Nextjs. I was initially using import {Link} from 'react-router-dom'; .However since this link doesn't work with Nextjs,  I have used the link/next import.

The issue is when, I try to click on "Aboutus" of my Navbar, I get the following error:

404
  This page could not be found.

Here is the code of my Navbar.tsx

```<code>import React from 'react';
import Link from 'next/link';
const Navbarr : React.FC = () => {
return (
<div>
<AppName >
        <Link href="/"><a>Abc</a></Link>
    </AppName>
    <Button>
        <Link href="/new">
          <a>Aboutus</a>
        </Link>
    </Button>
</div>)}
export default NavBarr;
</code>```

答:
In Next.js when a file is added to the pages directory it's automatically available as a route.

I suggest you to read https://nextjs.org/docs/routing/introduction

Body:
I am facing an issue with routing and links in Nextjs. I have created a blog like page using React+Typescript and I would like to use the same code in Nextjs. I was initially using import {Link} from 'react-router-dom'; .However since this link doesn't work with Nextjs,  I have used the link/next import.

The issue is when, I try to click on "Aboutus" of my Navbar, I get the following error:

404
  This page could not be found.

Here is the code of my Navbar.tsx

import React from 'react';
import Link from 'next/link';
const Navbarr : React.FC = () => {
return (

<AppName >
        <Link href="/">Abc</Link>
    </AppName>
    <Button>
        <Link href="/new">
          Aboutus
        </Link>
    </Button>

)}
export default NavBarr;


问:
Cannot update TextView from another class
My android project has 3 class MainActivity.java , itemlist.java and Bill.java

I created the object of Bill class from itemlist.java class and passed context from there.
So when i try to update textview from Bill.java class it simply does not update but when i do same from MainActivity it works

So my question is how to make this TextView update work?

```<code>package com.example.smit.databasedemo.Functions;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.example.smit.databasedemo.MainActivity;
import com.example.smit.databasedemo.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Smit on 18-02-2020.
 */

public class Bill extends AppCompatActivity{
    private LayoutInflater inflater;
    private final View view;

    public Bill(Context context){
        inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.activity_main,null);
    }
</code>```

Here context is passed by using getApplicationContext() passed from MainActivity

```<code>    public void calculate(String bill){

        final TextView billText = (TextView) view.findViewById(R.id.useless);

        String text = (billText.getText().toString())+bill;
        //Here the text is fetched from same textbox but fail's to update
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(text);
        String[] amount= new String[2];
        int i=0;
        while(m.find()){
            amount[i] = m.group();
            i++;
        }
        int amount_prev = Integer.valueOf(amount[0]);
        final int total = (amount_prev)+(Integer.valueOf(amount[1]));
        billText.setText("Total Bill:"+total+"Rs");
        //Cannot update this textbox

    }

}

final Bill bill = new Bill(context);

//this is how its called
public void onClick(View v) {
                        counter++;
                        price= (finalViewHolder.price.getText().toString());
                        finalViewHolder.item.setText(String.valueOf(counter));
                        bill.calculate(price);

                    }
</code>```

p.s tried running on uiThread() does not work

答:
You have to pass the Context reference via constructor:

```<code>public Bill(Context context){
    this.context=context;
//rest of your code...

}
</code>```

Also find the TextView like this:

```<code>TextView billText = (TextView) ((Activity)context).findViewById(R.id.useless);
</code>```

Body:
My android project has 3 class MainActivity.java , itemlist.java and Bill.java

I created the object of Bill class from itemlist.java class and passed context from there.
So when i try to update textview from Bill.java class it simply does not update but when i do same from MainActivity it works

So my question is how to make this TextView update work?

package com.example.smit.databasedemo.Functions;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.example.smit.databasedemo.MainActivity;
import com.example.smit.databasedemo.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Smit on 18-02-2020.
 */

public class Bill extends AppCompatActivity{
    private LayoutInflater inflater;
    private final View view;

    public Bill(Context context){
        inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.activity_main,null);
    }

Here context is passed by using getApplicationContext() passed from MainActivity

    public void calculate(String bill){

        final TextView billText = (TextView) view.findViewById(R.id.useless);

        String text = (billText.getText().toString())+bill;
        //Here the text is fetched from same textbox but fail's to update
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(text);
        String[] amount= new String[2];
        int i=0;
        while(m.find()){
            amount[i] = m.group();
            i++;
        }
        int amount_prev = Integer.valueOf(amount[0]);
        final int total = (amount_prev)+(Integer.valueOf(amount[1]));
        billText.setText("Total Bill:"+total+"Rs");
        //Cannot update this textbox

    }

}

final Bill bill = new Bill(context);

//this is how its called
public void onClick(View v) {
                        counter++;
                        price= (finalViewHolder.price.getText().toString());
                        finalViewHolder.item.setText(String.valueOf(counter));
                        bill.calculate(price);

                    }

p.s tried running on uiThread() does not work

Body:
You have to pass the Context reference via constructor:

public Bill(Context context){
    this.context=context;
//rest of your code...

}

Also find the TextView like this:

TextView billText = (TextView) ((Activity)context).findViewById(R.id.useless);


问:
Change Rundeck storage password
Is there any way to change the storage password for an existing Rundeck installation? This is the password referred to in rundeck-config.properties as rundeck.storage.converter.1.config.password and rundeck.config.storage.converter.1.config.password.

I presume it would be a case of going through each stored item, decrypting with the old password, encrypting with the new password, and finally updating the config file, but I'm hoping there's already a tool/script to do this.

thanks!

答:
You must follow these steps for your projects:

Export projects (this script looks useful for do that massively on ZIP file).

Delete all projects. (if you like, via RD CLI or API).

Stop the Rundeck service.

Change the encrypt passwords in the rundeck-config.properties file.

Start the Rundeck service.

And later import projects (if you like, via RD CLI or API).

Now your projects are encrypted with your new password. About the keys, you need to recreate it again.

Advice: test before in some non-prod environment.

Title: Change Rundeck storage password


问:
Write config in Zend Framework with APPLICATION_PATH
For an application I'd like to create some kind of setup-steps. In one of the steps the database configuration is written to the application.ini file. This all works, but something very strange happens: All the paths to the directories (library, layout, ...) are changed from paths with APPLICATION_PATH . to full paths. As you can imagine, this isn't very systemfriendly. Any idea how I can prevent that?

I update the application.ini with this code:

```<code># read existing configuration
$config = new Zend_Config_Ini(
    $location,
    null,
    array('skipExtends'        => true,
    'allowModifications' => true));

# add new values
$config->production->doctrine->connection = array();
$config->production->doctrine->connection->host = $data['server'];
$config->production->doctrine->connection->user = $data['username'];
$config->production->doctrine->connection->password = $data['password'];
$config->production->doctrine->connection->database = $data['database'];

# write new configuration
$writer = new Zend_Config_Writer_Ini(
    array(
        'config'   => $config,
    'filename' => $location));
$writer->write();
</code>```

答:
Since Zend_Config_Ini uses the default ini scanning mode (INI_SCANNER_NORMAL), it will parse all options and replace constants with their respective values. What you could do, is call parse_ini_file directly, using the INI_SCANNER_RAW mode, so the options aren't parsed.

ie. use

```<code>$config = parse_ini_file('/path/to/your.ini', TRUE, INI_SCANNER_RAW);
</code>```

You will get an associative array that you can manipulate as you see fit, and afterwards you can write that back with the following snippet (from the comments):

```<code>function write_ini_file($assoc_arr, $path, $has_sections=FALSE) {
    $content = "";
    if ($has_sections) {
        foreach ($assoc_arr as $key=>$elem) {
            $content .= "[".$key."]\n";
            foreach ($elem as $key2=>$elem2) {
                if(is_array($elem2))
                {
                    for($i=0;$i<count($elem2);$i++)
                    {
                        $content .= $key2."[] = ".$elem2[$i]."\n";
                    }
                }
                else if($elem2=="") $content .= $key2." = \n";
                else $content .= $key2." = ".$elem2."\n";
            }
        }
    }
    else {
        foreach ($assoc_arr as $key=>$elem) {
            if(is_array($elem))
            {
                for($i=0;$i<count($elem);$i++)
                {
                    $content .= $key2."[] = ".$elem[$i]."\n";
                }
            }
            else if($elem=="") $content .= $key2." = \n";
            else $content .= $key2." = ".$elem."\n";
        }
    }

    if (!$handle = fopen($path, 'w')) {
        return false;
    }
    if (!fwrite($handle, $content)) {
        return false;
    }
    fclose($handle);
    return true;
}
</code>```

ie. call it with :

```<code>write_ini_file($config, '/path/to/your.ini', TRUE);
</code>```

after manipulating the $config array. Just make sure you add double quotes to the option values where needed...

Or alternatively - instead of using that function - you could try writing it back using Zend_Config_Writer_Ini, after converting the array back to a Zend_Config object, I guess that should work as well...

Body:
For an application I'd like to create some kind of setup-steps. In one of the steps the database configuration is written to the application.ini file. This all works, but something very strange happens: All the paths to the directories (library, layout, ...) are changed from paths with APPLICATION_PATH . to full paths. As you can imagine, this isn't very systemfriendly. Any idea how I can prevent that?

I update the application.ini with this code:

# read existing configuration
$config = new Zend_Config_Ini(
    $location,
    null,
    array('skipExtends'        => true,
    'allowModifications' => true));

# add new values
$config->production->doctrine->connection = array();
$config->production->doctrine->connection->host = $data['server'];
$config->production->doctrine->connection->user = $data['username'];
$config->production->doctrine->connection->password = $data['password'];
$config->production->doctrine->connection->database = $data['database'];

# write new configuration
$writer = new Zend_Config_Writer_Ini(
    array(
        'config'   => $config,
    'filename' => $location));
$writer->write();

Body:
Since Zend_Config_Ini uses the default ini scanning mode (INI_SCANNER_NORMAL), it will parse all options and replace constants with their respective values. What you could do, is call parse_ini_file directly, using the INI_SCANNER_RAW mode, so the options aren't parsed.

ie. use

$config = parse_ini_file('/path/to/your.ini', TRUE, INI_SCANNER_RAW);

You will get an associative array that you can manipulate as you see fit, and afterwards you can write that back with the following snippet (from the comments):

function write_ini_file($assoc_arr, $path, $has_sections=FALSE) {
    $content = "";
    if ($has_sections) {
        foreach ($assoc_arr as $key=>$elem) {
            $content .= "[".$key."]\n";
            foreach ($elem as $key2=>$elem2) {
                if(is_array($elem2))
                {
                    for($i=0;$i<count($elem2);$i++)
                    {
                        $content .= $key2."[] = ".$elem2[$i]."\n";
                    }
                }
                else if($elem2=="") $content .= $key2." = \n";
                else $content .= $key2." = ".$elem2."\n";
            }
        }
    }
    else {
        foreach ($assoc_arr as $key=>$elem) {
            if(is_array($elem))
            {
                for($i=0;$i<count($elem);$i++)
                {
                    $content .= $key2."[] = ".$elem[$i]."\n";
                }
            }
            else if($elem=="") $content .= $key2." = \n";
            else $content .= $key2." = ".$elem."\n";
        }
    }

    if (!$handle = fopen($path, 'w')) {
        return false;
    }
    if (!fwrite($handle, $content)) {
        return false;
    }
    fclose($handle);
    return true;
}

ie. call it with :

write_ini_file($config, '/path/to/your.ini', TRUE);

after manipulating the $config array. Just make sure you add double quotes to the option values where needed...

Or alternatively - instead of using that function - you could try writing it back using Zend_Config_Writer_Ini, after converting the array back to a Zend_Config object, I guess that should work as well...


问:
Backslash confusion using bash/sed to replace variable user name with variable name?
Using Bash, the following sed substitution replaces the user name in the input string with %USERNAME (which is a DOS variable):

```<code>echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" \
   | sed -e "s=\\$USERNAME\>=\\%USERNAME%="
</code>```

The following fails to do the same:

```<code>echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" \
   | sed -e "s=home\\$USERNAME\>=home\\%USERNAME%="
</code>```

Context

This is going into a bash function

```<code>cpawusr () { cygpath -aw "$@" | sed -e "s=\\home\\$USERNAME\>=\\home\\%USERNAME%=g" ; }
</code>```

The function will be used by different users, and I want $USERNAME
to expand out when the function is called, hence the double quotes.

答:
The problem is how many programs are interpreting backslashes.  One solution is to replace some of the double backslashes with quadruple backslashes:

```<code>echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" |
    sed -e "s=home\\\\$USERNAME\>=home\\\\%USERNAME%="
</code>```

Another solution is to use single quotes where possible:

```<code>echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" |
    sed -e 's=home\\'"$USERNAME"'\>=home\\%USERNAME%='
</code>```

In the original code with the double quotes, the shell parses the string, and replaces each \\ pair by a single \.  Then sed sees a single backslash and uses that to escape the next character.  When you use quadruple backslashes, then sed sees \\ and treats that as \, as intended.

In the single-quoted script, the shell doesn't interpret the data in single quotes, but it does expand $USERNAME in the double quotes.

I note that the \> notation requires GNU sed; BSD (macOS) sed does not recognize it, even with -E for extended regular expressions.

Body:
Using Bash, the following sed substitution replaces the user name in the input string with %USERNAME (which is a DOS variable):

echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" \
   | sed -e "s=\\$USERNAME\>=\\%USERNAME%="

The following fails to do the same:

echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" \
   | sed -e "s=home\\$USERNAME\>=home\\%USERNAME%="

Context

This is going into a bash function

cpawusr () { cygpath -aw "$@" | sed -e "s=\\home\\$USERNAME\>=\\home\\%USERNAME%=g" ; }

The function will be used by different users, and I want $USERNAME
to expand out when the function is called, hence the double quotes.

Body:
The problem is how many programs are interpreting backslashes.  One solution is to replace some of the double backslashes with quadruple backslashes:

echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" |
    sed -e "s=home\\\\$USERNAME\>=home\\\\%USERNAME%="

Another solution is to use single quotes where possible:

echo "c:\\cygwin64\\home\\$USERNAME\SomeFolder" |
    sed -e 's=home\\'"$USERNAME"'\>=home\\%USERNAME%='

In the original code with the double quotes, the shell parses the string, and replaces each \\ pair by a single \.  Then sed sees a single backslash and uses that to escape the next character.  When you use quadruple backslashes, then sed sees \\ and treats that as \, as intended.

In the single-quoted script, the shell doesn't interpret the data in single quotes, but it does expand $USERNAME in the double quotes.

I note that the \> notation requires GNU sed; BSD (macOS) sed does not recognize it, even with -E for extended regular expressions.


问:
GitLab CI : npm command not found in Vue.js project
I have been playing around with GitLab CI and encountered an issue.
Runner says:

npm command not found

My gitlab-cli.yml

```<code>image: node:latest

cache:
  paths:
    - node_modules/

before_script:
  - npm install

unit test:
    stage: test
    script:
        - npm run unit

</code>```

The Runner Exceutor was Shell. Tried with docker executor too. Still the same error.

Can someone help?

答:
So what kind of runner you are using ? shared runner ?

here is a sample of my .gitlab-ci.yml. hope that will help you!

```<code>stages:
  - build

variables:
  VERSION: "1.0"

build:
  image: node:12.14.0-alpine3.10
  stage: build
  before_script:
    - npm i
    - npm install -g @angular/cli

  script:
    - ng build
  artifacts:
    paths:
      - dist/
</code>```

Body:
I have been playing around with GitLab CI and encountered an issue.
Runner says:

npm command not found

My gitlab-cli.yml

image: node:latest

cache:
  paths:
    - node_modules/

before_script:
  - npm install

unit test:
    stage: test
    script:
        - npm run unit

The Runner Exceutor was Shell. Tried with docker executor too. Still the same error.

Can someone help?

Body:
So what kind of runner you are using ? shared runner ?

here is a sample of my .gitlab-ci.yml. hope that will help you!

stages:
  - build

variables:
  VERSION: "1.0"

build:
  image: node:12.14.0-alpine3.10
  stage: build
  before_script:
    - npm i
    - npm install -g @angular/cli

  script:
    - ng build
  artifacts:
    paths:
      - dist/


问:
What are non-scriptable objects in Django?
I have the following model:

```<code>class Performance(Event):
    date_created = models.DateTimeField(_('date created'), default=timezone.now)
    date_modified = models.DateTimeField(_('date_modified'), auto_now=True)

class PerformanceWork(models.Model):
    perf = models.ForeignKey(Performance, related_name='perf_work', blank=True, null=True, on_delete=models.CASCADE)
    work =  models.ForeignKey(WorkMusic, related_name='work', blank=True, null=True, on_delete=models.CASCADE)

class WorkMusic(MPTTModel, Work):
    ...
</code>```

In my view.py:

```<code>class PerformanceView(TemplateView):
    template_name = 'performances/performance.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'perf': Performance.objects.get(pk=self.kwargs['pk'])
        })
        return context
</code>```

In my template, I am trying to render a recursive tree with this in my template:

```<code>  {% for work in perf.perf_work.all %}
    {% recursetree work.work %}
    <li>
      {% if node.is_leaf_node %}
        {{ node.name_original }}
      {% endif %}
      {% if not node.is_leaf_node %}
        <ul class="children">
          {{ children }}
        </ul>
      {% endif %}
    </li>
    {% endrecursetree %}
{% endfor %}
</code>```

When run my app, I get the following error.

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/performance/2/

Django Version: 3.0
Python Version: 3.7.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'opus',
 'generic',
 'art_perf',
 'art_visual',
 'debug_toolbar',
 'mptt',
 'import_export',
 'googlemaps']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware')

Template error:
In template /Users/howiec/Desktop/Opus/templates/performances/base.html, error at line 0
   'WorkMusic' object is not subscriptable
   1 : {% load static i18n %}
   2 :
   3 : <!DOCTYPE html>
   4 : <html lang="en" class="{% block html_class %}{% endblock %}">
   5 : <head>
   6 :     <meta charset="UTF-8">
   7 :     <meta name="viewport" content="width=device-width, initial-scale=1.0">
   8 :     <meta http-equiv="X-UA-Compatible" content="ie=edge">
   9 :
   10 :     <link rel="stylesheet" type="text/css" href="{% static 'css/performance.css' %}">

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "/usr/local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 257, in render
    roots = cache_tree_children(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 236, in cache_tree_children
    return get_cached_trees(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/utils.py", line 232, in get_cached_trees
    parent_attr = queryset[0]._mptt_meta.parent_attr

Exception Type: TypeError at /performance/2/
Exception Value: 'WorkMusic' object is not subscriptable
</code>```

Work.work is a queryset with a WorkMusic object:

I know this is graphable when I just graph a WorkMusic object directly. I'm not sure why this break when I access the object through another model?

答:
To access a model object field in Django, you have to use dot notation otherwise you get a not subscriptable error.

This will throw the error:

work_music_object['some_field']
```

<p>This will not:</p>

<pre class="lang-py prettyprint-override"><code>work_music_object.some_field
</code>```

Body:
I have the following model:

class Performance(Event):
    date_created = models.DateTimeField(_('date created'), default=timezone.now)
    date_modified = models.DateTimeField(_('date_modified'), auto_now=True)

class PerformanceWork(models.Model):
    perf = models.ForeignKey(Performance, related_name='perf_work', blank=True, null=True, on_delete=models.CASCADE)
    work =  models.ForeignKey(WorkMusic, related_name='work', blank=True, null=True, on_delete=models.CASCADE)

class WorkMusic(MPTTModel, Work):
    ...

In my view.py:

class PerformanceView(TemplateView):
    template_name = 'performances/performance.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'perf': Performance.objects.get(pk=self.kwargs['pk'])
        })
        return context

In my template, I am trying to render a recursive tree with this in my template:

  {% for work in perf.perf_work.all %}
    {% recursetree work.work %}

      {% if node.is_leaf_node %}
        {{ node.name_original }}
      {% endif %}
      {% if not node.is_leaf_node %}

          {{ children }}

      {% endif %}

    {% endrecursetree %}
{% endfor %}

When run my app, I get the following error.

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/performance/2/

Django Version: 3.0
Python Version: 3.7.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'opus',
 'generic',
 'art_perf',
 'art_visual',
 'debug_toolbar',
 'mptt',
 'import_export',
 'googlemaps']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware')

Template error:
In template /Users/howiec/Desktop/Opus/templates/performances/base.html, error at line 0
   'WorkMusic' object is not subscriptable
   1 : {% load static i18n %}
   2 :
   3 : <!DOCTYPE html>
   4 :
   5 :
   6 :     <meta charset="UTF-8">
   7 :     <meta name="viewport" content="width=device-width, initial-scale=1.0">
   8 :     <meta http-equiv="X-UA-Compatible" content="ie=edge">
   9 :
   10 :     <link rel="stylesheet" type="text/css" href="{% static 'css/performance.css' %}">

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "/usr/local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 257, in render
    roots = cache_tree_children(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 236, in cache_tree_children
    return get_cached_trees(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/utils.py", line 232, in get_cached_trees
    parent_attr = queryset[0]._mptt_meta.parent_attr

Exception Type: TypeError at /performance/2/
Exception Value: 'WorkMusic' object is not subscriptable

Work.work is a queryset with a WorkMusic object:

I know this is graphable when I just graph a WorkMusic object directly. I'm not sure why this break when I access the object through another model?

Body:
To access a model object field in Django, you have to use dot notation otherwise you get a not subscriptable error.

This will throw the error:

work_music_object['some_field']

This will not:

work_music_object.some_field


问:
Training accuracy is less than validation accuracy
I have created a CNN model for classifying text data. Please help me interpret my result and tell me why is my training accuracy less than validation accuracy?

I have a total of 2619 Data, all of them are text data. There are two different classes. Here is a sample of my dataset.

The validation set has 34 data. Rest of 2619 data are training data.

I have done RepeatedKfold cross-validation. Here is my code.

```<code>from sklearn.model_selection import RepeatedKFold
kf = RepeatedKFold(n_splits=75, n_repeats=1, random_state= 42)

for train_index, test_index in kf.split(X,Y):
      #print("Train:", train_index, "Validation:",test_index)
      x_train, x_test = X.iloc[train_index], X.iloc[test_index]
      y_train, y_test = Y.iloc[train_index], Y.iloc[test_index]
</code>```

I have used CNN. Here is my model.

```<code>model = Sequential()
model.add(Embedding(2900,2 , input_length=1))
model.add(Conv1D(filters=2, kernel_size=3, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), activation='sigmoid'))
model.add(Dropout(0.25))
adam = optimizers.Adam(lr = 0.0005, beta_1 = 0.9, beta_2 = 0.999, epsilon = None, decay = 0.0, amsgrad = False)
model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
print(model.summary())
history = model.fit(x_train, y_train, epochs=300,validation_data=(x_test, y_test), batch_size=128, shuffle=False)
# Final evaluation of the model
scores = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
</code>```

And here is the result.

```<code>Epoch 295/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6920 - acc: 0.7528 - val_loss: 0.5839 - val_acc: 0.8235
Epoch 296/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6532 - acc: 0.7617 - val_loss: 0.5836 - val_acc: 0.8235
Epoch 297/300
2585/2585 [==============================] - 0s 27us/step - loss: 1.5328 - acc: 0.7551 - val_loss: 0.5954 - val_acc: 0.8235
Epoch 298/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6289 - acc: 0.7524 - val_loss: 0.5897 - val_acc: 0.8235
Epoch 299/300
2585/2585 [==============================] - 0s 21us/step - loss: 1.7000 - acc: 0.7582 - val_loss: 0.5854 - val_acc: 0.8235
Epoch 300/300
2585/2585 [==============================] - 0s 25us/step - loss: 1.5475 - acc: 0.7451 - val_loss: 0.5934 - val_acc: 0.8235
Accuracy: 82.35%
</code>```

Please help me with my problem. Thank you.

答:
Your training accuracy is less than validation accuracy likely because of using dropout: it "turns off" some neurons during training to prevent overfitting. During validation dropout is off, so your network uses all its neurons, thus making (in that particular case) more accurate predictions.

In general, I agree with advice by Thibault Bacqueyrisses and want to add that it's also usually a bad practice to put dropout before batch normalization (which is not about this particular case anyway).

Body:
I have created a CNN model for classifying text data. Please help me interpret my result and tell me why is my training accuracy less than validation accuracy?

I have a total of 2619 Data, all of them are text data. There are two different classes. Here is a sample of my dataset.

The validation set has 34 data. Rest of 2619 data are training data.

I have done RepeatedKfold cross-validation. Here is my code.

from sklearn.model_selection import RepeatedKFold
kf = RepeatedKFold(n_splits=75, n_repeats=1, random_state= 42)

for train_index, test_index in kf.split(X,Y):
      #print("Train:", train_index, "Validation:",test_index)
      x_train, x_test = X.iloc[train_index], X.iloc[test_index]
      y_train, y_test = Y.iloc[train_index], Y.iloc[test_index]

I have used CNN. Here is my model.

model = Sequential()
model.add(Embedding(2900,2 , input_length=1))
model.add(Conv1D(filters=2, kernel_size=3, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), activation='sigmoid'))
model.add(Dropout(0.25))
adam = optimizers.Adam(lr = 0.0005, beta_1 = 0.9, beta_2 = 0.999, epsilon = None, decay = 0.0, amsgrad = False)
model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
print(model.summary())
history = model.fit(x_train, y_train, epochs=300,validation_data=(x_test, y_test), batch_size=128, shuffle=False)
# Final evaluation of the model
scores = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

And here is the result.

Epoch 295/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6920 - acc: 0.7528 - val_loss: 0.5839 - val_acc: 0.8235
Epoch 296/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6532 - acc: 0.7617 - val_loss: 0.5836 - val_acc: 0.8235
Epoch 297/300
2585/2585 [==============================] - 0s 27us/step - loss: 1.5328 - acc: 0.7551 - val_loss: 0.5954 - val_acc: 0.8235
Epoch 298/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6289 - acc: 0.7524 - val_loss: 0.5897 - val_acc: 0.8235
Epoch 299/300
2585/2585 [==============================] - 0s 21us/step - loss: 1.7000 - acc: 0.7582 - val_loss: 0.5854 - val_acc: 0.8235
Epoch 300/300
2585/2585 [==============================] - 0s 25us/step - loss: 1.5475 - acc: 0.7451 - val_loss: 0.5934 - val_acc: 0.8235
Accuracy: 82.35%

Please help me with my problem. Thank you.