问:
.htaccess satisfy www/ssl rules before redirection
I've looked through tens of articles regarding this but none of them has solved my issue and it continues to give me a headache.

Here's what I want to achieve:

1) I have an second domain name which needs redirecting to the main domain while keeping the rest of the URL,

2) All files should lose .php extension,

3) Force WWW,

4) Force HTTPS.

Now the problem is that my current .htaccess only works this way for the main domain and only if the WWW condition is met. Let me explain.

If I type in domain1.com/page or domain2.com/page, it will open https:// www.domain1/2.com/page.php but it should only be /page without .php.

If I type in www.domain1.com/page, it will open https:// www.domain1.com/page - Expected behaviour,
but if I type in www.domain2.com/page, it will open https:// domain1.com/page.php.

How can I make sure that any conbination of HTTP/HTTPS and WWW/non-WWW, domain1.com/domain2.com always redirects to https:// www.domain1.com/page ?

I'm also happy for any php code suggestions that I might put  the top of every .php file to automatically redirect to the extensionless version but would really love to understand why my .htaccess isn't working.

Here's the code:

```<code>## Main Rules
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

## Redirect Domain2.com to Main
RewriteCond %{HTTP_HOST} ^www\.domain2\.com [NC]
RewriteRule ^(.*)$ https://www.domain1.com/$1 [R,L]

## Remove .php Extensions
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

## Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Force WWW
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

ErrorDocument 404 /404
</code>```

Thanks a lot!

答:
You have the directives in the wrong order. Importantly, the rule that appends the .php extension via an internal rewrite (which you've labelled "Remove .php Extensions") should go at the end, after the external redirects. Your rewrite is appending .php to the requested URL, ie. page becomes page.php and then you are triggering an external redirect which naturally exposes the underlying filename.

However, your directives will result in multiple redirects and can be simplified. The last redirect, for instance, does not canonicalise the protocol (and replies on previous rules to have done this).

For example:

```<code>ErrorDocument 404 /404

## Main Rules
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

## Redirect Domain2.com to Main
RewriteCond %{HTTP_HOST} ^(www\.)?domain2\.com [NC]
RewriteRule (.*) https://www.domain1.com/$1 [R,L]

## Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Force WWW
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Append .php Extensions
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule (.*) $1.php [L]
</code>```

If you have no intention of implementing HSTS then you should reverse the "Force HTTPS" and "Force WWW" rules in order to avoid an additional redirect when requesting http://domain1.com/page.

Note that your initial redirect from domain2.com to domain1.com is a 302 (temporary) redirect.

UPDATE: Note that MultiViews should also be disabled, if not already. For example:

```<code>Options +FollowSymLinks -MultiViews
</code>```

If MultiViews was enabled, then this would also result in the first redirect exposing the file extension since mod_negotiation would issue an internal subrequest for page.php before mod_rewrite processes the request. However, if MultiViews was enabled, then this would also mean that your final rewrite rule that appends the .php extension was effectively being bypassed (since the 2nd conditon would always fail, unless page.php.php existed.).

With MultiViews disabled then this highlights a potential bug with the final rewrite. In that a request for /page/foo, where /page.php exists as an actual file (as in your example) would result in a 500 internal server error due to a rewrite loop. To correct this, the final rewrite rule that appends the .php extension should be changed to the following:

```<code>## Append .php Extensions
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]
</code>```

(There's no need to check that the request is not a directory and is a file, since it can never be both.)

Body:
I've looked through tens of articles regarding this but none of them has solved my issue and it continues to give me a headache.

Here's what I want to achieve:

1) I have an second domain name which needs redirecting to the main domain while keeping the rest of the URL,

2) All files should lose .php extension,

3) Force WWW,

4) Force HTTPS.

Now the problem is that my current .htaccess only works this way for the main domain and only if the WWW condition is met. Let me explain.

If I type in domain1.com/page or domain2.com/page, it will open https:// www.domain1/2.com/page.php but it should only be /page without .php.

If I type in www.domain1.com/page, it will open https:// www.domain1.com/page - Expected behaviour,
but if I type in www.domain2.com/page, it will open https:// domain1.com/page.php.

How can I make sure that any conbination of HTTP/HTTPS and WWW/non-WWW, domain1.com/domain2.com always redirects to https:// www.domain1.com/page ?

I'm also happy for any php code suggestions that I might put  the top of every .php file to automatically redirect to the extensionless version but would really love to understand why my .htaccess isn't working.

Here's the code:

## Main Rules
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

## Redirect Domain2.com to Main
RewriteCond %{HTTP_HOST} ^www\.domain2\.com [NC]
RewriteRule ^(.*)$ https://www.domain1.com/$1 [R,L]

## Remove .php Extensions
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

## Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Force WWW
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

ErrorDocument 404 /404

Thanks a lot!

Body:
You have the directives in the wrong order. Importantly, the rule that appends the .php extension via an internal rewrite (which you've labelled "Remove .php Extensions") should go at the end, after the external redirects. Your rewrite is appending .php to the requested URL, ie. page becomes page.php and then you are triggering an external redirect which naturally exposes the underlying filename.

However, your directives will result in multiple redirects and can be simplified. The last redirect, for instance, does not canonicalise the protocol (and replies on previous rules to have done this).

For example:

ErrorDocument 404 /404

## Main Rules
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

## Redirect Domain2.com to Main
RewriteCond %{HTTP_HOST} ^(www\.)?domain2\.com [NC]
RewriteRule (.*) https://www.domain1.com/$1 [R,L]

## Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Force WWW
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Append .php Extensions
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule (.*) $1.php [L]

If you have no intention of implementing HSTS then you should reverse the "Force HTTPS" and "Force WWW" rules in order to avoid an additional redirect when requesting http://domain1.com/page.

Note that your initial redirect from domain2.com to domain1.com is a 302 (temporary) redirect.

UPDATE: Note that MultiViews should also be disabled, if not already. For example:

Options +FollowSymLinks -MultiViews

If MultiViews was enabled, then this would also result in the first redirect exposing the file extension since mod_negotiation would issue an internal subrequest for page.php before mod_rewrite processes the request. However, if MultiViews was enabled, then this would also mean that your final rewrite rule that appends the .php extension was effectively being bypassed (since the 2nd conditon would always fail, unless page.php.php existed.).

With MultiViews disabled then this highlights a potential bug with the final rewrite. In that a request for /page/foo, where /page.php exists as an actual file (as in your example) would result in a 500 internal server error due to a rewrite loop. To correct this, the final rewrite rule that appends the .php extension should be changed to the following:

## Append .php Extensions
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

(There's no need to check that the request is not a directory and is a file, since it can never be both.)


来源: stackexchange

问:
Batch OCR Program for PDFs
This has been asked before, but I don't really know if the answers help me.  Here is my problem: I got a bunch of (10,000 or so) pdf files.  Some were text files that were saved using adobe's print feature (so their text is perfect and I don't want to risk screwing them up).  And some were scanned images (so they don't have any text and I will have to settle for OCR).  The files are in the same directory and I can't tell which is which.  Ultimately I want to turn them into .txt files and then do string processing on them.  So I want the most accurate OCR possible.

It seems like people have recommended:

adobe pdf (I don't have a licensed copy of this so ... plus if ABBYY finereader or something is better, why pay for it if I won't use it)

ocropus (I can't figure out how to use this thing),

Tesseract (which seems like it was great in 1995 but I'm not sure if there's something more accurate plus it doesn't do pdfs natively and I've have to convert to TIFF. that raises its own problem as I don't have a licensed copy of acrobat so I don't know how I'd convert 10,000 files to tiff. plus i don't want 10,000 30 page documents turned into 30,000 individual tiff images).

wowocr

pdftextstream (that was from 2009)

ABBYY FineReader (apparently its' $$$, but I will spend $600 to get this done if this thing is significantly better, i.e. has more accurate ocr).

Also I am a n00b to programming so if it's going to take like weeks to learn how to do something, I would rather pay the $$$.  Thx for input/experiences.

BTW, I'm running Linux Mint 11 64 bit and/or windows 7 64 bit.

Here are the other threads:

Batch OCRing PDFs that haven't already been OCR'd

Open source OCR

PDF Text Extraction Approach Using OCR

https://superuser.com/questions/107678/batch-ocr-for-many-pdf-files-not-already-ocred

答:
Just to put some of your misconceptions straight...

" I don't have a licensed copy of acrobat so I don't know how I'd convert 10,000 files to tiff."

You can convert PDFs to TIFF with the help of Free (as in liberty) and free (as in beer) Ghostscript. Your choice if you want to do it on Linux Mint or on Windows 7. The commandline for Linux is:

```<code>gs \
 -o input.tif \
 -sDEVICE=tiffg4 \
  input.pdf
</code>```

"i don't want 10,000 30 page documents turned into 30,000 individual tiff images"

You can have "multipage" TIFFs easily. Above command does create such TIFFs of the G4 (fax tiff) flavor. Should you even want single-page TIFFs instead, you can modify the command:

```<code>gs \
 -o input_page_%03d.tif \
 -sDEVICE=tiffg4 \
  input.pdf
</code>```

The %03d part of the output filename will automatically translate into a series of 001, 002, 003 etc.

Caveats:

The default resolution for the tiffg4 output device is 204x196 dpi. You probably want a better value. To get 720 dpi you should add -r720x720 to the commandline.

Also, if your Ghostscript installation uses letter as its default media size, you may want to change it. You can use -gXxY to set widthxheight in device points. So to get ISO A4 output page dimensions in landscape you can add a -g8420x5950 parameter.

So the full command which controls these two parameters, to produce 720 dpi output on A4 in portrait orientation, would read:

```<code>gs \
 -o input.tif \
 -sDEVICE=tiffg4 \
 -r720x720 \
 -g5950x8420 \
  input.pdf
</code>```

ContentLicense: CC BY-SA 3.0

Title: Batch OCR Program for PDFs

Body:
Just to put some of your misconceptions straight...

" I don't have a licensed copy of acrobat so I don't know how I'd convert 10,000 files to tiff."

You can convert PDFs to TIFF with the help of Free (as in liberty) and free (as in beer) Ghostscript. Your choice if you want to do it on Linux Mint or on Windows 7. The commandline for Linux is:

gs \
 -o input.tif \
 -sDEVICE=tiffg4 \
  input.pdf

"i don't want 10,000 30 page documents turned into 30,000 individual tiff images"

You can have "multipage" TIFFs easily. Above command does create such TIFFs of the G4 (fax tiff) flavor. Should you even want single-page TIFFs instead, you can modify the command:

gs \
 -o input_page_%03d.tif \
 -sDEVICE=tiffg4 \
  input.pdf

The %03d part of the output filename will automatically translate into a series of 001, 002, 003 etc.

Caveats:

The default resolution for the tiffg4 output device is 204x196 dpi. You probably want a better value. To get 720 dpi you should add -r720x720 to the commandline.

Also, if your Ghostscript installation uses letter as its default media size, you may want to change it. You can use -gXxY to set widthxheight in device points. So to get ISO A4 output page dimensions in landscape you can add a -g8420x5950 parameter.

So the full command which controls these two parameters, to produce 720 dpi output on A4 in portrait orientation, would read:

gs \
 -o input.tif \
 -sDEVICE=tiffg4 \
 -r720x720 \
 -g5950x8420 \
  input.pdf


问:
Difference between $_SERVER['DOCUMENT_ROOT'] and $_SERVER['HTTP_HOST']
I am back with a simple question (or related question).

The question is simple however I have not received an answer yet. I have asked many people with different experience in PHP. But the response I get is: "I don't have any idea. I've never thought about that." Using Google I have not been able to find any article on this. I hope that I will get a satisfying answer here.

So the question is:

What is the difference between $_SERVER['DOCUMENT_ROOT'] and $_SERVER['HTTP_HOST'] ?

Are there any advantages of one over the other?

Where should we use HTTP_HOST & where to use DOCUMENT_ROOT?

答:
The Title question is perfectly awnsered by John Ledbetter.

This awnser is intended to expand and offer additional information about what seems to be the original poster inner concerns:

Where would make sense to use the URL based location: $_SERVER['HTTP_HOST'] ?

Where would make sense to use the local based location: $_SERVER['DOCUMENT_ROOT'] ?

Where both can be used, what are the Advantages and Disadvantages of each one. ?

Following my awnsers:

By usign the HTTP_HOST you can abstract yourself from the machine Folder System which means in cases where portability is a concern and you are expected to install the Application on multiple servers potentially with diferent OS this approach could be easier to maintain.

You can also take advantage of HTTP_HOST if your server is going to become unavailible and you want a diferent one from the cluster to handle the request.

By Using the DOCUMENT_ROOT you can access the whole filesystem (depends on the permissions you give to php) it makes sense if you want to access a program which you dont want to be accesible from the web or when the Folder System is relevant to your Application.

You can also take advantage of DOCUMENT_ROOT to get the subsite root instead of the Host.

```<code>$_SERVER['HTTP_HOST'] = "www.example.com";
$_SERVER['DOCUMENT_ROOT'] = "var/www/domain/subsite1" // equivalent to www.example.com/subsite1
</code>```

Body:
The Title question is perfectly awnsered by John Ledbetter.

This awnser is intended to expand and offer additional information about what seems to be the original poster inner concerns:

Where would make sense to use the URL based location: $_SERVER['HTTP_HOST'] ?

Where would make sense to use the local based location: $_SERVER['DOCUMENT_ROOT'] ?

Where both can be used, what are the Advantages and Disadvantages of each one. ?

Following my awnsers:

By usign the HTTP_HOST you can abstract yourself from the machine Folder System which means in cases where portability is a concern and you are expected to install the Application on multiple servers potentially with diferent OS this approach could be easier to maintain.

You can also take advantage of HTTP_HOST if your server is going to become unavailible and you want a diferent one from the cluster to handle the request.

By Using the DOCUMENT_ROOT you can access the whole filesystem (depends on the permissions you give to php) it makes sense if you want to access a program which you dont want to be accesible from the web or when the Folder System is relevant to your Application.

You can also take advantage of DOCUMENT_ROOT to get the subsite root instead of the Host.

$_SERVER['HTTP_HOST'] = "www.example.com";
$_SERVER['DOCUMENT_ROOT'] = "var/www/domain/subsite1" // equivalent to www.example.com/subsite1

ContentLicense: CC BY-SA 4.0


问:
QtQuick: Creating menu from ListModel
i am new to the forum and i started designing several things in QtQuick.
I am still exploring and learning the basic stuff and i stumbled upon the following problem.
When i try to create a menu (menubar) from a ListModel using Listview, i simply dont get any menu at all.
Maybe i have still an misunderstanding about the principles and you can help me.
Here is my basic code:

```<code>import QtQuick 2.12
import QtQuick.Window 2.14
import QtQuick.Layouts 1.12
import QtQuick.Dialogs 1.3
import QtQuick.Controls 2.14
MenuBar{
  id: menuBarId

  ListModel{
  id: listModelMenuId
  ListElement {menuname: "Test1"}
  ListElement {menuname: "Test2"}

  }
  ListView{
  id: listViewMenuId
  model: listModelMenuId
  delegate: Menu {
          id: menu
          title: model.menuname
          Action { text: qsTr("Tool Bar"); checkable: true }
          Action { text: qsTr("Side Bar"); checkable: true; checked: true }
          Action { text: qsTr("Status Bar"); checkable: true; checked: true;}

          MenuSeparator {
              contentItem: Rectangle {
                  implicitWidth: 200
                  implicitHeight: 1
                  color: "#21be2b"
              }
          }
          Menu {
              title: qsTr("Advanced")
          }

          topPadding: 2
          bottomPadding: 2
//          delegate: mydelegateid

          background: Rectangle {
              implicitWidth: 200
              implicitHeight: 40
              color: "#ffffff"
              border.color: "#21be2b"
              radius: 2

          }
      }} }
</code>```

I got my sample from the qt site and tampered with it by adding the ListModel.
Also interesting is that if i want to refactor the original coding by using a component where i pack up the MenuItem and call the compoenent it also not works. Can it be that menus in general work different thand other Items?
If i left something important out just tell me, i'll add more information.

Best regards!

答:
i resolved the issue.
Example to delegate your style in a MenuBar

This resolved the problem in general. However, i still wonder why i can not encapsulate the MenuItem into a component and use the components id to delegate the style for the items....
Regards,
Seryoga

Title: QtQuick: Creating menu from ListModel

Body:
i am new to the forum and i started designing several things in QtQuick.
I am still exploring and learning the basic stuff and i stumbled upon the following problem.
When i try to create a menu (menubar) from a ListModel using Listview, i simply dont get any menu at all.
Maybe i have still an misunderstanding about the principles and you can help me.
Here is my basic code:

import QtQuick 2.12
import QtQuick.Window 2.14
import QtQuick.Layouts 1.12
import QtQuick.Dialogs 1.3
import QtQuick.Controls 2.14
MenuBar{
  id: menuBarId

  ListModel{
  id: listModelMenuId
  ListElement {menuname: "Test1"}
  ListElement {menuname: "Test2"}

  }
  ListView{
  id: listViewMenuId
  model: listModelMenuId
  delegate: Menu {
          id: menu
          title: model.menuname
          Action { text: qsTr("Tool Bar"); checkable: true }
          Action { text: qsTr("Side Bar"); checkable: true; checked: true }
          Action { text: qsTr("Status Bar"); checkable: true; checked: true;}

          MenuSeparator {
              contentItem: Rectangle {
                  implicitWidth: 200
                  implicitHeight: 1
                  color: "#21be2b"
              }
          }
          Menu {
              title: qsTr("Advanced")
          }

          topPadding: 2
          bottomPadding: 2
//          delegate: mydelegateid

          background: Rectangle {
              implicitWidth: 200
              implicitHeight: 40
              color: "#ffffff"
              border.color: "#21be2b"
              radius: 2

          }
      }} }

I got my sample from the qt site and tampered with it by adding the ListModel.
Also interesting is that if i want to refactor the original coding by using a component where i pack up the MenuItem and call the compoenent it also not works. Can it be that menus in general work different thand other Items?
If i left something important out just tell me, i'll add more information.

Best regards!


问:
SOAP Webservice in Quarkus fails with Unknown JAXBContext implementation
I have a Quarkus service in which I publish a SOAP service on startup like this:

```<code>@WebService(serviceName = "/service", portName = "ServicePort")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@ApplicationScoped
public class Astute implements AstuteManager {

  void onStart(@Observes StartupEvent ev) {
    String url = "http://localhost:9005/";
    Endpoint.publish(url, this);
}

@WebMethod(operationName = "Retrieve", action = "Retrieve")
@WebResult(name = "response", targetNamespace = "http://some.namepsace")
@RequestWrapper(localName = "RetrieveInfo", targetNamespace = "http://some.namepsace",
     className = "dto.RetrieveDto")
@ResponseWrapper(localName = "RetrieveReply", targetNamespace = "http://some.namespace",
    className = "dto.RetrieveReplyDto")
public RetrieveReplyDto retrieveClientPortfolio(
    @WebParam(name = "request", targetNamespace = "http://some.namespace") RetrieveInfo request) {
    //do something
}
</code>```

When I hit that endpoint I get:

```<code>SEVERE [com.sun.xml.int.ws.tra.htt.HttpAdapter] (pool-4-thread-1) Unknown JAXBContext implementation:
   class com.sun.xml.bind.v2.runtime.JAXBContextImpl: com.sun.xml.internal.ws.spi.db.DatabindingException:
   Unknown JAXBContext implementation: class com.sun.xml.bind.v2.runtime.JAXBContextImpl
        at com.sun.xml.internal.ws.spi.db.BindingContextFactory.getJAXBFactory(BindingContextFactory.java:192)
        at com.sun.xml.internal.ws.spi.db.BindingContextFactory.create(BindingContextFactory.java:134)
        at com.sun.xml.internal.ws.message.jaxb.JAXBMessage.create(JAXBMessage.java:152)
        at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createSOAP11Fault(SOAPFaultBuilder.java:424)
        at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createSOAPFaultMessage(SOAPFaultBuilder.java:201)
        at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createSOAPFaultMessage(SOAPFaultBuilder.java:189)
        at com.sun.xml.internal.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:411)
        at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:706)
        at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:260)
        at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(WSHttpHandler.java:98)
        at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(WSHttpHandler.java:82)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79)
        at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:82)
        at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:675)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79)
        at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:647)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

I'm thinking it's perhaps a dependency clash, but nothing in my dependency tree stands out.
Is this the correct way to start a SOAP service from Quarkus?

Here are the dependencies in the pom:

```<code><dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-core</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jaxb</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jdbc-mssql</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
     <version>3.7</version>
</dependency>
</code>```

Quarkus V1.2.0

答:
I think it could be a class loading issues similar to what we have seen in the past with JAXB when some of the classes come from the JDK itself and some from the dependencies.

Could you try:
- upgrading to 1.3.0.Alpha1 (use quarkus-bom not quarkus-universe-bom) and also upgrade the Quarkus Maven plugin version
- then add the following dependencies to your pom.xml:

<dependency>
  <groupId>javax.xml.ws</groupId>
  <artifactId>jaxws-api</artifactId>
  <version>2.3.1</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.ws</groupId>
  <artifactId>rt</artifactId>
  <version>2.3.1</version>
</dependency>
```

and see if it solves your issue.

If it doesn't, please create a simple reproducer and create an issue on our GitHub so that we can have a closer look.

Body:
I have a Quarkus service in which I publish a SOAP service on startup like this:

@WebService(serviceName = "/service", portName = "ServicePort")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@ApplicationScoped
public class Astute implements AstuteManager {

  void onStart(@Observes StartupEvent ev) {
    String url = "http://localhost:9005/";
    Endpoint.publish(url, this);
}

@WebMethod(operationName = "Retrieve", action = "Retrieve")
@WebResult(name = "response", targetNamespace = "http://some.namepsace")
@RequestWrapper(localName = "RetrieveInfo", targetNamespace = "http://some.namepsace",
     className = "dto.RetrieveDto")
@ResponseWrapper(localName = "RetrieveReply", targetNamespace = "http://some.namespace",
    className = "dto.RetrieveReplyDto")
public RetrieveReplyDto retrieveClientPortfolio(
    @WebParam(name = "request", targetNamespace = "http://some.namespace") RetrieveInfo request) {
    //do something
}

When I hit that endpoint I get:

SEVERE [com.sun.xml.int.ws.tra.htt.HttpAdapter] (pool-4-thread-1) Unknown JAXBContext implementation:
   class com.sun.xml.bind.v2.runtime.JAXBContextImpl: com.sun.xml.internal.ws.spi.db.DatabindingException:
   Unknown JAXBContext implementation: class com.sun.xml.bind.v2.runtime.JAXBContextImpl
        at com.sun.xml.internal.ws.spi.db.BindingContextFactory.getJAXBFactory(BindingContextFactory.java:192)
        at com.sun.xml.internal.ws.spi.db.BindingContextFactory.create(BindingContextFactory.java:134)
        at com.sun.xml.internal.ws.message.jaxb.JAXBMessage.create(JAXBMessage.java:152)
        at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createSOAP11Fault(SOAPFaultBuilder.java:424)
        at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createSOAPFaultMessage(SOAPFaultBuilder.java:201)
        at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.createSOAPFaultMessage(SOAPFaultBuilder.java:189)
        at com.sun.xml.internal.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:411)
        at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:706)
        at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:260)
        at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(WSHttpHandler.java:98)
        at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(WSHttpHandler.java:82)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79)
        at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:82)
        at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:675)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:79)
        at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:647)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

I'm thinking it's perhaps a dependency clash, but nothing in my dependency tree stands out.
Is this the correct way to start a SOAP service from Quarkus?

Here are the dependencies in the pom:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-core</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jaxb</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jdbc-mssql</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
     <version>3.7</version>
</dependency>

Quarkus V1.2.0

Body:
I think it could be a class loading issues similar to what we have seen in the past with JAXB when some of the classes come from the JDK itself and some from the dependencies.

Could you try:
- upgrading to 1.3.0.Alpha1 (use quarkus-bom not quarkus-universe-bom) and also upgrade the Quarkus Maven plugin version
- then add the following dependencies to your pom.xml:

<dependency>
  <groupId>javax.xml.ws</groupId>
  <artifactId>jaxws-api</artifactId>
  <version>2.3.1</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.ws</groupId>
  <artifactId>rt</artifactId>
  <version>2.3.1</version>
</dependency>

and see if it solves your issue.

If it doesn't, please create a simple reproducer and create an issue on our GitHub so that we can have a closer look.


问:
Custom field for background color for every category in categories.blade (from admin panel to view)(laravel , controller)
hi guys i want to add a specific background for every category that i added from my category.blade in admin panel

i have 2 field : on for the name and the second for image

i want to add the third field (select box) , this field for select the category color .

when i choose a color from the selectbox it will be the background in the categories.blade for every category of course (we can use function to add Id='$color' by this way every category HAVE ID = HAVE COLOR)

-categories blade (admin) :

```<code>    {{ Form::open(['class' => 'form-horizontal', 'files' => true]) }}

    <div class="form-group {{ $errors->has('category_name')? 'has-error':'' }}">
        <label for="category_name" class="col-sm-4 control-label">@lang('app.category_name')</label>
        <div class="col-sm-8">
            <input type="text" class="form-control" id="category_name" value="{{ old('category_name') }}" name="category_name" placeholder="@lang('app.category_name')"> {!! $errors->has('category_name')? '
            <p class="help-block">'.$errors->first('category_name').'</p>':'' !!} </div></div>

    <div class="form-group {{ $errors->has('image')? 'has-error':'' }}">
        <label for="image" class="col-sm-4 control-label">@lang('app.image')</label>
        <div class="col-sm-8">
            <input type="file" name="image" id="image" class="form-control"> {!! $errors->has('image')? '
            <p class="help-block">'.$errors->first('image').'</p>':'' !!} </div></div>
</code>```

category controller :

```<code>public function category($category_name){  return view('content.category' , compact('post'));
    }
    public function index(){
        $title = trans('app.categories');
        $categories = Category::all();

            return view('admin.categories', compact('title', 'categories'));
        }

        public function store(Request $request)
        {
            $rules = [
                'category_name' => 'required',
                'image'         => 'image'
            ];
            $this->validate($request, $rules);

            $slug = str_slug($request->category_name);
            $duplicate = Category::where('category_slug', $slug)->count();
            if ($duplicate > 0){
                return back()->with('error', trans('app.category_exists_in_db'));
            }

            /**
             * Upload image if any
             */
            $image_name = '';
            if ($request->hasFile('image')){
                $upload_dir = public_path('uploads/images/');
                if ( ! file_exists($upload_dir)){
                    mkdir($upload_dir, 0777, true);
                }

                $image = $request->file('image');
                $file_base_name = str_replace('.'.$image->getClientOriginalExtension(), '', $image->getClientOriginalName());
                $resized = Image::make($image)->resize(300, 200);

                $image_name = strtolower(time().str_random(5).'-'.str_slug($file_base_name)).'.' . $image->getClientOriginalExtension();
                $imageFileName = $upload_dir.$image_name;

                try{
                    $resized->save($imageFileName);
                } catch (\Exception $e){
                    return $e->getMessage();
                }
            }

            $data = [
                'category_name' => $request->category_name,
                'category_slug' => $slug,
                'image' => $image_name,
            ];

            Category::create($data);
            return back()->with('success', trans('app.category_created'));
        }
</code>```

category blade view :

```<code>    <a href="{{route('single_category', [$cat->id, $cat->category_slug])}}">
    <div  class="wow flipInY col-md-2 col-sm-6 col-xs-12 col-center">
    <div class="home-category-box">
    <img id="" src="{{ $cat->get_image_url() }}" />
    <div class="title">
    <a href="{{route('single_category', [$cat->id, $cat->category_slug])}}">{{
    $cat->category_name }}</a>
</code>```

答:
First you will have to add the select box to your form:

```<code><div class="form-group {{ $errors->has('color')? 'has-error':'' }}">
    <label for="color" class="col-sm-4 control-label">@lang('app.color')</label>
    <div class="col-sm-8">
        <select name="color" id="color" class="form-control" onchange="setColor()">
            <option value="red">Red</option>
            <option value="green">Blue</option>
            <option value="blue">Blue</option>
        </select>
        {!! $errors->has('image')? '<p class="help-block">'.$errors->first('image').'</p>':'' !!}
    </div>
</div>
</code>```

Then add some JavaScript to change the background color of the select box to the chosen color:

```<code><script type="text/javascript">
function setColor() {
    document.getElementById("color").setAttribute("style", "background-color: " + document.getElementById("color").value);
}
</script>
</code>```

Body:
hi guys i want to add a specific background for every category that i added from my category.blade in admin panel

i have 2 field : on for the name and the second for image

i want to add the third field (select box) , this field for select the category color .

when i choose a color from the selectbox it will be the background in the categories.blade for every category of course (we can use function to add Id='$color' by this way every category HAVE ID = HAVE COLOR)

-categories blade (admin) :

    {{ Form::open(['class' => 'form-horizontal', 'files' => true]) }}

has('category_name')? 'has-error':'' }}">
        @lang('app.category_name')

            <input type="text" class="form-control" id="category_name" value="{{ old('category_name') }}" name="category_name" placeholder="@lang('app.category_name')"> {!! $errors->has('category_name')? '

'.$errors->first('category_name').'
':'' !!}

has('image')? 'has-error':'' }}">
        @lang('app.image')

            <input type="file" name="image" id="image" class="form-control"> {!! $errors->has('image')? '

'.$errors->first('image').'
':'' !!}

category controller :

public function category($category_name){  return view('content.category' , compact('post'));
    }
    public function index(){
        $title = trans('app.categories');
        $categories = Category::all();

            return view('admin.categories', compact('title', 'categories'));
        }

        public function store(Request $request)
        {
            $rules = [
                'category_name' => 'required',
                'image'         => 'image'
            ];
            $this->validate($request, $rules);

            $slug = str_slug($request->category_name);
            $duplicate = Category::where('category_slug', $slug)->count();
            if ($duplicate > 0){
                return back()->with('error', trans('app.category_exists_in_db'));
            }

            /**
             * Upload image if any
             */
            $image_name = '';
            if ($request->hasFile('image')){
                $upload_dir = public_path('uploads/images/');
                if ( ! file_exists($upload_dir)){
                    mkdir($upload_dir, 0777, true);
                }

                $image = $request->file('image');
                $file_base_name = str_replace('.'.$image->getClientOriginalExtension(), '', $image->getClientOriginalName());
                $resized = Image::make($image)->resize(300, 200);

                $image_name = strtolower(time().str_random(5).'-'.str_slug($file_base_name)).'.' . $image->getClientOriginalExtension();
                $imageFileName = $upload_dir.$image_name;

                try{
                    $resized->save($imageFileName);
                } catch (\Exception $e){
                    return $e->getMessage();
                }
            }

            $data = [
                'category_name' => $request->category_name,
                'category_slug' => $slug,
                'image' => $image_name,
            ];

            Category::create($data);
            return back()->with('success', trans('app.category_created'));
        }

category blade view :

    id, $cat->category_slug])}}">

    get_image_url() }}" />

    id, $cat->category_slug])}}">{{
    $cat->category_name }}

Body:
First you will have to add the select box to your form:

<div class="form-group {{ $errors->has('color')? 'has-error':'' }}">
    <label for="color" class="col-sm-4 control-label">@lang('app.color')</label>
    <div class="col-sm-8">
        <select name="color" id="color" class="form-control" onchange="setColor()">
            <option value="red">Red</option>
            <option value="green">Blue</option>
            <option value="blue">Blue</option>
        </select>
        {!! $errors->has('image')? '<p class="help-block">'.$errors->first('image').'</p>':'' !!}
    </div>
</div>

Then add some JavaScript to change the background color of the select box to the chosen color:

<script type="text/javascript">
function setColor() {
    document.getElementById("color").setAttribute("style", "background-color: " + document.getElementById("color").value);
}
</script>


问:
error: Object literal may only specify known properties in angular
I'm going crazy for this error:

```<code>Object literal may only specify known properties, and 'brand' does not exist in type 'BrandCB[]'.
</code>```

I don't know what's happen. How to solve this issue?
this is the code:
gallery.component.ts

```<code>import { CarsService } from '../services/cars.service';
import { Car } from './../models/car';
import { Component, OnInit } from '@angular/core';
import { BrandCB } from '../models/brandCB';

@Component({
  selector: 'app-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {

  cars:Car[];
  brands:BrandCB[];
  selectedBrand:string;
  observableCars;
  observableBrands;

  constructor(public carsService: CarsService) {

  }

  ngOnInit() {
    this.getCars('all');
    this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
      this.brands = {brand:data['brand'], checked:'false'}; //this is the error row
      console.table(data);
    });
  }

  onOptionsSelected(event: { target: { filter: any; }; }){
    this.getCars(this.selectedBrand)
  }

  getCars(filter){

    this.observableCars = this.carsService.getCars().subscribe(data => {

      if(filter!="all"){
        this.cars = data.filter( car => car.brand == this.selectedBrand);
      }else{
        this.cars = data;
      }

    });
  }

  a(event){
    let name = event.target.name;
    let checked = event.target.checked;

    if(name=='all'){
      if(checked==true){
        //uncheck tutti gli altri
      }
    } else {
      // filtra in base alle caselle checked
        // crea un array di checked items
    }

  }

  ngOnDestroy(){
    this.observableCars.unsubscribe();
    this.observableBrands.unsubscribe();
  }
}
</code>```

brandCB.ts

```<code>export class BrandCB {
    brand:any;
    checked:boolean;
}
</code>```

StackOverflow is telling me that my post is mostly code and i should write something else, so I m doing, bla bla bla and more bla bla bla. Have you seen the accident outside?

答:
I solved.</p>

```<code>this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
  for(let x=0;x<data.length;x++){
    this.brands.push(new BrandCB(data[x].brand, false));
  }
});
</code>```

Body:
I'm going crazy for this error:

Object literal may only specify known properties, and 'brand' does not exist in type 'BrandCB[]'.

I don't know what's happen. How to solve this issue?
this is the code:
gallery.component.ts

import { CarsService } from '../services/cars.service';
import { Car } from './../models/car';
import { Component, OnInit } from '@angular/core';
import { BrandCB } from '../models/brandCB';

@Component({
  selector: 'app-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {

  cars:Car[];
  brands:BrandCB[];
  selectedBrand:string;
  observableCars;
  observableBrands;

  constructor(public carsService: CarsService) {

  }

  ngOnInit() {
    this.getCars('all');
    this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
      this.brands = {brand:data['brand'], checked:'false'}; //this is the error row
      console.table(data);
    });
  }

  onOptionsSelected(event: { target: { filter: any; }; }){
    this.getCars(this.selectedBrand)
  }

  getCars(filter){

    this.observableCars = this.carsService.getCars().subscribe(data => {

      if(filter!="all"){
        this.cars = data.filter( car => car.brand == this.selectedBrand);
      }else{
        this.cars = data;
      }

    });
  }

  a(event){
    let name = event.target.name;
    let checked = event.target.checked;

    if(name=='all'){
      if(checked==true){
        //uncheck tutti gli altri
      }
    } else {
      // filtra in base alle caselle checked
        // crea un array di checked items
    }

  }

  ngOnDestroy(){
    this.observableCars.unsubscribe();
    this.observableBrands.unsubscribe();
  }
}

brandCB.ts

export class BrandCB {
    brand:any;
    checked:boolean;
}

StackOverflow is telling me that my post is mostly code and i should write something else, so I m doing, bla bla bla and more bla bla bla. Have you seen the accident outside?

Body:
I solved.

this.observableBrands = this.carsService.getBrands().subscribe( (data:any) => {
  for(let x=0;x<data.length;x++){
    this.brands.push(new BrandCB(data[x].brand, false));
  }
});


问:
How to debug Page Faults in the Linux Kernel
Currently I am faced to some ugly Kernel OOPS with reboot. I run a MPC5200 based custom design. I get OOPS Messages like this:

```<code>VM: Either in interrupt or mm = NULL. mm=0xc0196520 in interrupt: 1
VM: Access of bad area @0x6e615c75
Oops: kernel access of bad area, sig: 11
NIP: C00302E4 XER: 20000000 LR: C00F15D4 SP: C6207B30 REGS: c6207a80 TRAP: 0300    Not tainted
MSR: 00009032 EE: 1 PR: 0 FP: 0 ME: 1 IR/DR: 11
DAR: 6E615C75, DSISR: 20000000
TASK = c6206000[4778] 'SimpleServer2' Last syscall: 102
last math c6206000 last altivec 00000000
GPR00: 7C74696B C6207B30 C6206000 6E615C5D 00000000 00000000 C01BFE68 00000001
GPR08: F0000500 C7CD1600 FFFFFFE3 C7CD1600 00000001 10152540 10100000 10100000
GPR16: C01B0000 00000000 C6207E48 000016D0 00001032 06207BF0 00000000 C0005CC0
GPR24: C0006DCC C6207EA0 C01B0000 C0190000 C0190000 C01D0000 C56A2220 00000001
Call backtrace:
C0018034 C00F1608 C00F6738 C0017D08 C0006EFC C0005CC0 C6207EA0
C011040C C012FEC4 C00EDC7C C00EF078 C00EF518 C0005A7C 10089C18
1001DFAC 10015660 10000608 10003E68 1000804C 10085A0C 100BC020
Kernel panic: Aiee, killing interrupt handler!
In interrupt handler - not syncing
<0>Rebooting in 1 seconds..
</code>```

These OOPS traces occur during high network load.
The main problem I am faced to is that the do_page_fault function is called by the mmu exception mechanism and therefore the stack context within the gdb is not reliable. After debugging and adding printouts I figured out, that the CPU seems to be in a interrupt context. And therefore this error is not recoverable.

As far as I understand the OOPS trace the address which causes the oops is stored in the DAR Register:   DAR: 6E615C75.

How can I get information from this address? I've tried to disassemble the address in gdb but it is not mapped to any function.

If some one is wondering about the OOPS format, this is generated by an outdated Kernel 2.4.25 Kernel, but I think the Mechanism should be the same, as in Kernel 2.6.

答:
Note that the value in DAR looks suspiciously like a fragment of an ASCII string.  In fact, it looks like an offset of 24 from the value in GPR03, 0x6E615C5D == "na\]".

I suspect you have a string overflowing a struct pointer, and the faulting instruction is dereferencing a member of that structure that is at offset 24.

Body:
Currently I am faced to some ugly Kernel OOPS with reboot. I run a MPC5200 based custom design. I get OOPS Messages like this:

VM: Either in interrupt or mm = NULL. mm=0xc0196520 in interrupt: 1
VM: Access of bad area @0x6e615c75
Oops: kernel access of bad area, sig: 11
NIP: C00302E4 XER: 20000000 LR: C00F15D4 SP: C6207B30 REGS: c6207a80 TRAP: 0300    Not tainted
MSR: 00009032 EE: 1 PR: 0 FP: 0 ME: 1 IR/DR: 11
DAR: 6E615C75, DSISR: 20000000
TASK = c6206000[4778] 'SimpleServer2' Last syscall: 102
last math c6206000 last altivec 00000000
GPR00: 7C74696B C6207B30 C6206000 6E615C5D 00000000 00000000 C01BFE68 00000001
GPR08: F0000500 C7CD1600 FFFFFFE3 C7CD1600 00000001 10152540 10100000 10100000
GPR16: C01B0000 00000000 C6207E48 000016D0 00001032 06207BF0 00000000 C0005CC0
GPR24: C0006DCC C6207EA0 C01B0000 C0190000 C0190000 C01D0000 C56A2220 00000001
Call backtrace:
C0018034 C00F1608 C00F6738 C0017D08 C0006EFC C0005CC0 C6207EA0
C011040C C012FEC4 C00EDC7C C00EF078 C00EF518 C0005A7C 10089C18
1001DFAC 10015660 10000608 10003E68 1000804C 10085A0C 100BC020
Kernel panic: Aiee, killing interrupt handler!
In interrupt handler - not syncing
<0>Rebooting in 1 seconds..

These OOPS traces occur during high network load.
The main problem I am faced to is that the do_page_fault function is called by the mmu exception mechanism and therefore the stack context within the gdb is not reliable. After debugging and adding printouts I figured out, that the CPU seems to be in a interrupt context. And therefore this error is not recoverable.

As far as I understand the OOPS trace the address which causes the oops is stored in the DAR Register:   DAR: 6E615C75.

How can I get information from this address? I've tried to disassemble the address in gdb but it is not mapped to any function.

If some one is wondering about the OOPS format, this is generated by an outdated Kernel 2.4.25 Kernel, but I think the Mechanism should be the same, as in Kernel 2.6.


问:
Line break and inject span with javascript
I need help. I'm trying to achieve this effect with the headings of a site.

I tried by using background color and padding, but when the text grows in two or more lines it makes a big rectangle. I'm trying to figure out a way to break lines automatically into spans using javascript.

can anyone help me, please?

thanks a lot!

答:
Try this:

.padded-multiline {
  line-height: 1.4;
  padding: 2px 0;
  width: 400px;
  margin: 20px auto;
}

.padded-multiline span {
  background-color: #c0c;
  color: #fff;
  display: inline;
  padding: 0.45rem;
  line-height: 60px;
  /* Needs prefixing */
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="padded-multiline">
  <span>How do I add padding to subsequent lines of an inline text element?</span>
</h1></code>```

Body:
Try this:

.padded-multiline {
  line-height: 1.4;
  padding: 2px 0;
  width: 400px;
  margin: 20px auto;
}

.padded-multiline span {
  background-color: #c0c;
  color: #fff;
  display: inline;
  padding: 0.45rem;
  line-height: 60px;
  /* Needs prefixing */
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

<h1 class="padded-multiline">
  <span>How do I add padding to subsequent lines of an inline text element?</span>
</h1>


问:
As ViewModelProviders.of() is deprecated, how should I create object of ViewModel?
I have been trying to create an Object of ViewModel in an Activity but ViewModelProviders is deprecated So what's the alternative to create the ViewModel's object.</p>

答:
This Gradle upgrade created the problem for me.

FROM

```<code>implementation 'androidx.core:core:1.1.0'
</code>```

TO

```<code>implementation 'androidx.core:core:1.2.0'
</code>```

IN MAIN ACTIVITY Java/Kotlin Files

This import statement

```<code>import androidx.lifecycle.ViewModelProviders
</code>```

had to be changed to

```<code>import androidx.lifecycle.ViewModelProvider
</code>```

This KOTLIN viewModel statement

```<code>viewModel = ViewModelProviders.of(this).get(MainActivityViewModel::class.java)
</code>```

had to be changed to

```<code>viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
</code>```

and in JAVA

This line of JAVA code

```<code>mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
</code>```

had to be changed to

```<code>mViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
</code>```

and then it all worked for me.

Based on:
An outline of the steps that created the problem for me

Body:
This Gradle upgrade created the problem for me.

FROM

implementation 'androidx.core:core:1.1.0'

TO

implementation 'androidx.core:core:1.2.0'

IN MAIN ACTIVITY Java/Kotlin Files

This import statement

import androidx.lifecycle.ViewModelProviders

had to be changed to

import androidx.lifecycle.ViewModelProvider

This KOTLIN viewModel statement

viewModel = ViewModelProviders.of(this).get(MainActivityViewModel::class.java)

had to be changed to

viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)

and in JAVA

This line of JAVA code

mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

had to be changed to

mViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);

and then it all worked for me.

Based on:
An outline of the steps that created the problem for me


问:
Can't download deployed sources with OWNER account
I have an app deployed to google cloud platform. I downloaded google cloud cli and logged in with gcloud auth login.

Then I tried to download project with the

```<code>C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\appcfg.py -A hello-world download_app hello-world
</code>```

but it ended up with error

```<code>08:27 PM Host: appengine.google.com
08:27 PM Fetching file list...
Error 403: --- begin server output ---
You do not have permission to modify this app
</code>```

I also checked the permissions in the "Over granted permissions" sidebar , but I do not know what to look for..

I do not have the original source code of java app, I want to download compiled classes to decompile it. I tried it with other test account and there was no problem with download. Maybe because I deployed the app and then downloaded it?

答:
Currently, you will not be able to download your code using this method.

In the past it was possible to do it with the method you are using as per referenced in this documentation, however, this is now deprecated and this function is no longer available.

What you could do, if you deployed recently, is to check your project's buckets, since during the deploy, everything is stored in a temporary bucket. Note that this is recycled constantly, so you code might already have been deleted from this bucket. Here is a community post related to the temporary buckets that the code is stores on, that might be of some help.

Body:
I have an app deployed to google cloud platform. I downloaded google cloud cli and logged in with gcloud auth login.

Then I tried to download project with the

C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\appcfg.py -A hello-world download_app hello-world

but it ended up with error

08:27 PM Host: appengine.google.com
08:27 PM Fetching file list...
Error 403: --- begin server output ---
You do not have permission to modify this app

I also checked the permissions in the "Over granted permissions" sidebar , but I do not know what to look for..

I do not have the original source code of java app, I want to download compiled classes to decompile it. I tried it with other test account and there was no problem with download. Maybe because I deployed the app and then downloaded it?


问:
How to delete a XML child node using SQL Server 2016
I have the following Xml example snippet taken from a larger file:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>
</code>```

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>
</code>```

I have used the following to SQL query the XML and isolate the above snippet(first one)

```<code>select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0
</code>```

I have tried

```<code>SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')
</code>```

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers

答:
In the XML snippet you have provided, you have a different root. So, in order for your delete to work, all you need is to adjust the path:

```<code>SET @XMLData.modify('delete /EntityAttributeValue/ProductTypeId');
</code>```

Body:
I have the following Xml example snippet taken from a larger file:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>

I have used the following to SQL query the XML and isolate the above snippet(first one)

select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0

I have tried

SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers

Body:
In the XML snippet you have provided, you have a different root. So, in order for your delete to work, all you need is to adjust the path:

SET @XMLData.modify('delete /EntityAttributeValue/ProductTypeId');


问:
Palindrome index in HackerRank
I am solving a palindrome index problem from HackerRank as explained below.

Some heads-up will go along way. Thank you!

Here is my code:

```<code># Complete the palindromeIndex function below.
def palindromeIndex(s)
  # slen = s.length
  splt = s.split('')

  n = s.reverse
  nsplt = n.split('')

  if n == s
    return -1
  elsif n != s
    splt.each do |p|
      if nsplt[p] != splt[p]
        return p
      end
    end
  else
    return -1
  end
end
</code>```

In the first line, I am first splitting the given string and its respective reverse form. Then I am trying to compare the original string with the reversed string. if they are equal my program should return -1. If not I should loop through the initially split strings and check the indices for any indifference and return the position of the character different from the main string.

So far I am not sure I am having me right but I am also getting an error in my first attempt.

```<code>solution.rb:18:in `block in palindromeIndex': no implicit conversion of String into Integer (TypeError)
from solution.rb:17:in `each'
from solution.rb:17:in `palindromeIndex'
from solution.rb:34:in `block in <main>'
from solution.rb:31:in `times'
from solution.rb:31:in `<main>'
</code>```

What could I be getting wrong here?

答:
```<code>splt.each do |p|
</code>```

The above returns each of the characters in s, not the positions of the characters.  This is why you're getting the error... for "abba" you're doing splt['a'] not splt[0]

If you want the position you can do each_with_index

```<code>splt.each_with_index do |_, p|
</code>```

Since you don't need the character itself, we've assigned underscore _ to it in the iteration.

Alternatively, you can use a range of integers

```<code>(0...splt.length).each do |p|
</code>```

Note the use of THREE dots in the range, which means from zero up to one less than the length since a string of five characters will only have indicies from 0 to 4.

Or you can simply do the loop for the number of times there are characters...

```<code>splt.length.times do |p|
</code>```

Title: Palindrome index in HackerRank

Body:
I am solving a palindrome index problem from HackerRank as explained below.

Some heads-up will go along way. Thank you!

Here is my code:

# Complete the palindromeIndex function below.
def palindromeIndex(s)
  # slen = s.length
  splt = s.split('')

  n = s.reverse
  nsplt = n.split('')

  if n == s
    return -1
  elsif n != s
    splt.each do |p|
      if nsplt[p] != splt[p]
        return p
      end
    end
  else
    return -1
  end
end

In the first line, I am first splitting the given string and its respective reverse form. Then I am trying to compare the original string with the reversed string. if they are equal my program should return -1. If not I should loop through the initially split strings and check the indices for any indifference and return the position of the character different from the main string.

So far I am not sure I am having me right but I am also getting an error in my first attempt.

solution.rb:18:in `block in palindromeIndex': no implicit conversion of String into Integer (TypeError)
from solution.rb:17:in `each'
from solution.rb:17:in `palindromeIndex'
from solution.rb:34:in `block in '
from solution.rb:31:in `times'
from solution.rb:31:in `'

What could I be getting wrong here?

Body:
splt.each do |p|

The above returns each of the characters in s, not the positions of the characters.  This is why you're getting the error... for "abba" you're doing splt['a'] not splt[0]

If you want the position you can do each_with_index

splt.each_with_index do |_, p|

Since you don't need the character itself, we've assigned underscore _ to it in the iteration.

Alternatively, you can use a range of integers

(0...splt.length).each do |p|

Note the use of THREE dots in the range, which means from zero up to one less than the length since a string of five characters will only have indicies from 0 to 4.

Or you can simply do the loop for the number of times there are characters...

splt.length.times do |p|


问:
How to use .blend file in iphone project?
I dont want to use any 3D engine like SIO2 etc engines in my project. But I still want to use .blender 3d files in my normal projects.

Can anyone please guide me how I can proceed with that.

Thanks

答:
Export your blend file to another format.

http://wiki.blender.org/index.php/Extensions:2.5/Py/Scripts#Import-Export_Scripts

Which you choose depends upon how you will render your objects.  Check out the "raw" exporter, since you are rolling your own renderer.


问:
PrivateRoute component for authentification
i am developping a Reactjs-nodejs application. I would like to make a JWT authentification. when we log in, i give a unique token to the user. Then, thanks to this token, if it is valid, i allow the user to navigate through my router. my private route component is like :
PrivateRoute

My function getId is like that:

async function getId(){
  let res = await axios('_/api/users/me',{config}).catch(err => { console.log(err)});

return res+1;
}

Finally the config component is the token stored in the localStorage :

const config = {
  headers: { Authorization: ${window.localStorage.getItem("token")} }
};

GetId() returns the id of the user if logged in, else it is null.

The problem now is that my privateRoute always redirect to "/" path. I think it is because of the axios(promise) that gives me the userId too late. please tell me if you understand well and if you have a solution.
Thanks you

答:
You can create private-route like this .

```<code>const PrivateRoute = ({ component: Component, ...props }) => {
  return (
    <Route
      {...props}
      render={innerProps =>
        localStorage.getItem("Token") ? (
          <Component {...innerProps} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
};
</code>```

then you can use

```<code><PrivateRoute path="/" component={FIlname} />
</code>```

Body:
You can create private-route like this .

const PrivateRoute = ({ component: Component, ...props }) => {
  return (
    <Route
      {...props}
      render={innerProps =>
        localStorage.getItem("Token") ? (
          <Component {...innerProps} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
};

then you can use

<PrivateRoute path="/" component={FIlname} />


问:
Husky not getting triggered on git events
I have created a react app which implements husky to capture lint errors:

Environment

git version 2.21.0 (Apple Git-122), node v8.16.2, npm v6.4.1

Lint implementation

Created a react using npx create-react-app my-app-name

Implemented eslint using eslint --init

Added the script to the package.json file:

“scripts”: {“lint”: “eslint src/**/*.js”,}

On running eslint src/**/*.js or npm run lint the lint errors are captured perfectly

Husky implementation

Installed husky npm install husky --save-dev

Added the husky hook to package.json:

"husky": {
    "hooks": {
      "pre-commit": "npm run lint:fix",
      "pre-push": "npm run lint"
    }
  }

Testing git commits

Ran git commit -m "test commit"

Problem

The lint is never called when the commit is triggered. What is wrong here? Btw, I have tried solutions proposed here.

答:
husky requires node > v10. Otherwise, it will skip with a warning message in the console.

Your node version is v8.16.2, please upgrade the same.


问:
How to make mat-icon disabled in angular?
Here i have multiple mat-icons, delete named mat-icon i want to make disabled i use disabled properties on this but it gives error like(Can't bind to 'disabled' since it isn't a known property of 'mat-icon') so how to show particular mat-icon disabled in angular 6?</p>

```<code><mat-icon color="warn" style="cursor: pointer;" [disabled]="payloadArray.enabled != 'true' ">delete</mat-icon>
<mat-icon color="warn" style="cursor: pointer;">person_add</mat-icon>
</code>```

答:
it's all post but what about two mat-icon?</p>

```<code><mat-icon *ngIf="payloadArray.enabled == 'true'"
  color="warn" style="cursor: pointer;">
    delete
</mat-icon>
<mat-icon *ngIf="payloadArray.enabled != 'true'"
  "color="warn" style="opacity:.5">
    delete
</mat-icon>
</code>```

Body:
Here i have multiple mat-icons, delete named mat-icon i want to make disabled i use disabled properties on this but it gives error like(Can't bind to 'disabled' since it isn't a known property of 'mat-icon') so how to show particular mat-icon disabled in angular 6?

<mat-icon color="warn" style="cursor: pointer;" [disabled]="payloadArray.enabled != 'true' ">delete</mat-icon>
<mat-icon color="warn" style="cursor: pointer;">person_add</mat-icon>

Body:
it's all post but what about two mat-icon?

<mat-icon *ngIf="payloadArray.enabled == 'true'"
  color="warn" style="cursor: pointer;">
    delete
</mat-icon>
<mat-icon *ngIf="payloadArray.enabled != 'true'"
  "color="warn" style="opacity:.5">
    delete
</mat-icon>


问:
Unable to download remote image with PHP CURL
Edit: I contact the support at scrapestack and confirmed that their api doesn't support image files.

I am trying to download a remote image using CURL with php. Below is my code. But whenever I try to open the downloaded image, I always get:

```<code>Cannot read this file. This is not a valid bitmap file, or its format is not currently supported.
</code>```

Anyone know what is wrong with my code? Thank you.

```<code>$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
$imageName = pathinfo( $image, PATHINFO_BASENAME );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
$source = curl_exec( $ch );
$info = curl_getinfo($ch);
curl_close( $ch );
file_put_contents( $imageName, $source );
</code>```

I am not able to open the file, when I tried to open it with sublime, it is stuck at Loading Image. When I open it with notepad, I got the following that looks like PNG image, but it is not a valid image. File starts with
    �PNG

```<code>IHDR       �   q�I�    IDATx�k�]�u�o��(��_�M��m�8:���_r�G
</code>```

You can see the file here: https://gofile.io/?c=cfsYf2

Looks like the problem is making the curl request through Scrapestack, because if I point the curl to image url directly, the image is downloaded correctly, like below:

```<code>$image ="https://i.imgur.com/Cbiu8Ef.png";
</code>```

答:
Edit: I played around with scrapestack a bit more today, it doesn't seem to support image scraping. It is best if you can reach out to their customer support and find out.

@Towsif is right, you are trying to get the page, not the actual image. I put something together really quick, try and see if this works for you.

```<code>$queryString = http_build_query([
  'access_key' => 'replace this with your own token',
  'url' => 'https://i.imgur.com/Cbiu8Ef.png',
]);

$ch = curl_init(sprintf('%s?%s', 'http://api.scrapestack.com/scrape', $queryString));
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$image_source = curl_exec( $ch );
curl_close( $ch );
file_put_contents( 'Cbiu8Ef.png' , $image_source );
</code>```

Body:
Edit: I contact the support at scrapestack and confirmed that their api doesn't support image files.

I am trying to download a remote image using CURL with php. Below is my code. But whenever I try to open the downloaded image, I always get:

Cannot read this file. This is not a valid bitmap file, or its format is not currently supported.

Anyone know what is wrong with my code? Thank you.

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
$imageName = pathinfo( $image, PATHINFO_BASENAME );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
$source = curl_exec( $ch );
$info = curl_getinfo($ch);
curl_close( $ch );
file_put_contents( $imageName, $source );

I am not able to open the file, when I tried to open it with sublime, it is stuck at Loading Image. When I open it with notepad, I got the following that looks like PNG image, but it is not a valid image. File starts with
    �PNG

IHDR       �   q�I�    IDATx�k�]�u�o��(��_�M��m�8:���_r�G

You can see the file here: https://gofile.io/?c=cfsYf2

Looks like the problem is making the curl request through Scrapestack, because if I point the curl to image url directly, the image is downloaded correctly, like below:

$image ="https://i.imgur.com/Cbiu8Ef.png";

Body:
Edit: I played around with scrapestack a bit more today, it doesn't seem to support image scraping. It is best if you can reach out to their customer support and find out.

@Towsif is right, you are trying to get the page, not the actual image. I put something together really quick, try and see if this works for you.

$queryString = http_build_query([
  'access_key' => 'replace this with your own token',
  'url' => 'https://i.imgur.com/Cbiu8Ef.png',
]);

$ch = curl_init(sprintf('%s?%s', 'http://api.scrapestack.com/scrape', $queryString));
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$image_source = curl_exec( $ch );
curl_close( $ch );
file_put_contents( 'Cbiu8Ef.png' , $image_source );


答:
if you are using redux, you can make the following:

in reduer:

```<code>case LOGIN_ADMIN_SUCCESS:
            localStorage.setItem("token", action.payload.token);
            return {
                ...state,
                user: action.payload,
                isSignedIn: true,
                loadingSignIn: false,
                token: action.payload.token,
            };
</code>```

then in your private router you have to check these values, like

```<code>const PrivateRoute = ({ component: Component, admin, ...rest }) => (
    <Route
        {...rest}
        render={(props) => {
            if (admin.loadingSignIn) {
                return <h3>Loading...</h3>;
            } else if (!admin.isSignedIn) {
                return <Redirect to="/login" />;
            } else {
                return <Component {...props} />;
            }
        }}
    />
);
</code>```

Title: PrivateRoute component for authentification

Body:
i am developping a Reactjs-nodejs application. I would like to make a JWT authentification. when we log in, i give a unique token to the user. Then, thanks to this token, if it is valid, i allow the user to navigate through my router. my private route component is like :
PrivateRoute

My function getId is like that:

async function getId(){
  let res = await axios('_/api/users/me',{config}).catch(err => { console.log(err)});

return res+1;
}

Finally the config component is the token stored in the localStorage :

const config = {
  headers: { Authorization: ${window.localStorage.getItem("token")} }
};

GetId() returns the id of the user if logged in, else it is null.

The problem now is that my privateRoute always redirect to "/" path. I think it is because of the axios(promise) that gives me the userId too late. please tell me if you understand well and if you have a solution.
Thanks you

Body:
if you are using redux, you can make the following:

in reduer:

case LOGIN_ADMIN_SUCCESS:
            localStorage.setItem("token", action.payload.token);
            return {
                ...state,
                user: action.payload,
                isSignedIn: true,
                loadingSignIn: false,
                token: action.payload.token,
            };

then in your private router you have to check these values, like

const PrivateRoute = ({ component: Component, admin, ...rest }) => (
    <Route
        {...rest}
        render={(props) => {
            if (admin.loadingSignIn) {
                return <h3>Loading...</h3>;
            } else if (!admin.isSignedIn) {
                return <Redirect to="/login" />;
            } else {
                return <Component {...props} />;
            }
        }}
    />
);


问:
HR SCHEMA ORACLE
HR SCHEMA ORACLE

Create Function “GET_EMPLOYEE_SUMMARY” that receives an Employee ID and that returns, through an output parameter, a data structure with the following information:
 - Employee ID
 - First Name
 - Last Name
 - Manager Name
 - Department Name

So, the manager_name is baseade on employee_id..

Query:

```<code>select

      e.first_name as first_name,
      e.last_name,
      e.employee_id,
      e.manager_id as Name,
      d.department_name

      from employees e
      Cross join departments d
</code>```

but i have some mistakes... idk

答:
You just need to do a self join with the EMPLOYEE table again and join with the DEPARTMENT table should be inner join.

Something like following is needed:

```<code>SELECT
    E.FIRST_NAME   AS FIRST_NAME,
    E.LAST_NAME,
    E.EMPLOYEE_ID,
    M.FIRST_NAME || M.LAST_NAME   AS MANAGER_NAME, -- Change it according to your requirement
    D.DEPARTMENT_NAME
FROM
    EMPLOYEES E
    JOIN EMPLOYEES M ON E.MANAGER_ID = M.EMPLOYEE_ID
    JOIN DEPARTMENTS D ON D.DEPARTMENT_ID = E.DEPARTMENT_ID
WHERE
    E.EMPLOYEE_ID = 100;
</code>```

Cheers!!

Title: HR SCHEMA ORACLE

Body:
HR SCHEMA ORACLE

Create Function “GET_EMPLOYEE_SUMMARY” that receives an Employee ID and that returns, through an output parameter, a data structure with the following information:
 - Employee ID
 - First Name
 - Last Name
 - Manager Name
 - Department Name

So, the manager_name is baseade on employee_id..

Query:

select

      e.first_name as first_name,
      e.last_name,
      e.employee_id,
      e.manager_id as Name,
      d.department_name

      from employees e
      Cross join departments d

but i have some mistakes... idk

Body:
You just need to do a self join with the EMPLOYEE table again and join with the DEPARTMENT table should be inner join.

Something like following is needed:

SELECT
    E.FIRST_NAME   AS FIRST_NAME,
    E.LAST_NAME,
    E.EMPLOYEE_ID,
    M.FIRST_NAME || M.LAST_NAME   AS MANAGER_NAME, -- Change it according to your requirement
    D.DEPARTMENT_NAME
FROM
    EMPLOYEES E
    JOIN EMPLOYEES M ON E.MANAGER_ID = M.EMPLOYEE_ID
    JOIN DEPARTMENTS D ON D.DEPARTMENT_ID = E.DEPARTMENT_ID
WHERE
    E.EMPLOYEE_ID = 100;

Cheers!!


问:
Undefined variable in view page laravel
Im getting error in laravel undefined variable all is good but won't know why its coming...
controller

view
 error

```<code>public function login(Request $req)
    {

        $user = users::where([

            ["email", "=", $req->email],
            ["password", "=", $req->password]

        ])->first();

        if (isset($user)) {

            $req->session()->put("log", $req->input());

            return redirect("/userlist");
        } else {
            $b="user not found";

            return view("login", compact("b"));
        }
</code>```

答:
make sure pass varibale to the view from your controller

example

```<code><?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}
</code>```

please see laravel controllers documnet

Title: Undefined variable in view page laravel

Body:
Im getting error in laravel undefined variable all is good but won't know why its coming...
controller

view
 error

public function login(Request $req)
    {

        $user = users::where([

            ["email", "=", $req->email],
            ["password", "=", $req->password]

        ])->first();

        if (isset($user)) {

            $req->session()->put("log", $req->input());

            return redirect("/userlist");
        } else {
            $b="user not found";

            return view("login", compact("b"));
        }

Body:
make sure pass varibale to the view from your controller

example

<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

please see laravel controllers documnet


问:
Blank layout appears before background. Using confirm()
My problem is that whenever my confirm() appears, the alert box appears without problem but then the background goes all blank, I tried a lot of different things, like putting the whole if statement at the bottom of the page, at the bottom of the body. But nothing has worked so far. Here is my code. I use a combination of php and JS. Btw this is a school project.
Here is a screen shoot of how it looks:

```<code><?php
// hier start ik de sessie
session_start();
// met deze maak ik db conectie
include_once("database_conn.php");

if (isset($_POST['kopen'])) {
  // hier check ik eerst als de sessie gezet is, als het zo is dan de gebruiker zou wel kunnen kopen
  if ($_SESSION) {
    $id = $_POST['menu'];
    $Userid = $_SESSION['user_id'];
    $Username = $_SESSION['username'];
    $db_conn->query("INSERT INTO `menulijst`(`user_id`, `menu_id`, `username`) VALUES ('$Userid', '$id', '$Username')")
      or die($db_conn->error);
  } else { ?>
    <!--  maar als de sessie niet gezet is dan de klant zou een melding ktijgen
   en er zou verteld worden dat ie eerst ingelogd moet zijn om iets te kunnen kopen. Daarvoor heb ik JS voor gebruikt -->
    <script type="text/javascript">
      var txt;
      if (confirm("Je moet eerst ingelogd zijn om iets te kunnen kopen! Druk op Ok om naar de inlog pagina te gaan!")) {
        txt = location.replace("login/pdo_login.php");
      } else {
        txt = "";
      }
    </script>
<?php }
} ?>

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Excellent Taste Menu</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <script src="https://code.iconify.design/1/1.0.3/iconify.min.js"></script>
  <link rel="stylesheet" type="text/css" href="style/style.css">
</head>

<body>
  <nav class="navbar navbar-inverse">
    <div class="container-fluid">
      <div class="navbar-header">
        <a class="navbar-brand" href="index.php">Excellent Taste</a>
      </div>
      <ul class="nav navbar-nav">
        <li><a href="index.php">Home</a></li>
        <li><a href="tafels.php">Tafels</a></li>
        <li class="active"><a href="menu.php">Menu</a></li>
        <li class="display-1"><a href="contact.php">Contact</a></li>
        <?php
        // hier doe ik twee checks eentje is of de sessie gezet is
        // als sessie een admin is, hij krijgt toegaan tot de admin panel
        if ($_SESSION) {
          if ($_SESSION['user_type'] == 'admin') { ?>
            <li><a href="admin/index.php">Admin Panel</a></li>
        <?php }
        } ?>
      </ul>
      <form class="navbar-form navbar-left" action="/action_page.php">
        <div class="form-group">
        </div>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <?php
        // hier check ik als de sessie gezet is, en als het gezet is dan krijg de buttons Winkelmand en log uit te zien
        if (isset($_SESSION['username'])) {
        ?>
          <li><a href="basket/"><span class="iconify" data-icon="fa-shopping-basket" data-inline="false"></span> Winkelmand</a></li>
          <li><a href="login/logout.php"><span class="glyphicon glyphicon-log-out"></span> Log uit</a></li>
        <?php
        } else {
          // anders krijg je log in button of registreren
        ?>
          <li><a href="login/pdo_login.php"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
          <li><a href="login/registreren.php"><span class="glyphicon glyphicon-user"></span> Registreren</a></li>
        <?php
        }
        ?>
      </ul>
    </div>
  </nav>
  <div class="container">
    <h2 class="align-content-center">Menu</h2>
    <!-- Hier maak ik gebruik van JQuery zodat de klant door de verschillende type gerechten en / of dranken kan sorteren -->
    <!-- Als de gebruiker de select bar heeft gebruikt de informatie wordt versturd naar de pagina fetch.php  -->
    <script src="jquery.js"></script>
    <script>
      $(document).ready(function() {
        $("#fetchval").on('change', function() {
          var keyword = $(this).val();
          $.ajax({
            url: 'fetch.php',
            type: 'POST',
            data: 'request=' + keyword,

            beforeSend: function() {
              $("#table-container").fadeOut(10);
            },
            success: function(data) {
              $("#table-container").html(data).fadeIn(3000);
            },
          });
        });
      });
    </script>
    <div style="display: inline-block">Sorteren op type gerecht en/of drank :</div>
    <!-- Deze is de select bar alles wat hier gekozen is gaat naar de functie van boven en wordt naar andere pagina verstuurd -->
    <select id="fetchval" name="fetchby" style="display: inline-block">
      <option value="">---Kies---</option>
      <option value="1">Koude eten</option>
      <option value="2">Warme eten</option>
      <option value="3">Drank</option>
    </select>
    <button onclick='window.location.reload();'>Hele menu</button>
    <br>
    <div id="table-container">
      <table class="table">
        <thead>
          <tr>
            <th></th>
            <th width="200">Gerecht Naam</th>
            <th>Parijs</th>
            <th>Omschrijving</th>
            <th></th>
          </tr>
        </thead>
        <?php
        // hier maak ik gebruik van sql statment om alles te selecteren van het tabel `menu`
        $sql = "SELECT * FROM `menu`";
        $statement = $db_conn->prepare($sql);
        $statement->execute();
        $menu = $statement->fetchAll(PDO::FETCH_ASSOC);
        // bij deze loop ik er om heen om alles op de scherm te tonen
        foreach ($menu as $row) : ?>
          <tr>
            <td>
              <img src="eten/<?php echo $row['gerecht_afbeelding']; ?>" class="card-img-top" style="width: 100px;">
            </td>
            <td>
              <?php echo $row['gerecht_naam']; ?>
            </td>
            <td>
              €<?php echo $row['gerecht_prijs']; ?>
            </td>
            <td style="word-break: break-all;">
              <?php echo $row['gerecht_omschrijving']; ?>
            </td>
            <td>
              <div style="display:flex">
                <?php
                // er wordt een check gedaan voor de sessie en als de sessie admin of mdw is dan krijgt ie de volgende buttons te zien (Edit en Verwijderen)
                if ($_SESSION) {
                  if ($_SESSION['user_type'] == 'admin' || $_SESSION['user_type'] == 'mdw') { ?>
                    <a href="CRUDmenu/edit.php?id=<?= $row['menu_id'] ?>" class="buttonSpace btn btn-info">Edit
                    </a>
                    <a href="CRUDmenu/proces.php?verwijder=<?php echo $row['menu_id']; ?>" class="buttonSpace btn btn-danger">Verwijderen
                    </a>
                <?php }
                } ?>
                <!-- Met deze button kunnen de klanten de product kopen -->
                <form method="post">
                  <input type="hidden" name="menu" value='<?php echo $row["menu_id"] ?>'>
                  <input type="submit" class="glyphicon glyphicon-shopping-cart button button4" name="kopen" value="Kopen">

                </form>
              </div>

            </td>

          </tr>
        <?php endforeach; ?>
      </table>

    </div>
    <?php
    // er wordt een check gedaan voor de sessie en als de sessie admin of mdw is dan krijgt ie de volgende button te zien (Toevoege)
    if ($_SESSION) {
      if ($_SESSION['user_type'] == 'admin' || $_SESSION['user_type'] == 'mdw') { ?>
        <a type=" button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" style="margin-bottom: 20px">
          Voeg een nieuwe gerecht toe
        </a>
    <?php }
    } ?>
  </div>
  <!-- Deze is een modal (van bootstrap), daarin zijn alle input fields -->
  <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title" id="exampleModalLabel">Toevoegen</h3>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="container">
            <div>
              <!-- Deze form is verbonden an de bestand proces.php zodat de informatie dat je hier vult direct naar de database gaat -->
              <form action="CRUDmenu/proces.php" method="post" class="col-xs-3">
                <label>Gerecht Naam</label>
                <input type="text" name="gerecht_naam" class="form-control" required />
                <br />
                <label>Gerecht Prijs</label>
                <input type="number" name="gerecht_prijs" class="form-control" required />
                <br />
                <label>Omschrijving</label>
                <input type="text" name="omschrijving" class="form-control" required />
                <br />
                <label>Type eten</label>
                <select name="type_eten" required>
                  <option>-Selecteer-</option>
                  <option value="1">Koude eten</option>
                  <option value="2">Warme eten</option>
                  <option value="3">Drank</option>
                </select>
                <br />
                <label>Afbeelding</label>
                <input type="file" name="afbeelding" class="form-control" required />
                <br />
                <input type="submit" name="toevoegen" class="btn btn-info" value="Save" />
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
</body>

</html>
</code>```

答:
i solved it by doing this. </p>

```<code>  if (isset($_POST['kopen'])) {
    // hier check ik eerst als de sessie gezet is, als het zo is dan de gebruiker zou wel kunnen kopen
    if ($_SESSION) {
      $id = $_POST['menu'];
      $Userid = $_SESSION['user_id'];
      $Username = $_SESSION['username'];
      $db_conn->query("INSERT INTO `menulijst`(`user_id`, `menu_id`, `username`) VALUES ('$Userid', '$id', '$Username')"); ?>
      <div class="alert2">
        <span class="closebtn2" onclick="this.parentElement.style.display='none';">×</span>
        <strong>Succes!</strong> Toegevoegd aan winkelmand.
      </div>
    <?php
    } else { ?>
      <!--  maar als de sessie niet gezet is dan de klant zou een melding ktijgen
   en er zou verteld worden dat ie eerst ingelogd moet zijn om iets te kunnen kopen. -->
      <div class="alert">
        <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
        <strong>Danger!</strong> Om een prodcut te kunnen kopen moet je eerst ingelogd zijn.
        <a style="color: black" href="login/pdo_login.php"><span class="glyphicon glyphicon-log-in"></span> Login</a>
      </div>
  <?php }
  } ?>```

And putting it in the body
</code>```

Body:
My problem is that whenever my confirm() appears, the alert box appears without problem but then the background goes all blank, I tried a lot of different things, like putting the whole if statement at the bottom of the page, at the bottom of the body. But nothing has worked so far. Here is my code. I use a combination of php and JS. Btw this is a school project.
Here is a screen shoot of how it looks:

<?php
// hier start ik de sessie
session_start();
// met deze maak ik db conectie
include_once("database_conn.php");

if (isset($_POST['kopen'])) {
  // hier check ik eerst als de sessie gezet is, als het zo is dan de gebruiker zou wel kunnen kopen
  if ($_SESSION) {
    $id = $_POST['menu'];
    $Userid = $_SESSION['user_id'];
    $Username = $_SESSION['username'];
    $db_conn->query("INSERT INTO `menulijst`(`user_id`, `menu_id`, `username`) VALUES ('$Userid', '$id', '$Username')")
      or die($db_conn->error);
  } else { ?>

<?php }
} ?>

<!DOCTYPE html>

  <title>Excellent Taste Menu</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <link rel="stylesheet" type="text/css" href="style/style.css">

        Excellent Taste

Home

Tafels

Menu

Contact

        <?php
        // hier doe ik twee checks eentje is of de sessie gezet is
        // als sessie een admin is, hij krijgt toegaan tot de admin panel
        if ($_SESSION) {
          if ($_SESSION['user_type'] == 'admin') { ?>

Admin Panel

        <?php }
        } ?>

      <form class="navbar-form navbar-left" action="/action_page.php">

      </form>

        <?php
        // hier check ik als de sessie gezet is, en als het gezet is dan krijg de buttons Winkelmand en log uit te zien
        if (isset($_SESSION['username'])) {
        ?>

 Winkelmand

 Log uit

        <?php
        } else {
          // anders krijg je log in button of registreren
        ?>

 Login

 Registreren

        <?php
        }
        ?>

Menu

Sorteren op type gerecht en/of drank :

    <select id="fetchval" name="fetchby" style="display: inline-block">
      <option value="">---Kies---</option>
      <option value="1">Koude eten</option>
      <option value="2">Warme eten</option>
      <option value="3">Drank</option>
    </select>
    <button onclick='window.location.reload();'>Hele menu</button>

            Gerecht Naam
            Parijs
            Omschrijving

        <?php
        // hier maak ik gebruik van sql statment om alles te selecteren van het tabel `menu`
        $sql = "SELECT * FROM `menu`";
        $statement = $db_conn->prepare($sql);
        $statement->execute();
        $menu = $statement->fetchAll(PDO::FETCH_ASSOC);
        // bij deze loop ik er om heen om alles op de scherm te tonen
        foreach ($menu as $row) : ?>

              <img src="eten/<?php echo $row['gerecht_afbeelding']; ?>" class="card-img-top" style="width: 100px;">

              <?php echo $row['gerecht_naam']; ?>

              €<?php echo $row['gerecht_prijs']; ?>

              <?php echo $row['gerecht_omschrijving']; ?>

                <?php
                // er wordt een check gedaan voor de sessie en als de sessie admin of mdw is dan krijgt ie de volgende buttons te zien (Edit en Verwijderen)
                if ($_SESSION) {
                  if ($_SESSION['user_type'] == 'admin' || $_SESSION['user_type'] == 'mdw') { ?>
                    <a href="CRUDmenu/edit.php?id=<?= $row['menu_id'] ?>" class="buttonSpace btn btn-info">Edit

                    <a href="CRUDmenu/proces.php?verwijder=<?php echo $row['menu_id']; ?>" class="buttonSpace btn btn-danger">Verwijderen

                <?php }
                } ?>

                <form method="post">
                  <input type="hidden" name="menu" value='<?php echo $row["menu_id"] ?>'>
                  <input type="submit" class="glyphicon glyphicon-shopping-cart button button4" name="kopen" value="Kopen">

                </form>

        <?php endforeach; ?>

    <?php
    // er wordt een check gedaan voor de sessie en als de sessie admin of mdw is dan krijgt ie de volgende button te zien (Toevoege)
    if ($_SESSION) {
      if ($_SESSION['user_type'] == 'admin' || $_SESSION['user_type'] == 'mdw') { ?>

          Voeg een nieuwe gerecht toe

    <?php }
    } ?>

Toevoegen

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

              <form action="CRUDmenu/proces.php" method="post" class="col-xs-3">
                Gerecht Naam
                <input type="text" name="gerecht_naam" class="form-control" required />

                Gerecht Prijs
                <input type="number" name="gerecht_prijs" class="form-control" required />

                Omschrijving
                <input type="text" name="omschrijving" class="form-control" required />

                Type eten
                <select name="type_eten" required>
                  <option>-Selecteer-</option>
                  <option value="1">Koude eten</option>
                  <option value="2">Warme eten</option>
                  <option value="3">Drank</option>
                </select>

                Afbeelding
                <input type="file" name="afbeelding" class="form-control" required />

                <input type="submit" name="toevoegen" class="btn btn-info" value="Save" />
              </form>

Body:
i solved it by doing this.

  if (isset($_POST['kopen'])) {
    // hier check ik eerst als de sessie gezet is, als het zo is dan de gebruiker zou wel kunnen kopen
    if ($_SESSION) {
      $id = $_POST['menu'];
      $Userid = $_SESSION['user_id'];
      $Username = $_SESSION['username'];
      $db_conn->query("INSERT INTO `menulijst`(`user_id`, `menu_id`, `username`) VALUES ('$Userid', '$id', '$Username')"); ?>
      <div class="alert2">
        <span class="closebtn2" onclick="this.parentElement.style.display='none';">&times;</span>
        <strong>Succes!</strong> Toegevoegd aan winkelmand.
      </div>
    <?php
    } else { ?>
      <!--  maar als de sessie niet gezet is dan de klant zou een melding ktijgen
   en er zou verteld worden dat ie eerst ingelogd moet zijn om iets te kunnen kopen. -->
      <div class="alert">
        <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
        <strong>Danger!</strong> Om een prodcut te kunnen kopen moet je eerst ingelogd zijn.
        <a style="color: black" href="login/pdo_login.php"><span class="glyphicon glyphicon-log-in"></span> Login</a>
      </div>
  <?php }
  } ?>```

And putting it in the body