问:
Upload File Blocked by Spring Security in Struts 2
I m using Spring and Struts 2, Hibernate, Spring Security.
My problem is when I click in submit the poster JSP Page blocked access .
I think the problem in resultAction that does not execute.

DocumentAction.java:

```<code>package com.web.actions;

import java.io.File;

import com.opensymphony.xwork2.ActionSupport;

public class DocumentAction extends ActionSupport {

        /**
     *
     */
    private static final long serialVersionUID = -8801071547543777086L;
        private File fileUpload;
        private String fileUploadContentType;
        private String fileUploadFileName;

        public String getFileUploadContentType() {
            return fileUploadContentType;
        }

        public void setFileUploadContentType(String fileUploadContentType) {
            this.fileUploadContentType = fileUploadContentType;
        }

        public String getFileUploadFileName() {
            return fileUploadFileName;
        }

        public void setFileUploadFileName(String fileUploadFileName) {
            this.fileUploadFileName = fileUploadFileName;
        }

        public File getFileUpload() {
            return fileUpload;
        }

        public void setFileUpload(File fileUpload) {
            this.fileUpload = fileUpload;
        }

        public String execute() throws Exception{
            System.out.println("Votre Fichier est bien telecharger");
            return SUCCESS;

        }

        public String display() {
            return NONE;
        }

    }
</code>```

Security.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.2.xsd">
    <http>

        <access-denied-handler error-page="/private/accessDenied.jsp" />

        <!-- permettre l'acces aux feuille de style, img, page public et JS à tous
            le monde -->
        <!-- isAnonymous() or hasRole('ROLE_ANONYMOUS') -->
        <intercept-url pattern="/css/**" access="permitAll" />
        <intercept-url pattern="/js/**" access="permitAll" />
        <intercept-url pattern="/img/**" access="permitAll" />
        <intercept-url pattern="/login*" access="isAnonymous()" />
        <intercept-url pattern="/logout*" access="isAuthenticated()" />

        <!-- permettre l'acces aux actions public -->
        <intercept-url pattern="/public/**" access="isAnonymous()" />

        <!-- zone privée user -->
        <intercept-url pattern="/private/user/*" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/user/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/user/professeur/*" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/user/professeur/**" access="hasRole('ROLE_USER')" />
        <!-- zone privée admin -->

        <intercept-url pattern="/private/admin/*" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/private/admin/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/**" access="isAuthenticated()" />

        <intercept-url pattern="/**" access="denyAll" />

        <form-login login-page="/public/showLoginPage"
            default-target-url="/private/initUserHome"
            authentication-failure-url="/public/loginFailure.jsp" />

        <logout logout-success-url="/public/showLoginPage" logout-url="/logout"
            delete-cookies="JSESSIONID" />

    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="utlisateurService">
            <password-encoder hash="sha">
                <salt-source user-property="username" />
            </password-encoder>

        </authentication-provider>
    </authentication-manager>

     <authentication-manager>
     <authentication-provider>
     <user-service>
     <user name="admin" password="admin" authorities="ROLE_ADMIN" />
     <user name="user" password="user" authorities="ROLE_USER" />
     </user-service>
    </authentication-provider>
     </authentication-manager>
</beans:beans>
</code>```

struts.xml:

```<code><package name="ProfesseurPackage" namespace="/private/user/professeur" extends="struts-default">

    <action name="fileUploadAction" class="com.web.actions.DocumentAction" method="display">
            <result name="none">fileupload.jsp</result>
        </action>

        <action name="resultAction" class="com.web.actions.DocumentAction" method="execute">

            <interceptor-ref name="exception"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">text/plain</param>
                <param name="maximumSize">10240</param>
            </interceptor-ref>
            <interceptor-ref name="params">
                <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>

            <result name="success">result.jsp</result>
            <result name="input">fileupload.jsp</result>

        </action>

    </package>
</code>```

fileupload.jsp:

```<code><%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>

<body>
<h1>Struts 2 <s:file> file upload example</h1>

<s:form action="resultAction" method="POST" enctype="multipart/form-data">
<input type="hidden" name="${_csrf.parameterName}"
                    value="${_csrf.token}" />
<s:file name="fileUpload" label="Select a File to upload" size="40" />

<s:submit value="submit" name="submit" />

</s:form>

</body>
</html
</code>```

答:
Add namespace attribute to the <s:form> tag. Because the upload action is configured under /private/user/professeur. The user should be identified to to use this namespace.

```<code><s:form action="resultAction" namespace="/private/user/professeur" method="POST" enctype="multipart/form-data">
</code>```

Body:
I m using Spring and Struts 2, Hibernate, Spring Security.
My problem is when I click in submit the poster JSP Page blocked access .
I think the problem in resultAction that does not execute.

DocumentAction.java:

package com.web.actions;

import java.io.File;

import com.opensymphony.xwork2.ActionSupport;

public class DocumentAction extends ActionSupport {

        /**
     *
     */
    private static final long serialVersionUID = -8801071547543777086L;
        private File fileUpload;
        private String fileUploadContentType;
        private String fileUploadFileName;

        public String getFileUploadContentType() {
            return fileUploadContentType;
        }

        public void setFileUploadContentType(String fileUploadContentType) {
            this.fileUploadContentType = fileUploadContentType;
        }

        public String getFileUploadFileName() {
            return fileUploadFileName;
        }

        public void setFileUploadFileName(String fileUploadFileName) {
            this.fileUploadFileName = fileUploadFileName;
        }

        public File getFileUpload() {
            return fileUpload;
        }

        public void setFileUpload(File fileUpload) {
            this.fileUpload = fileUpload;
        }

        public String execute() throws Exception{
            System.out.println("Votre Fichier est bien telecharger");
            return SUCCESS;

        }

        public String display() {
            return NONE;
        }

    }

Security.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.2.xsd">
    <http>

        <access-denied-handler error-page="/private/accessDenied.jsp" />

        <intercept-url pattern="/css/**" access="permitAll" />
        <intercept-url pattern="/js/**" access="permitAll" />
        <intercept-url pattern="/img/**" access="permitAll" />
        <intercept-url pattern="/login*" access="isAnonymous()" />
        <intercept-url pattern="/logout*" access="isAuthenticated()" />

        <intercept-url pattern="/public/**" access="isAnonymous()" />

        <intercept-url pattern="/private/user/*" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/user/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/user/professeur/*" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/user/professeur/**" access="hasRole('ROLE_USER')" />

        <intercept-url pattern="/private/admin/*" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/private/admin/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/private/**" access="isAuthenticated()" />

        <intercept-url pattern="/**" access="denyAll" />

        <form-login login-page="/public/showLoginPage"
            default-target-url="/private/initUserHome"
            authentication-failure-url="/public/loginFailure.jsp" />

        <logout logout-success-url="/public/showLoginPage" logout-url="/logout"
            delete-cookies="JSESSIONID" />

    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="utlisateurService">
            <password-encoder hash="sha">
                <salt-source user-property="username" />
            </password-encoder>

        </authentication-provider>
    </authentication-manager>

     <authentication-manager>
     <authentication-provider>
     <user-service>
     <user name="admin" password="admin" authorities="ROLE_ADMIN" />
     <user name="user" password="user" authorities="ROLE_USER" />
     </user-service>
    </authentication-provider>
     </authentication-manager>
</beans:beans>

struts.xml:

<package name="ProfesseurPackage" namespace="/private/user/professeur" extends="struts-default">

    <action name="fileUploadAction" class="com.web.actions.DocumentAction" method="display">
            <result name="none">fileupload.jsp</result>
        </action>

        <action name="resultAction" class="com.web.actions.DocumentAction" method="execute">

            <interceptor-ref name="exception"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">text/plain</param>
                <param name="maximumSize">10240</param>
            </interceptor-ref>
            <interceptor-ref name="params">
                <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>

            <result name="success">result.jsp</result>
            <result name="input">fileupload.jsp</result>

        </action>

    </package>

fileupload.jsp:

<%@ taglib prefix="s" uri="/struts-tags" %>

<s:head />

Struts 2 <s:file> file upload example

<s:form action="resultAction" method="POST" enctype="multipart/form-data">
<input type="hidden" name="${_csrf.parameterName}"
                    value="${_csrf.token}" />
<s:file name="fileUpload" label="Select a File to upload" size="40" />

<s:submit value="submit" name="submit" />

</s:form>

</html

Body:
Add namespace attribute to the <s:form> tag. Because the upload action is configured under /private/user/professeur. The user should be identified to to use this namespace.

<s:form action="resultAction" namespace="/private/user/professeur" method="POST" enctype="multipart/form-data">


来源: stackexchange

问:
alert() not working in WKWebview evaluateJavaScript()
I don't why my question is marked as duplicate of this one, first I execute javascript code with evaluateJavaScript as the question title shows which it's apparently different from that quesiton. What's more I've noted that I've try the answer in that question without no success at the end of my question body.

I use wkwebview.evaluateJavaScript() funciton to execute javascript in the wkwebview of swift3. But the alert() didnot open the alert dialog. And there is no errors and issues shows. While I can use evaluateJavaScript() to execute javascript code to modify the page content.

```<code>class WebViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate {
    var wk:WKWebView!
    self.wk.navigationDelegate = self
    self.wk.uiDelegate = self
    self.wk.scrollView.delegate = self
    self.wk.customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0"

    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        let config = WKWebViewConfiguration()
        self.wk = WKWebView(frame: CGRect(x: frame.minX, y: frame.minY+20, width: frame.width, height: frame.height-70), configuration: config)
        self.wk.navigationDelegate = self
        ...
    }

    ...
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Finished navigation to url \(String(describing: webView.url))")
        //self.wk.evaluateJavaScript("document.getElementById('test').innerHTML = 'sssssssssssssss';", completionHandler: nil)          //this works well
        self.wk.evaluateJavaScript("alert('aaaaaaa');", completionHandler: nil)     //this not show the alert dialog
    }
    ...
}
</code>```

I also refer to this post and answer, while that question is not on evaluateJavaScript. I add WKUIDelegate for my WebViewController and add self.wk.uiDelegate = self to my viewDidLoad(), but nothing changes.

added, below the console.log() put the log in the console, while alert() not pop up the dialog.  And the UIAlertController also works.

```<code>self.wk.evaluateJavaScript("alert('aa');console.log('1234');var rect = document.getElementById('liveMovie').getBoundingClientRect();[rect.left, rect.top];") {
    (result, error) -> Void in
    if((result) != nil)
    {
        self.player?.view?.frame.origin.x = (result as! Array)[0]
        self.player?.view?.frame.origin.y = (result as! Array)[1]
    }
}

let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
     if(true)
     {
     }
}))
</code>```

答:
First of all you need to implement the required WKUIDelegate methods, in your case you need to implement:</p>

```<code>optional func webView(_ webView: WKWebView,
    runJavaScriptAlertPanelWithMessage message: String,
         initiatedByFrame frame: WKFrameInfo,
        completionHandler: @escaping () -> Void)
{
    // parameter **message** will hold your actual alert message.

    // Write Your Customised code to display the alert message
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I don't why my question is marked as duplicate of this one, first I execute javascript code with evaluateJavaScript as the question title shows which it's apparently different from that quesiton. What's more I've noted that I've try the answer in that question without no success at the end of my question body.

I use wkwebview.evaluateJavaScript() funciton to execute javascript in the wkwebview of swift3. But the alert() didnot open the alert dialog. And there is no errors and issues shows. While I can use evaluateJavaScript() to execute javascript code to modify the page content.

class WebViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate {
    var wk:WKWebView!
    self.wk.navigationDelegate = self
    self.wk.uiDelegate = self
    self.wk.scrollView.delegate = self
    self.wk.customUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0"

    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        let config = WKWebViewConfiguration()
        self.wk = WKWebView(frame: CGRect(x: frame.minX, y: frame.minY+20, width: frame.width, height: frame.height-70), configuration: config)
        self.wk.navigationDelegate = self
        ...
    }

    ...
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Finished navigation to url \(String(describing: webView.url))")
        //self.wk.evaluateJavaScript("document.getElementById('test').innerHTML = 'sssssssssssssss';", completionHandler: nil)          //this works well
        self.wk.evaluateJavaScript("alert('aaaaaaa');", completionHandler: nil)     //this not show the alert dialog
    }
    ...
}

I also refer to this post and answer, while that question is not on evaluateJavaScript. I add WKUIDelegate for my WebViewController and add self.wk.uiDelegate = self to my viewDidLoad(), but nothing changes.

added, below the console.log() put the log in the console, while alert() not pop up the dialog.  And the UIAlertController also works.

self.wk.evaluateJavaScript("alert('aa');console.log('1234');var rect = document.getElementById('liveMovie').getBoundingClientRect();[rect.left, rect.top];") {
    (result, error) -> Void in
    if((result) != nil)
    {
        self.player?.view?.frame.origin.x = (result as! Array)[0]
        self.player?.view?.frame.origin.y = (result as! Array)[1]
    }
}

let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
     if(true)
     {
     }
}))

Body:
First of all you need to implement the required WKUIDelegate methods, in your case you need to implement:

optional func webView(_ webView: WKWebView,
    runJavaScriptAlertPanelWithMessage message: String,
         initiatedByFrame frame: WKFrameInfo,
        completionHandler: @escaping () -> Void)
{
    // parameter **message** will hold your actual alert message.

    // Write Your Customised code to display the alert message
}


问:
Update Codeigniter's data on Table #2 based Table #1's id
I have 2 tables, reservation and is customer

```<code>table #1 : reservation
------------------------
- reservation_id
- reservation_status
- customer_id

table #2 : customer
------------------------
- customer_id
- customer_name
- customer_status
</code>```

I'm new in codeigniter but how I can update/change customer status (from 0 to 1 or 1 to somevalue) based on reservation id

is there using join and update or somewhat.
Thanks

答:
try this code </p>

```<code>UPDATE customer
        JOIN reservation
        ON customer.customer_id = reservation.customer_id
SET     customer.customer_status = your_value;
WHERE   reservation.reservation_id="your_id"';
</code>```

Body:
I have 2 tables, reservation and is customer

table #1 : reservation
------------------------
- reservation_id
- reservation_status
- customer_id

table #2 : customer
------------------------
- customer_id
- customer_name
- customer_status

I'm new in codeigniter but how I can update/change customer status (from 0 to 1 or 1 to somevalue) based on reservation id

is there using join and update or somewhat.
Thanks

Body:
try this code

UPDATE customer
        JOIN reservation
        ON customer.customer_id = reservation.customer_id
SET     customer.customer_status = your_value;
WHERE   reservation.reservation_id="your_id"';


问:
Angular 2 material mat-tab size
I have the following piece of code

```<code>  <mat-tab-group>
    <div *ngFor="let question of subcategory.questions">
        <mat-tab label={{question.question_id}} class="question-tab">{{question.question}}</mat-tab>
    </div>
  </mat-tab-group>
</code>```

which displays like:

However I want to reduce tabs width, like this:

The problem is, when I change css at run time, it adjusts fine, but when I put css like:

```<code>.mat-tab {
  min-width: 50px !important;
}
.mat-tab-label[_ngcontent-c9]{
    min-width: 50px !important;
}
</code>```

It doesn't work. Any idea how to approach this ?

答:
Try this:

```<code>/deep/.mat-tab-label, /deep/.mat-tab-label-active{
 min-width: 0!important;
 padding: 3px!important;
 margin: 3px!important;
}
</code>```

NOTE: In angular 8 /deep/ not working... you can use ::ng-deep, like so:

```<code>::ng-deep.mat-tab-label, ::ng-deep.mat-tab-label-active{
 min-width: 0!important;
 padding: 3px!important;
 margin: 3px!important;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular 2 material mat-tab size

Body:
I have the following piece of code

  <mat-tab-group>

        <mat-tab label={{question.question_id}} class="question-tab">{{question.question}}</mat-tab>

  </mat-tab-group>

which displays like:

However I want to reduce tabs width, like this:

The problem is, when I change css at run time, it adjusts fine, but when I put css like:

.mat-tab {
  min-width: 50px !important;
}
.mat-tab-label[_ngcontent-c9]{
    min-width: 50px !important;
}

It doesn't work. Any idea how to approach this ?

Body:
Try this:

/deep/.mat-tab-label, /deep/.mat-tab-label-active{
 min-width: 0!important;
 padding: 3px!important;
 margin: 3px!important;
}

NOTE: In angular 8 /deep/ not working... you can use ::ng-deep, like so:

::ng-deep.mat-tab-label, ::ng-deep.mat-tab-label-active{
 min-width: 0!important;
 padding: 3px!important;
 margin: 3px!important;
}


问:
JavaFX warning: Argument 'getClass().getClassLoader().getResource( "view/RootLayout.fxml" )' might be null
IntelliJ Idea is giving me this warning:

```<code>Argument 'getClass().getClassLoader().getResource( "view/RootLayout.fxml" )' might be null
</code>```

However, it always works.  I just want the clear warning, preferably without annotations or disabling the inspection.

Per this thread: IntelliJ IDEA - getClass().getResource("...") return null

I have my resources folder set as a Resources Root.

I added *.fxml to Settings -> Build, Execution, Deployment -> Compiler -> Resource patterns

I even added ?.fxml and !?.fxml to cover more possibilities.

None of those seem to make any difference.

Here is my start() method:

```<code>@Override
public void start( Stage primaryStage ) throws Exception
{
    // Load the FXML file containing all of the UI elements.
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation( getClass().getResource( "view/RootLayout.fxml" ) );
    Parent root = FXMLLoader.load( getClass().getClassLoader().getResource( "view/RootLayout.fxml" ) );

    // Create the stage and set the window title.
    primaryStage.setTitle( "SNMP Link Utilization" );

    // Set the scene using root, with the specified width and height.
    primaryStage.setScene( new Scene( root, 500, 600 ) );

    // Set the icon for a non-Maven build.
    //primaryStage.getIcons().add( new Image( "file:resources/images/nic.png" ) );
    // Set the icon for a Maven build.
    primaryStage.getIcons().add( new Image( "images/nic.png" ) );

    primaryStage.show();
}
</code>```

Am I doing anything wrong?  I've tried a few other ways of creating the Parent object, but all that I have tried end up failing.

答:
You can get rid of that warning if you refactor the code a little bit this way:</p>

```<code>    FXMLLoader loader = new FXMLLoader(getClass().getResource(
            "view/RootLayout.fxml"));
    Parent root = loader.load();
</code>```

Body:
IntelliJ Idea is giving me this warning:

Argument 'getClass().getClassLoader().getResource( "view/RootLayout.fxml" )' might be null

However, it always works.  I just want the clear warning, preferably without annotations or disabling the inspection.

Per this thread: IntelliJ IDEA - getClass().getResource("...") return null

I have my resources folder set as a Resources Root.

I added *.fxml to Settings -> Build, Execution, Deployment -> Compiler -> Resource patterns

I even added ?.fxml and !?.fxml to cover more possibilities.

None of those seem to make any difference.

Here is my start() method:

@Override
public void start( Stage primaryStage ) throws Exception
{
    // Load the FXML file containing all of the UI elements.
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation( getClass().getResource( "view/RootLayout.fxml" ) );
    Parent root = FXMLLoader.load( getClass().getClassLoader().getResource( "view/RootLayout.fxml" ) );

    // Create the stage and set the window title.
    primaryStage.setTitle( "SNMP Link Utilization" );

    // Set the scene using root, with the specified width and height.
    primaryStage.setScene( new Scene( root, 500, 600 ) );

    // Set the icon for a non-Maven build.
    //primaryStage.getIcons().add( new Image( "file:resources/images/nic.png" ) );
    // Set the icon for a Maven build.
    primaryStage.getIcons().add( new Image( "images/nic.png" ) );

    primaryStage.show();
}

Am I doing anything wrong?  I've tried a few other ways of creating the Parent object, but all that I have tried end up failing.

Body:
You can get rid of that warning if you refactor the code a little bit this way:

    FXMLLoader loader = new FXMLLoader(getClass().getResource(
            "view/RootLayout.fxml"));
    Parent root = loader.load();


问:
nodejs expressjs sendFile with angular resource
I have my index.html, when I click on a button, it calls a angular service that use $resource.

```<code>var serviceRest = $resource(URL_API, null,
    {
       "connect" : { method: "GET", url: "http://localhost/login"}
     });
</code>```

And then in my expressJS route I have this :

```<code>router.get('/',function(req,res){
    console.log("Hi there");
    res.sendFile('../public/views/login.html', {root: __dirname});
});
</code>```

But it does nothing. Nothing happens but my console log display so my sendFile might be false... I stay on my index.html.

```<code>| -- Agenda
     | -- public
          | -- views
               | -- login.html
     | -- controllers
          | -- routes.js
</code>```

My router file is in ./controllers, and my login.html is in ./public/views

EDIT :

Ok, so the problem is not a path problem. But, in all solution that I tried, only one gave me a good result.

```<code>res.sendFile(path.join(__dirname, '../public/views/login.html'));
</code>```

After that, I asked myself "What I am returning in the Angular Service with the $resource. And this is at this moment that I saw that my connect() function :

```<code>var serviceRest = $resource(URL_API, null,
{
    "connect" : { method: "GET", url: "http://localhost/login"}
});

return {

    connect: function() {
        console.log("connect");
        console.log(serviceRest.connect());
        return serviceRest.connect();

    }
}
</code>```

This console.log(serviceRest.connect()); shows me a Promise in the browser console. And this is a huge array with one character per element, that containing my login.html code lol. Funny but not help me haha

答:
root option is the directory from which you want to serve the files from. Assuming your folder structure is like below :

```<code>| yourApp
  | -- public/
       | -- views/
         |-- login.html
  | -- controllers/
       | -- routes.js
</code>```

Try setting the root directory with yourApp

```<code>res.sendFile('public/views/login.html', {root: '../<root folder name>'});
</code>```

Replace the "root folder name" above with the parent directory name of 'public' folder.
Considering the above folder structure that would be :

```<code>res.sendFile('public/views/login.html', {root: '../yourApp'});
</code>```

Body:
I have my index.html, when I click on a button, it calls a angular service that use $resource.

var serviceRest = $resource(URL_API, null,
    {
       "connect" : { method: "GET", url: "http://localhost/login"}
     });

And then in my expressJS route I have this :

router.get('/',function(req,res){
    console.log("Hi there");
    res.sendFile('../public/views/login.html', {root: __dirname});
});

But it does nothing. Nothing happens but my console log display so my sendFile might be false... I stay on my index.html.

| -- Agenda
     | -- public
          | -- views
               | -- login.html
     | -- controllers
          | -- routes.js

My router file is in ./controllers, and my login.html is in ./public/views

EDIT :

Ok, so the problem is not a path problem. But, in all solution that I tried, only one gave me a good result.

res.sendFile(path.join(__dirname, '../public/views/login.html'));

After that, I asked myself "What I am returning in the Angular Service with the $resource. And this is at this moment that I saw that my connect() function :

var serviceRest = $resource(URL_API, null,
{
    "connect" : { method: "GET", url: "http://localhost/login"}
});

return {

    connect: function() {
        console.log("connect");
        console.log(serviceRest.connect());
        return serviceRest.connect();

    }
}

This console.log(serviceRest.connect()); shows me a Promise in the browser console. And this is a huge array with one character per element, that containing my login.html code lol. Funny but not help me haha

Body:
root option is the directory from which you want to serve the files from. Assuming your folder structure is like below :

| yourApp
  | -- public/
       | -- views/
         |-- login.html
  | -- controllers/
       | -- routes.js

Try setting the root directory with yourApp

res.sendFile('public/views/login.html', {root: '../<root folder name>'});

Replace the "root folder name" above with the parent directory name of 'public' folder.
Considering the above folder structure that would be :

res.sendFile('public/views/login.html', {root: '../yourApp'});


问:
SPA with Deepstream.io HTTP authentication for a login page
Im new in programming and Im trying to use deepstream authentication for a real username and password (already built its API with Hash).
It should only redirect to the next page when uses those specific username and password.

I want my deepstream respond invalid authorization when its another username and password and i want it to redirect to the next page when its valid.

Thank you for your help in advance!

答:
It looks like you've gotten most of the way with this, not too familiar with React but in general when logging in with a deepstream client, a callback is returned with a boolean indicated whether or not the login was successful.

```<code>client.login({ ... }, (success) => {
    // success is true or false
})
</code>```

Inside this callback you'll want to do you React specific redirect. Ie. if the success variable is false, redirect to the error page, otherwise redirect to your app. We have a great tutorial on using HTTP authentication [1] that I'd really recommend checking out.

You might also want to look at some info on React for redirecting etc [2].

[1] deepstream HTTP authentication

[2] How to redirect to another route programmatically

Body:
It looks like you've gotten most of the way with this, not too familiar with React but in general when logging in with a deepstream client, a callback is returned with a boolean indicated whether or not the login was successful.

client.login({ ... }, (success) => {
    // success is true or false
})

Inside this callback you'll want to do you React specific redirect. Ie. if the success variable is false, redirect to the error page, otherwise redirect to your app. We have a great tutorial on using HTTP authentication [1] that I'd really recommend checking out.

You might also want to look at some info on React for redirecting etc [2].

[1] deepstream HTTP authentication

[2] How to redirect to another route programmatically


问:
Problems importing component ej from grid syncfusion using the react
I'm using the react and I want in one of my components to render a syncfusion grid. However I have problems with one of the components of the grid. The grid component ej is not found. I've tried importing in a number of ways but I was not successful. Has anyone had this problem and found a solution? Error Message

Example code:

```<code>import React, { Component } from "react";
import $ from "jquery";
//This import does not find the component (ej) needed to render the grid
import  {ej} from "syncfusion-javascript";
//There are scripts in the index.html file to mount the grid according to
the Syncfusion documentation

class GridSeries extends Component {

constructor() {
    super();
    this.menuGrid = this.menuGrid.bind(this);
}

//Function responsible for mounting the grid it is called inside my render method
menuGrid() {
    $(function () {
        $("#Grid").ejGrid({
            dataSource: teste,
            allowPaging: true,
            allowSorting: true,
            allowGrouping: true,
            allowFiltering: true,
            allowReordering: true,
            allowMultiSorting: true,
            filterSettings: {filterType: "excel"},
            toolbarSettings: {showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport]},
            columns: [
                {type: "checkbox", width: 50},
                {field: "OrderID", headerText: "Order ID", width: 75, textAlign: ej.TextAlign.Right},
                {field: "CustomerID", headerText: "Customer ID", width: 80},
                {field: "EmployeeID", headerText: "Employee ID", width: 75, textAlign: ej.TextAlign.Right},
                {field: "Freight", width: 75, format: "{0:C}", textAlign: ej.TextAlign.Right},
                {field: "OrderDate", headerText: "Order Date", width: 80, format: "{0:MM/dd/yyyy}", textAlign: ej.TextAlign.Right},
                {field: "ShipCity", headerText: "Ship City", width: 110}
            ],
            toolbarClick: function (e) {
                this.exportGrid = this["export"];
                if (e.itemName == "Excel Export") {
                    this.exportGrid(window.baseurl + 'api/grid/ExcelExport')
                    e.cancel = true;
                } else if (e.itemName == "Word Export") {
                    this.exportGrid(window.baseurl + 'api/grid/WordExport')
                    e.cancel = true;
                } else if (e.itemName == "PDF Export") {
                    this.exportGrid(window.baseurl + 'api/grid/PdfExport')
                    e.cancel = true;
                    document.getElementById('container')
                }
            },
        });
    });

    //Test Base
    var teste = [
        {Name: "bruno", City: "Brasilia"},
        {Name: "bruno1", City: "Riacho Fundo l"},
        {Name: "bruno2", City: "Guára"},
        {Name: "bruno3", City: "Cruzeiro"}
    ];
}
render() {
    return (
            <div className="content-container-fluid">
                <div className="row">
                    <div className="cols-mple-area">
                        { this.menuGrid()}
                        <div id="Grid"></div>
                    </div>
                </div>
            </div>
            );
   }
}

export default GridSeries;
</code>```

答:
The cause of the issue is that you have load the scripts from node package and we can’t load the require scripts from the node package in the react component by default. So, we suggest you to use either webpack or browserify technique to achieve your requirement. Please refer to the below knowledge base document.

https://www.syncfusion.com/kb/7547/how-to-bundle-syncfusion-reactjs-components-using-webpack-and-browserify

Body:
I'm using the react and I want in one of my components to render a syncfusion grid. However I have problems with one of the components of the grid. The grid component ej is not found. I've tried importing in a number of ways but I was not successful. Has anyone had this problem and found a solution? Error Message

Example code:

import React, { Component } from "react";
import $ from "jquery";
//This import does not find the component (ej) needed to render the grid
import  {ej} from "syncfusion-javascript";
//There are scripts in the index.html file to mount the grid according to
the Syncfusion documentation

class GridSeries extends Component {

constructor() {
    super();
    this.menuGrid = this.menuGrid.bind(this);
}

//Function responsible for mounting the grid it is called inside my render method
menuGrid() {
    $(function () {
        $("#Grid").ejGrid({
            dataSource: teste,
            allowPaging: true,
            allowSorting: true,
            allowGrouping: true,
            allowFiltering: true,
            allowReordering: true,
            allowMultiSorting: true,
            filterSettings: {filterType: "excel"},
            toolbarSettings: {showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport]},
            columns: [
                {type: "checkbox", width: 50},
                {field: "OrderID", headerText: "Order ID", width: 75, textAlign: ej.TextAlign.Right},
                {field: "CustomerID", headerText: "Customer ID", width: 80},
                {field: "EmployeeID", headerText: "Employee ID", width: 75, textAlign: ej.TextAlign.Right},
                {field: "Freight", width: 75, format: "{0:C}", textAlign: ej.TextAlign.Right},
                {field: "OrderDate", headerText: "Order Date", width: 80, format: "{0:MM/dd/yyyy}", textAlign: ej.TextAlign.Right},
                {field: "ShipCity", headerText: "Ship City", width: 110}
            ],
            toolbarClick: function (e) {
                this.exportGrid = this["export"];
                if (e.itemName == "Excel Export") {
                    this.exportGrid(window.baseurl + 'api/grid/ExcelExport')
                    e.cancel = true;
                } else if (e.itemName == "Word Export") {
                    this.exportGrid(window.baseurl + 'api/grid/WordExport')
                    e.cancel = true;
                } else if (e.itemName == "PDF Export") {
                    this.exportGrid(window.baseurl + 'api/grid/PdfExport')
                    e.cancel = true;
                    document.getElementById('container')
                }
            },
        });
    });

    //Test Base
    var teste = [
        {Name: "bruno", City: "Brasilia"},
        {Name: "bruno1", City: "Riacho Fundo l"},
        {Name: "bruno2", City: "Guára"},
        {Name: "bruno3", City: "Cruzeiro"}
    ];
}
render() {
    return (

                        { this.menuGrid()}

            );
   }
}

export default GridSeries;


问:
Pushing an object with unique_ptr into vector in C++
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

```<code>#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}
</code>```

I get compiler errors when adding the new state object to the vector:

```<code>Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
</code>```

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

```<code>int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}
</code>```

答:
You need to make an ownership decision.

The owner (or owners) of a new allocated object are responsible for ensuring it is 'delete'ed at the end of its lifecycle.

If the vector<> owns the object then std::move() the std::unique_ptr<> into the vector and continue to access the object through a 'raw' pointer but will be invalidated if the vector is destructed or the std::unique_ptr is erased/reset.

If the vector<> doesn't own the object than declare it vector<State*> and recognise it will be invalidated when the std::unique_ptr is destructed (unless you intervene).

If there's a complex relationship consider std::shared_ptr<> which will allow multiple objects to share ownership but make sure that circular referencing can't take place.

Beyond that you're into more complex ownership models and possible 'garbage collection'.

A superficial examination suggests a 'State' probably owns its Transitions because on the whole they make sense while the state exists and stop making sense when it doesn't. So continue with the vector<std::unique_ptr<> > and access State and/or Transition as a pointer.

If that doesn't work in your case, you probably need a 'FiniteState' context object that owns all the states and all the transitions and takes care to remove all the states and all the associated transitions from and to when a state is destroyed.

Body:
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}

I get compiler errors when adding the new state object to the vector:

Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}


问:
summing 2 distance matrices for getting a third 'overall' distance matrix (ecological context)
I am ecologist, using mainly the vegan R package.

I have 2 matrices (sample x abundances) (See data below):

matrix 1/ nrow= 6replicates*24sites, ncol=15 species abundances (fish)
    matrix 2/ nrow= 3replicates*24sites, ncol=10 species abundances (invertebrates)

The sites are the same in both matrices. I want to get the overall bray-curtis dissimilarity (considering both matrices) among pairs of sites. I see 2 options:

option 1, averaging over replicates (at the site scale) fishes and macro-invertebrates abundances, cbind the two mean abundances matrix (nrow=24sites, ncol=15+10 mean abundances) and calculating bray-curtis.

option 2, for each assemblage, computing bray-curtis dissimilarity among pairs of sites, computing distances among sites centroids. Then summing up the 2 distance matrix.

In case I am not clear, I did these 2 operations in the R codes below.

Please, could you tell me if the option 2 is correct and more appropriate than option 1.

thank you in advance.

Pierre

here is below the R code exemples

generating data

```<code>library(plyr);library(vegan)

#assemblage 1: 15 fish species, 6 replicates per site
a1.env=data.frame(
  Habitat=paste("H",gl(2,12*6),sep=""),
  Site=paste("S",gl(24,6),sep=""),
  Replicate=rep(paste("R",1:6,sep=""),24))

summary(a1.env)

a1.bio=as.data.frame(replicate(15,rpois(144,sample(1:10,1))))

names(a1.bio)=paste("F",1:15,sep="")

a1.bio[1:72,]=2*a1.bio[1:72,]

#assemblage 2: 10 taxa of macro-invertebrates, 3 replicates per site

a2.env=a1.env[a1.env$Replicate%in%c("R1","R2","R3"),]

summary(a2.env)

a2.bio=as.data.frame(replicate(10,rpois(72,sample(10:100,1))))

names(a2.bio)=paste("I",1:10,sep="")

a2.bio[1:36,]=0.5*a2.bio[1:36,]

#environmental data at the sit scale

env=unique(a1.env[,c("Habitat","Site")])

env=env[order(env$Site),]
</code>```

OPTION 1, averaging abundances and cbind

```<code>a1.bio.mean=ddply(cbind(a1.bio,a1.env),.(Habitat,Site),numcolwise(mean))

a1.bio.mean=a1.bio.mean[order(a1.bio.mean$Site),]

a2.bio.mean=ddply(cbind(a2.bio,a2.env),.(Habitat,Site),numcolwise(mean))

a2.bio.mean=a2.bio.mean[order(a2.bio.mean$Site),]

bio.mean=cbind(a1.bio.mean[,-c(1:2)],a2.bio.mean[,-c(1:2)])

dist.mean=vegdist(sqrt(bio.mean),"bray")
</code>```

OPTION 2, computing for each assemblage distance among centroids and summing the 2 distances matrix

```<code>a1.dist=vegdist(sqrt(a1.bio),"bray")

a1.coord.centroid=betadisper(a1.dist,a1.env$Site)$centroids

a1.dist.centroid=vegdist(a1.coord.centroid,"eucl")

a2.dist=vegdist(sqrt(a2.bio),"bray")

a2.coord.centroid=betadisper(a2.dist,a2.env$Site)$centroids

a2.dist.centroid=vegdist(a2.coord.centroid,"eucl")
</code>```

summing up the two distance matrices using Gavin Simpson 's fuse()

```<code>dist.centroid=fuse(a1.dist.centroid,a2.dist.centroid,weights=c(15/25,10/25))
</code>```

summing up the two euclidean distance matrices (thanks to Jari Oksanen correction)

```<code>dist.centroid=sqrt(a1.dist.centroid^2 + a2.dist.centroid^2)
</code>```

and the 'coord.centroid' below for further distance-based analysis (is it correct ?)

```<code>coord.centroid=cmdscale(dist.centroid,k=23,add=TRUE)
</code>```

COMPARING OPTION 1 AND 2

```<code>pco.mean=cmdscale(vegdist(sqrt(bio.mean),"bray"))

pco.centroid=cmdscale(dist.centroid)

comparison=procrustes(pco.centroid,pco.mean)

protest(pco.centroid,pco.mean)
</code>```

答:
I like this simplicity of this answer, but it only applies to adding 2 distance matrices:

```<code>d.fused = (w * d.x) + ((1 - w) * d.y)
</code>```

so I wrote my own snippet to combine an array of multiple distance matrices (not just 2), and using standard R packages:

```<code># generate array of distance matrices
x <- matrix(rnorm(100), nrow = 5)
y <- matrix(rnorm(100), nrow = 5)
z <- matrix(rnorm(100), nrow = 5)
dst_array <- list(dist(x),dist(y),dist(z))

# create new distance matrix with first element of array
dst <- dst_array[[1]]

# loop over remaining array elements, add them to distance matrix
for (jj in 2:length(dst_array)){
  dst <- dst + dst_array[[jj]]
}
</code>```

You could also use a vector of similar size to dst_array in order to define scaling factors

```<code>dst <- dst + my_scale[[jj]] * dst_array[[jj]]
</code>```

Body:
I am ecologist, using mainly the vegan R package.

I have 2 matrices (sample x abundances) (See data below):

matrix 1/ nrow= 6replicates*24sites, ncol=15 species abundances (fish)
    matrix 2/ nrow= 3replicates*24sites, ncol=10 species abundances (invertebrates)

The sites are the same in both matrices. I want to get the overall bray-curtis dissimilarity (considering both matrices) among pairs of sites. I see 2 options:

option 1, averaging over replicates (at the site scale) fishes and macro-invertebrates abundances, cbind the two mean abundances matrix (nrow=24sites, ncol=15+10 mean abundances) and calculating bray-curtis.

option 2, for each assemblage, computing bray-curtis dissimilarity among pairs of sites, computing distances among sites centroids. Then summing up the 2 distance matrix.

In case I am not clear, I did these 2 operations in the R codes below.

Please, could you tell me if the option 2 is correct and more appropriate than option 1.

thank you in advance.

Pierre

here is below the R code exemples

generating data

library(plyr);library(vegan)

#assemblage 1: 15 fish species, 6 replicates per site
a1.env=data.frame(
  Habitat=paste("H",gl(2,12*6),sep=""),
  Site=paste("S",gl(24,6),sep=""),
  Replicate=rep(paste("R",1:6,sep=""),24))

summary(a1.env)

a1.bio=as.data.frame(replicate(15,rpois(144,sample(1:10,1))))

names(a1.bio)=paste("F",1:15,sep="")

a1.bio[1:72,]=2*a1.bio[1:72,]

#assemblage 2: 10 taxa of macro-invertebrates, 3 replicates per site

a2.env=a1.env[a1.env$Replicate%in%c("R1","R2","R3"),]

summary(a2.env)

a2.bio=as.data.frame(replicate(10,rpois(72,sample(10:100,1))))

names(a2.bio)=paste("I",1:10,sep="")

a2.bio[1:36,]=0.5*a2.bio[1:36,]

#environmental data at the sit scale

env=unique(a1.env[,c("Habitat","Site")])

env=env[order(env$Site),]

OPTION 1, averaging abundances and cbind

a1.bio.mean=ddply(cbind(a1.bio,a1.env),.(Habitat,Site),numcolwise(mean))

a1.bio.mean=a1.bio.mean[order(a1.bio.mean$Site),]

a2.bio.mean=ddply(cbind(a2.bio,a2.env),.(Habitat,Site),numcolwise(mean))

a2.bio.mean=a2.bio.mean[order(a2.bio.mean$Site),]

bio.mean=cbind(a1.bio.mean[,-c(1:2)],a2.bio.mean[,-c(1:2)])

dist.mean=vegdist(sqrt(bio.mean),"bray")

OPTION 2, computing for each assemblage distance among centroids and summing the 2 distances matrix

a1.dist=vegdist(sqrt(a1.bio),"bray")

a1.coord.centroid=betadisper(a1.dist,a1.env$Site)$centroids

a1.dist.centroid=vegdist(a1.coord.centroid,"eucl")

a2.dist=vegdist(sqrt(a2.bio),"bray")

a2.coord.centroid=betadisper(a2.dist,a2.env$Site)$centroids

a2.dist.centroid=vegdist(a2.coord.centroid,"eucl")

summing up the two distance matrices using Gavin Simpson 's fuse()

dist.centroid=fuse(a1.dist.centroid,a2.dist.centroid,weights=c(15/25,10/25))

summing up the two euclidean distance matrices (thanks to Jari Oksanen correction)

dist.centroid=sqrt(a1.dist.centroid^2 + a2.dist.centroid^2)

and the 'coord.centroid' below for further distance-based analysis (is it correct ?)

coord.centroid=cmdscale(dist.centroid,k=23,add=TRUE)

COMPARING OPTION 1 AND 2

pco.mean=cmdscale(vegdist(sqrt(bio.mean),"bray"))

pco.centroid=cmdscale(dist.centroid)

comparison=procrustes(pco.centroid,pco.mean)

protest(pco.centroid,pco.mean)

Body:
I like this simplicity of this answer, but it only applies to adding 2 distance matrices:

d.fused = (w * d.x) + ((1 - w) * d.y)

so I wrote my own snippet to combine an array of multiple distance matrices (not just 2), and using standard R packages:

# generate array of distance matrices
x <- matrix(rnorm(100), nrow = 5)
y <- matrix(rnorm(100), nrow = 5)
z <- matrix(rnorm(100), nrow = 5)
dst_array <- list(dist(x),dist(y),dist(z))

# create new distance matrix with first element of array
dst <- dst_array[[1]]

# loop over remaining array elements, add them to distance matrix
for (jj in 2:length(dst_array)){
  dst <- dst + dst_array[[jj]]
}

You could also use a vector of similar size to dst_array in order to define scaling factors

dst <- dst + my_scale[[jj]] * dst_array[[jj]]


问:
using awk to match a PATH starting with /root/ and ending before character "
i have a command that produces a random output with a path in it
And i need to extract this path using awk.
The path always starts with the same pattern (lets assume it always starts with /root) but the rest can change

for example :

```<code>error reason  05/30/2017 12:18:37 [74575:45687]: "/root/this/is/my/path/" random text random text random text random text random text random    text
</code>```

to extract /root/this/is/my/path/ : I have tryed using grep + awk in the following way :

```<code>command.sh | grep error  |awk '/root/{mypath=$6}'.
</code>```

But i then figured out my path was not always located at the same place. more over, i don't want to extract the double quotes.

```<code>i need to have /root/this/is/my/path/ not "/root/this/is/my/path/"
</code>```

Anyone can help please?

答:
This should also work: </p>

```<code>command.sh | awk '/^error/{ for ( i = 1; i <= NF; i++) if ( $i ~ /^"/){ gsub(/"/, "", $i); print $i} }' -
</code>```

<p>Output: </p>

```<code>/root/this/is/my/path/
</code>```

Body:
i have a command that produces a random output with a path in it
And i need to extract this path using awk.
The path always starts with the same pattern (lets assume it always starts with /root) but the rest can change

for example :

error reason  05/30/2017 12:18:37 [74575:45687]: "/root/this/is/my/path/" random text random text random text random text random text random    text

to extract /root/this/is/my/path/ : I have tryed using grep + awk in the following way :

command.sh | grep error  |awk '/root/{mypath=$6}'.

But i then figured out my path was not always located at the same place. more over, i don't want to extract the double quotes.

i need to have /root/this/is/my/path/ not "/root/this/is/my/path/"

Anyone can help please?

Body:
This should also work:

command.sh | awk '/^error/{ for ( i = 1; i <= NF; i++) if ( $i ~ /^"/){ gsub(/"/, "", $i); print $i} }' -

Output:

/root/this/is/my/path/


问:
Postgres join very slow because of temp table
I have two simple queries that are effectively the same on a small-medium size table that are giving me radically different results and I'm trying to understand why.

This is the fast one (1sec):

```<code>select      *
from        financials.income f
where       f.itemtype in ('SALES') and f.company_id=6445
</code>```

This is the slow one (1min):

```<code>create temp table t_co as select 6445 as company_id;
select      f.*
from        financials.income f
inner join  t_co on f.company_id=t_co.company_id
where       f.itemtype in ('SALES')
</code>```

Here is the explain analyze for the fast one:

```<code>[
  {
    "Execution Time": 97.271,
    "Planning Time": 2.833,
    "Plan": {
      "Exact Heap Blocks": 29,
      "Node Type": "Bitmap Heap Scan",
      "Actual Total Time": 96.876,
      "Shared Hit Blocks": 14822,
      "Plans": [
        {
          "Node Type": "Bitmap Index Scan",
          "Actual Total Time": 76.988,
          "Shared Hit Blocks": 14793,
          "Shared Read Blocks": 0,
          "Local Hit Blocks": 0,
          "Local Dirtied Blocks": 0,
          "Temp Written Blocks": 0,
          "Plan Width": 0,
          "Total Cost": 69.98,
          "Actual Startup Time": 76.988,
          "Temp Read Blocks": 0,
          "Local Read Blocks": 0,
          "Index Name": "unique_income_daterange",
          "Startup Cost": 0,
          "Shared Dirtied Blocks": 0,
          "Shared Written Blocks": 0,
          "Local Written Blocks": 0,
          "Plan Rows": 956,
          "Index Cond": "((company_id = 6445) AND (itemtype = 'SALES'::text))",
          "Parallel Aware": false,
          "Actual Rows": 1883,
          "Parent Relationship": "Outer",
          "Actual Loops": 1
        }
      ],
      "Shared Read Blocks": 0,
      "Relation Name": "income",
      "Local Hit Blocks": 0,
      "Local Dirtied Blocks": 0,
      "Temp Written Blocks": 0,
      "Plan Width": 75,
      "Actual Loops": 1,
      "Rows Removed by Index Recheck": 0,
      "Lossy Heap Blocks": 0,
      "Alias": "f",
      "Recheck Cond": "((company_id = 6445) AND (itemtype = 'SALES'::text))",
      "Temp Read Blocks": 0,
      "Actual Startup Time": 96.406,
      "Local Read Blocks": 0,
      "Startup Cost": 70.22,
      "Shared Dirtied Blocks": 0,
      "Shared Written Blocks": 0,
      "Local Written Blocks": 0,
      "Plan Rows": 956,
      "Parallel Aware": false,
      "Actual Rows": 1883,
      "Total Cost": 3698.02
    },
    "Triggers": []
  }
]
</code>```

And for the slow one:

```<code>[
  {
    "Execution Time": 69825.054,
    "Planning Time": 0.166,
    "Plan": {
      "Node Type": "Hash Join",
      "Actual Total Time": 69823.936,
      "Shared Hit Blocks": 11135,
      "Plans": [
        {
          "Node Type": "Seq Scan",
          "Actual Total Time": 0.007,
          "Shared Hit Blocks": 0,
          "Shared Read Blocks": 0,
          "Relation Name": "t_co",
          "Local Hit Blocks": 1,
          "Local Dirtied Blocks": 0,
          "Temp Written Blocks": 0,
          "Plan Width": 4,
          "Actual Loops": 1,
          "Actual Startup Time": 0.005,
          "Alias": "t_co",
          "Temp Read Blocks": 0,
          "Local Read Blocks": 0,
          "Startup Cost": 0,
          "Shared Dirtied Blocks": 0,
          "Shared Written Blocks": 0,
          "Local Written Blocks": 0,
          "Plan Rows": 2550,
          "Parallel Aware": false,
          "Actual Rows": 1,
          "Parent Relationship": "Outer",
          "Total Cost": 35.5
        },
        {
          "Node Type": "Hash",
          "Actual Total Time": 69787.311,
          "Peak Memory Usage": 3137,
          "Shared Hit Blocks": 11135,
          "Plans": [
            {
              "Exact Heap Blocks": 25326,
              "Node Type": "Bitmap Heap Scan",
              "Actual Total Time": 68990.682,
              "Shared Hit Blocks": 11135,
              "Plans": [
                {
                  "Node Type": "Bitmap Index Scan",
                  "Actual Total Time": 52693.721,
                  "Shared Hit Blocks": 11135,
                  "Shared Read Blocks": 193938,
                  "Local Hit Blocks": 0,
                  "Local Dirtied Blocks": 0,
                  "Temp Written Blocks": 0,
                  "Plan Width": 0,
                  "Total Cost": 107233,
                  "Actual Startup Time": 52693.721,
                  "Temp Read Blocks": 0,
                  "Local Read Blocks": 0,
                  "Index Name": "unique_income_daterange",
                  "Startup Cost": 0,
                  "Shared Dirtied Blocks": 0,
                  "Shared Written Blocks": 0,
                  "Local Written Blocks": 0,
                  "Plan Rows": 1565411,
                  "Index Cond": "(itemtype = 'SALES'::text)",
                  "Parallel Aware": false,
                  "Actual Rows": 1519378,
                  "Parent Relationship": "Outer",
                  "Actual Loops": 1
                }
              ],
              "Shared Read Blocks": 219264,
              "Relation Name": "income",
              "Local Hit Blocks": 0,
              "Local Dirtied Blocks": 0,
              "Temp Written Blocks": 0,
              "Plan Width": 75,
              "Actual Loops": 1,
              "Rows Removed by Index Recheck": 0,
              "Lossy Heap Blocks": 0,
              "Alias": "f",
              "Recheck Cond": "(itemtype = 'SALES'::text)",
              "Temp Read Blocks": 0,
              "Actual Startup Time": 52699.492,
              "Local Read Blocks": 0,
              "Startup Cost": 107624.35,
              "Shared Dirtied Blocks": 0,
              "Shared Written Blocks": 0,
              "Local Written Blocks": 0,
              "Plan Rows": 1565411,
              "Parallel Aware": false,
              "Actual Rows": 1511066,
              "Parent Relationship": "Outer",
              "Total Cost": 317692.99
            }
          ],
          "Shared Read Blocks": 219264,
          "Local Hit Blocks": 0,
          "Original Hash Batches": 64,
          "Local Dirtied Blocks": 0,
          "Temp Written Blocks": 19128,
          "Plan Width": 75,
          "Actual Loops": 1,
          "Original Hash Buckets": 65536,
          "Hash Batches": 64,
          "Actual Startup Time": 69787.311,
          "Temp Read Blocks": 0,
          "Local Read Blocks": 0,
          "Hash Buckets": 65536,
          "Startup Cost": 317692.99,
          "Shared Dirtied Blocks": 0,
          "Shared Written Blocks": 0,
          "Local Written Blocks": 0,
          "Plan Rows": 1565411,
          "Parallel Aware": false,
          "Actual Rows": 1511066,
          "Parent Relationship": "Inner",
          "Total Cost": 317692.99
        }
      ],
      "Shared Read Blocks": 219264,
      "Join Type": "Inner",
      "Temp Written Blocks": 19192,
      "Local Dirtied Blocks": 0,
      "Local Hit Blocks": 1,
      "Plan Width": 75,
      "Actual Loops": 1,
      "Actual Startup Time": 69793.165,
      "Hash Cond": "(t_co.company_id = f.company_id)",
      "Temp Read Blocks": 355,
      "Local Read Blocks": 0,
      "Startup Cost": 357134.63,
      "Shared Dirtied Blocks": 0,
      "Shared Written Blocks": 0,
      "Local Written Blocks": 0,
      "Plan Rows": 3019514,
      "Parallel Aware": false,
      "Actual Rows": 1883,
      "Total Cost": 605158.39
    },
    "Triggers": []
  }
]
</code>```

There is an index on company_id, a primarykey on 4 columns, and a constraint to make sure that dates don't overlap. The slow query looks like its hitting a constraint that is used to make sure that dates don't overlap, but I don't understand why as I'm only joining on the one column?

```<code>ADD CONSTRAINT unique_income_daterange EXCLUDE USING gist (
validrangez WITH &&,
company_id WITH =,
balancedate WITH =,
itemtype WITH =);
</code>```

答:
The problem is that for a temporary table no table statistics are collected automatically, so PostgreSQL plans the query without valid statistics and arrives at a bad plan.

You can fix that by running

```<code>ANALYZE t_co;
</code>```

before you run the query.

The reason why the temporary view suggested by wildplasser works is that in this case the SELECT 6445 becomes part of the SQL query, so that the optimizer has more information. Note that the temporary view does not point to any table.

Body:
I have two simple queries that are effectively the same on a small-medium size table that are giving me radically different results and I'm trying to understand why.

This is the fast one (1sec):

select      *
from        financials.income f
where       f.itemtype in ('SALES') and f.company_id=6445

This is the slow one (1min):

create temp table t_co as select 6445 as company_id;
select      f.*
from        financials.income f
inner join  t_co on f.company_id=t_co.company_id
where       f.itemtype in ('SALES')

Here is the explain analyze for the fast one:

[
  {
    "Execution Time": 97.271,
    "Planning Time": 2.833,
    "Plan": {
      "Exact Heap Blocks": 29,
      "Node Type": "Bitmap Heap Scan",
      "Actual Total Time": 96.876,
      "Shared Hit Blocks": 14822,
      "Plans": [
        {
          "Node Type": "Bitmap Index Scan",
          "Actual Total Time": 76.988,
          "Shared Hit Blocks": 14793,
          "Shared Read Blocks": 0,
          "Local Hit Blocks": 0,
          "Local Dirtied Blocks": 0,
          "Temp Written Blocks": 0,
          "Plan Width": 0,
          "Total Cost": 69.98,
          "Actual Startup Time": 76.988,
          "Temp Read Blocks": 0,
          "Local Read Blocks": 0,
          "Index Name": "unique_income_daterange",
          "Startup Cost": 0,
          "Shared Dirtied Blocks": 0,
          "Shared Written Blocks": 0,
          "Local Written Blocks": 0,
          "Plan Rows": 956,
          "Index Cond": "((company_id = 6445) AND (itemtype = 'SALES'::text))",
          "Parallel Aware": false,
          "Actual Rows": 1883,
          "Parent Relationship": "Outer",
          "Actual Loops": 1
        }
      ],
      "Shared Read Blocks": 0,
      "Relation Name": "income",
      "Local Hit Blocks": 0,
      "Local Dirtied Blocks": 0,
      "Temp Written Blocks": 0,
      "Plan Width": 75,
      "Actual Loops": 1,
      "Rows Removed by Index Recheck": 0,
      "Lossy Heap Blocks": 0,
      "Alias": "f",
      "Recheck Cond": "((company_id = 6445) AND (itemtype = 'SALES'::text))",
      "Temp Read Blocks": 0,
      "Actual Startup Time": 96.406,
      "Local Read Blocks": 0,
      "Startup Cost": 70.22,
      "Shared Dirtied Blocks": 0,
      "Shared Written Blocks": 0,
      "Local Written Blocks": 0,
      "Plan Rows": 956,
      "Parallel Aware": false,
      "Actual Rows": 1883,
      "Total Cost": 3698.02
    },
    "Triggers": []
  }
]

And for the slow one:

[
  {
    "Execution Time": 69825.054,
    "Planning Time": 0.166,
    "Plan": {
      "Node Type": "Hash Join",
      "Actual Total Time": 69823.936,
      "Shared Hit Blocks": 11135,
      "Plans": [
        {
          "Node Type": "Seq Scan",
          "Actual Total Time": 0.007,
          "Shared Hit Blocks": 0,
          "Shared Read Blocks": 0,
          "Relation Name": "t_co",
          "Local Hit Blocks": 1,
          "Local Dirtied Blocks": 0,
          "Temp Written Blocks": 0,
          "Plan Width": 4,
          "Actual Loops": 1,
          "Actual Startup Time": 0.005,
          "Alias": "t_co",
          "Temp Read Blocks": 0,
          "Local Read Blocks": 0,
          "Startup Cost": 0,
          "Shared Dirtied Blocks": 0,
          "Shared Written Blocks": 0,
          "Local Written Blocks": 0,
          "Plan Rows": 2550,
          "Parallel Aware": false,
          "Actual Rows": 1,
          "Parent Relationship": "Outer",
          "Total Cost": 35.5
        },
        {
          "Node Type": "Hash",
          "Actual Total Time": 69787.311,
          "Peak Memory Usage": 3137,
          "Shared Hit Blocks": 11135,
          "Plans": [
            {
              "Exact Heap Blocks": 25326,
              "Node Type": "Bitmap Heap Scan",
              "Actual Total Time": 68990.682,
              "Shared Hit Blocks": 11135,
              "Plans": [
                {
                  "Node Type": "Bitmap Index Scan",
                  "Actual Total Time": 52693.721,
                  "Shared Hit Blocks": 11135,
                  "Shared Read Blocks": 193938,
                  "Local Hit Blocks": 0,
                  "Local Dirtied Blocks": 0,
                  "Temp Written Blocks": 0,
                  "Plan Width": 0,
                  "Total Cost": 107233,
                  "Actual Startup Time": 52693.721,
                  "Temp Read Blocks": 0,
                  "Local Read Blocks": 0,
                  "Index Name": "unique_income_daterange",
                  "Startup Cost": 0,
                  "Shared Dirtied Blocks": 0,
                  "Shared Written Blocks": 0,
                  "Local Written Blocks": 0,
                  "Plan Rows": 1565411,
                  "Index Cond": "(itemtype = 'SALES'::text)",
                  "Parallel Aware": false,
                  "Actual Rows": 1519378,
                  "Parent Relationship": "Outer",
                  "Actual Loops": 1
                }
              ],
              "Shared Read Blocks": 219264,
              "Relation Name": "income",
              "Local Hit Blocks": 0,
              "Local Dirtied Blocks": 0,
              "Temp Written Blocks": 0,
              "Plan Width": 75,
              "Actual Loops": 1,
              "Rows Removed by Index Recheck": 0,
              "Lossy Heap Blocks": 0,
              "Alias": "f",
              "Recheck Cond": "(itemtype = 'SALES'::text)",
              "Temp Read Blocks": 0,
              "Actual Startup Time": 52699.492,
              "Local Read Blocks": 0,
              "Startup Cost": 107624.35,
              "Shared Dirtied Blocks": 0,
              "Shared Written Blocks": 0,
              "Local Written Blocks": 0,
              "Plan Rows": 1565411,
              "Parallel Aware": false,
              "Actual Rows": 1511066,
              "Parent Relationship": "Outer",
              "Total Cost": 317692.99
            }
          ],
          "Shared Read Blocks": 219264,
          "Local Hit Blocks": 0,
          "Original Hash Batches": 64,
          "Local Dirtied Blocks": 0,
          "Temp Written Blocks": 19128,
          "Plan Width": 75,
          "Actual Loops": 1,
          "Original Hash Buckets": 65536,
          "Hash Batches": 64,
          "Actual Startup Time": 69787.311,
          "Temp Read Blocks": 0,
          "Local Read Blocks": 0,
          "Hash Buckets": 65536,
          "Startup Cost": 317692.99,
          "Shared Dirtied Blocks": 0,
          "Shared Written Blocks": 0,
          "Local Written Blocks": 0,
          "Plan Rows": 1565411,
          "Parallel Aware": false,
          "Actual Rows": 1511066,
          "Parent Relationship": "Inner",
          "Total Cost": 317692.99
        }
      ],
      "Shared Read Blocks": 219264,
      "Join Type": "Inner",
      "Temp Written Blocks": 19192,
      "Local Dirtied Blocks": 0,
      "Local Hit Blocks": 1,
      "Plan Width": 75,
      "Actual Loops": 1,
      "Actual Startup Time": 69793.165,
      "Hash Cond": "(t_co.company_id = f.company_id)",
      "Temp Read Blocks": 355,
      "Local Read Blocks": 0,
      "Startup Cost": 357134.63,
      "Shared Dirtied Blocks": 0,
      "Shared Written Blocks": 0,
      "Local Written Blocks": 0,
      "Plan Rows": 3019514,
      "Parallel Aware": false,
      "Actual Rows": 1883,
      "Total Cost": 605158.39
    },
    "Triggers": []
  }
]

There is an index on company_id, a primarykey on 4 columns, and a constraint to make sure that dates don't overlap. The slow query looks like its hitting a constraint that is used to make sure that dates don't overlap, but I don't understand why as I'm only joining on the one column?

ADD CONSTRAINT unique_income_daterange EXCLUDE USING gist (
validrangez WITH &&,
company_id WITH =,
balancedate WITH =,
itemtype WITH =);

Body:
The problem is that for a temporary table no table statistics are collected automatically, so PostgreSQL plans the query without valid statistics and arrives at a bad plan.

You can fix that by running

ANALYZE t_co;

before you run the query.

The reason why the temporary view suggested by wildplasser works is that in this case the SELECT 6445 becomes part of the SQL query, so that the optimizer has more information. Note that the temporary view does not point to any table.


问:
porting screen shot java app on android
i want your help very badly..bcz i am seeking an answer for this from couple of day's but did not find a bit...

my query is i have a screen shot app written in java...i just want to port it on android emulator and run it..i know i have to rewrite some android specific code but can anyone tell me what changes i should make to the screen shot java app to make it run on android platform..
here is my java screen shot app: (i know for this the device should be rooted i am okay for that)

```<code>import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

class ScreenCapture {

  public static void main(String args[]) throws
           AWTException, IOException {

     // capture the whole screen

     BufferedImage screencapture = new Robot().createScreenCapture(
           new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );

     // Save as JPEG
     File file = new File("screencapture.jpg");

     ImageIO.write(screencapture, "jpg", file);

     // Save as PNG
     // File file = new File("screencapture.png");
     // ImageIO.write(screencapture, "png", file);
  }

}
</code>```

答:
There aren't just a few changes that you have to made. You have to rewrite the whole app and that wouldn't be so easy since making screenshots in Android isn't this easy as in plain Java.

For example you can't use java.awt.Robot because this lib isn't included in Android.

Afaik you also need root rights on a Android phone to make a screenshot. I would recommend that you google for librarys or apps that are already able to do screenshots and use them.

For example the Android Screenshot Library (ASL) is a good point to start with.

ContentLicense: CC BY-SA 2.5

Title: porting screen shot java app on android

Body:
i want your help very badly..bcz i am seeking an answer for this from couple of day's but did not find a bit...

my query is i have a screen shot app written in java...i just want to port it on android emulator and run it..i know i have to rewrite some android specific code but can anyone tell me what changes i should make to the screen shot java app to make it run on android platform..
here is my java screen shot app: (i know for this the device should be rooted i am okay for that)

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

class ScreenCapture {

  public static void main(String args[]) throws
           AWTException, IOException {

     // capture the whole screen

     BufferedImage screencapture = new Robot().createScreenCapture(
           new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );

     // Save as JPEG
     File file = new File("screencapture.jpg");

     ImageIO.write(screencapture, "jpg", file);

     // Save as PNG
     // File file = new File("screencapture.png");
     // ImageIO.write(screencapture, "png", file);
  }

}

OwnerDisplayName: anon


问:
ASP.Net Worker Process Memory Profile Tools
We have a fairly high volume ASP.Net site written in c# using MS commerce server, running in a 32-bit environment. I see the worker process up to 980 megabytes quite often. I would like to profile this process and determine where any gains could be made in code to reduce the memory foot print of this site. My question what tools have worked well for you doing this sort of thing on ASP.Net web applications?

I am looking for tools that will give me very specific feedback, that will really help to clearly see what needs to change in the code. It would be best if this tool could profile our production environment worker process for a more concrete set of data to compare.

[edit]

So far it seems the consensus is that it's a toss up between Ants and JetBrains. Has anyone used both? If so which one was superior, or what are the pros and cons of each?

答:
There's a free way.

launch the task manager

right-click the w3wp process

select "create dump" (I'm amazed how few people know about this feature - including myself at some point!)

copy the dump file to your local machine (so we don't bother the production server)

open the file in Visual Studio

enjoy

select "Debug Managed memory" for advanced view which class uses memory etc.

AFAIK, the above requires Visual Studio "Ultimate" edition (I guess its called "Enterprise" now?). If you don't have one, then follow these steps (very simple too)

launch WinDbg (free tool, part of Windows SDK, there are tons of answers here on StackOverflow on how to download WinDbg without all the SDK bloatware)

Press Ctrl + D and load the dump file into WinDbg

type .loadby sos clr (this will load SOS.dll that allows WinDbg to analyze .NET processes, SOS.dll is a part of NET Framework so you probably already have it)

type !dumpheap -stat (this will output the class names, sorted by memory usage, ascending order. Skip system.string and system.byte[] classes cause these are side-effects, not the cause...)

UPDATE FROM 2019: WinDbg is now available via MS Store, just search for "WinDbg", then couple of clicks and its there.


问:
Interpolation function approx() in r gives error - need at least two non-NA values to interpolate
I am using R Studio on Windows 8 machine. I am trying to interpolate a point between two points.

```<code>x1 = -159.9, y1 = 56.5,
x2 = -159.9, y2 = 56.3
</code>```

I am using approx() function in the following manner (reproducible)

```<code>approx(c(-159.9,-159.9), c(56.5,56.3), n = 3)
</code>```

which gives me an error

```<code>Error in approx(c(-159.9, -159.9), c(56.5, 56.3), n = 3) :
need at least two non-NA values to interpolate
</code>```

Its expecting two non-NA values, which I have provided.

The function is working flawlessly for other points. Just this is the problem.
If you have come across any such error, please let me know how did you solve this?

答:
From the Details of ?approx():

The inputs can contain missing values which are deleted, so at least
  two complete (x, y) pairs are required (for method = "linear", one
  otherwise). If there are duplicated (tied) x values and ties is a
  function it is applied to the y values for each distinct x value.

Body:
I am using R Studio on Windows 8 machine. I am trying to interpolate a point between two points.

x1 = -159.9, y1 = 56.5,
x2 = -159.9, y2 = 56.3

I am using approx() function in the following manner (reproducible)

approx(c(-159.9,-159.9), c(56.5,56.3), n = 3)

which gives me an error

Error in approx(c(-159.9, -159.9), c(56.5, 56.3), n = 3) :
need at least two non-NA values to interpolate

Its expecting two non-NA values, which I have provided.

The function is working flawlessly for other points. Just this is the problem.
If you have come across any such error, please let me know how did you solve this?


问:
3 boxes inline, content alignment
I have 3 boxes with dynamic content, in each box there is a form with submit button, and some other things. How to get the effect from the picture.

Height of the each box is max from all boxes. Submit buttons in one line, on the bottom.

body {
  width: 720px;
}
form input {
  display: block;
  margin-bottom: 15px;
  width: 100%;
}
form label {
  text-align: left;
  width: 100%;
  display: block;
}
.box-container {
  display: flex;
}
.box {
  border: 1px solid #000;
  flex: 1 1 auto;
  max-width: calc(33% - 2px);
  text-align: center;
  box-sizing: border-box;
  padding: 10px;
}
.box p {
  text-align: justify;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">
  <div class="box">
    <h1>bla bla bla</h1>
    <p> some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s</p>
    <form>
      <label>value 1</label>
      <input type="text"/>
      <label>value 2</label>
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>
  </div>
  <div class="box">
    <h1>bla bla bladada das dasd asd</h1>
    <p>Longer information<br> some information dasd asd asd asd an</p>
    <form>
      <label>value 1</label>
      <input type="text"/>
      <label>value 2</label>
      <input type="text"/>
      <label>value 3</label>
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>
  </div>
  <div class="box">
    <h1>bla bla b</h1>
    <p>Longer information</p>
    <form>
      <label>value 1</label>
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>
  </div>
<div></code>```

答:
I wrote something from scratch for you to  use as base.

HTML

```<code><div class="wrapper">
    <div>
        <input type="submit"/>
    </div>
    <div>
        <input type="submit"/>
    </div>
    <div>
        <input type="submit"/>
    </div>
</div>

<div class="clearfix"></div>
</code>```

CSS

```<code>.wrapper > div {
    border: 1px solid #000;
    float: left;
    width: 250px;
    height: 300px;
    margin: 0 10px;
    position: relative;
}

.wrapper {
    margin: 0 auto;
    width: 830px;
}

.wrapper > div > input[type="submit"] {
    position: absolute;
    bottom: 20px;
    left: 25px;
    display: block;
    width: 200px;
}

.clearfix:before, .clearfix:after {
    content: "";
    clear: both;
    display: block;
}
</code>```

At the end, it looks something like this. I added .clearfix just in case you'll add more content after it.

Play around with it here. Hopefully, this can help you out.

Also, if you don't like the idea of using position absolute. I did it this way just to demonstrate how it will look like, without the dummy contents above the buttons.

An alternative is to create a wrapper for each of those rectangular nodes. Inside the wrapper, declare two divs that overlap each other. The bottom div should contain the submit button.

Title: 3 boxes inline, content alignment

Body:
I have 3 boxes with dynamic content, in each box there is a form with submit button, and some other things. How to get the effect from the picture.

Height of the each box is max from all boxes. Submit buttons in one line, on the bottom.

body {
  width: 720px;
}
form input {
  display: block;
  margin-bottom: 15px;
  width: 100%;
}
form label {
  text-align: left;
  width: 100%;
  display: block;
}
.box-container {
  display: flex;
}
.box {
  border: 1px solid #000;
  flex: 1 1 auto;
  max-width: calc(33% - 2px);
  text-align: center;
  box-sizing: border-box;
  padding: 10px;
}
.box p {
  text-align: justify;
}

bla bla bla

 some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s

    <form>
      value 1
      <input type="text"/>
      value 2
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>

bla bla bladada das dasd asd

Longer information
 some information dasd asd asd asd an

    <form>
      value 1
      <input type="text"/>
      value 2
      <input type="text"/>
      value 3
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>

bla bla b

Longer information

    <form>
      value 1
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>

Body:
I wrote something from scratch for you to  use as base.

HTML

<div class="wrapper">
    <div>
        <input type="submit"/>
    </div>
    <div>
        <input type="submit"/>
    </div>
    <div>
        <input type="submit"/>
    </div>
</div>

<div class="clearfix"></div>

CSS

.wrapper > div {
    border: 1px solid #000;
    float: left;
    width: 250px;
    height: 300px;
    margin: 0 10px;
    position: relative;
}

.wrapper {
    margin: 0 auto;
    width: 830px;
}

.wrapper > div > input[type="submit"] {
    position: absolute;
    bottom: 20px;
    left: 25px;
    display: block;
    width: 200px;
}

.clearfix:before, .clearfix:after {
    content: "";
    clear: both;
    display: block;
}

At the end, it looks something like this. I added .clearfix just in case you'll add more content after it.

Play around with it here. Hopefully, this can help you out.

Also, if you don't like the idea of using position absolute. I did it this way just to demonstrate how it will look like, without the dummy contents above the buttons.

An alternative is to create a wrapper for each of those rectangular nodes. Inside the wrapper, declare two divs that overlap each other. The bottom div should contain the submit button.


问:
Laravel 5.4 one to many relationship
I have two tables in my model:
- Groups (id, name, category_id)
- Categories (id, name)

I would need to show in my view a list with every group name and its corresponding category. Could you please show me how to populate the Eloquent method and also what do I need in the view side?

This is what I have so far but of course is not working

-- GroupController

```<code>`       public function index()
{
    $groups = Category::find(1);

    return view('groups.groups',compact('groups'));
}
</code>```

-- Group

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

-- CategoryController

```<code>`       public function groups()
{
    return $this->hasMany('App\Group');
}`
</code>```

-- Category

```<code>`       public function groups()
{
    return $this->hasMany('App\Group');
}`
</code>```

-- view

@foreach($groups as $group)
{{$group->category}}
{{$group->category->name}}
@endforeach

thanks!!

答:
An easy approach would be using Eloquent's Eager Loading:
https://laravel.com/docs/4.2/eloquent#querying-relations

```<code>Group::with('category')->get()
</code>```

For example:

```<code>      # Loop through all groups
      foreach(Group::with('category')->get() as $group){
        #get group name
        print $group->name;

        #get all categories related to this group
        $categories =  $group->category;
        foreach ($categories as $category){
            print $category->name;
        }
        print "<br>";
    }
</code>```

Title: Laravel 5.4 one to many relationship

Body:
I have two tables in my model:
- Groups (id, name, category_id)
- Categories (id, name)

I would need to show in my view a list with every group name and its corresponding category. Could you please show me how to populate the Eloquent method and also what do I need in the view side?

This is what I have so far but of course is not working

-- GroupController

`       public function index()
{
    $groups = Category::find(1);

    return view('groups.groups',compact('groups'));
}

-- Group

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

-- CategoryController

`       public function groups()
{
    return $this->hasMany('App\Group');
}`

-- Category

`       public function groups()
{
    return $this->hasMany('App\Group');
}`

-- view

@foreach($groups as $group)
{{$group->category}}
{{$group->category->name}}
@endforeach

thanks!!

Body:
An easy approach would be using Eloquent's Eager Loading:
https://laravel.com/docs/4.2/eloquent#querying-relations

Group::with('category')->get()

For example:

      # Loop through all groups
      foreach(Group::with('category')->get() as $group){
        #get group name
        print $group->name;

        #get all categories related to this group
        $categories =  $group->category;
        foreach ($categories as $category){
            print $category->name;
        }
        print "<br>";
    }


问:
moment-timezones.js, how to convert date in spesific timezone to utc, disregarding my local timezone?
my system uses timezone UTC+03:00 ,

im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc

```<code>const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York")
  .tz("Z").toDate();
</code>```

doesnt work correctly

how am i even suppose to convert to utc time?

-----------edit---------------

i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:

```<code>moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York").tz("Africa/Accra")
</code>```

but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!

is there a way to set the utc offset to 0 in momentjs-timezones?

答:
i found a function that does what i was trying to do, it belongs to the momentjs library itself: utcOffset(n) sets the offset to n.

(i also had to explicitly write the date string format correctly, thanks VincenzoC)

this is the code i was trying to write:

```<code>const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York");
const dateUTC = dateInNY.utcOffset(0).toDate();
</code>```

however, the toDate function changes the timezone to my local timezone anyway, so .utcOffset(0) is redundat, and i can just use moment this way:

```<code>const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York");
const dateUTC = dateInNY.toDate();
</code>```

and change the Date objects date to utc time later (in my case, the JSON.stringify stuff i use later does that for me)

Body:
my system uses timezone UTC+03:00 ,

im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc

const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York")
  .tz("Z").toDate();

doesnt work correctly

how am i even suppose to convert to utc time?

-----------edit---------------

i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:

moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York").tz("Africa/Accra")

but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!

is there a way to set the utc offset to 0 in momentjs-timezones?

Body:
i found a function that does what i was trying to do, it belongs to the momentjs library itself: utcOffset(n) sets the offset to n.

(i also had to explicitly write the date string format correctly, thanks VincenzoC)

this is the code i was trying to write:

const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York");
const dateUTC = dateInNY.utcOffset(0).toDate();

however, the toDate function changes the timezone to my local timezone anyway, so .utcOffset(0) is redundat, and i can just use moment this way:

const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York");
const dateUTC = dateInNY.toDate();

and change the Date objects date to utc time later (in my case, the JSON.stringify stuff i use later does that for me)


问:
Do c++ references work like macro substitutions?
```<code>std::vector<int> v;
v.push_back(1);
int &r0=v[0],*p0=&v[0];
v.insert(v.begin(),0);
for (int i=2; i<1000000; i++) v.push_back(i);
</code>```

After I insert and add the additional elements is it the case that the whole vector might be shifted to a different memory location?

So what will r0 and p0 return?

If the vector has shifted I'm guessing p0 will point to garbage but will the reference still work (i.e. return 0)? Is a reference similar to a macro substitution?

答:
A reference is nothing like a macro substitution.

Any operation that increases the size of a std::vector invalidates its end() iterators.   If the resizing also increases capacity of the vector (i.e. reallocates the underlying memory) the begin() iterators are also invalidated.

That means both r0 and p0 are potentially invalidated.    Without checking and comparing the results of v.capacity() before and after the resizing (and confirming there is no change of capacity) there is no guarantee that r0 and p0 reference or point to the first element of the vector v.

The strategy used to update size and capacity of the vector is implementation-defined.   Given that your code is inserting a million and one elements (1000001), it is very likely that the capacity is increased at some point, and that both r0 and p0 are invalidated (i.e. left dangling) - realistically, few implementations of std::vector would use a strategy that won't require resizing when adding that number of elements.   So, practically, it is a fair bet that r0 and p0 are both invalidated.

The address of the vector (i.e. &v) will not change.   Characteristics of data managed by v (v.capacity(), v.size(), v.data(), v.begin(), v.end(), etc) are what will (potentially) change.

Body:
std::vector<int> v;
v.push_back(1);
int &r0=v[0],*p0=&v[0];
v.insert(v.begin(),0);
for (int i=2; i<1000000; i++) v.push_back(i);

After I insert and add the additional elements is it the case that the whole vector might be shifted to a different memory location?

So what will r0 and p0 return?

If the vector has shifted I'm guessing p0 will point to garbage but will the reference still work (i.e. return 0)? Is a reference similar to a macro substitution?


问:
Iam using bootstrap-multiselect.js for dropdown select options, i need to select checkboxes for a certain limit..?
Iam using below javascript to limit the check boxes.

```<code>function tdClick(value){
var no = 3;
$('input.single-checkbox').on('change', function(evt) {
    if($(this).siblings(':checked').length >= no) {
        this.checked = false;
    }
});
</code>```

But i am not able to figure out the select ids in the code. The bootstrap-multiselect.js is internally listing out the options. can anyone help me with this..?

答:
use this $("#selector-id :selected").length; to get the length of selected options

function tdClick(value){
var no = 3;
$("#selector_id").on("change", function () {

    var count = $("#selector_id :selected").length;

    if(count>3){
      // your logic
    }

});```

Body:
Iam using below javascript to limit the check boxes.

function tdClick(value){
var no = 3;
$('input.single-checkbox').on('change', function(evt) {
    if($(this).siblings(':checked').length >= no) {
        this.checked = false;
    }
});

But i am not able to figure out the select ids in the code. The bootstrap-multiselect.js is internally listing out the options. can anyone help me with this..?


问:
UWP - Google Analytics - change trackingid at run time
I have and APP. Many customers use this APP.
I'd like to have an Google Trackingid for any Costumer.
Now i'd write my tracking id into my  Analytics.xml

I use
xmlns="http://googleanalyticssdk.codeplex.com/ns/easytracker"

When in my code write

GoogleAnalytics.EasyTracker.GetTracker().SetCustomDimension(1, "Title")

 GoogleAnalytics.EasyTracker.GetTracker().SetCustomDimension(2, "ID")
 GoogleAnalytics.EasyTracker.GetTracker().SendView("Book")

I can't change TrackingId ...is possible to do this ?

Thanks

答:
So, i had to change SDK
Now i use UWP.SDKforGoogleAnalytics.managed and i had wrote these rows

Dim _TrakerId As String = "UA-XXXX0-0"

Dim MyTraker As GoogleAnalytics.Tracker = GoogleAnalytics.AnalyticsManager.Current.CreateTracker(_TrakerId)
MyTraker.ScreenName = "Images"

Dim Hit = GoogleAnalytics.HitBuilder.CreateScreenView.Build

MyTraker.Send(Hit)

All work good... BUT... now i'd like to use Custom dimensions.
Can anyone hel me ??


问:
Why method call is giving error?
When I am writing this code I am getting error

```<code>public class MethodOverloading
{

void m(short i)
{
System.out.println("SHort");
}

public static void main(String[] args)
{

MethodOverloading ml=new MethodOverloading();
ml.m(10);
}

}
</code>```

I am getting error that m(short) is not applicable for m(int) but when I am
assigning int value to short then no error then if am not able to pass int
value as an argument to method that accepts short then how short variable is accepting int value as below?

```<code>short d=10;
System.out.println(d);
</code>```

答:
This is static binding, and the assignment operator '=' is not strict on down casting.But method binder is strict on type. Just  imagine you have one more method void m(int i)  along with void m(int i) the method binder must bind the call to the right method. So it must be strict.

In short s = 10 case, jdk will downcast the value on compilation, so the value will be assigned to s will be down caste of short 10, also if you try to assign a real int range value say 99999999 it will not compile.

Finally static method binding is strict on type.

Title: Why method call is giving error?

Body:
When I am writing this code I am getting error

public class MethodOverloading
{

void m(short i)
{
System.out.println("SHort");
}

public static void main(String[] args)
{

MethodOverloading ml=new MethodOverloading();
ml.m(10);
}

}

I am getting error that m(short) is not applicable for m(int) but when I am
assigning int value to short then no error then if am not able to pass int
value as an argument to method that accepts short then how short variable is accepting int value as below?

short d=10;
System.out.println(d);